學習鏈接:
https://cnodejs.org/topic/5a9661ff71327bb413bbff5b
https://github.com/nswbmw/node-in-debugging/blob/master/4.3%20Visual%20Studio%20Code.md
1、新建 test 文件夾,新建 index.js
var http = require('http'); var server = http.createServer(function (req, rep) { rep.writeHead(200, {"Content-Type": "text/plain"}); console.log(20180716211300, 'Hello'); rep.end("Hello World!!"); }) server.listen(3000, function (err) { console.log('start'); });
2、用 vscode 打開 test 文件夾(項目)
- 單擊左側第 4 個 tab,切換到調試模式。
- 單擊代碼第 5 行
rep.end("Hello World!!");
左側空白處添加斷點。 - 單擊左上角 ”調試“ 的綠色三角按鈕啟動調試。(你可能需要配置一下launch.json)
- 單擊左上角的終端圖標打開調試控制台。
你可能需要配置一下launch.json:
{ // 使用 IntelliSense 了解相關屬性。 // 懸停以查看現有屬性的描述。 // 欲了解更多信息,請訪問: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "啟動程序", "program": "${workspaceFolder}/\\index.js" } ] }
3、開始愉快的調試
切換到終端,然后輸入 curl http://localhost:3000,正常的話,會發現斷點成功。
4、再切換到調試控制台(chrome Dev Tool)
就可以打印出變量了。當然通常直接通過鼠標查看變量更方便。
5、自動重啟nodejs
首先,全局安裝 nodemon:
$ npm i nodemon -g
然后,修改 launch.json:
{ // 使用 IntelliSense 了解相關屬性。 // 懸停以查看現有屬性的描述。 // 欲了解更多信息,請訪問: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "啟動程序", "runtimeExecutable": "nodemon", "restart": true, "console": "integratedTerminal", "program": "${workspaceFolder}/\\index.js" } ] }
多添加了如下幾個字段:
"runtimeExecutable": "nodemon",
"restart": true, "console": "integratedTerminal",
這時候我們在運行,保存會自動重啟了
6、對現有Nodejs進程進行調試
第一步:我們不使用 vs code 啟動項目,而使用傳統手動命令行啟動 nodejs
$ node index.js
第二步:需要先對launch.js 進行配置:
{ // 使用 IntelliSense 了解相關屬性。 // 懸停以查看現有屬性的描述。 // 欲了解更多信息,請訪問: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Attach to node", "type": "node", "request": "attach", "restart": true, "processId": "${command:PickProcess}" } ] }
配置成功后,啟動選項會變成 “Attach to node”
此時點擊運行按鈕,會列出所有的 node 線程。
附加成功后,就可以試試上例的斷點調試之類的啦~~