How to Pass V8 Flags to Node.js Scripts

This article provides a quick overview and step-by-step guide on how to run Node.js scripts with customized V8 engine flags. You will learn how to configure these flags directly from the command line, use environment variables for broader application, and implement them within npm scripts to optimize Node.js performance and memory allocation, specifically using the --max-old-space-size flag.

Method 1: Passing V8 Flags via Command Line

The most direct way to run a Node.js script with V8 flags is to pass them directly in your terminal execution command. Crucially, V8 flags must be placed before the filename of your script in the command.

To increase the maximum heap memory size to 4GB (4096 megabytes) for a specific script, use the following syntax:

node --max-old-space-size=4096 app.js

If you put the flag after the script name (e.g., node app.js --max-old-space-size=4096), Node.js will treat it as a standard argument passed to your application code (process.argv) rather than a configuration for the V8 runtime environment.

Method 2: Using the NODE_OPTIONS Environment Variable

If you are running your script through a task runner, a bundler, or a process manager like PM2, you might not have direct control over the node execution command. In these scenarios, you can use the NODE_OPTIONS environment variable.

On Linux and macOS:

export NODE_OPTIONS="--max-old-space-size=4096"
node app.js

On Windows (Command Prompt):

set NODE_OPTIONS=--max-old-space-size=4096
node app.js

On Windows (PowerShell):

$env:NODE_OPTIONS="--max-old-space-size=4096"
node app.js

Any Node.js process started in the same terminal session will inherit these V8 configurations automatically.

Method 3: Defining Flags in package.json Scripts

For collaborative projects, it is best practice to define these configurations in your package.json file. This ensures that every developer on your team runs the project with the same V8 engine allocations.

Add the flags directly to your scripts block:

{
  "name": "my-node-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node --max-old-space-size=4096 index.js"
  }
}

You can then run the script using your package manager:

npm run start

How to Verify the V8 Flag is Active

To verify that your V8 configuration changes have been applied successfully, you can check the memory limit programmatically inside your Node.js script using the v8 built-in module:

const v8 = require('v8');
const heapStats = v8.getHeapStatistics();
const totalHeapSizeInGB = (heapStats.heap_size_limit / 1024 / 1024 / 1024).toFixed(2);

console.log(`Maximum allowed heap size: ${totalHeapSizeInGB} GB`);