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

基本原理

  1. 启动 WebSocket 进行基于 inspect protocol 双工通信
    1. current_node_process <=> current_websocket <=> current_inspect_tool
  2. 启动 HTTP 服务,记录源(Meta)信息
  3. 每个程序会生成一个 UUID

IDE

VS Code

VS code 中打断点,然后进入 debugger 面板,点击开始。

7ca8f0208e4d7e1e2b06d21c744034a1.png

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:
ca43e801db77429cd844f3c91a82e032.png

Then we could see this:
f8f287de675922d747f3782bdfb38062.png

We could write manaul or auto generate new:
8cbd03755ca4f26a00de0d37d639ab58.png

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:
57d6310b23c560dee2eb66afc06d29cd.png

Chrome DEVTOOLS

chrome://inspect

1st: Run CMD in terminal and the CLI options are right here:
b21497d8dfa6fa59051d193962a7db69.png

node debug -help # it is very useful as well
# or 
node inspect dmeo.js

> help

2nd: Navigates to chrome://inspect page
fb19f29e187f9d1b7307bb51867d0b5e.png

inspect protocol

1st: Run CMD in terminal and the CLI options are right here:
b21497d8dfa6fa59051d193962a7db69.png

复制 HOST + PORT 端口号进入浏览器:
7115cc7926d181abe11f9a94f45daef3.png

HOST + PORT + "/json" 查看 HTTP
6c3040ba7e1b563e7b5ed552ea940f16.png

复制返回的 JSON 字符串中的 devtoolsFrontendUrl 字段,打上 breakpoint, 开始调试:
aff76522d3593547ba468108f5d2946c.png

DEVTOOLS Node ICON

only works for OSX and Linux.
点击绿色的 nodeJS ICON.

14ea54f6bb54a6a98e28763e1ebff904.png

性能调优

open DEVTOOLS - JSProfiler recording, then refresh current page to record how long used of each function execute.

672e1f762236e04f080ccc071a13fcfe.png

END

Have fun with NodeJS.

猜你喜欢

转载自www.cnblogs.com/givingwu/p/10569056.html