What are memory leaks in Node.js and how do you detect them?

Answer

A memory leak occurs when memory that is no longer needed is not released, causing the process's memory consumption to grow over time until it crashes or becomes severely degraded. Common causes in Node.js: (1) Unremoved event listeners: adding listeners with on() without ever calling off(); (2) Unbounded caches: storing data in objects/Maps without eviction; (3) Closures holding large objects: a callback closes over a large variable that can't be garbage collected; (4) Global variables: accidentally assigning to global scope; (5) Timers not cleared: setInterval without clearInterval; (6) Streams not properly closed. Detection: (1) process.memoryUsage().heapUsed — monitor over time; (2) --inspect flag + Chrome DevTools heap snapshots — take two snapshots and diff them to see what grew; (3) clinic.js (npm install -g clinic) — specialized Node.js performance toolkit; (4) heapdump npm package — generate heap snapshots programmatically; (5) node --expose-gc + V8 API for forced GC in tests.