并行运行子进程以调试NodeJS



我正在尝试基于此API示例生成子进程:https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows

我只是想并行运行3个命令(来自NPM,如npm run x-script),并将它们的输出流式传输到父命令,但我是得到:

节点:事件:491年

throw er; // Unhandled 'error' event

错误:spawn npm run debug-js-watch enent

在Process.ChildProcess._handle
  • 。onexit(节点:内部/child_process: 283:19)
  • at onErrorNT (node:internal/child_process:478:16)
  • at processTicksAndRejections (node:internal/process/task_queues:83:21)在ChildProcess实例上触发'error'事件:
  • 在Process.ChildProcess._handle
  • 。onexit(节点:内部/child_process: 289:12)
  • at onErrorNT (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: []
}

代码如下:

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', []);

spawn接受一个命令和一个参数列表。你可以通过拆分字符串来解决这个问题。

function runInParallel(cmd) {
const [ command, ...argumentsList ] = cmd.split(' ')
let childProcess = spawn(command, argumentsList);
// etc
runInParallel('npm run debug-js-watch');
// etc

看起来spawn没有找到npm。我不得不使用exec代替,它工作:

const {exec} = require('node:child_process');
function runInParallel(cmd) {
let childProcess = exec(cmd);
...
}

最新更新