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表格化输出复杂数据
📝 发现内容有误?点击此处直接编辑