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

Node.js能否按需启用Profiler而非通过--prof启动参数?

Node.js 生产环境动态启用 Profiler 的方法

可以的,Node.js 支持通过编程方式或信号触发两种方式动态启用/禁用 Profiler,无需启动时加--prof参数,完美适配生产环境按需开启的需求。

一、通过信号触发(类似 Inspector 的 SIGUSR1 方式)

从 Node.js v14.11.0 开始,支持用SIGUSR2信号来启动/停止 CPU Profiler:

  • 启动 Profiler:向进程发送SIGUSR2信号
    kill -SIGUSR2 <pid>
    
  • 再次发送SIGUSR2会停止 Profiler,并将生成的 .cpuprofile 文件写入当前工作目录(文件名格式类似CPU-<pid>-<timestamp>.cpuprofile)

注意:如果进程已经启动了 Inspector(比如通过SIGUSR1),SIGUSR2会直接通过 Inspector 的 API 来生成 Profiler 数据,无需额外配置。

二、编程方式动态控制

你也可以通过 Node.js 的内置inspector模块在代码里直接控制 Profiler 的启停,适合需要更精细控制(比如定时开启、自定义保存路径)的场景:

示例代码:

const inspector = require('inspector');
const fs = require('fs');
const profiler = inspector.Profiler;

// 启动 CPU Profiler
function startProfiling() {
  profiler.start();
  console.log('Profiler 已启动');
}

// 停止并保存 Profiler 数据
function stopProfiling() {
  profiler.stop((err, profile) => {
    if (err) {
      console.error('停止 Profiler 失败:', err);
      return;
    }
    const fileName = `CPU-Profiler-${Date.now()}.cpuprofile`;
    fs.writeFileSync(fileName, JSON.stringify(profile));
    console.log(`Profiler 数据已保存到 ${fileName}`);
  });
}

// 监听自定义信号切换启停状态
process.on('SIGUSR1', () => {
  if (!profiler.isRunning()) {
    startProfiling();
  } else {
    stopProfiling();
  }
});

console.log(`进程 PID: ${process.pid}`);
console.log('发送 SIGUSR1 信号可切换 Profiler 启停状态');

使用时:

  • 启动进程后,发送kill -SIGUSR1 <pid>启动 Profiler
  • 再次发送kill -SIGUSR1 <pid>停止并保存数据

注意事项

  • 性能开销:Profiler 运行时确实会带来一定性能损耗(通常在 5%-20% 左右),建议只在排查问题时短时间开启
  • 版本兼容:信号触发的方式需要 Node.js v14.11.0 及以上版本,编程方式从 Node.js v8.0.0 开始支持
  • 内存占用:生成的 .cpuprofile 文件可能较大,确保磁盘有足够空间

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:03:18