【发布时间】:2021-09-19 04:33:12
【问题描述】:
我正在尝试使用 Electron(使用 React)编写桌面应用程序。
当用户单击桌面应用程序中的按钮时,它将运行外部 Node.js 脚本。我想使用 Electron 构建一个 GUI,它能够在用户单击按钮后调用脚本来完成一些工作。
【问题讨论】:
我正在尝试使用 Electron(使用 React)编写桌面应用程序。
当用户单击桌面应用程序中的按钮时,它将运行外部 Node.js 脚本。我想使用 Electron 构建一个 GUI,它能够在用户单击按钮后调用脚本来完成一些工作。
【问题讨论】:
查看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;
}
});
【讨论】: