How to increase nodejs default memory?

When the server starts, 2 GB (approximately) of data is exported from mongodb to redis, and then an error appears like FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory .

Then I started the server using this command node --max-old-space-size=4076 server.js and it works fine. But you need to configure nodejs in your application so that the node server always starts with 4 GB of memory. Please help me how to fix this? Thanks.

+15
source share
5 answers

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

+7
source share

one option: npm startup scripts

https://docs.npmjs.com/misc/scripts

They are added to your package.json package in the scripts section.

 { //other package.json stuff "scripts":{ "start": "node --max-old-space-size=4076 server.js" } } 

then start the npm start call instead of typing in node + args + execution points.

Note: if you call it something other than run, npm run [yourScriptNameHere] will be the command to run

This is a better option than trying to reconfigure node to use 4gb by default (I don’t even know if its tbh is possible). This makes your configuration portable using the baked methods in their current form and allows others who encounter your code in the future to understand this is a necessity.

+18
source share

You can also set NODE_OPTIONS when running the npm script, and not the node itself:

 "scripts": { "start": "NODE_OPTIONS=--max-old-space-size=4096 serve", }, 
+2
source share

PM2

 pm2 start index.js --node-args="--max_old_space_size=4096" 
0
source share

Here are some flag values ​​to add additional information on how to allocate more memory when starting up your site’s server.

1 GB - 8 GB

 #increase to 1gb node --max-old-space-size=1024 index.js #increase to 2gb node --max-old-space-size=2048 index.js #increase to 3gb node --max-old-space-size=3072 index.js #increase to 4gb node --max-old-space-size=4096 index.js #increase to 5gb node --max-old-space-size=5120 index.js #increase to 6gb node --max-old-space-size=6144 index.js #increase to 7gb node --max-old-space-size=7168 index.js #increase to 8gb node --max-old-space-size=8192 index.js 
0
source share

All Articles