Home > Mobile >  Run child processes in parallel for debugging with NodeJS
Run child processes in parallel for debugging with NodeJS

Time:12-05

I'm trying to spawn child processes based on this API example: https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows

I simply want to run 3 commands (from NPM, like npm run x-script) in parallel and stream their output to the parent, but I'm getting:

node:events:491

throw er; // Unhandled 'error' event

Error: spawn npm run debug-js-watch ENOENT

  • at Process.ChildProcess._handle.onexit (node:internal/child_process:283:19)
  • at one rrorNT (node:internal/child_process:478:16)
  • at processTicksAndRejections (node:internal/process/task_queues:83:21) Emitted 'error' event on ChildProcess instance at:
  • at Process.ChildProcess._handle.onexit (node:internal/child_process:289:12)
  • at one rrorNT (node:internal/child_process:478:16)
  • at processTicksAndRejections (node:internal/process/task_queues:83:21)
{
  errno: -4058,
  code: 'ENOENT',
  syscall: 'spawn npm run debug-js-watch',
  path: 'npm run debug-js-watch',
  spawnargs: []
}

Here's the code:

const path = require('path');
const { spawn } = require('node:child_process');

function runInParallel(command, argumentsList) {
    let childProcess = spawn(command, argumentsList);
    childProcess.stdout.on('data', (data) => {
        console.log(data.toString());
    });

    childProcess.stderr.on('data', (data) => {
        console.error(data.toString());
    });

    /*
    childProcess.on('exit', (code) => {
        console.log(`Child exited with code ${code}`);
    });
    */
}

runInParallel('npm run debug-js-watch', []);
runInParallel('npm run debug-css-watch', []);
runInParallel('npm run debug-serve', []);

CodePudding user response:

spawn takes a command and an arguments list. You can fix this by splitting your string.

function runInParallel(cmd) {
    const [ command, ...argumentsList ] = cmd.split(' ')
    let childProcess = spawn(command, argumentsList);
    // etc

runInParallel('npm run debug-js-watch');
// etc

CodePudding user response:

It looks like spawn doesn't find npm. I had to use exec instead and it worked:

const {exec} = require('node:child_process');

function runInParallel(cmd) {
    let childProcess = exec(cmd);
    ...
}
  • Related