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

Node.js 调试基础

Node.js 提供多种调试方式,本文介绍最常用的调试基础。

console 调试

基本输出

JavaScript
console.log('普通日志');
console.warn('警告信息');
console.error('错误信息');

// 格式化输出
console.log('用户: %s, 年龄: %d', '张三', 25);

// 对象输出
const obj = { name: '张三', age: 25 };
console.dir(obj, { depth: null, colors: true });

// 计时
console.time('耗时');
// ... 代码
console.timeEnd('耗时'); // 耗时: 123.456ms

console.table

JavaScript
const users = [
  { name: '张三', age: 25 },
  { name: '李四', age: 30 }
];
console.table(users);

debugger 语句

代码断点

JavaScript
function calculate(a, b) {
  debugger; // 程序在此暂停
  return a + b;
}

inspect 调试模式

启动调试

Bash
# 启动调试模式
node inspect app.js

# 或使用 --inspect
node --inspect app.js

# 指定端口
node --inspect=9229 app.js

# 启动时暂停
node --inspect-brk app.js

内置调试器命令

常用命令

命令说明
c继续执行
n单步跳过
s单步进入
o单步跳出
pause暂停
cont继续
repl进入 REPL 模式

调试示例

Bash
$ node inspect app.js
debug> n  # 单步执行
debug> s  # 进入函数
debug> o  # 跳出函数
debug> c  # 继续执行
debug> repl  # 进入交互模式
> variableName  # 查看变量

查看变量

JavaScript
// 在调试器中
debug> exec('variableName')  // 查看变量
debug> exec('Object.keys(obj)')  // 执行表达式
debug> setBreakpoint('script.js', 10)  // 设置断点
debug> clearBreakpoint('script.js', 10)  // 清除断点

注意事项

  • console.log 适合快速调试,不适合生产环境
  • debugger 语句在生产代码中应移除
  • --inspect 允许外部调试器连接
  • VS Code 和 Chrome DevTools 调试体验更好

要点总结

  • console.log/warn/error 快速输出调试
  • debugger 语句设置代码断点
  • node --inspect 启动调试服务器
  • 内置调试器使用 n/s/o/c 单步执行
  • console.table 表格化输出复杂数据

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

← 上一篇 Node.js 调试器 CLI
下一篇 → Node.js Nodemon 自动重启
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

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

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