调试 Node
node --inspect、using-debugger。
35 分钟
调试 Node
nodejs-essentials 用 console.log 起步;nva-errors 讲错误分类。本课用 Inspector 协议、node --inspect、断点与 CPU/Heap 分析——定位 nrt-timers 阻塞与 nrt-gc 泄漏。
学习目标
- 启动 inspect 并在 Chrome DevTools 或 VS Code 中下断点
- 使用
debugger语句与 conditional breakpoint - 对 Worker 与 async 链做基本步进调试
启动 Inspector
node --inspect app.js # 默认 9229,首行可能断住
node --inspect-brk app.js # 第一行暂停,适合来不及下断点的脚本
node --inspect=0.0.0.0:9229 app.js # 远程调试(注意安全组/防火墙)
终端会打印 devtools:// 链接;Chrome 打开 chrome://inspect → Configure → 添加 localhost:9229。
安全:生产环境不要对公网暴露 9229;用 SSH 隧道或仅本地 bind。
VS Code launch.json 片段
{
"type": "node",
"request": "launch",
"name": "Debug App",
"program": "${workspaceFolder}/app.js",
"skipFiles": ["<node_internals>/**"]
}
skipFiles 跳过 Node 内部帧,async 栈更易读。测试调试可对 node-test 用 "runtimeArgs": ["--inspect-brk"]。
debugger 与日志断点
function compute(n) {
debugger; // 运行到此处暂停(需 inspect 附着)
return n * 2;
}
DevTools Logpoint 可在不改代码的情况下 console.log 表达式——适合临时看变量。
调试 async 与 Promise
- Async stack traces:Settings 勾选「Async stack traces」。
- 步进时区分 Step over(跳过 async 内部)与 Step into(进入 then/await)。
await挂起时 call stack 会显示 microtask——结合 nrt-callbacks 理解。
CPU Profiler 与 Heap
| 工具 | 用途 |
|---|---|
| Performance / CPU profile | 找同步热点、Event Loop 长任务 |
| Memory → Heap snapshot |