I’ve encountered this scary-looking error on multiple occasions when my application ran out of memory.

In this short article, I’ll first give you a solution that you can use to fix this issue quickly.

After that, in case you want to know more about it, I’ll explain what the causes of this error can be and how to prevent it from happening in the future.

  • How to solve the “Heap out of memory” error in JavaScript
  • What does this error even mean?
  • The memory limits of different Node.js versions
  • How to prevent Node.js from running out of memory
  • Conclusion

How to solve the “Heap out of memory” error in JavaScript

The fastest way of solving this issue is by increasing the memory limit of Node. Starting from Node.js v8, you can set the limit in MB with the --max-old-space-size flag like this:

node --max-old-space-size=4096 index.js

4096 translates to 4 GB of memory. You can set the limit to whatever you like, but make sure you don’t use all the available memory, or otherwise, your system might crash.

As an alternative to this, you can also set the flag in an environment variable like this:

NODE_OPTIONS="--max-old-space-size=4096" node index.js

Change the Node.js memory limits of your environment

If you want to change the memory limits of Node.js for your entire environment, you need to set the following variable in your environment’s configuration file. (.bashrc, .bash_profile, sometimes .zshrc, etc.)

Add this line to your configuration file:

~/.bashrc

export NODE_OPTIONS=--max_old_space_size=4096

“npm install” heap out of memory

If you run into this issue when installing a package with npm or yarn, you can bypass the memory limit temporarily by installing the package as follows:

node --max-old-space-size=4096 $(which npm) install -g nextawesomelib

#javascript #programming #web-development #developer

JavaScript Heap Out Of Memory Error
13.45 GEEK