Node.js ยท Chapter 35 of 43

Debugging Node.js

Debugging helps you find and fix issues by inspecting code execution step by step. Node.js supports the built-in inspector protocol, usable from Chrome DevTools or VS Code.

Beyond breakpoints, simple techniques like strategic `console.log()` statements remain extremely useful for quick investigations.

Using the inspector

Run `node --inspect app.js` and open `chrome://inspect` in Chrome to attach DevTools for breakpoints and step debugging.

VS Code debugging

VS Code has built-in Node.js debugging support โ€” set breakpoints in the editor and run the debugger directly from the Run panel.

Example 1 (javascript)
node --inspect-brk app.js
Output
Debugger listening on ws://127.0.0.1:9229/...

--inspect-brk pauses execution at the very first line, waiting for a debugger to attach.

Example 2 (javascript)
function divide(a, b) {
  console.log('dividing', a, b);
  return a / b;
}
console.log(divide(10, 2));
Output
dividing 10 2
5

Simple console.log statements can quickly reveal what values flow through your code.

Key points

  • Use `node --inspect` to enable the debugger protocol.
  • Chrome DevTools or VS Code can attach to debug Node.js apps.
  • --inspect-brk pauses at the first line for immediate debugging.
  • console.log remains a fast, simple debugging tool.
๐Ÿ’ก Note: The `debugger;` statement in code also creates a breakpoint when running under the inspector.

๐Ÿ“ Quick Quiz

1. Which flag enables Node's debugger protocol?

2. Where can you attach Chrome DevTools to debug Node?

3. What keyword creates a breakpoint directly in code?