Debugging is as crucial a part of the development cycle as any other. So it’s always good practice to demystify the job of debugging, making it easier and less time-consuming, so that we can end work on time and reduce stress.
Like the majority of languages out there, Node provides some excellent debugging tools which make defects in code easily found and fixed. I always advocate the usage of a debugger because personally I find using debuggers really eliminates the need for any guesswork and makes us better developers in general.
Node.js includes a full-featured out-of-process debugging utility accessible via a simple TCP-based protocol and built-in debugging client.
For example, to use the debugger to debug a file named script.js
, you can simply call node using the debug
flag as so:
$ node debug script.js < debugger listening on port 5858 connecting... ok debug>
Now that you have started a debugging session, anywhere in your script that you call debugger
from will be a breakpoint for the debugger.
So, for example, let’s add a debugger statement to the script.js:
foo = 2;
setTimeout(() => {
debugger;
console.log('bugger');
}, 1000);
console.log('de');
Now if we run this script the debugger will be called on our breakpoint and we can control the script control via using the cont
or next
commands (c
or n
for short).
We can pause the script execution at any time by using p
.
$ node debug script.js
< debugger listening on port 5858
connecting... ok
break in /home/tom/web/envatodebug/myscript.js:1
1 foo = 5;
2 setTimeout(() => {
3 debugger;
debug> cont
< de
break in /home/tom/web/envatodebug/myscript.js:3
1 foo = 5;
2 setTimeout(() => {
3 debugger;
4 console.log('bugger');
5 }, 1000);
debug> next
break in /home/tom/web/envatodebug/myscript.js:4
2 setTimeout(() => {
3 debugger;
4 console.log('bugger');
5 }, 1000);
6 console.log('de');
debug> next
< bugger
break in /home/tom/web/envatodebug/myscript.js:5
3 debugger;
4 console.log('bugger');
5 }, 1000);
6 console.log('de');
7
debug> .exit