How to Use Debugger in Node.js: Simple Guide
To use the debugger in
Node.js, start your script with node inspect yourfile.js or add the --inspect flag to enable debugging with Chrome DevTools. You can also insert the debugger statement in your code to pause execution and inspect variables.Syntax
Use node inspect yourfile.js to start the built-in debugger in the terminal. Alternatively, use node --inspect yourfile.js to enable debugging via Chrome DevTools. Insert debugger; in your code where you want to pause execution.
node inspect yourfile.js: Runs the debugger in the terminal.node --inspect yourfile.js: Opens a debugging port for Chrome DevTools.debugger;: Pauses execution at this line when debugger is active.
bash
node inspect yourfile.js // or node --inspect yourfile.js // In your JavaScript code: debugger;
Example
This example shows how to use the debugger statement to pause execution and inspect variables using the terminal debugger.
javascript
function add(a, b) { const sum = a + b; debugger; return sum; } console.log('Result:', add(5, 3));
Output
Breakpoint 1 set in add at line 3
> 1 (function add(a, b) {
2 const sum = a + b;
3 debugger;
4 return sum;
5 })
debug> n
> 4 ( return sum;)
debug> n
Result: 8
debug> c
Common Pitfalls
Common mistakes include forgetting to start Node.js with the inspect flag, which disables debugging, or placing debugger statements where they never get executed. Also, some developers try to use node inspect but expect Chrome DevTools to open automatically, which requires the --inspect flag instead.
Always ensure your Node.js version supports the --inspect flag (Node.js 8+).
javascript
/* Wrong way: debugger statement without starting with inspect */ function test() { debugger; console.log('Hello'); } test(); /* Right way: start with inspect flag */ // Run in terminal: // node --inspect yourfile.js
Quick Reference
| Command/Concept | Description |
|---|---|
| node inspect yourfile.js | Start debugger in terminal mode |
| node --inspect yourfile.js | Enable debugging with Chrome DevTools |
| debugger; | Pause execution at this line when debugging |
| chrome://inspect | URL to open Chrome DevTools for Node.js debugging |
| n (next) | Step to next line in terminal debugger |
| c (continue) | Continue execution until next breakpoint |
Key Takeaways
Start Node.js with --inspect flag to debug using Chrome DevTools.
Use the debugger statement in code to pause execution at desired points.
node inspect runs the debugger in the terminal but does not open DevTools.
Ensure your Node.js version supports the inspect flag (Node.js 8+).
Use Chrome's chrome://inspect page to connect to Node.js debugging sessions.