A debugger is a program that helps us to debug the errors or bugs in a piece of code. Nodejs comes with a debugger which we can use to hunt for different bugs. In this article, we'll learn how to use debugger in our Nodejs program.
In order to use the node.js debugger, we need to pass "debug" parameter when invoking a nodejs script. Just for an example if we want to debug a file named hello.js, we'll start the debugger as shown below.
node debug hello.js
< debugger listening on port 5858
connecting... ok
Some of the useful debugger commands include step, next, list, backtrace
which are explained below :
Note : In computing, a stack trace (also called stack backtrace or stack traceback) is a report of the active stack frames at a certain point in time during the execution of a program.
// Step-1 Run the script without any breakpoint
var x = 5;
var y = 6;
var z = x + y;
// run a for loop which will throw an error
// add debugger here
for(var i=0;i<12;i++){
debugger;
console.log(i)
}
< Debugger listening on [::]:5858
connecting to 127.0.0.1:5858 ... ok
break in debugger.js:3
1 // Step-1 Run the script without any breakpoint
2
> 3 var x = 5;
4 var y = 6;
5 var z = x + y;
debug> next
break in debugger.js:4
2
3 var x = 5;
> 4 var y = 6;
5 var z = x + y;
6
debug> cont
break in debugger.js:11
9
10 for(var i=0;i<12;i++){
>11 debugger;
12 console.log(i)
13 }
As is clear from the example above, whereas the next step moves the execution 1 step at a time, the cont command can be used to jump to the next break point in the code. Also note that by default, the debugger starts at the first line of the code, in order to make it jump to our break point, we need to use the "cont" command.
Following are commonly used shortcuts while debugging ::
cont
, c
- Continue execution
next
, n
- Step next
step
, s
- Step in