debugjavascriptnodejsCriticalpending
Debug: Node.js memory leak detection
Viewed 0 times
memory-leakheapsnapshotgrowing-memoryevent-listener
Error Messages
Problem
Node.js process memory keeps growing over time, eventually crashing with heap out of memory error.
Solution
Step-by-step memory leak detection:
setInterval(() => {
const used = process.memoryUsage();
console.log(
}, 10000);
node --inspect app.js
# Open chrome://inspect, take heap snapshots
# Compare two snapshots to find growing objects
- Event listeners not removed: emitter.on() without off()
- Closures holding references to large objects
- Growing arrays/maps used as caches without eviction
- Timers not cleared: setInterval without clearInterval
- Global variables accumulating data
const v8 = require('v8');
const fs = require('fs');
const snapshotStream = v8.writeHeapSnapshot();
// Generates .heapsnapshot file, load in Chrome DevTools
node --max-old-space-size=512 app.js
- Monitor memory usage:
setInterval(() => {
const used = process.memoryUsage();
console.log(
Heap: ${(used.heapUsed / 1024 / 1024).toFixed(1)} MB);}, 10000);
- Take heap snapshots:
node --inspect app.js
# Open chrome://inspect, take heap snapshots
# Compare two snapshots to find growing objects
- Common leak sources:
- Event listeners not removed: emitter.on() without off()
- Closures holding references to large objects
- Growing arrays/maps used as caches without eviction
- Timers not cleared: setInterval without clearInterval
- Global variables accumulating data
- Programmatic heap dump:
const v8 = require('v8');
const fs = require('fs');
const snapshotStream = v8.writeHeapSnapshot();
// Generates .heapsnapshot file, load in Chrome DevTools
- Use --max-old-space-size to control crash point:
node --max-old-space-size=512 app.js
- Tools: clinic.js, memwatch-next, heapdump npm packages
Revisions (0)
No revisions yet.