Aaron Beall
Aaron Beall

Reputation: 52143

Spawn child node process from Electron

I have an existing node script that I run from CLI like node script.js --args.

I am trying to build an Electron app to replace the CLI. To run the actual script I can use child_process:

function run(arg) {
    const script = spawn("node", ["./script.js", "run", "--arg", arg], { cwd: TOOLS_DIR, env: process.env });

    script.stdout.on('data', (data) => {
        console.log(`stdout: ${data}`);
    });

    script.stderr.on('data', (data) => {
        console.log(`stderr: ${data}`);
    });

    script.on('close', (code) => {
        console.log(`child process exited with code ${code}`);
    });
}

However this only works when I launch electron from my app folder. When I run the built app using electron-packager the run() call fails with error:

Uncaught Error: spawn node ENOENT

It seems that the built app cannot run node commands. I have NodeJS installed but if I log process.env.PATH I notice that from the built app /usr/local/bin (where node lives) is not in the $PATH, but if I run electron from my app folder it is. In either case, since Electron runs on NodeJS is there an easy way to run a node script from an Electron app?

Upvotes: 4

Views: 4404

Answers (1)

Aaron Beall
Aaron Beall

Reputation: 52143

For anyone interested, I eventually got it working in my case by using a combination of fork() (which uses the Electron packaged NodeJS runtime instead of depending on NodeJS installed on client machine) and patching the env's $PATH (to allow the script.js command to itself spawn some commands):

const env = { ...process.env, PATH: `${process.env.PATH}:/usr/local/bin` };
const child = fork("./script.js", args, { cwd: TOOLS_DIR, env, silent: true });

The incomplete $PATH is a known issue in Electron and there's the fix-path library as a solution, but I could not get that to work for some reason.

Upvotes: 6

Related Questions