From a57cee345920d07ffacb76c8efa07b6921ed8de4 Mon Sep 17 00:00:00 2001 From: tannal Date: Sun, 15 Jun 2025 07:16:32 +0800 Subject: [PATCH] cli: add --max-heap-size option --- doc/api/cli.md | 7 ++++ src/node_options.cc | 1 + test/common/v8-max-heap-size-option.js | 49 ++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 test/common/v8-max-heap-size-option.js diff --git a/doc/api/cli.md b/doc/api/cli.md index e5a6cfe665bb30..0199620669b675 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -3454,6 +3454,7 @@ V8 options that are allowed are: * `--expose-gc` * `--interpreted-frames-native-stack` * `--jitless` +* `--max-heap-size` * `--max-old-space-size` * `--max-semi-space-size` * `--perf-basic-prof-only-functions` @@ -3796,6 +3797,12 @@ documented here: ### `--jitless` +### `--max-heap-size` + +Specifies the maximum heap size (in megabytes) for the process. + +This option is typically used to limit the amount of memory the process can use for its JavaScript heap. + diff --git a/src/node_options.cc b/src/node_options.cc index c3edfb0344ac27..1b4c3a99d13000 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -1070,6 +1070,7 @@ PerIsolateOptionsParser::PerIsolateOptionsParser( "help system profilers to translate JavaScript interpreted frames", V8Option{}, kAllowedInEnvvar); + AddOption("--max-heap-size", "", V8Option{}, kAllowedInEnvvar); AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvvar); AddOption("--max-semi-space-size", "", V8Option{}, kAllowedInEnvvar); AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvvar); diff --git a/test/common/v8-max-heap-size-option.js b/test/common/v8-max-heap-size-option.js new file mode 100644 index 00000000000000..4487b011a97cdf --- /dev/null +++ b/test/common/v8-max-heap-size-option.js @@ -0,0 +1,49 @@ +'use strict'; + +const assert = require('assert'); +const { spawnSync } = require('child_process'); +const path = require('path'); +const fs = require('fs'); +const tmpdir = require('./tmpdir'); + +const testScript = ` + const v8 = require('v8'); + const stats = v8.getHeapStatistics(); + const maxHeapSizeMB = Math.round(stats.heap_size_limit / 1024 / 1024); + console.log(maxHeapSizeMB); +`; + +tmpdir.refresh(); +const scriptPath = path.join(tmpdir.path, 'heap-limit-test.js'); +fs.writeFileSync(scriptPath, testScript); + +const child = spawnSync( + process.execPath, + [scriptPath], + { + encoding: 'utf8', + env: { + ...process.env, + NODE_OPTIONS: '--max-heap-size=750', + }, + }, +); + +assert.strictEqual( + child.status, + 0, + [ + `Child process did not exit cleanly.`, + ` Exit code: ${child.status}`, + child.stderr ? ` Stderr: ${child.stderr.toString()}` : '', + child.stdout ? ` Stdout: ${child.stdout.toString()}` : '', + ].filter(Boolean).join('\n'), +); +const output = child.stdout.trim(); +const heapLimit = Number(output); + +assert.strictEqual( + heapLimit, + 750, + `max heap size is ${heapLimit}MB, expected 750MB`, +);