InterviewHubPRO
Section Overview
Q14

Question 14 of 60

Part 2: Runtime Internals, Libuv & The Event Loop (6 - 20)

23%
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:

  1. Global variables: Accidentally holding references to large objects in global scope.
  2. Uncleared event listeners: Repeatedly attaching .on('event', fn) to long-lived objects without .off().
  3. Unbounded caches: Storing items in plain JavaScript objects/maps without LRU eviction.
  4. 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);
}