Node.js — Increase the Memory Limit for Your Process

The system process of Node.js starts your applications with a default memory limit. If you’re going to run an application that saves a lot of data into variables and therefore memory, you may run into a Node.js process exit due to allocation issues.

Increasing Node’s memory limit is the topic of this tutorial and you’ll find the problem description and solution following below.

Node.js Series Overview

  1. Callback and Promise Support in your Node.js Modules
  2. Increase the Memory Limit for Your Process
  3. Why You Should Add “node” in Your Travis Config
  4. How to Run an Asynchronous Function in Array.map()
  5. Create a PDF from HTML with Puppeteer and Handlebars
  6. Get Number of Seconds Since Epoch in JavaScript (Coming soon)
  7. Create Your Custom Error (Coming soon)
  8. Extend Multiple Classes (Multi Inheritance) (Coming soon)
  9. Filter Data in Streams (Coming soon)
  10. Get a File’s Created Date (Coming soon)
  11. Get a File’s Last Modified/Updated Date (Coming soon)
  12. How to Reset and Empty an Array (Coming soon)
  13. Human-Readable JSON.stringify() With Spaces and Line Breaks (Coming soon)
  14. String Replace All Appearances (Coming soon)
  15. Write a JSON Object to a File (Coming soon)

Problem

Running a memory dependent app consumes all available JS heap space during its processing. You’ll receive an error output and message like this:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

…

[1]    15759 abort      node server.js

Actually, there’s a quite simple fix! The next section guides you through the single step that’s required to make your app work.

Solution

The solution to run your Node.js app with increased memory is to start the process with an additional V8 flag: --max-old-space-size. You need to append your desired memory size in megabytes.

The following command will start the server.js with a memory limit of 8 GB.

node --max-old-space-size=8192 server.js  

Please notice the order of arguments after the node command. You need to add desired parameters first to adjust the related values appropriately. Then, start the file that should run as a Node.js process.

Outlook

The solution to increase the memory limit is kind of straight forward. The hardest part of the problem is to remember the name of the flag. Honestly, that’s the reason I’m writing this tutorial, because I need to Google the flag every time I want to use it!

Nonetheless, hopefully you’ll benefit from this short guide and bookmark it for fast access ;-)

We appreciate feedback and love to help you if there’s a question in your mind. Let us know in the comments or on twitter @futurestud_io.

Make it rock & enjoy coding!

Explore the Library

Find interesting tutorials and solutions for your problems.