Debugging Node.js
Debugging is the hunt for why a program acts wrong. Node can pause a program so each step can be watched.
Start the debugger
This command starts the debugger on the program.
node --inspect debug.jsPrint a value
This line prints the total of the numbers.
console.log("Total:", total);Example
const numbers = [1, 2, 3, 4, 5];
let total = 0;
for (const n of numbers) {
total += n;
}
console.log("Total:", total);Key points
- Debugging is the hunt for why a program acts wrong.
- Run node with --inspect to start the debugger.
- Node prints a listening line with an address.
- The address names the debugger the tools can attach to.
- Add console.log lines to print values while the program runs.
- Fix one thing at a time and run the program again.
In this example, total adds the numbers 1 to 5. The loop adds each number in turn. The print shows 15. The debugger lines come first, because --inspect starts the debugger before the program runs.
Note
The listening line carries a fresh code on each run, so your code differs from the one shown here.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which flag starts the Node debugger?