5 min read
•Question 53 of 62hardHow to detect and fix memory leaks in Node.js?
Finding and resolving memory leaks.
What You'll Learn
- Common causes of memory leaks
- Detection tools
- How to fix them
Common Causes
- Global variables
- Closures retaining references
- Event listeners not removed
- Growing arrays/objects
- Timers not cleared
Detection
code.jsJavaScript
// Monitor memory usage
setInterval(() => {
const used = process.memoryUsage();
console.log({
heapTotal: Math.round(used.heapTotal / 1024 / 1024) + 'MB',
heapUsed: Math.round(used.heapUsed / 1024 / 1024) + 'MB',
external: Math.round(used.external / 1024 / 1024) + 'MB'
});
}, 5000);Using Heap Snapshots
$ terminalBash
node --inspect app.jsOpen Chrome DevTools and take heap snapshots.
Common Fixes
code.jsJavaScript
// ❌ Memory leak: event listeners pile up
socket.on('data', handleData);
// ✅ Fix: remove listener when done
socket.on('data', handleData);
socket.on('close', () => {
socket.removeListener('data', handleData);
});
// ❌ Memory leak: growing array
const cache = [];
function addToCache(item) {
cache.push(item);
}
// ✅ Fix: limit size
function addToCache(item) {
if (cache.length >= 1000) cache.shift();
cache.push(item);
}
// ❌ Memory leak: timer not cleared
const interval = setInterval(doSomething, 1000);
// ✅ Fix: clear when done
clearInterval(interval);Using clinic.js
$ terminalBash
npm install -g clinic
clinic doctor -- node app.js