0
0
NodejsDebug / FixBeginner · 4 min read

How to Fix Heap Out of Memory Error in Node.js

The heap out of memory error in Node.js happens when your program uses more memory than the default limit. You can fix it by increasing the memory limit with --max-old-space-size flag or by optimizing your code to use less memory.
🔍

Why This Happens

This error occurs because Node.js has a default memory limit (usually around 1.5GB to 2GB). When your program tries to use more memory than this limit, it crashes with a heap out of memory error. This often happens with large data processing or memory leaks.

javascript
function createLargeArray() {
  const arr = [];
  while (true) {
    arr.push(new Array(1e6).fill('data'));
  }
}

createLargeArray();
Output
FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory
🔧

The Fix

You can fix this by increasing Node.js memory limit using the --max-old-space-size flag when running your script. For example, to increase to 4GB, run node --max-old-space-size=4096 your_script.js. Also, review your code to avoid infinite loops or large memory allocations.

javascript
function createLargeArray() {
  const arr = [];
  for (let i = 0; i < 10; i++) {
    arr.push(new Array(1e6).fill('data'));
  }
  console.log('Array created with limited size');
}

createLargeArray();
Output
Array created with limited size
🛡️

Prevention

To avoid this error in the future, follow these tips:

  • Use streaming or chunking to process large data instead of loading it all at once.
  • Check for memory leaks by monitoring memory usage during development.
  • Use tools like node --inspect and Chrome DevTools to profile memory.
  • Set appropriate memory limits with --max-old-space-size based on your app needs.
  • Write clean code avoiding infinite loops or excessive object retention.
⚠️

Related Errors

Other errors related to memory in Node.js include:

  • JavaScript heap out of memory: Same as this error, caused by exceeding memory limits.
  • Garbage collection pauses: When GC takes too long due to large memory usage, causing slow app response.
  • Process crashes: When memory leaks cause the app to crash unexpectedly.

Fixes usually involve memory profiling, code optimization, and increasing memory limits.

Key Takeaways

Increase Node.js memory limit with --max-old-space-size to fix heap out of memory errors.
Avoid loading huge data all at once; use streaming or chunking instead.
Monitor and profile memory usage to detect leaks early.
Write code that limits memory growth and avoids infinite loops.
Use Node.js debugging tools to understand memory behavior.