温馨提示×

centos nodejs调试怎么开启

小樊
46
2026-09-21 03:23:36
栏目: 编程语言

在 CentOS 上调试 Node.js,常见有几种方式,下面按使用场景给你总结一下。


一、开启 Node.js 调试模式(最基础)

1️⃣ 使用 --inspect

node --inspect app.js

默认监听:

ws://127.0.0.1:9229

终端会输出类似:

Debugger listening on ws://127.0.0.1:9229/xxxx

2️⃣ 指定端口

node --inspect=9229 app.js

3️⃣ 调试第一行业务代码(常用)

node --inspect-brk app.js

⚠️ 程序会在第一行暂停,方便打断点


二、CentOS 远程调试(重要)

问题

CentOS 通常在服务器上,本地是 Windows / Mac

解决:监听 0.0.0.0

node --inspect=0.0.0.0:9229 app.js

⚠️ 安全警告:

  • 不要公网直接暴露 9229
  • 建议用 SSH 隧道

三、通过 SSH 端口转发(推荐)

在本地执行:

ssh -L 9229:127.0.0.1:9229 user@centos_ip

CentOS 上运行:

node --inspect app.js

本地浏览器打开:

chrome://inspect

四、使用 VS Code 调试 CentOS Node.js

1️⃣ CentOS 启动

node --inspect=9229 app.js

2️⃣ VS Code launch.json

{
  "type": "node",
  "request": "attach",
  "name": "Attach to CentOS",
  "address": "127.0.0.1",
  "port": 9229,
  "localRoot": "${workspaceFolder}",
  "remoteRoot": "/path/to/project"
}

五、PM2 调试(生产常用)

临时调试

pm2 start app.js --node-args="--inspect=9229"

查看状态

pm2 list

六、日志 / 错误调试(无 GUI)

node app.js 2>&1 | tee log.txt

或:

pm2 logs

七、常见问题

❌ 端口连不上

firewall-cmd --list-ports
firewall-cmd --add-port=9229/tcp --permanent
firewall-cmd --reload

❌ 权限问题

sudo node --inspect app.js

总结

场景 命令
本地调试 node --inspect app.js
首行断点 node --inspect-brk app.js
远程 --inspect=0.0.0.0:9229
安全 SSH 隧道
生产 PM2 + inspect

如果你用的是 CentOS 7 / 8 / Stream,或者 Docker / PM2 / NestJS / Express,可以告诉我具体环境,我可以给你更精确的方案。

0 踩