Debugging Node.js Programs
Learn to read errors, find bugs, and pause your code to look inside
- read a stack trace and find the exact line that broke,
- recognise the three most common errors:
ReferenceError,TypeError, andCannot find module, - use
console.log,console.error, and friends to see what your code is doing, - pause your program with the built-in debugger and step through it line by line.
1. What is a bug, and what is debugging?
A bug is a mistake in your code that makes it behave in a way you did not want. Sometimes the program crashes and stops with an error. Other times it keeps running but gives the wrong answer - that is called a silent bug, and it can be trickier to spot.
Debugging is the detective work of tracking down a bug. Like a detective, you do not guess randomly. You collect clues (the error message, the values in your variables), follow them to the scene (the exact line), and figure out what really happened.
Analogy. Imagine a light in your house will not turn on. You do not tear down the whole wall. You check the bulb, then the switch, then the fuse - one step at a time. Debugging is the same: you narrow the problem down calmly until you find the one thing that is wrong.