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 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即可进入调试,这是很传统的界面试调试工具的样子,使用起来很方便。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值