如何使用 Electron-React 应用程序 运行 外部脚本
How to run external script using an Electron-React app
我正在尝试使用 Electron(带有 React)编写桌面应用程序。
当用户单击桌面应用程序中的按钮时,它将 运行 一个外部 Node.js 脚本。我想使用 Electron 构建一个 GUI,该 GUI 能够在用户单击按钮后调用脚本来完成一些工作。
查看 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
window。
要终止进程,您必须使用 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;
}
});
我正在尝试使用 Electron(带有 React)编写桌面应用程序。
当用户单击桌面应用程序中的按钮时,它将 运行 一个外部 Node.js 脚本。我想使用 Electron 构建一个 GUI,该 GUI 能够在用户单击按钮后调用脚本来完成一些工作。
查看 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
window。
要终止进程,您必须使用 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;
}
});