更多相关内容见博客 https://github.com/zhuanyongxigua/blognode
调试nodejs有不少方式,能够看这一篇How to Debug Node.js with the Best Tools Available,其中我最喜欢使用的仍是V8 Inspector和vscode的方式。git
在vscode中,点击那个蜘蛛的按钮github
就能看出现debug的侧栏,接下来添加配置npm
选择环境json
就能看到launch.json的文件了。babel
启动的时候,选择相应的配置,而后点击指向右侧的绿色三角spa
{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "program": "${workspaceRoot}/index.js" }, { "type": "node", "request": "attach", "name": "Attach to Port", "address": "localhost", "port": 5858 } ] }
当request
为launch时,就是launch模式了,这是程序是从vscode这里启动的,若是是在调试那将一直处于调试的模式。而attach模式,是链接已经启动的服务。好比你已经在外面将项目启动,忽然须要调试,不须要关掉已经启动的项目再去vscode中从新启动,只要以attach的模式启动,vscode能够链接到已经启动的服务。当调试结束了,断开链接就好,明显比launch更方便一点。debug
不少时候咱们将很长的启动命令及配置写在了package.json
的scripts
中,好比3d
"scripts": { "start": "NODE_ENV=production PORT=8080 babel-node ./bin/www", "dev": "nodemon --inspect --exec babel-node --presets env ./bin/www" },
咱们但愿让vscode使用npm的方式启动并调试,这就须要以下的配置调试
{ "name": "Launch via NPM", "type": "node", "request": "launch", "runtimeExecutable": "npm", "runtimeArgs": [ "run-script", "dev" //这里的dev就对应package.json中的scripts中的dev ], "port": 9229 //这个端口是调试的端口,不是项目启动的端口 },
仅仅使用npm启动,虽然在dev
命令中使用了nodemon,程序也能够正常的重启,可重启了以后,调试就断开了。因此须要让vscode去使用nodemon启动项目。
{ "type": "node", "request": "launch", "name": "nodemon", "runtimeExecutable": "nodemon", "args": ["${workspaceRoot}/bin/www"], "restart": true, "protocol": "inspector", //至关于--inspect了 "sourceMaps": true, "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "runtimeArgs": [ //对应nodemon --inspect以后除了启动文件以外的其余配置 "--exec", "babel-node", "--presets", "env" ] },
注意这里的runtimeArgs
,若是这些配置是写在package.json
中的话,就是这样的
nodemon --inspect --exec babel-node --presets env ./bin/www
这样就很方便了,项目能够正常的重启,每次重启同样会开启调试功能。
但是,咱们并不想时刻开启调试功能怎么办?
这就须要使用上面说的attach模式了。
使用以下的命令正常的启动项目
nodemon --inspect --exec babel-node --presets env ./bin/www
当咱们想要调试的时候,在vscode的debug中运行以下的配置
{ "type": "node", "request": "attach", "name": "Attach to node", "restart": true, "port": 9229 }
完美!
参考资料
我在github https://github.com/zhuanyongx...