In this lesson, you will learn how to use Node.js runtime flags to fine-tune your application’s memory usage and garbage collection behavior directly from the terminal.
Controlling the V8 Engine
When you run a script using node app.js, you are executing your code inside the V8 engine. By default, Node.js makes automated decisions about how much system memory to use and when to trigger the "Garbage Collector" (the process that clears out unused memory). Sometimes, for performance tuning, you need to step in and give the engine specific instructions.
We do this using runtime flags. These flags must be placed before your file name in the terminal command.
Managing Memory with --max-old-space-size
The most common flag for performance is --max-old-space-size. This tells Node.js the maximum amount of memory (in megabytes) the V8 heap can use before it forces a garbage collection or crashes due to an "out of memory" error.
If you have a large data processing task that requires 4GB of RAM, you would start your app like this:
node --max-old-space-size=4096 app.js
By default, Node.js might set a much lower limit depending on your system, so increasing this helps prevent crashes in memory-intensive applications.
Triggering Garbage Collection
If you are debugging memory leaks or trying to optimize how your application handles objects, you can use the --expose-gc flag. This flag makes the global.gc() function available in your code, allowing you to manually trigger the garbage collector at specific moments:
node --expose-gc app.js
Inside your app.js, you can then call global.gc() to see how memory usage drops. Note: You should generally avoid calling this in production, as manual garbage collection is usually less efficient than the engine’s automated management.
The Order Matters
Remember that Node.js separates flags from script arguments. If you put the flag after your filename (e.g., node app.js --max-old-space-size=4096), Node will treat the flag as a simple string argument passed into your process.argv array rather than a command to the V8 engine. Always place your runtime flags immediately after the node command.
Key Takeaway: Use runtime flags like --max-old-space-size before your filename to directly influence how the V8 engine allocates memory and cleans up resources.