全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-15 7 分钟 ✍️ juanwangdev

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>

常用调试命令

执行控制

命令缩写说明
contc继续执行
nextn单步跳过
steps单步进入
outo单步跳出
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) 监视表达式变化

📝 发现内容有误?点击此处直接编辑

← 上一篇 Node.js ESLint 与代码风格检查
下一篇 → Node.js 调试基础
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库