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

生产环境下如何不使用Nodemon通过npm脚本重启Node.js服务器?

无Nodemon实现Node.js生产环境服务器重启方案

核心逻辑是先终止当前运行的Node服务进程,再重新拉起新的服务实例,无需依赖Nodemon这类开发工具,以下是不同场景的配置方式:

类Unix环境(Linux/macOS)原生配置

直接在package.json的scripts字段中添加如下配置即可:

{
  "scripts": {
    "start": "node your-server-entry.js",
    "restart-me": "pkill -f 'node your-server-entry.js' || true && npm run start"
  }
}
  • 将your-server-entry.js替换为你实际的服务入口文件名称
  • 命令中的|| true是为了兼容旧进程不存在的场景,避免首次运行重启命令时报错
  • 若服务需要权限运行,执行时加上sudo即可:sudo npm run restart-me

Windows环境原生配置

Windows下使用系统自带的taskkill命令实现进程终止,配置如下:

{
  "scripts": {
    "start": "node your-server-entry.js",
    "restart-me": "taskkill /F /IM node.exe /FI \"imagename eq node.exe\" 2>nul & npm run start"
  }
}
  • 上述命令会强制终止所有Node进程,若需要精准匹配特定服务,可以调整taskkill的筛选参数
  • 2>nul作用是忽略进程不存在时的报错信息

跨平台通用配置

如果需要一套配置兼容多系统,可以写一个轻量的Node.js重启脚本,无需额外安装第三方依赖:

  1. 项目根目录新建restart.js文件:
const { exec } = require('child_process');
const path = require('path');

const entryFile = 'your-server-entry.js';
const killCommand = process.platform === 'win32' 
  ? `taskkill /F /IM node.exe /FI "args eq *${entryFile}*"`
  : `pkill -f "node ${entryFile}"`;

exec(killCommand, (killErr) => {
  // 忽略进程不存在的错误
  if (killErr && killErr.code !== 1 && killErr.code !== 128) {
    console.error('终止旧服务进程失败:', killErr.message);
    return process.exit(1);
  }

  // 启动新服务实例,后台运行
  const serverProcess = exec(`node ${entryFile}`, {
    cwd: path.resolve(__dirname),
    detached: true,
    stdio: 'ignore'
  });
  serverProcess.unref();
  console.log('服务重启成功');
  process.exit(0);
});
  1. 在package.json中配置脚本:
{
  "scripts": {
    "restart-me": "node restart.js"
  }
}

生产环境使用时建议配合系统进程守护能力(如Linux下的systemd),可以避免服务意外退出后无法自动恢复的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:45:05