[英]How to run external script using an Electron-React app
I am trying to write a desktop app using Electron (with React).我正在尝试使用 Electron(使用 React)编写桌面应用程序。
When a user clicks on a button in the desktop app it will run an external Node.js script.当用户单击桌面应用程序中的按钮时,它将运行外部 Node.js 脚本。 I want to use Electron to build a GUI that is able to call a script to do some work after the user clicks the button.
我想使用 Electron 构建一个 GUI,该 GUI 能够在用户单击按钮后调用脚本来完成一些工作。
Look into the child_process
node js module.查看
child_process
节点 js 模块。 You can implement something like this:你可以实现这样的东西:
On the client side:在客户端:
const { ipcRenderer } = require("electron");
document.getElementById("someButton").addEventListener(e => {
ipcRenderer.send("runScript");
});
On the electron side:在电子方面:
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);
});
});
Keep in mind, in order to use ipcRenderer on the client side you may need to enable nodeIntegration
in your browser window.请记住,为了在客户端使用 ipcRenderer,您可能需要在浏览器窗口中启用
nodeIntegration
。
To be able to kill a process you would have to use the child_process.spawn
method and save that in a variable then run variableThatProcessWasSpawned.stdin.pause();
为了能够
child_process.spawn
进程,您必须使用child_process.spawn
方法并将其保存在一个变量中,然后运行variableThatProcessWasSpawned.stdin.pause();
then variableThatProcessWasSpawned.kill()
.然后
variableThatProcessWasSpawned.kill()
。 For example例如
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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.