1. 程式人生 > >如何 debug nodeJS 代碼? how to inspect NodeJS code?

如何 debug nodeJS 代碼? how to inspect NodeJS code?

may ebs pan proc space rec rgs docs program

基本原理

  1. 啟動 WebSocket 進行基於 inspect protocol 雙工通信
    1. current_node_process <=> current_websocket <=> current_inspect_tool
  2. 啟動 HTTP 服務,記錄源(Meta)信息
  3. 每個程序會生成一個 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?