Does your Javascript app get slow or stuck when running an NPM script like npm install, npm run build, npm start or running a JS app from direct Node command like node yourFile.js?

At worse, your app canget stuck/slow/crashed showing an error message like Allocation failed - JavaScript heap out of memory.

These errors and symptoms can possible occur when your application / program is constantly attempting to allocate and use heap size that is greater than the available free memory in your server / runtime container.

You can simply solve all these issues by setting a fixed value for heap size and instructing Node program to be in that limit. You will be using --max-old-space-size flag with your Node command / NPM script for this.

  • Option 1: Pass a flag with node command
$ node --max-old-space-size=4096 yourFile.js
  • Option 2: Set NODE_OPTIONS environment variable (this will apply to entire session)
$ export NODE_OPTIONS="--max-old-space-size=4096" 
$ node --max-old-space-size=4096 yourFile.js
  • Option 3: Add to NPM scripts in package.json
   "scripts": {
     "ng": "ng",
     "start": "ng serve",
     "build": "node --max_old_space_size=4096 node_modules/@angular/cli/bin/ng build --prod",
     "test": "ng test",
     "lint": "ng lint",
     "e2e": "ng e2e"

Any questions? Please comment below.

Leave a comment