如何 debug nodeJS 代碼? how to inspect NodeJS code?
基本原理
- 啟動 WebSocket 進行基於 inspect protocol 雙工通信
- current_node_process <=> current_websocket <=> current_inspect_tool
- 啟動 HTTP 服務,記錄源(Meta)信息
- 每個程序會生成一個 UUID
IDE
VS Code
VS code 中打斷點,然後進入 debugger 面板,點擊開始。
Config launch.json
mkdir node-debug-demo cd node-debug-demo touch cmd.js echo "console.log(process.argv.slice(2))" >> cmd.js node cmd.js -t test -a abort
Will show folling results:
[ '-t',
'test',
'-a',
'abort' ]
But may they never been show for VS code debug mode, so we need canfig the .vscode/launch.json
:
Then we could see this:
We could write manaul or auto generate new:
Code:
{ "type": "node", "request": "launch", "name": "Test cmd.js", "program": "${workspaceFolder}/cmd.js", "args": [ "-t", "test", "-a", "abort" ] }
Use VS code debug panel to debug the cmd.js before this we must chekcout to it:
Chrome DEVTOOLS
chrome://inspect
1st: Run CMD in terminal and the CLI options are right here:
node debug -help # it is very useful as well
# or
node inspect dmeo.js
> help
2nd: Navigates to chrome://inspect page
inspect protocol
1st: Run CMD in terminal and the CLI options are right here:
復制 HOST + PORT 端口號進入瀏覽器:
HOST + PORT + "/json" 查看 HTTP
復制返回的 JSON 字符串中的 devtoolsFrontendUrl
字段,打上 breakpoint, 開始調試:
DEVTOOLS Node ICON
only works for OSX
and Linux
.
點擊綠色的 nodeJS ICON.
性能調優
open DEVTOOLS - JSProfiler recording, then refresh current page to record how long used of each function execute.
END
Have fun with NodeJS.
如何 debug nodeJS 代碼? how to inspect NodeJS code?