天天看點

nodejs 調試 debug

整理一下node的debug方式

======================================================

之前網上搜尋到資料是在終端中使用以下指令運作js:

node debug index.js

node --debug index.js

node --debug-brk index.js
           

三者的差別可以自行搜尋,但是我用的node版本是12,運作以上指令會有以下提示:

DeprecationWarning: `node debug` is deprecated. Please use `node inspect` instead.

`node --debug` and `node --debug-brk` are invalid. Please use `node --inspect` and `node --inspect-brk` instead.
           

========================================================

可見debug要麼棄用要麼無效,已經被inspect取代了,對應着以下指令:

node inspect index.js

node --inspect index.js

node --inspect-brk index.js
           

node --inspect 與 node --inspect-brk的差別在後面的内容會有提及。

index.js部分代碼,啟動成功之後列印一條資訊:

app.listen(config.port, function () {
  console.log(`${pkg.name} listening on port ${config.port}`)
});
           

調試node,分為兩種方式:1、借助chrome開發者工具;2、使用指令行。

node --inspect node --inspect-brk
開發者工具
node inspect

因為使用指令行進行調試個人感覺不友好,是以不做介紹,隻介紹如何使用開發者工具進行調試

一、使用node --inspect:

1、運作node --inspect index.js

nodejs 調試 debug

正在監聽9229,同時列印了語句,說明已經成功運作了。

2、在chrome位址欄輸入:chrome://inspect

nodejs 調試 debug

稍等

nodejs 調試 debug

3、當Remote Target出現内容之後,可以看到目前在運作的js,點選inspect,彈出nodejs專用的開發者工具,同時終端輸出資訊有變化

nodejs 調試 debug

4、在Sources面闆,手動選中項目目錄,并運作開發者工具通路

nodejs 調試 debug

5、後面的調試步驟就和調試web項目一樣了。

nodejs 調試 debug

還有更另外一種方式打開nodejs專用的開發者工具,首先打開開發者工具,點選nodejs圖示,效果與上面一樣

nodejs 調試 debug

二、使用node --inspect-brk:

1、運作node --inspect-brk index.js

nodejs 調試 debug

同樣也是監聽了一個開發展工具得預設端口,但是并沒有列印我們要輸出得語句,這一點與node --inspect是有差別的。

2、直接打開開發者工具,點選nodejs圖示,會發現,自動在第一行加了一個斷點,這個也是與node --inspect是有差別的。

nodejs 調試 debug
nodejs 調試 debug

後面就可以按自己的步驟進行調試了。

當然有一些優秀的IDE也提供了debug模式,比如IDEA、VS Code等,這裡也不再贅述了。