3.13 Debugging Node.js Applications

This time we are learning how to debug from the command line.

Basic Navigation

var person = {
name : 'Jude'
}
person.age = 25
person.name = 'Alice'
console.log(person);
$ node inspect debugging.js
< Debugger listening on ws://127.0.0.1:9229/5de1a43b-d74e-4174-a8eb-78f005a434b3
< For help see https://nodejs.org/en/docs/inspector
Break on start in debugging.js:1
> 1 (function (exports, require, module, __filename, __dirname) { var person =
{
2 name : 'Jude'
3 }
debug>
debug> list(10)
> 1 (function (exports, require, module, __filename, __dirname) { var person =
{
2 name : 'Jude'
3 }
4
5 person.age = 25
6
7 person.name = 'Alice'
8
9 console.log(person);
10
11 });
debug> n
break in debugging.js:1
> 1 (function (exports, require, module, __filename, __dirname) { var person =
{
2 name : 'Jude'
3 }
debug> c
< { name: 'Alice', age: 25 }
< Debugger attached.
< Waiting for the debugger to disconnect...

Do it Again. Debug!

$ node inspect debugging.js
< Debugger listening on ws://127.0.0.1:9229/1d81da7b-bb25-4965-9023-3a04b3bfcaa7
< For help see https://nodejs.org/en/docs/inspector
Break on start in debugging.js:1
> 1 (function (exports, require, module, __filename, __dirname) { var person =
{
2 name : 'Jude'
3 }
debug>
debug> repl
Press Ctrl + C to leave debug repl
> person
{ name: 'Jude', age: 25 }
> person.age
25
> person.age+1003
1028
> person.age=10
10
> person
{ name: 'Jude', age: 10 }

Add Breakpoint

var person = {
name : 'Jude'
}
person.age = 25
debugger; // notice this
person.name = 'Alice'
console.log(person);
debug> c
break in debugging.js:6
4
5 person.age = 25
> 6 debugger;
7 person.name = 'Alice'
8
debug>

Exercise

var logNote = (note) => {
// Break on this line and use REPL to output note
// Via reading a Note
console.log('--');
console.log(`Title: ${note.title}`);
console.log(`Body: ${note.body}`);
}

Use nodemon Instead

nodemon inspect app.js read --title="to buy"

Whenever a change to the source file is made, the debugger will be rerun with the same application.