如何获取 Node.js 项目的 CPU 配置文件快照?

Node.js 性能优化中,了解如何获取 CPU 分析快照对排查性能瓶颈至关重要。本文介绍了两种主要方法:使用内置命令行参数和 `v8-profiler` 模块。

Node.js 中等 性能分析 性能优化 CPU Profiling

获取 Node.js 项目的 CPU profile 快照主要用于性能分析。可以通过以下两种常用方式实现:

  1. 使用 Node.js 内置命令行参数
    • 运行应用时添加 --cpu-prof 标志:
      node --cpu-prof app.js
      

      此命令会在应用运行目录生成一个 .cpuprofile 文件。

    • 在浏览器中导入该文件:直接在 Chrome DevTools 的 “Performance” 面板加载,即可可视化分析 CPU 占用情况,定位性能瓶颈。这种方法适用于无需额外模块的快速分析。
  2. 使用 v8-profiler npm 模块
    • 首先安装依赖:
      npm install v8-profiler
      
    • 在代码中添加自定义采样逻辑(支持控制采样时长和频率):
      const profiler = require('v8-profiler');
      const fs = require('fs');
      
      profiler.startProfiling('my-cpu-snapshot');
      setTimeout(() => {
        const profile = profiler.stopProfiling();
        profile.export((error, result) => {
          if (error) throw error;
          fs.writeFileSync('cpu-profile.cpuprofile', result);
          profile.delete();
          console.log('CPU profile 已保存');
        });
      }, 5000); // 采样时间为 5 秒(可调整)
      

      此方式可在运行中动态采集数据,生成 .cpuprofile 格式文件,同样兼容 Chrome DevTools 进行分析,适用于复杂或分布式环境。