1

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.

1 Answer 1

3

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;
   }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution bro, it work like charm! BTW do you know the way to kill the running process when clicking a button?
I'll edit my answer with the way to do that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.