Node.js 项目调试指南

Node.js 项目调试指南

🧭 一、调试工具和方式总览

方式难度场景说明
console.log 调试简单问题定位最常见,但效率低
debug 模块★★模块化输出日志支持命名空间的调试日志
VSCode 断点调试★★★跟踪函数调用、变量状态推荐使用
node inspect / ndb★★★★CLI 下高级调试脚本、远程调试
日志管理工具(如 winston★★生产调试日志分级管理
APM 工具(如 New Relic)★★★★★生产级监控对系统性能进行监控

📌 二、使用 console.log() 基础调试(初级)

这是最常见的调试方式:

app.get('/user/:id', (req, res) => {
  console.log('User ID:', req.params.id);
  res.send('OK');
});

优点: 简单直接
缺点: 多处嵌套或异步函数中难以追踪,不适合生产环境


🎯 三、使用 debug 模块进行模块化日志调试(推荐)

1. 安装

npm install debug

2. 使用方法

const debug = require('debug')('myapp:server');

app.get('/test', (req, res) => {
  debug('This is a test log');
  res.send('debugging');
});

3. 开启调试

运行项目时开启对应命名空间:

DEBUG=myapp:* node app.js

🛠️ 四、使用 VSCode 进行断点调试(强烈推荐)

1. 配置 launch.json

.vscode/launch.json 中添加如下配置:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug Express App",
      "program": "${workspaceFolder}/app.js",
      "env": {
        "NODE_ENV": "development"
      },
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}

2. 添加断点并运行调试

  • 在代码行号左侧点击添加断点;
  • 在 VSCode 左侧点击 ▶️ “Debug Express App”;
  • 使用调试控制台查看变量、调用栈等信息。

🔍 五、使用 node inspect CLI 调试

1. 启动带调试的 Node.js 程序

node inspect app.js

或使用 Chrome DevTools:

node --inspect-brk app.js

然后打开 Chrome,访问:chrome://inspect


📜 六、集成日志记录工具(如 winston

1. 安装

npm install winston

2. 使用示例

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.simple()
  ),
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'logs/app.log' })
  ]
});

logger.info('Server started');
logger.error('Something went wrong');

📡 七、远程和生产环境调试

  • 使用 PM2 管理进程并查看日志:
npm install pm2 -g
pm2 start app.js --name my-app
pm2 logs my-app
  • 使用 APM 工具(如 New Relic、Datadog)监控性能、内存、错误。

🧠 八、调试 Express 中间件和异步代码注意事项

1. 异步代码中的错误追踪

app.get('/', async (req, res, next) => {
  try {
    const data = await fetchData();
    res.send(data);
  } catch (err) {
    next(err);
  }
});

2. 错误处理中间件

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

✅ 总结

调试方式推荐场景难度
console.log快速测试
debug日志分类调试
VSCode 调试开发断点、变量跟踪中高
node inspect命令行调试
winston日志归档、记录
APM 工具生产环境监控

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Code_Geo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值