Debugging Node.js
// 1. Using the built-in debugger\n// Run: node inspect app.js\n// Or add: debugger;\n\nfunction calculateTotal(items) {\n debugger; // Execution pauses here\n return items.reduce((sum, item) => sum + item.price, 0);\n}\n\n// 2. Chrome DevTools\n// Run: node --inspect app.js\n// Open chrome://inspect in Chrome\n\n// 3. VS Code debugging\n// Create .vscode/launch.json:\n// {\n// \"version\": \"0.2.0\",\n// \"configurations\": [{\n// \"type\": \"node\",\n// \"request\": \"launch\",\n// \"name\": \"Launch Program\",\n// \"program\": \"${workspaceFolder}/app.js\"\n// }]\n// }\n\n// 4. Console debugging\nconsole.log('Value:', variable);\nconsole.table(array); // Tabular output\nconsole.time('label'); // Start timer\n// ... code ...\nconsole.timeEnd('label'); // End timer\nconsole.trace('Stack trace'); // Print stack trace\n\n// 5. Profiling\nconst { performance } = require('perf_hooks');\nconst start = performance.now();\n// ... heavy operation ...\nconsole.log(`Took ${performance.now() - start}ms`);
Memory Leak Detection
// Monitor memory usage\nconst used = process.memoryUsage();\nconsole.log({\n rss: `${Math.round(used.rss / 1024 / 1024)} MB`,\n heapTotal: `${Math.round(used.heapTotal / 1024 / 1024)} MB`,\n heapUsed: `${Math.round(used.heapUsed / 1024 / 1024)} MB`,\n});\n\n// Heap dump for analysis\n// Run with: node --heapsnapshot-signal=SIGUSR2 app.js\n// Then: kill -USR2
Examples
const { performance, PerformanceObserver } = require('perf_hooks');
// Measure function performance
function measure(fn, label) {
const start = performance.now();
const result = fn();
const duration = performance.now() - start;
console.log(`${label}: ${duration.toFixed(2)}ms`);
return result;
}
// Simulate heavy computation
function heavyComputation(n) {
let sum = 0;
for (let i = 0; i < n; i++) {
sum += Math.sqrt(i);
}
return sum;
}
// Profile with labels
console.time('total');
const result1 = measure(() => heavyComputation(100000), '100k iterations');
const result2 = measure(() => heavyComputation(1000000), '1M iterations');
console.timeEnd('total');
// Memory usage
console.log('Memory:', process.memoryUsage());
// Watch for memory leaks
let leaks = [];
setInterval(() => {
leaks.push(Buffer.alloc(1024 * 1024)); // 1MB each
console.log(`Leaked ${leaks.length}MB`);
if (leaks.length > 5) {
console.log('Memory leak detected!');
process.exit(1);
}
}, 1000);