Node Inspect 调试器 是做什么的?
用于需要检查器访问的 Node.js 调试:隐藏局部变量、异步挂起、不稳定测试、子进程、启动竞态、内存增长或 CPU 热点路径。
默认优先使用 node inspect。仅在需要脚本化断点、自动状态捕获、堆快照或 CPU 性能分析时使用 Chrome DevTools 协议。
快速开始
- 在入口暂停:
node inspect path/to/script.js - TypeScript:
node --inspect-brk --import tsx path/to/script.ts - 现有进程 PID:
kill -SIGUSR1 <pid>然后node inspect -p <pid> - 检查目标列表:
curl -s http://127.0.0.1:9229/json/list | jq - OpenClaw CLI 路径:
node --inspect-brk openclaw.mjs ... - OpenClaw 测试路径:
OPENCLAW_VITEST_MAX_WORKERS=1 node --inspect-brk scripts/run-vitest.mjs <file>
调试器 REPL
- 继续/单步:
cont,next,step,out,pause - 断点:
sb('file.js', 42),sb(42),sb('functionName'),breakpoints,cb('file.js', 42) - 检查:
bt,list(8),watch('expr'),exec expr - 当前作用域:
repl,然后直接计算局部变量;Ctrl+C退出 repl 模式。 - 安全退出:如果进程需要继续,则在退出前使用
cont;否则使用kill。
OpenClaw 提示
- 优先使用
127.0.0.1检查器绑定。不要暴露--inspect=0.0.0.0,除非网络是隔离的。 - 对于 Vitest,使用一个工作进程调试一个文件。步进时避免使用工作进程池。
- 对于 TypeScript 源断点,在有用时使用
--enable-source-maps;node inspect仍然可能显示编译后的路径。 - 对于子进程,
NODE_OPTIONS=--inspect-brk可以传播检查器,但每个子进程需要自己的端口。 - 对于长期运行的网关或开发进程,在通过
/json/list确认目标后,通过 PID 附加。
程序化 CDP
在项目外部安装工具,除非项目已经依赖它们:
mkdir -p /tmp/cdp-tools
npm --prefix /tmp/cdp-tools i chrome-remote-interface
NODE_PATH=/tmp/cdp-tools/node_modules node /tmp/cdp-debug.cjs
最小驱动示例:
const CDP = require("chrome-remote-interface");
(async () => {
const client = await CDP({ port: 9229 });
const { Debugger, Runtime } = client;
Debugger.paused(async ({ callFrames, reason }) => {
const top = callFrames[0];
console.log("paused", reason, top.url, top.location.lineNumber + 1);
const { result } = await Debugger.evaluateOnCallFrame({
callFrameId: top.callFrameId,
expression: "JSON.stringify({ pid: process.pid })",
});
console.log(result.value ?? result.description);
await Debugger.resume();
});
await Runtime.enable();
await Debugger.enable();
await Debugger.setBreakpointByUrl({ urlRegex: ".*target\\.js$", lineNumber: 41 });
await Runtime.runIfWaitingForDebugger();
})();
性能分析
- CPU:启用
Profiler,start,等待,stop,写入/tmp/profile.cpuprofile,在 Chrome DevTools 中打开。 - 堆:启用
HeapProfiler,收集addHeapSnapshotChunk,调用takeHeapSnapshot,写入/tmp/heap.heapsnapshot。
陷阱
--inspect不会暂停;在需要在代码运行前完成设置时使用--inspect-brk。- 默认端口是
9229;对于并行目标,使用--inspect=0或一个唯一的端口。 - 如果断点未命中,请确认文件路径、source map 行为以及执行是否已经过该行。
- 如果分离后进程似乎冻结了,它可能仍然暂停在调试器中。