如何顺序执行多个带文件监听的package.json脚本并支持正常终止?
实现顺序启动常驻监听命令的可行方案
方案一:调整npm-run-all参数解决进程终止问题
你遇到的npm-run-all无法用ctrl+c终止所有进程的问题,是因为缺少相关参数配置,不需要换其他工具,调整配置即可满足需求:
- 首先确认已安装npm-run-all:
yarn add npm-run-all -D - 按如下方式修改
scripts字段:
{ "scripts": { "cmd1": "cd packages/apis/ && yarn start", "cmd2": "cd packages/utils/ && yarn start", "cmd3": "cd packages/components/ && yarn start", "cmd4": "cd services/ad/ && yarn dev", "start": "run-s -r --kill-signal SIGTERM cmd1 cmd2 cmd3 cmd4" } }
- 参数说明:
run-s是npm-run-all提供的串行执行命令的缩写,替代你原来的&&逻辑,不会并行执行命令-r参数表示只要有一个命令退出,就自动终止所有其他关联进程--kill-signal SIGTERM指定终止信号,确保所有子进程都会被正常清理,不会残留
方案二:自定义Node启动脚本(无额外依赖、更可控)
如果不想依赖第三方工具,可以自己写个几十行的Node脚本实现需求,同时100%保证进程终止逻辑正常:
- 在项目根目录新建
start.js文件,写入以下内容:
const { spawn } = require('child_process') const runningProcesses = [] // 按顺序填要启动的命令 const commandList = [ { command: 'yarn', args: ['cmd1'] }, { command: 'yarn', args: ['cmd2'] }, { command: 'yarn', args: ['cmd3'] }, { command: 'yarn', args: ['cmd4'] } ] async function startAll() { for (const item of commandList) { const childProcess = spawn(item.command, item.args, { stdio: 'inherit', shell: process.platform === 'win32' }) runningProcesses.push(childProcess) // 可根据自己项目的启动速度调整等待时间,确保上一个服务启动完成再跑下一个 await new Promise(resolve => setTimeout(resolve, 2000)) } } // 监听终止信号,清理所有子进程 process.on('SIGINT', () => { console.log('\n正在停止所有服务...') runningProcesses.forEach(p => p.kill()) process.exit(0) }) startAll().catch(console.error)
- 修改package.json的start命令:
"start": "node start.js"
内容的提问来源于stack exchange,提问作者Om3ga
相关产品推荐
相关产品推荐

