Wednesday 7 June 2017

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?



via Aaron

No comments:

Post a Comment