a blog for those who code

Monday 5 October 2015

How to solve process out of memory exception in NodeJS

In this post we will be showing how to solve process out of memory exception in Nodejs. You will get an exception like FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory when your application is out of memory.


This error occurs when the memory allocated for the execution of your application is less than the required memory by your application. You will get an error like below when you run your application.


For Example, when I execute the below code it will give me an error "FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory when your application is out of memory"

var arr = [];
var a = 1;
var b = 154987;
while(a<b) {
  a = a+1;
  arr.push(a);
}
console.log(arr.length);
console.log(arr);

To solve this issue you need to run your application by increasing the memory limit by using the command --max-old-space-size. By default the memory limit of Node.js is 512 mb. Lets say I run the above code using the command node --max-old-space-size=512 example5.js, it will give me the same error - FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory as shown below.


Now when I increase the memory and let say run using the command node --max-old-space-size=1024 example5.js it will again give the same exception.


Again we will increase the memory and try to run at 2000 MB using the command node --max-old-space-size=2000 example5.js, this time we will not get any exception and the program will run.


Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

1 comment:

  1. I'm trying to crawl my website and capture screenshots of the pages, but I keep getting the out of memory error. I'm using a lib called "crawl" and another one called "capture", which uses phantomjs to extract the urls from the "crawl" and convert them into screenshots. Since my site is so big, it crashes after about 30 minutes. The command I use is "crawl mysite.com | capture". I tried preceding it with "node --max-old-space-size=8192", but it throws an error. Any ideas?

    ReplyDelete