首页 > 科技 > Node.JS实战53:调试node程序

Node.JS实战53:调试node程序

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

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 reconnectkill                  Kill a running application or disconnectcont, c               Resume executionnext, n               Continue to next line in current filestep, s               Step into, potentially entering a functionout, o                Step out, leaving the current functionbacktrace, bt         Print the current backtracelist                  Print the source around the current line where execution                      is currently pausedsetBreakpoint, sb     Set a breakpointclearBreakpoint, cb   Clear a breakpointbreakpoints           List all known breakpointsbreakOnException      Pause execution whenever an exception is thrownbreakOnUncaught       Pause execution whenever an exception isn't caughtbreakOnNone           Don't pause on exceptions (this is the default)watch(expr)           Start watching the given expressionunwatch(expr)         Stop watching an expressionwatchers              Print all watched expressions and their current valuesexec(expr)            Evaluate the expression and print the valuerepl                  Enter a debug repl that works like execscripts               List application scripts that are currently loadedscripts(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即可进入调试,这是很传统的界面试调试工具的样子,使用起来很方便。

更多本系列文章:

Node.JS实战52:捕获错误之“未捕获的异常”

Node.JS实战51:捕获错误之“错误参数”

Node.JS实战50:捕获错误之“错误事件”

Node.JS实战49:捕获错误之隐式异常

Node.JS实战48:捕获错误之显示异常

Node.JS实战47:MongoDB!?大型项目数据库首选

本文来自投稿,不代表本人立场,如若转载,请注明出处:http://www.souzhinan.com/kj/264029.html