In Entwicklung Letztes Updateated:
Teilen:
Cloudways bietet verwaltetes Cloud-Hosting für Unternehmen jeder Größe zum Hosten einer Website oder komplexer Webanwendungen.

JavaScript remains one of the most-used programming languages due to its versatility. To run JavaScript outside a browser environment, developers must install Node.js, a cross-platform run-time environment. 

Der JavaScript-Heap-Fehler „Nicht genügend Arbeitsspeicher“ tritt häufig auf, wenn ein JavaScript-Node.js-Projekt ausgeführt wird. 

JavaScript heap out of memory problem is an error that occurs when the default memory allocated by the computer system is insufficient to run a big project. 

Wenn Sie auf den Fehler Heap out of Memory stoßen, stürzt Ihr Programm ab und zeigt diese Ausgabe an.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

Or 

Fatal error: invalid table size allocation failed - javascript heap out of memory

Ursachen für JavaScript-Heap-Fehler

  • Vorhandensein großer Datenstrukturen: Working with large data structures such as matrices or arrays can consume a lot of space, eventually causing heap out of memory error.

Dies ist ein Beispiel für eine große Datenstruktur mit einer Milliarde Elementen; 

let array = [];

for (let i = 0; i < 1000000000; i++) {

  array.push(i);

}
  • Schlechte Speicherverwaltung: Als Ihre Bewerbung grows, you need to let go of some of the objects that you no longer need. 

Dies ist ein Beispiel für eine Funktion, die zu einem Speicherverlust führt;

let array = [];

setInterval(function() {

  array.push(new Array(1000000).join("x"));

}, 1000);
  • Endlosschleifen: Such a code runs forever as a terminating condition is never reached. 

This is an example of an infinite loop that will execute foreväh;

while (true) {

    console.log(1);

}

Endlosschleifen können zu diesem Fehler führen, da der Speicher ziemlich schnell verbraucht wird. 

  • Rekursive Funktionen: A recursive function is a function that calls itself indirectly or directly to repeat an/ certain set of instruction(s) until a certain condition(s) is/are met. If these functions are well-designed, they will likely lead to memory lead and, eventually heap of memory error. 
  • Vorhandensein vieler Objekte in einem Stück Code: Wenn Ihr Code viele große Objekte enthält, kann der von diesen Objekten insgesamt belegte Speicher zu einer Überlastung führen. 

Beheben Sie den JS-Heap-Kein-Speicher-Fehler

This error can occur in Windows, macOS, and Linux-based operating systems like Ubuntu. Luckily, the error is fixable, irrespective of your operating system. 

# 1. Fixing the JavaScript heap out of memory error on Windows Betriebssystem

Schritt 1: Click on start menu and locate Advanced System Settings.

Schritt 2: Klicken Sie auf Environment Variables on the bottom left part of the dialogue box. 

Schritt 3: Klicken Sie auf New an jeder User variables or System variables. Die erste Option wendet die Änderungen auf das aktuelle Benutzerkonto an. Die zweite Option wendet die Änderungen jedoch auf das gesamte System an. 

Schritt 4: Es werden zwei Optionen angezeigt; An variable name, eingeben NODE_OPTIONS und Variable value, eingeben --max-old-space-size=4096. In diesem Schritt wird die 4096 figure will allocate 4GB virtual memory to Node.js. You can allocate more such as 8GB, by setting the value as –max-old-space-size=8192. 

Schritt 5: Klicken Sie auf ok, apply und Flosseally, ok um die Änderungen zu speichern. 

Sie können auch die Tasten Windows PowerShell terminal to solve the error. Open the terminal on your Windows OS and enter the following command;

env:NODE_OPTIONS="--max-old-space-size=4096"

Sie können den Fehler auch vorübergehend beheben, indem Sie diesen Befehl ausführen, bevor Sie Ihre App ausführen.

set NODE_OPTIONS=--max-old-space-size=4096

# 2. Behebung des JavaScript-Heap-Fehlers unter Linux

  • Schritt 1: Identifizieren Sie die Fehlerquelle. Überprüfen Sie die Konsolenprotokolle oder -ausgaben, um die Code-/Dateizeilen zu ermitteln, die den Fehler verursachen.
  • Schritt 2: Export an environment variable specifying the virtual memory you have allocated to Node.js. Use this command; 
export NODE_OPTIONS=--max-old-space-size=4096

These steps will allocate 4GB virtual memory to Node.js. If the error still persists, you can increase the memory size by doubling. 

For instance, if you want to allocate 8GB as the virtual memory, you can run this command;

export NODE_OPTIONS=--max-old-space-size=8192

# 3. Behebung des Fehlers „JavaScript-Heap-out-of-Memory“ unter macOS 

Sie können den JavaScript-Heap-out-of-Memory-Fehler in macOS mit einem ähnlichen Ansatz wie in Linux lösen. Folge diesen Schritten;

  • Schritt 1: Identifizieren Sie die Fehlerquelle, indem Sie die Konsolenprotokolle oder -ausgaben überprüfen, um die Codezeilen/Datei zu bestimmen, die den Fehler verursachen.
  • Schritt 2: Export an environment variable specifying virtual memory you have allocated to Node.js. Use this command; 
export NODE_OPTIONS=--max-old-space-size=4096

These steps will allocate 4GB virtual memory to Node.js. If the error still persists, you can increase the memory size by doubling. 

For instance, if you want to allocate 8GB as the virtual memory, you can run this command;

export NODE_OPTIONS=--max-old-space-size=8192

