這兩天鼓搗了一下node項目,記錄一下node的調試方法。html
前端開發的調試能夠用打日誌(console.log)或者斷點調試(debugger;配合Chrome或firebug)甚至IDE(webstorm)來調試。前端
Node也差很少。node
console.dir,console.log,引入 asserts 模塊,對調試區域進行debug等方法, 這種方法平時檢測一下仍是能夠的,真正有難纏的bug的時候會有種暴力窮舉的感受。git
斷點調試也有幾種方法github
基於TCP的協議,經過commod界面能夠對nodejs腳本進行調試web
$ node debug myscript.js< debugger listening on port 5858chrome
connecting... okbreak in /home/indutny/Code/git/indutny/myscript.js:1npm
1 x = 5;api
2 setTimeout(() => {瀏覽器
3 debugger;
debug>
腳本上用debugger;設置斷點。
用debug模式運行腳本,node debug app.js
--debug 和 --debug-brk參數。這兩個參數只會啓動Debugger監聽模式,不會進入命令行調試模式,並且前者會運行完全部代碼,一般可用於事件調試,後者會在進入時中斷,方便從頭開始調試。
詳細調試指令在debug模式下輸入help或參考官方文檔,https://nodejs.org/dist/latest-v7.x/docs/api/debugger.html
試了以後,效率感人,操做有點繁瑣,命令行界面作調試始終有點不友好
node-inspector可讓咱們在devtools裏面斷點調試。
Node.js原生Debugger模塊使用的是V8-Debug Protcol,並且DevTools使用Chrome Debugging Protcol。因此node-inspector在其中起到了翻譯和轉達的做用。
安裝node-inspector
npm install -g node-inspector
之後臺方式運行node-inspector 默認debug端口爲5858,監聽8080端口,
node-inspector &
也能夠修改端口
node-inspector --web-port 8088 --debug-port 5859
這裏的 --web-port 是 Chrome Devtools 的調試頁面地址端口,--debug-port 爲 NodeJS 啓動的內建 debug 端口
咱們能夠在 http://localhost:8080/debug?port=5858打開頁面,調試使用 --debug(-brk) 參數打開的程序
V8 Inspector Integration 可讓 DevTools 直接鏈接 Node.js的Debugger進行調試。
新版本的Chrome瀏覽器和新版本的Node.js支持經過一個新的調試協議能互相直接通信了,就再也不須要node-inspector了。
nodejs 6.3+
Chrome 55+
運行 node --inspect app.js
在Chrome打開輸出的地址,如
chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8onl
y=true&ws=127.0.0.1:9229/9c1562a2-7f51-4605-a77d-4217cbfb4965
新開一個標籤或窗口,進入頁面進行調試,如
http://localhost:8999
由於這個內置的debug已經足夠強大,node-inspector都不更新了。。
然而,我並不滿意,而後找到了vscode
在vscode能夠很方便的相似ide那樣對node進行調試,詳見圖
打開項目 進入debug,直接run,請求接口或頁面
進入斷點,調試界面以下
還能夠attach process 和 add configuration
怎麼樣,是否是很像visual studio,滿滿的親切感~
這個eclipse和webstorm均可以很容易作到
奈何我更喜歡輕量級的編輯器
http://www.barretlee.com/blog/2015/10/07/debug-nodejs-in-command-line/
NodeJS的代碼調試和性能調優
http://i5ting.github.io/node-debug-tutorial/
node-debug tutorial
https://www.npmjs.com/package/node-inspector
node-inspector
https://www.madcoder.cn/node-debug-inspect.html
最新Node.js調試大法 — v8_inspector
https://nodejs.org/dist/latest-v7.x/docs/api/debugger.html nodejs官方文檔