在 Ubuntu 上调试 Node.js,常见方式包括命令行调试、IDE 调试(VS Code)、日志调试、性能调试等。下面按使用场景给你一个完整、实用的调试指南。
node -v
npm -v
如果没有安装:
sudo apt update
sudo apt install nodejs npm
建议使用 NodeSource 安装新版本:
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
console.log(最常用)console.log('data:', data);
console.error('error:', err);
✅ 优点:简单
❌ 缺点:不直观、不适合复杂问题
node inspect app.js
或旧版本:
node --inspect app.js
默认监听:
ws://127.0.0.1:9229
debugger;
示例:
function test() {
debugger;
console.log('hello');
}
test();
运行:
node inspect app.js
常用命令:
| 命令 | 作用 |
|---|---|
c |
继续执行 |
n |
下一行 |
s |
进入函数 |
o |
跳出函数 |
repl |
查看变量 |
quit |
退出 |
node --inspect-brk app.js
--inspect-brk会在第一行暂停
地址栏输入:
chrome://inspect
点击:
Open dedicated DevTools for Node.js
✅ 功能:
.vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Node",
"program": "${workspaceFolder}/app.js"
}
]
}
✅ 支持:
{
"type": "node",
"request": "launch",
"name": "Debug npm start",
"runtimeExecutable": "npm",
"runtimeArgs": ["start"],
"skipFiles": ["<node_internals>/**"]
}
node --inspect-brk ./bin/www
VS Code 配置:
"program": "${workspaceFolder}/app.js"
node app.js 2>&1 | tee error.log
process.on('uncaughtException', err => {
console.error('Uncaught Exception:', err);
});
process.on('unhandledRejection', err => {
console.error('Unhandled Rejection:', err);
});
node --prof app.js
生成:
node --prof-process isolate-*.log > result.txt
node --inspect app.js
使用 Chrome DevTools → Memory
| 工具 | 场景 |
|---|---|
console.log |
快速定位 |
node inspect |
命令行调试 |
| Chrome DevTools | 可视化调试 |
| VS Code | 日常开发 |
| clinic.js | 性能分析 |
| ndb | 高级调试 |
你可以直接贴:
我可以一步步带你调 ✅