Erhöhen des Arbeitsspeichers während der NPM-Installation

The solutions we have offered so far suit errors that occur when you run a Node.js application. However, you can allocate virtual memory to solve heap out of memory error as you install JavaScript packages. Use this command;

node --max-old-space-size=4096 (which npm) install

Hinweis: You can keep increasing virtual memory allocation by 1GB, 2GB, 3GB or 4GB. You must specify memory size in MBs. However, don’t allocate the entire memory of machine to the Node.js as this may cause your program to crash. As a good practise, if your machine has 16GB, you can allocate up to 8GB to Node.js. 

Prevent JavaScript the heap out of memory error

We have so far discussed how to fix the JavaScript heap out-of-memory error when it occurs. Luckily, you can also have measures to prevent this error from occurring as you run JavaScript code. These are some of the best approaches:

# 1. Teilen Sie Daten in kleine Stücke auf

Möglicherweise haben Sie ein Node.js-Programm, das große Datensätze aus großen CSV-Dateien über das importiert ETL: Extract – Transform – Load process. You may find that your app always crashes when you try to import the data. If you are working with MongoDB, können Sie den Fehler beheben, indem Sie eine Befehlszeilenanweisung wie z.

split -l 1000000 users.csv

Dieser Befehl weist Node.js an, eine Datei mit dem Namen Benutzer in mehrere Dateien mit jeweils 1000000 Benutzern aufzuteilen. Der -l flag gibt an, dass die Datei basierend auf der Anzahl der Codezeilen aufgeteilt werden soll. 

# 2. Monitor Speichernutzung

You can use a memory profiler to detect memory leaks in your code. You can combine Node.js’ inbuilt memory and the ChromeDevTools to achieve this. The two can detect issues in your code and fix them.

You can also use external tools such as Datadog, New Relic und AppDynamics zu monitor the performance of your app and take the necessary action. You can also check memory usage on your Node.js app through the process.memoryUsage() Methode. 

# 3. Speicherlecks vermeiden

Speicherlecks treten auf, wenn Ihre Node.js-App Verweise auf Objekte behält, die sie nicht mehr benötigt. Wenn solche Objekte nicht von der Garbage Collection erfasst werden, kommt es im Laufe der Zeit zu einer Zunahme der Speichernutzung.

Es gibt mehrere Ansätze, um Speicherlecks zu vermeiden, z. B. das Vermeiden globaler Variablen in Ihrem Code, das Vermeiden des Blockierens von E/A-Operationen und das Verwenden von let und const Schlüsselwörter beim Deklarieren Ihrer Variablen anstelle von var

# 4. Laichen processes

Wenn Sie Node.js auf einem Computer mit begrenztem Arbeitsspeicher ausführen, z Raspberry Pi, you are likely to run into heap out of memory errors. You can have one master process, and others are grouped as workers. As soon as the master process detects that the system is running out of memory, it will kill that process and assign the task to another one that is not overloaded. 

# 5. Update Hardware

If increasing memory allocation and carrying the listed processes of preventing heap out of memory error don’t solve your problems, then you may consider updating your hardware. Node.js can run on RAM as low as 512MB. However, your app will demand more RAM as it grows. 

On the other hand, increasing the number of CPUs can also improve memory allocation. Ideally, 2 or more CPUs will allow your application to use worker threads for CPU-intensive tasks such as cryptography and Image processIng..

Häufig gestellte Fragen (FAQs)

Was verursacht den Fehler „JavaScript Heap Out of Memory“?

Dieser Fehler kann mehrere Ursachen haben;
1. Speicherlecks
2. Endlosschleifen
3. Vorhandensein vieler Objekte in einem Projekt
4. Vorhandensein großer Datenstrukturen

Ist der Fehler "JavaScript Heap Out of Memory" lösbar?

Ja. Sie können den Fehler beheben durch;
1. Node.js mehr virtuellen Speicher zuweisen
2. Beseitigen von Speicherlecks
3. Optimierung Ihres Codes
4. Upgrade Ihrer Hardware

Wie können Sie den Heap Out of Memory-Fehler in der React-App lösen? 

React is one of the most popular JavaScript libraries. Locate the package.json file on the root directory and these lines to the scripts section;

"scripts": {

    "start": "react-scripts --max_old_space_size=4096 start",

    "build": "react-scripts --max_old_space_size=4096 build",

    "test": "react-scripts test",

    "eject": "react-scripts eject"

}

Fazit

Die meisten Entwickler sind an Fehler und Codefehler gewöhnt, nicht an Laufzeitfehler, wenn sie ihre Node.js-Programme ausführen. Glücklicherweise müssen Sie sich keine Sorgen machen, da der Heap-Out-of-Memory-Fehler behoben werden kann. Wir haben definiert, was ein JavaScript-Heap-out-of-Memory-Fehler ist, erklärt, wie Sie ihn lösen und wie Sie ihn in Ihrem nächsten Node.js-Projekt vermeiden können. 

Als nächstes können Sie auch lesen, wie Sie einige häufige vermeiden können JavaScript-Fehler.

Teilen:
  • Titus Kamunya
    Autor
    Titus ist Software-Ingenieur und Techniker Writer. Er entwickelt Web-Apps und schreibt über SaaS, React, HTML, CSS, JavaScript, Ruby und Ruby on Rails

Danke an unsere Sponsoren

Weitere großartige Lektüre zum Thema Entwicklung

Treiben Sie Ihr Geschäft an

Einige der Tools und Services, die Ihrem Unternehmen helfen grow.