在 Linux 环境下调试 Node.js 代码有多种方式,以下是几种常用的方法和工具,以及详细的操作步骤:
console.log 快速调试虽然简单,但在快速定位问题时非常有效。
console.log('变量值:', myVar);
Node.js 内置了基于命令行的调试工具(通过 inspect 协议)。
启动调试模式:
node inspect app.js
inspect 命令(支持 Chrome DevTools):
bash
node --inspect app.js
bash
node --inspect=9229 app.js # 指定端口调试命令:
c:继续执行。n:下一步(跳过函数)。s:进入函数。repl:进入交互式环境查看变量。watch('变量名'):监视变量。通过 Chrome DevTools 调试:
chrome://inspectinspect 链接。VS Code 是 Node.js 调试的推荐工具,支持图形化断点和变量监控。
.vscode/launch.json 文件:
json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Node.js",
"program": "${workspaceFolder}/app.js",
"skipFiles": ["<node_internals>/**"]
}
]
}F5 启动调试。x === 5)。Log Message(无需暂停执行)。ndb 调试器Google 开发的增强版调试工具,支持异步堆栈跟踪。
npx ndb app.js
node --cpu-prof app.js
生成 .cpuprofile 文件,用 Chrome DevTools 或 VS Code 分析。
node --heap-prof app.js
使用 chrome://inspect 或 clinic.js 工具分析堆快照。
node-inspect:旧版 CLI 调试器(Node.js < 8)。--inspect=9229 指定端口。9229),并安全暴露服务。console.log + Chrome DevTools。ndb 或性能分析工具。根据需求选择合适的方式,多数场景下 VS Code 的集成调试器已经足够强大。