node --inspect app.js 配合 Chrome DevTools 打断点(ch"> node --inspect app.js 配合 Chrome DevTools 打断点(ch"> node --inspect app.js 配合 Chrome DevTools 打断点(ch">
Node.js 词条目录
前端Wiki/Node.js/实战/上线与排查

调试与性能技巧

调试:最直接的是 node --inspect app.js 配合 Chrome DevTools 打断点(chrome://inspect);快速定位用 nodemon 改代码自动重启,省去手动重启。

性能:先用 --prof 或 clinic.js 找到耗时函数,再优化。实战技巧:绝不让同步 API 出现在请求路径上、用 stream 替代 readFile 处理大文件、频繁访问的数据加缓存、JSON.stringify 大对象分块输出。

  • --inspect + chrome://inspect:断点调试 Node 就像调前端
  • nodemon:文件变动自动重启,开发效率神器
  • 性能排查:--prof 看 CPU 耗时;事件循环被阻塞的表现是“所有请求一起变慢”
JS
// 调试内置:node --inspect app.js 后在 Chrome 打开 chrome://inspect

// 性能技巧 1:大文件用流,别 readFile(内存会被撑爆)
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
  const stream = fs.createReadStream('./big.mp4');
  stream.pipe(res);              // 边读边发,常量内存
}).listen(3000);

// 性能技巧 2:计算结果缓存,避免每请求重算
const cache = new Map();
function getConfig(file) {
  if (!cache.has(file)) cache.set(file, loadConfig(file));
  return cache.get(file);
}

// 性能技巧 3:setImmediate 让出事件循环
// 长循环里每处理一批任务 setImmediate(next),给其他请求喘息机会
function batchWork(items, i = 0) {
  for (const end = Math.min(i + 1000, items.length); i < end; i++) doWork(items[i]);
  if (i < items.length) setImmediate(() => batchWork(items, i));
}
本节要点调试用 --inspect/或 nodemon;性能优化就是四招:流式、缓存、别同步、让出事件循环。