在Debian系统中调试Node.js应用程序有多种方法,以下是一些常用的调试技巧:
使用 debug
包进行调试
-
安装
debug
包:npm install debug
-
在代码中引入并使用
debug
模块:const debug = require('debug')('myapp'); debug('Hello, debug!');
-
动态开启调试: 通过设置
DEBUG
环境变量来控制调试器的输出:DEBUG=myapp node app.js
-
使用命名空间:
const debug = require('debug'); const serverDebug = debug.extend('myapp:server'); const databaseDebug = debug.extend('myapp:database'); serverDebug('Hello, server!'); databaseDebug('Hello, database!');
-
自定义输出格式:
DEBUG_COLORS=true DEBUG_FD=3 node app.js
使用 Chrome DevTools 调试
-
启动 Node.js 进程时使用
--inspect-brk
标志:node server.js --inspect-brk
-
在 Chrome 浏览器中打开 DevTools: 访问
chrome://inspect
,点击“为 Node 打开专用 DevTools”,然后连接到你的 Node.js 进程。 -
调试异常: 在 Chrome DevTools 的“Sources”标签页中,点击带有暂停符号的八角形按钮来暂停异常抛出。
-
添加断点: 在行号区域单击以创建断点,或使用右键菜单添加条件断点。
在 Visual Studio Code 中调试
-
创建
.vscode/launch.json
文件:{ "version": "0.2.0", "configurations": [ { "name": "Debug nextjs", "type": "node-terminal", "request": "launch", "command": "npm run dev" } ] }
-
直接调试客户端代码: 配置
type
为chrome
并提供一个 URL:{ "version": "0.2.0", "configurations": [ { "name": "Debug client-side", "type": "chrome", "request": "launch", "url": "http://localhost:3000" } ] }
使用 Node.js Inspector
-
启动调试模式: 使用
--inspect
或--inspect-brk
标志启动 Node.js 进程。 -
在 IDE 中配置调试器: 在 Visual Studio Code 等 IDE 中配置 Node.js 调试器,连接到 V8 Inspector 进行调试。
这些技巧可以帮助你在Debian系统中高效地调试Node.js应用程序,无论是通过命令行工具、浏览器开发工具还是集成开发环境(IDE)。