Node.js Debugging Tips and Techniques
Beyond console.log, Node.js offers powerful debugging tools. Here's how to use them effectively.
Built-in Debugger
Start Node.js with the inspector:
# Start with inspector
node --inspect server.js
# Break on first line
node --inspect-brk server.jsConnect via Chrome DevTools at chrome://inspect or use VS Code's built-in debugger with this launch config:
{
"type": "node",
"request": "launch",
"name": "Debug Server",
"program": "${workspaceFolder}/server.js",
"console": "integratedTerminal"
}Async Stack Traces
Enable long stack traces in Node.js 16+:
node --enable-source-maps --async-stack-traces server.jsThis shows the full async call chain instead of truncated traces.
Debug Memory Leaks
// Take heap snapshots
const v8 = require('v8');
const fs = require('fs');
function writeHeapSnapshot() {
const filename = v8.writeHeapSnapshot();
console.log(`Heap snapshot written to ${filename}`);
}
// Monitor memory growth
setInterval(() => {
const usage = process.memoryUsage();
console.log(`RSS: ${Math.round(usage.rss / 1024 / 1024)}MB`);
console.log(`Heap: ${Math.round(usage.heapUsed / 1024 / 1024)}MB`);
}, 30000);Common leak sources:
- Event listeners not removed — use
emitter.listenerCount()to check - Closures holding references — large arrays captured in callbacks
- Global caches without eviction — use LRU cache with max size
Debug Unhandled Rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
// In production, report to error tracking and exit
process.exit(1);
});Conditional Debugging
Use the debug module for toggleable logs:
const debug = require('debug');
const dbLog = debug('app:db');
const httpLog = debug('app:http');
dbLog('Query executed in %dms', duration);
httpLog('Request: %s %s', method, path);Enable with: DEBUG=app:* node server.js
For production debugging, Bugsly captures unhandled exceptions and rejections with full context, eliminating the need to reproduce issues locally.
Try Bugsly Free
AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.
Get Started FreeRelated Articles
How to Fix Query Error in Python
Learn how to diagnose and fix the query error in Python. Includes code examples and prevention tips.
Read moreFix Memory Leak in Svelte
Fix memory leaks in Svelte applications caused by unsubscribed stores, lingering event listeners, and improper component cleanup.
Read moreHow to Fix Dependency Conflict in Python
Learn how to fix the Dependency Conflict in Python. Step-by-step guide with code examples.
Read moreFix Cache Error in Next.js
Learn how to fix the Cache error in Next.js. Step-by-step guide with code examples and solutions. Quick, practical guide for developers.
Read more