學習連結:
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)
- 單擊左上角的終端圖示打開調試控制台。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsISPrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdsATOfd3bkFGazxCMx8VesATMfhHLlN3XnxCMwEzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5iYxgTNhJTMmRjNxI2MlVTYyImMlZ2Y4Y2M5IjZzIzMz8CXxEzLchDMxIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjL2M3Lc9CX6MHc0RHaiojIsJye.png)
你可能需要配置一下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 線程。