Spawn a child process in Electron


#1

I’m using Node v6.2.2 and Electron v1.2.5.

I have a small application that I’ve built on top of Electron and now I need to fork the process to run some long running task in another node process but it doesn’t seems to work, when I’m looking at the ChildProcess object I can see that in the argument spawnargs[0] is initialized with the electron executable instead of node so what I did is I’ve tried to use spawn instead but it’s not working as far as I can tell.

Here is the code I’m using to spawn the process (lives inside the file ./modules/tester.js):

    const {spawn} = require('child_process');

    var child = spawn("node", ["worker.js"], { stdio: ['inherit', 'inherit', 'inherit', 'ipc'] });

    const self = {};

    self.start = () => {
        console.log("start");
        child.send("ping");
    };

And here is the code I’m using for my worker.js file:

    process.on("message", (data) => {
        console.log(data);
        console.log("pong");
    });

And finally this is how I’m consuming it.

    const {app} = require("electron");

    const tester = require("./modules/tester");

    app.on("ready", () => {
        tester.start();
    });

Maybe I’m doing it wrong but I don’t think so because when I’m using nodejs it seems to work just fine.

I’ve tried many examples but none of them seems to work, another possibility is that I need to do something special in Electron for it to work but I don’t know.


#2

According to the Node.js documentation, child_process.send can only be used when using fork:

When an IPC channel has been established between the parent and child (i.e. when using child_process.fork()), the child.send() method can be used to send messages to the child process.


#3

@leedohm, fork is a special case of spawn, this perfectly valid code in NodeJS and it works! I simply pass IPC to stdio and this allows me to use send just like it can be used in fork.

Not to mention that I did mention that I’ve used fork in my post but this didn’t work and so I tried to use spawn in hopes that it will work,

I’m not a newbie, I know NodeJS fairly good, I’m however quite new to Electron and maybe I’m missing something, however, what I did to solve this is exactly the reverse, spawn a child process from NodeJS and run Electron.

Anyway, thank you for the answer.


#4

@eyalsk are you attempting spawn a script with an asar file?