如果只是启动一个 Node 脚本,直接传可执行文件和参数,通常比拼一整条命令更容易拿到真实的退出码和信号:
import { spawn } from 'node:child_process';
const child = spawn(process.execPath, ['scripts/build.mjs'], {
stdio: 'inherit'
});
child.on('exit', (code, signal) => {
console.log({ code, signal });
});
环境:Node.js 18+。只有确实需要管道、重定向这类 shell 语法时再开 shell: true;外部输入也别直接拼进命令字符串。Windows 下如果启动的是 npm 脚本,还要留意 npm.cmd 的差异。