核心 node.js 偵錯程式和節點檢查器

使用核心偵錯程式

Node.js 提供了非圖形化除錯實用程式的構建。要在偵錯程式中啟動構建,請使用以下命令啟動應用程式:

node debug filename.js

請考慮 debugDemo.js 中包含的以下簡單 Node.js 應用程式

'use strict';

function addTwoNumber(a, b){
// function returns the sum of the two numbers
debugger
  return a + b;
}

var result = addTwoNumber(5, 9);
console.log(result);

關鍵字 debugger 將在程式碼中停止偵錯程式。

命令參考

  1. 步進
cont, c - Continue execution
next, n - Step next
step, s - Step in
out, o - Step out
  1. 斷點
setBreakpoint(), sb() - Set breakpoint on current line
setBreakpoint(line), sb(line) - Set breakpoint on specific line

要除錯上面的程式碼,請執行以下命令

node debug debugDemo.js

上述命令執行後,你將看到以下輸出。要退出偵錯程式介面,請鍵入 process.exit()

StackOverflow 文件

使用 watch(expression) 命令新增要監視其值的變數或表示式,並使用 restart 重新啟動應用程式並進行除錯。

使用 repl 以互動方式輸入程式碼。repl 模式與你正在除錯的行具有相同的上下文。這允許你檢查變數的內容並測試程式碼行。按 Ctrl+C 離開除錯 repl。

使用內建節點檢查器

Version => v6.3.0

你可以執行 node 的內建 v8 檢查器! 該節點巡視員 ,不再需要外掛。

只需傳遞檢查員標誌,你將獲得檢查員的 URL

node --inspect server.js

使用節點檢查器

安裝節點檢查器:

npm install -g node-inspector

使用 node-debug 命令執行你的應用程式:

node-debug filename.js

之後,點選 Chrome:

http://localhost:8080/debug?port=5858

有時埠 8080 可能在你的計算機上不可用。你可能會收到以下錯誤:

無法在 0.0.0.0:8080 啟動伺服器。錯誤:聽 EACCES。

在這種情況下,使用以下命令在另一個埠上啟動節點檢查器。

$node-inspector --web-port=6500

你會看到這樣的東西:

StackOverflow 文件