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.
node --inspect-brk app.jsDebugger listening on ws://127.0.0.1:9229/...--inspect-brk pauses execution at the very first line, waiting for a debugger to attach.
function divide(a, b) {
console.log('dividing', a, b);
return a / b;
}
console.log(divide(10, 2));dividing 10 2
5Simple 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.
