Node.js 调试器 CLI
Node.js 内置 CLI 调试器,无需额外工具即可调试代码。
启动调试器
基本启动方式
Bash
# 方式一:inspect 命令
node inspect app.js
# 方式二:--inspect 标志
node --inspect app.js
# 方式三:启动时暂停
node inspect --port=9229 app.js
调试器提示符
Bash
$ node inspect app.js
< Debugger listening on ws://127.0.0.1:9229/...
< For help, see: https://nodejs.org/en/docs/inspector
break in app.js:1
> 1 const http = require('http');
2
3 const server = http.createServer();
debug>
常用调试命令
执行控制
| 命令 | 缩写 | 说明 |
|---|---|---|
cont | c | 继续执行 |
next | n | 单步跳过 |
step | s | 单步进入 |
out | o | 单步跳出 |
pause | 暂停执行 |
断点管理
| 命令 | 说明 |
|---|---|
setBreakpoint(file, line) | 设置断点 |
sb(file, line) | 设置断点(简写) |
clearBreakpoint(file, line) | 清除断点 |
cb(file, line) | 清除断点(简写) |
breakpoints | 列出所有断点 |
信息查看
| 命令 | 说明 |
|---|---|
list(n) | 显示当前行前后 n 行代码 |
backtrace | 显示调用栈 |
bt | 显示调用栈(简写) |
watch(expr) | 添加监视表达式 |
watchers | 显示所有监视值 |
断点操作示例
设置断点
Bash
debug> sb('app.js', 10) # 在 app.js 第 10 行设置断点
debug> sb('app.js', 15) # 在 app.js 第 15 行设置断点
debug> breakpoints # 查看所有断点
条件断点
Bash
# 不支持直接条件断点,可用 repl 模拟
debug> repl
> if (count > 10) { debugger; }
清除断点
Bash
debug> cb('app.js', 10) # 清除第 10 行断点
debug> clearAllBreakpoints() # 清除所有断点
变量查看与修改
exec 执行表达式
Bash
debug> exec('variableName') # 查看变量
debug> exec('Object.keys(obj)') # 执行表达式
debug> exec('JSON.stringify(data)') # 格式化输出
repl 模式
Bash
debug> repl
Press Ctrl+C to leave debug repl
> variableName # 查看变量
> obj.property # 访问属性
> variableName = 'new' # 修改变量
> functionCall() # 调用函数
监视表达式
Bash
debug> watch('userId') # 监视 userId 变量
debug> watch('data.length') # 监视表达式
debug> watchers # 显示所有监视值
0: userId = "12345"
1: data.length = 5
debug> unwatch('userId') # 取消监视
调用栈查看
Bash
debug> bt
#0 exampleFunc app.js:15:5
#1 main app.js:25:10
#2 Object.<anonymous> app.js:30:1
#3 Module._compile internal/modules/cjs/loader.js:1085:14
完整调试流程
Bash
$ node inspect server.js
debug> sb('server.js', 10) # 设置断点
debug> c # 继续执行
break in server.js:10
8
9 function handleRequest(req, res) {
>10 const data = parseBody(req);
11 return process(data);
12 }
debug> n # 单步执行
debug> exec('req.url') # 查看变量
debug> s # 进入函数
debug> o # 跳出函数
debug> c # 继续执行
注意事项
- CLI 调试器适合远程服务器调试场景
- 复杂调试建议使用 DevTools 或 VS Code
repl模式下可用 Ctrl+C 退出- 调试异步代码时注意事件循环
要点总结
node inspect启动 CLI 调试器n/s/o/c控制单步执行sb(file, line)设置断点exec()和repl查看修改变量watch(expr)监视表达式变化
📝 发现内容有误?点击此处直接编辑