Node.js Advanced Debugging
Here is a complete and beginner-friendly guide on Node.js Advanced Debugging, covering professional tools, techniques, and real-world debugging workflows.
๐ Node.js Advanced Debugging
Debugging is a crucial part of backend development. Node.js provides multiple advanced techniques and tools to identify and fix bugs, performance issues, and memory leaks.
This guide covers:
โ
Debugging with Chrome DevTools
โ
VS Code Debugging
โ
Inspecting Variables & Call Stack
โ
Breakpoints (Manual & Conditional)
โ
Using console advanced tricks
โ
Performance profiling
โ
Memory leak debugging
โ
Using Node.js built-in debugger
โ
Debugging async code
โ
Logging best practices
๐ 1. Start Node.js with Debug Mode
Enable debugging:
Enable with break before start:
This opens the debugging interface in DevTools.
๐งญ 2. Debugging in Chrome DevTools
Open Chrome and go to:
Click:
๐ Open dedicated DevTools for Node
You get:
Breakpoints
Watch variables
Scope inspection
Call stack visualization
Step-in / Step-out / Step-over
Execution timeline
๐งช 3. Debugging with VS Code (Recommended)
Create .vscode/launch.json
Features:
Set breakpoints in code
Hover variables
Inspect call stack
Pause on exceptions
Debug async calls
Restart on file save
๐ฏ 4. Manual Breakpoints
You can force the debugger to pause using:
Example:
๐๏ธ 5. Conditional Breakpoints
Useful for breaking only when a condition is true:
In VS Code โ Right-click breakpoint โ Edit โ Enter condition:
Or in DevTools.
๐งฉ 6. Advanced console Debugging Techniques
Styled logs:
Table output:
Trace call stack:
Timing:
๐งต 7. Debugging Asynchronous Code
Async stack traces:
Run Node with:
To debug promises:
๐ฆ 8. Debugging Event Loop Lag
Check event loop delay:
โก 9. Performance Profiling (CPU Profiling)
Run CPU profiler:
Generate readable report:
Shows slow functions, blocking operations, etc.
๐ง 10. Memory Leak Debugging
Start Node with heap snapshots:
In Chrome DevTools โ Memory:
Take heap snapshots
Compare memory before & after operations
Find detached DOM nodes (if using SSR)
Find growing objects
Track heap usage:
๐งฝ 11. Using Nodeโs Built-in Debugger (CLI)
Run:
Commands:
| Command | Description |
|---|---|
cont | Continue execution |
next | Step over |
step | Step into |
out | Step out |
watch('x') | Watch variable |
repl | Open REPL at current breakpoint |
๐ 12. Debugging Crash Issues
Catch sync errors:
Catch async errors:
๐ 13. Logging Best Practices
Use logging libraries instead of console.log():
Winston:
Example:
๐ 14. Debugging Production Apps
Use monitoring tools:
PM2 Monitoring
Sentry
Datadog
New Relic
LogDNA
Example PM2 command:
๐ Summary
| Feature | Tools |
|---|---|
| Basic Debugging | --inspect, DevTools |
| Breakpoints | VS Code, Chrome |
| Async Debugging | Call stack tracing |
| Performance Audit | Node Profiler |
| Memory Leak Detection | Heap snapshots |
| Error Handling | process.on() |
| Logging | Winston / Morgan |
