Memory errors can be scary and confusing, but this Node.js one is easy to fix.
What Is Heap Memory?
Before you look at fixing the error, it’s useful to understand what heap memory is and how programs use it.
Memory allocated on the system heap is also called dynamically allocated memory. It’s up to the programmer to use the available memory as they see fit. More importantly, the heap size for a program depends on the available virtual memory allocated to it.
You can add an environment variable through Control Panel to increase the memory allocated to a Node.js project.
- Open the Start menu, search for Advanced System Settings, and select the Best match.
- From the dialog box, click on Environment Variables, then click on New from either System variables or User variables. The former applies to all users on your computer, while the latter affects just your current account
- In the Variable name field enter NODE_OPTIONS. In the Variable value field enter –max-old-space-size=4096. This value will allocate 4GB of virtual memory to Node.js. To set a different value, multiply the amount you require in GB by 1024 (the variable value needs to be in MB).
- Click on OK to save your changes, then click Apply and finally click OK once more. Restart your project for the changes to take effect.
You can also set an environment variable through a Windows PowerShell terminal.
Launch a PowerShell terminal, type the below command and press Enter:
If you only want to increase the heap memory temporarily, run the below command in a PowerShell terminal before running your project:
Once you’ve entered this command, you can deploy/run your project using npm run dev or your own script.
Remember always to enter the required memory size in MB. Not doing so can cause unexpected behavior in your program. It is also vital not to allocate your entire available memory as this can cause a significant system failure.
On macOS and Linux, the heap memory fix is very similar. You should export an environment variable that specifies the amount of virtual memory allocated to Node.js.
In your terminal, before you run your project, enter the following command and press Enter:
This will allocate 4GB of virtual memory to the execution space of Node.js. To set a different amount of memory, replace 4096 with the required amount in MB.
You can avoid this error by ensuring your program is free of memory leaks. Proper memory management is crucial when writing your programs, especially in a low-level language.
While increasing the allocated memory will temporarily fix the problem, you should find the root cause and fix it.