How to Find Memory Leak in Node.js: Tools and Techniques
To find a memory leak in
Node.js, use the built-in --inspect flag to connect Chrome DevTools and take heap snapshots to compare memory usage over time. You can also use tools like heapdump or clinic.js to analyze memory allocation and identify leaks.Syntax
Use the --inspect flag to start your Node.js app with debugging enabled. Then connect Chrome DevTools to inspect memory.
node --inspect app.js: Starts Node.js with debugging enabled.- Heap snapshots: Capture memory state at different times to compare.
heapdumpmodule: Programmatically create heap snapshots.
bash
node --inspect app.js
Output
Debugger listening on ws://127.0.0.1:9229/uuid
For help, see: https://nodejs.org/en/docs/inspector
Example
This example shows how to use the heapdump module to create heap snapshots on demand, which you can analyze in Chrome DevTools to find memory leaks.
javascript
import heapdump from 'heapdump'; import http from 'http'; let leaks = []; http.createServer((req, res) => { // Simulate memory leak by pushing data into array leaks.push(new Array(1000000).fill('leak')); if (req.url === '/heapdump') { const filename = `./heap-${Date.now()}.heapsnapshot`; heapdump.writeSnapshot(filename, (err, filename) => { if (err) res.end('Error creating heapdump'); else res.end(`Heapdump saved to ${filename}`); }); } else { res.end('Hello World'); } }).listen(3000); console.log('Server running on http://localhost:3000');
Output
Server running on http://localhost:3000
Common Pitfalls
Memory leaks often happen when references to objects are unintentionally kept, preventing garbage collection.
- Global variables holding large data.
- Closures capturing large objects.
- Event listeners not removed.
Example of a leak and fix:
javascript
let leaks = []; function leakMemory() { leaks.push(new Array(1000000).fill('leak')); } // Leak: calling leakMemory repeatedly without cleanup setInterval(leakMemory, 1000); // Fix: clear array periodically setInterval(() => { leaks = []; }, 10000);
Quick Reference
- Start Node.js with
--inspectand openchrome://inspectin Chrome. - Take heap snapshots before and after suspected leaks.
- Use
heapdumpto create snapshots programmatically. - Analyze retained objects and detached DOM nodes.
- Use
clinic.jsfor advanced profiling.
Key Takeaways
Use Node.js's --inspect flag and Chrome DevTools to take and compare heap snapshots.
Programmatically create heap snapshots with the heapdump module to analyze memory usage.
Look for objects that grow over time and are not released to find leaks.
Common leaks come from global variables, closures, and unremoved event listeners.
Tools like clinic.js provide advanced memory profiling for Node.js apps.