我正在尝试写一个桌面应用程序使用电子(与反应)。
当用户点击桌面应用程序中的按钮时,它将运行外部Node.js脚本。我想使用Electron来建立一个图形用户界面,能够调用脚本做一些工作后,用户点击按钮。
发布于 2021-07-09 04:42:12
查看child_process节点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;
}
});https://stackoverflow.com/questions/68306193
复制相似问题