Memory management helps your Node.js app run smoothly without using too much computer memory. It stops your app from slowing down or crashing.
0
0
Memory management best practices in Node.js
Introduction
When your app handles many users or big data
When you notice your app is slow or uses a lot of memory
When you want to avoid crashes caused by running out of memory
When you build long-running servers or background jobs
When you want to keep your app stable and fast
Syntax
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.
Examples
Using variables inside functions helps memory get freed when the function ends.
Node.js
// Avoid global variables to prevent memory leaks
function processData() {
let tempData = [];
// use tempData inside function
}
processData();Streams let you process data bit by bit, saving memory.
Node.js
// 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); });
Stopping timers frees memory and CPU resources.
Node.js
// Clear timers and intervals when no longer needed const timer = setInterval(() => { console.log('Running'); }, 1000); setTimeout(() => { clearInterval(timer); console.log('Timer stopped'); }, 5000);
Sample Program
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.
Node.js
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); });
OutputSuccess
Important Notes
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.
Summary
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.