JavaScript

How to Fix Node.js Heap Out of Memory Issues?

Node.js is basically a runtime environment that executes the program written in JavaScript format over the server. The size of each JavaScript program file varies from each other depending on the module or lines of code utilized in it. However, a fixed heap size is allotted for each node.js script, if the size of the program exceeds the heap size then the error of “heap out of bound memory” occurs.

That’s all about fixing the Node.js heap out-of-memory issue.

What are the Heap Out of Memory Issues and what are its Causes?

The main cause of heap out of memory is the leakage of memory which occurs due to extra assignment of values into the heap than its maximum limit. This leads to the lossage of data and sends a warning to the developer about leakage of memory in the “heap out of bound memory”.

Let’s visit the below table to understand some causes of the node.js “heap out memory” error:

Cause Description
Presence of large data structures If there is a data structure inside the program that has been allotted a maximum value that exceeds the heap size. Then, the “heap out of memory” error will be raised.
Poor memory management If the variables reside in the program longer than their need then the “heap out of memory” error will be raised.
Infinite loops Due to a part of the code that runs infinitely, and has no terminating condition.
Presence of many objects In case you have many installed variables in your code and the memory used by these variables when combined leads to overhead.
Recursive functions A recursive function is one that calls itself and its excess usage leads to overhead as well.

Let’s say the error is caused due to the presence of a large data structure, in such case the error is faced as follows:

var dummy = [];

for (var k = 0; k < 99999999; k++) {
  dummy.push(k);
}

console.log("Hello Linuxhint Users!");

In the above code, using the “for” loop a large length “array” data structure has been created which leads to the cause of a “heap out of memory” error.

Place the above code in a new file and then execute it by running the below command:

node <fileName>

The generated output after the compilation shows that the “heap out of memory” error has been generated:

How to Fix Node.js Heap Out of Memory Issues?

The default heap size assigned for the node.js is “700 MB” for 32-bit operating systems and “1400 MB” for 64-bit operating systems. However, if the node.js application exceeds the default allocated size then with the help of environment variables, the custom size can be added to the heap. Visit the below section to cover the practical demonstration of the below-listed solutions to resolve the heap out-of-memory issue:

Solution 1: Using the “–max-old-space-size” Variable

The “–max-old-space-size” variable is specifically used to allocate the heap memory, it sets the heap for a temporary basis and eliminates the memory size issues. It is mostly set as the multiple of “1024” which is equal to “1 GB” so if the user wants to increase the heap size to “12 GB”, the variable should assign the value of “12225”. The syntax to set and execute the “–max-old-space-size” variable is demonstrated below:

node --max-old-space-size={size} <fileName>

In the above command, the “size” is the size of an allotted heap in bytes that is going to be allotted to the provided “fileName”. For instance, the “8 GB” of heap size is going to be allotted by running the below command:

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

After executing the above code on the Command Prompt, the heap memory issues get resolved and now that file will get executed easily:

Solution 2: Setting the “–max-old-space-size” Variable From Package.json File

The more optimized and better approach is to assign extra space to resolve the “heap out of memory” error by setting the “–max-old-space-size” variable inside the package.json file. In our case, the command to increase the heap size is going to be inserted as the “script” having the key “start”.

Now, the process of execution becomes more concise, automated, and easy as the same functionality will now be performed by executing the custom “npm start” command. The script that needs to be inserted inside the “package.json” file is shown below:

"scripts": {
  "start": "node --max-old-space-size=8192 app.js"
},

After setting the custom script, let’s execute it by running the assigned key with “npm”:

npm start

After execution, the heap size error will be resolved, and our desired “app.js” file gets executed as desired:

Solution 3: Fixing the Heap Out of Memory Error Via NODE_OPTIONS Environment Variable

The “NODE_OPTIONS” environment variable deals with setting the command line options for the node.js when it gets executed. The “–max-old-space-size” variable can be assigned to it, in order to resolve the heap out-of-memory issue at the runtime. This “NODE_OPTIONS” environment variable can be set up using two approaches:

Method 1: Setting NODE_OPTIONS Environment Variable Using GUI

