Reputation: 57
I am trying to write a desktop app using Electron (with React).
When a user clicks on a button in the desktop app it will run an external Node.js script. 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.
Upvotes: 1
Views: 1636
Reputation: 2000
Look into the child_process
node js module. 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.
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();
then 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;
}
});
Upvotes: 3