2018年1月16日 星期二

前端網頁除錯(2) --- Node.JS 搭配 Visual Studio Code 進行除錯

Visual Studio Code 是微軟開發,它功能介於編輯器與程式開發IDE之間,對於工程師來說是一個不錯的工具,今天就用 Visual Studio Code 來進行 Node.JS 除錯。
滑鼠右鍵,用 VSCode 開啟 123 資料夾。

滑鼠右鍵快捷設定,可在 Visual Studio Code 安裝勾選加入。

或已經安裝 Visual Studio Code 的環境上,將以下註冊機碼存於 OpenWithCode.reg。
Windows Registry Editor Version 5.00
; Open files
[HKEY_CLASSES_ROOT\*\shell\Open with VS Code]
@="Edit with VS Code"
"Icon"="C:\\Program Files\\Microsoft VS Code\\Code.exe,0"
[HKEY_CLASSES_ROOT\*\shell\Open with VS Code\command]
@="\"C:\\Program Files\\Microsoft VS Code\\Code.exe\" \"%1\""
; This will make it appear when you right click ON a folder
; The "Icon" line can be removed if you don't want the icon to appear
[HKEY_CLASSES_ROOT\Directory\shell\vscode]
@="Open Folder as VS Code Project"
"Icon"="\"C:\\Program Files\\Microsoft VS Code\\Code.exe\",0"
[HKEY_CLASSES_ROOT\Directory\shell\vscode\command]
@="\"C:\\Program Files\\Microsoft VS Code\\Code.exe\" \"%1\""
; This will make it appear when you right click INSIDE a folder
; The "Icon" line can be removed if you don't want the icon to appear
[HKEY_CLASSES_ROOT\Directory\Background\shell\vscode]
@="Open Folder as VS Code Project"
"Icon"="\"C:\\Program Files\\Microsoft VS Code\\Code.exe\",0"
[HKEY_CLASSES_ROOT\Directory\Background\shell\vscode\command]
@="\"C:\\Program Files\\Microsoft VS Code\\Code.exe\" \"%V\""

使用以下程式碼來進行VSCode除錯。
const http = require('http');
const server = http.createServer(function (req, res) {
  res.writeHead(200, { 'content-type': 'text/html' });
  var context = '<h1>It works!</h1>';
  res.end(context);
});
server.listen(3000, function () {
  console.log('Listening on http://localhost:3000');
});

VSCode環境設定:
如圖步驟操作,由VSCode產生 Debug 設定檔 launch.json。

launch.json 中,Visual Studio Code 提供兩種 Debug 模式。
一種是「Launch」,啟動一個獨立的具有 debug 模式的程式。
一種是「Attach」,附加於(也可以說「監聽」) 一個已經啟動的程式 (必須已經開啟 Debug 模式)。



執行偵錯,在沒有指定 port 前,Visual Studio Code 偵錯會隨機挑選可用的 port。

執行偵錯,指定 port = 9229,偵錯就都會以 9229 為除錯的 port。


也可在同一份 launch.json 設定檔,添加「Attach」除錯模式。

關於 launch.json 設定檔內容,可參考微軟官網 visualstudio 的說明。

參考資料: