在 Ubuntu 下調試 Node.js 代碼,你可以使用內置的調試器 node --inspect
或者使用 Visual Studio Code 等集成開發環境(IDE)進行調試。下面是兩種方法的詳細步驟:
方法一:使用內置調試器 node --inspect
debugger;
語句。例如,在你想要暫停執行的代碼行之前添加一行 debugger;
。function test() {
const a = 1;
const b = 2;
debugger; // 在這里暫停執行
const c = a + b;
console.log(c);
}
test();
node --inspect your_script.js
將 your_script.js
替換為你的 JavaScript 文件名。
chrome://inspect
在 “Remote Target” 列表中,你應該能看到你的 Node.js 腳本。點擊 “inspect” 鏈接,這將打開一個新的開發者工具窗口。
在開發者工具中,你可以設置斷點、單步執行、查看變量值等,以便調試你的代碼。
方法二:使用 Visual Studio Code
安裝 Visual Studio Code(VSCode):訪問 https://code.visualstudio.com/ 下載并安裝適用于 Ubuntu 的 VSCode。
打開你的項目文件夾:在 VSCode 中,點擊 “File” > “Open Folder”,然后選擇你的項目文件夾。
創建一個 launch.json 文件:點擊左側的 “Run and Debug” 圖標,然后點擊 “create a launch.json file”。VSCode 將為你生成一個默認的調試配置文件。
修改 launch.json 文件,使其適用于 Node.js 調試。將默認配置替換為以下內容:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/your_script.js"
}
]
}
將 your_script.js
替換為你的 JavaScript 文件名。
在你的代碼中添加斷點:在 VSCode 的左側 “Run and Debug” 面板中,點擊 “create a launch.json file” 圖標,然后選擇 “Node.js” 環境。這將在你的代碼中添加一個紅色的圓點,表示斷點。
點擊 “Run and Debug” 面板中的綠色三角形按鈕,或按下 F5 鍵啟動調試。VSCode 將啟動你的 Node.js 應用程序,并在斷點處暫停執行。
在調試過程中,你可以查看變量值、單步執行、設置監視表達式等。
這就是在 Ubuntu 下使用內置調試器和 Visual Studio Code 調試 Node.js 代碼的方法。祝你調試愉快!