Node.js & Libuv•Part 2: Runtime Internals, Libuv & The Event Loop (6 - 20)
Common causes of Memory Leaks in Node.js.
How to Explain in an Interview:
- Global variables: Accidentally holding references to large objects in global scope.
- Uncleared event listeners: Repeatedly attaching
.on('event', fn)to long-lived objects without.off(). - Unbounded caches: Storing items in plain JavaScript objects/maps without LRU eviction.
- Closures: Functions retaining outer scope variables that reference heavy objects.
javascript
const v8 = require('v8');
const fs = require('fs');
// Diagnostic: Dump heap snapshot for Chrome DevTools analysis:
function snapshotMemory() {
const snapshotStream = v8.getHeapSnapshot();
const fileStream = fs.createWriteStream(`heap-${Date.now()}.heapsnapshot`);
snapshotStream.pipe(fileStream);
}