Error Encyclopedia

JavaScript Heap Out of Memory Error

Fix 'JavaScript heap out of memory' errors in Node.js. Learn to increase memory limits, detect memory leaks, and optimize memory usage.

What Does This Error Mean?

The 'JavaScript heap out of memory' error means Node.js has exhausted the memory allocated for the V8 JavaScript engine. This typically happens when processing large datasets, running memory-intensive operations, or due to memory leaks.

Common Causes

1

Loading an entire large file into memory (e.g., GB-sized JSON)

2

Memory leak — objects not being garbage collected

3

Circular references preventing garbage collection

4

Large arrays or buffers created in a loop without cleanup

5

Default Node.js memory limit (512MB-1GB) is too low for the workload

6

Using synchronous file operations that block the event loop

How to Fix It

Increase the Node.js memory limit

Use the --max-old-space-size flag to allocate more memory.

# Increase to 4GB
node --max-old-space-size=4096 app.js

# Set in package.json
"scripts": {
  "start": "node --max-old-space-size=4096 app.js"
}

Use streams for large files

Process files line by line or in chunks instead of loading everything into memory.

const fs = require("fs")
const readline = require("readline")

// ❌ Loads entire file into memory
const data = JSON.parse(fs.readFileSync("large-file.json", "utf-8"))

// ✅ Process with streams
const rl = readline.createInterface({
  input: fs.createReadStream("large-file.json"),
  crlfDelay: Infinity
})

rl.on("line", (line) => {
  const row = JSON.parse(line)
  // Process one row at a time
})

Detect memory leaks

Use heap snapshots to find objects that are not being garbage collected.

# Take heap snapshot
node --inspect app.js
# Open chrome://inspect in Chrome

# Monitor memory usage
const used = process.memoryUsage()
console.log(`Heap used: ${(used.heapUsed / 1024 / 1024).toFixed(2)} MB`)
console.log(`Heap total: ${(used.heapTotal / 1024 / 1024).toFixed(2)} MB`)

Related Tools

Use these tools to debug and fix this error:

Related Errors

Other common errors in this category: