主题
子进程
node:child_process 用于运行外部命令。命令或参数来自用户输入时风险极高:避免 shell,使用参数数组和固定的命令白名单。
选择 API
| API | 适用场景 |
|---|---|
spawn(command, args) | 长时间运行、输出量大、需要流式读取 |
execFile(file, args) | 运行固定可执行文件并收集输出;不经 shell |
exec(command) | 需要 shell 特性时使用;有注入风险与输出缓冲上限 |
fork(modulePath) | 启动 Node.js 子进程并使用 IPC |
js
import { spawn } from 'node:child_process'
const child = spawn('pnpm', ['build'], {
stdio: 'inherit',
shell: false,
})
child.once('error', (error) => console.error('无法启动命令', error))
child.once('exit', (code, signal) => {
console.log({ code, signal })
})注意事项
execSync、spawnSync会阻塞事件循环,只用于 CLI 或启动阶段。- 使用
AbortSignal或child.kill()实现取消,并同时处理error、exit。 exec默认通过 shell 解析命令,拼接用户输入可能导致命令注入。
