当需要检测问题、调试,甚至想要一步步的运行代码时,使用调试器是最好的办法。

Node有内置的调试器:debug,而且颇强大,可以下断点、查看变量、单步执行等等。

下面通过一段示例,展示其用法:

var a = 1;
function b(){
  a = 2;
}
b();
a = 3;
a = 4;
debugger;
a = 5;
var c;
a = 6;
console.log(a);

使用调试器启动该程序:

node debug test53.js(本例文件名)

注:旧版本的启动参数是debug,新版为inspect。

node inspect test53.js

启动后,进入debug模式:

输入help,可以查看到所有的调试指令:

run, restart, r       Run the application or reconnect
kill                  Kill a running application or disconnect

cont, c               Resume execution
next, n               Continue to next line in current file
step, s               Step into, potentially entering a function
out, o                Step out, leaving the current function
backtrace, bt         Print the current backtrace
list                  Print the source around the current line where execution
                      is currently paused

setBreakpoint, sb     Set a breakpoint
clearBreakpoint, cb   Clear a breakpoint
breakpoints           List all known breakpoints
breakOnException      Pause execution whenever an exception is thrown
breakOnUncaught       Pause execution whenever an exception isn't caught
breakOnNone           Don't pause on exceptions (this is the default)

watch(expr)           Start watching the given expression
unwatch(expr)         Stop watching an expression
watchers              Print all watched expressions and their current values

exec(expr)            Evaluate the expression and print the value
repl                  Enter a debug repl that works like exec

scripts               List application scripts that are currently loaded
scripts(true)         List all scripts (including node-internals)

profile               Start CPU profiling session.
profileEnd            Stop current CPU profiling session.
profiles              Array of completed CPU profiling sessions.
profiles[n].save(filepath = 'node.cpuprofile')
                      Save CPU profiling session to disk as JSON.

takeHeapSnapshot(filepath = 'node.heapsnapshot')
                      Take a heap snapshot and save to disk as JSON.

比如:

c指令是继续执行,前题是如果中断的话;
n指令是执行下一行;
r是重启;
等等。

调试效果:

但是在命令行下调试,虽然显的像“高手“,但用起来效率还是很高。

调试Node程序还有其它方式,比如用Chrome浏览器也可以,但更好用更方便的当属在开发环境中了,比如vs:

在VS中从调试菜单,或直接按F5即可进入调试,这是很传统的界面试调试工具的样子,使用起来很方便。