You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为npm脚本设置超时:超时后自动终止进程?

解决Angular构建脚本超时自动终止的通用方法

一、利用系统原生超时工具(跨平台适配)

  • Linux/macOS:直接用系统自带的timeout命令,修改npm脚本即可:
    "build": "timeout 30m ng build my-project-name"
    
    30m代表设置30分钟超时,超时后会强制终止整个进程链,不会残留输出。如果需要超时后自动重启,套个循环就行:
    "build-with-retry": "while true; do timeout 30m ng build my-project-name && break; done"
    
  • Windows:用PowerShell的进程控制命令实现,修改脚本如下:
    "build": "powershell -Command \"$proc = Start-Process ng -ArgumentList 'build my-project-name' -NoNewWindow -PassThru; if (-not $proc.WaitForExit(1800000)) { $proc.Kill() }\""
    
    1800000是毫秒数(对应30分钟),-NoNewWindow保证输出在当前终端,超时后直接杀掉进程。

二、改进Node.js脚本彻底终止进程树

之前的问题是只杀掉了主进程,没处理关联的子进程。可以借助tree-kill包实现进程树全终止:

  1. 先安装依赖:npm i tree-kill --save-dev
  2. 新建build-with-timeout.js脚本:
const { spawn } = require('child_process');
const treeKill = require('tree-kill');

// 启动原始构建命令
const buildProcess = spawn('npm', ['run', 'build:original'], { stdio: 'inherit' });
const timeout = 30 * 60 * 1000; // 30分钟超时

// 设置超时定时器
const timeoutId = setTimeout(() => {
  treeKill(buildProcess.pid, 'SIGTERM', (err) => {
    if (err) console.error('终止进程失败:', err);
    console.log('构建超时,重启中...');
    // 递归调用实现重启
    require('./build-with-timeout.js');
  });
}, timeout);

// 监听构建进程退出事件
buildProcess.on('exit', (code) => {
  clearTimeout(timeoutId);
  if (code === 0) {
    console.log('构建成功');
    process.exit(0);
  } else {
    console.log('构建失败,重启中...');
    require('./build-with-timeout.js');
  }
});
  1. 在package.json中添加对应脚本:
"build:original": "ng build my-project-name",
"build": "node build-with-timeout.js"

这样能彻底清理所有关联进程,不会出现输出残留的问题。

三、使用轻量npm包npm-timeout

这个包封装了跨平台的超时终止逻辑,无需自己写复杂脚本:

  1. 安装包:npm i npm-timeout --save-dev
  2. 修改npm脚本:
"build": "npm-timeout --timeout 1800000 ng build my-project-name"

要实现超时重启,同样套循环:

"build-with-retry": "while true; do npm-timeout --timeout 1800000 ng build my-project-name && break; done"

内容的提问来源于stack exchange,提问作者Ivan Koshelev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 11:06:18