To set the “NODE_OPTIONS” environment variable to the “–max-old-space-size” variable containing some values in Bytes to fix the heap out-of-bound memory error. The graphical approach can be utilized, due to its less complexity and lower chances of errors. The below-stated steps need to be followed to get the desired outcome:

Step 1: Opening the Environment Variable Window

Press the “Window + S” command to open the “Search” menu and insert the “environment” keyword inside the search bar. Then, select the “Edit the system environment variable” control panel option from the generated list:

Step 2: Opening the Environment Variable Window

Select the “Environment Variables” button residing inside the “Advanced” tab of the opened window named “System Properties”:

From the opened “Environment Variables” window, select the “New” button available in the “System variables” section. After selecting the button, a window named “New System Variable” gets opened, as shown below:

Step 3: Setting Up “NODE_OPTIONS” Environment Variable

Inside the “Variable name” and “Variable value” fields insert the value of “NODE_OPTIONS” and “–max-old-space-size=4096” respectively. To set the required “NODE_OPTIONS” environment variable, as shown below:

Finally, restart your node.js terminal on which the current project is running to take the effect of changes.

Method 2: Setting NODE_OPTIONS Environment Variable Using CLI

In order to set the “NODE_OPTIONS” environment variable to resolve the “heap out of bound memory” issue using the CLI approach, the “set” and “setx” commands are used. To be more clear, visit the below syntaxes.

The “set” command will temporarily increase the heap size by setting the specified value of “–max-old-space-size” for the environment variable “NODE_OPTIONS”:

set NODE_OPTIONS --max-old-space-size={heapSize}

If the user wants to increase heap size permanently, the below syntax of a command is utilized:

setx NODE_OPTIONS --max-old-space-size={heapSize}

Now, let’s utilize the above command to permanently increase the heap memory size to “6 GB” which is equivalent to “4096” Bytes by running the below command:

setx NODE_OPTIONS --max-old-space-size=4096

The above code shows that by running the “setx” command, the specified value is set as heap memory. The error that arises during the executing time of targeted “app.js” due to the “heap out of memory” issue is also resolved:

Method 3: Setting NODE_OPTIONS Environment Variable Using “cross-env” Module

The “cross-env” module can also be used to set the “NODE_OPTIONS” environment variable, and it manages the allocated heap size across all operating systems. Demolishing the need to extend the heap memory at all operating systems. The user must first install the “cross-env” module in the “development” environment inside its Node.js project by running the below-shown command:

npm install cross-env --save-dev

After the installation of the “cross-env” module, traverse to the “package.json” file and insert below the line of code as “script”:

{
"scripts": {
  "size": "cross-env NODE_OPTIONS='--max-old-space-size=1024' node app.js"
}
}

In the above line of code:

  • First, the script named “size” is created that sets the modified heap size as a value for the “NODE_OPTIONS” environment variable.
  • The heap size is going to be modified for the provided “app.js” file which is then executed as well.
  • After that, save the “package.json” file and run the “npm run size” command to execute the provided “app.js” and set its heap memory size to “4096” which is equivalent to “4 GB”.
  • Now, when the command executes first the heap size is going to be modified.
  • After that, the “app.js” file gets executed, and this time the “heap out of memory” error will not appear. The custom-defined script to start the execution is stated below:
npm run size

The generated output shows that the targeted file has been executed without raising a “heap out of memory” error:

That’s all about fixing the Node.js heap out-of-memory issues.

Conclusion

To fix the “heap out of memory” issue in Node.js, allocate the “–max-old-space-size” variable with the necessary memory for specific tasks during the execution of the Node.js script. To be more systematic, configure the “–max-old-space-size” variable within the “package.json” file’s “scripts” section. Another approach is to employ the “NODE_OPTIONS” environment variable which sets the “–max-old-space-size” option, to simplify the management of memory limits over cross-platforms. This guide has explained the terms to fix the heap out-of-memory issue in Node.js.

About the author

Abdul Moeed

I'm a versatile technical author who thrives on adaptive problem-solving. I have a talent for breaking down complex concepts into understandable terms and enjoy sharing my knowledge and experience with readers of all levels. I'm always eager to help others expand their understanding of technology.