【问题标题】:How to run external script using an Electron-React app如何使用 Electron-React 应用程序运行外部脚本
【发布时间】:2021-09-19 04:33:12
【问题描述】:

我正在尝试使用 Electron(使用 React)编写桌面应用程序。

当用户单击桌面应用程序中的按钮时,它将运行外部 Node.js 脚本。我想使用 Electron 构建一个 GUI,它能够在用户单击按钮后调用脚本来完成一些工作。

【问题讨论】:

    标签: node.js reactjs electron


    【解决方案1】:

    查看child_process node js 模块。你可以实现这样的东西:

    在客户端:

    const { ipcRenderer } = require("electron");
    document.getElementById("someButton").addEventListener(e => {
      ipcRenderer.send("runScript");
    });
    

    在电子方面:

    const { ipcMain } = require("electron");
    const exec = require('child_process').exec;
    
    ipcMain.on("runScript", (event, data) => {
       exec("node script.js", (error, stdout, stderr) => { 
            console.log(stdout);
        });
    });
    

    请记住,要在客户端使用 ipcRenderer,您可能需要在浏览器窗口中启用 nodeIntegration

    为了能够杀死一个进程,您必须使用child_process.spawn 方法并将其保存在一个变量中,然后运行variableThatProcessWasSpawned.stdin.pause();,然后运行variableThatProcessWasSpawned.kill()。例如

    const spawn = require('child_process').spawn ;
    
    let process = null;
    
    ipcMain.on("runScript", (event, data) => {
       process = spawn("node script.js");
    });
    
    ipcMain.on("killProcess", (event, data) => {
       if(process !== null) {
           process.stdin.pause();
           process.stdin.kill();
           process = null;
       }
    });
    

    【讨论】:

    • 感谢兄弟的解决方案,它就像魅力一样!顺便说一句,您知道单击按钮时杀死正在运行的进程的方法吗?
    • 我会用这样的方式编辑我的答案
    猜你喜欢
    • 2017-05-03
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2017-11-09
    • 2021-01-17
    • 2021-10-23
    • 2022-10-18
    • 2021-08-05
    相关资源
    最近更新 更多