Memory management helps your Node.js app run smoothly without using too much computer memory. It stops your app from slowing down or crashing.
Memory management best practices in Node.js
// Example: Using global.gc() to trigger garbage collection if (global.gc) { global.gc(); } else { console.log('Run Node.js with --expose-gc to enable manual garbage collection'); }
Node.js automatically manages memory with garbage collection.
You can manually trigger garbage collection only if Node.js is started with --expose-gc.
// Avoid global variables to prevent memory leaks
function processData() {
let tempData = [];
// use tempData inside function
}
processData();// Use streams to handle large files without loading all in memory const fs = require('fs'); const readStream = fs.createReadStream('largefile.txt'); readStream.on('data', chunk => { console.log('Read chunk:', chunk.length); });
// Clear timers and intervals when no longer needed const timer = setInterval(() => { console.log('Running'); }, 1000); setTimeout(() => { clearInterval(timer); console.log('Timer stopped'); }, 5000);
This program reads a file in small parts (chunks) instead of loading it all at once. This way, it uses less memory and stays fast.
import fs from 'fs'; // Read a large file using stream to save memory const readStream = fs.createReadStream('example.txt', { encoding: 'utf8' }); readStream.on('data', (chunk) => { console.log(`Received chunk of size: ${chunk.length}`); }); readStream.on('end', () => { console.log('Finished reading file'); }); readStream.on('error', (err) => { console.error('Error reading file:', err); });
Always watch for memory leaks by checking if objects are kept longer than needed.
Use Node.js tools like --inspect and Chrome DevTools to monitor memory usage.
Be careful with global variables and event listeners that never get removed.
Node.js manages memory automatically but you can help by writing clean code.
Use streams for big data to save memory.
Clear timers and avoid global variables to prevent leaks.
Practice
Solution
Step 1: Understand memory usage with large data
Loading large data all at once uses a lot of memory. Streams process data in small chunks, saving memory.Step 2: Evaluate options for memory efficiency
Using global variables or never clearing timers can cause memory leaks. Avoiding async functions doesn't help memory.Final Answer:
Use streams to process large data instead of loading it all at once -> Option AQuick Check:
Streams save memory by chunking data [OK]
- Thinking global variables are memory efficient
- Ignoring the need to clear timers
- Believing async functions cause memory leaks
Solution
Step 1: Identify the correct function to clear a timeout
Node.js uses clearTimeout() to stop timers set by setTimeout().Step 2: Match function to timer type
clearInterval() clears intervals, not timeouts. stopTimer() and removeTimer() are invalid.Final Answer:
clearTimeout(timerId); -> Option AQuick Check:
clearTimeout() stops setTimeout timers [OK]
- Confusing clearTimeout with clearInterval
- Using non-existent functions like stopTimer
- Not clearing timers at all
const data = [];
setInterval(() => {
data.push(new Array(1000000).fill('x'));
console.log('Data length:', data.length);
}, 1000);
Solution
Step 1: Analyze the setInterval behavior
Every second, a large array is added to the data array, increasing its size.Step 2: Understand memory impact
Since data keeps growing without clearing, memory usage grows indefinitely, risking leaks.Final Answer:
Data length increases indefinitely, causing memory to grow -> Option BQuick Check:
Growing arrays without cleanup increase memory [OK]
- Assuming data length resets automatically
- Expecting an error without memory limits
- Thinking memory stays stable without cleanup
let cache = {};
function addToCache(key, value) {
cache[key] = value;
}
setInterval(() => {
addToCache(Date.now(), new Array(1000000).fill('leak'));
}, 1000);
Solution
Step 1: Examine cache growth
Each second, a new large array is added with a unique key, so cache size grows endlessly.Step 2: Understand memory leak cause
Without removing old entries, memory usage increases causing a leak.Final Answer:
The cache object grows indefinitely without cleanup -> Option CQuick Check:
Uncleared caches cause memory leaks [OK]
- Thinking Date.now() causes syntax errors
- Assuming setInterval clears itself
- Underestimating array size impact
Solution
Step 1: Choose memory-efficient file processing
Streams process large files in chunks, reducing memory use compared to loading whole files.Step 2: Manage timers and caches properly
Clearing timers prevents leaks. Avoiding global caches stops memory from growing endlessly.Final Answer:
Use streams to process files, clear timers after use, and avoid global caches -> Option DQuick Check:
Streams + clear timers + no globals = best memory practice [OK]
- Loading full files into memory
- Not clearing timers causing leaks
- Using global caches without cleanup
Ready to prove it?
Pass the test and this pattern moves unknown
