Open In App

How to solve “Process out of Memory Exception” in Node.js ?

Last Updated : 02 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to solve the ProcessOutOfMemory exception in NodeJS. Process out of Memory Exception is an exception that occurs when your node.js program gets out of memory. This happens when the default memory allocated to our program gets exceeded by our program while execution. 

This exception can be solved by increasing the default memory allocated to our program to the required memory by using the following command.

Syntax:

node --max-old-space-size=<SPACE_REQD> index.js

Parameters: 

  • SPACE_REQD: Pass the increased memory space (in Megabytes).

Example: First, let’s recreate this exception then we will understand the reason behind this exception.

index.js




let items = [];
  
for (let i = 0; i < 99999995; i++) {
    items.push(i);
}
  
console.log(items);


Run the index.js file using the following command.

node index.js

Output: We will get a FATAL ERROR saying FatalProcessOutOfMemory as shown below.

Note: The default memory allocated to a node.js program is 512MB on 32-bit systems and 1024MB on 64-bit systems (Above program was run on a 64-bit system).

Example 1: In the below example, we have increased the memory space requirements to 2048MB or 2GB. Use the following command to run the JS file(index.js in my case).

Syntax: 

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

Now we can see, that our program is running perfectly without any exceptions. If you run the below code by using the standard “node index.js” command, it will throw the same exception: FatalProcessOutOfMemory, because our program exceeds the default memory space allocated to it.

So we use the –max-old-space-size command to increase the allocated memory space, so our program won’t run out of memory.

index.js




let items = [];
  
for (let i = 0; i < 99999995; i++) {
    items.push(i);
}
  
console.log(items);


Output:

Example 2: In the below example, we have increased the memory space requirements to 3072MB or 3GB. Use the following command to run the JS file(index.js in my case).

Syntax: 

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

If you run the below code by using the standard “node index.js” command, it will throw the same exception: FatalProcessOutOfMemory, because our program exceeds the default memory space allocated to it. 

So we use the –max-old-space-size command to increase the allocated memory space, so our program won’t run out of memory.

index.js




let items = [];
  
for (let i = 0; i < 90000000; i++) {
    items.push("GeeksforGeeks");
}
  
console.log(items);


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads