From 6f79b0ac09bbe944fc04a3a564ca5073557c2d91 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Mon, 23 Nov 2026 00:20:06 +0000 Subject: [PATCH 1/4] lib: fix node --help missing env vars The help text was dropping the `NODE_ICU_DATA`, `NODE_OPTIONS`, `OPENSSL_CONF`, `SSL_CERT_DIR`, and `SSL_CERT_FILE` env vars. Signed-off-by: James M Snell Assisted-by: Claude --- lib/internal/main/print_help.js | 8 ++++---- test/parallel/test-cli-node-print-help.js | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/lib/internal/main/print_help.js b/lib/internal/main/print_help.js index d788c823fb2c..e8c0b3737f26 100644 --- a/lib/internal/main/print_help.js +++ b/lib/internal/main/print_help.js @@ -77,17 +77,17 @@ const envVars = new SafeMap(ArrayPrototypeConcat([ 'libuv\'s threadpool' }], ], hasIntl ? [ ['NODE_ICU_DATA', { helpText: 'data path for ICU (Intl object) data' + - hasSmallICU ? '' : ' (will extend linked-in data)' }], -] : []), (hasNodeOptions ? [ + (hasSmallICU ? '' : ' (will extend linked-in data)') }], +] : [], hasNodeOptions ? [ ['NODE_OPTIONS', { helpText: 'set CLI options in the environment via a ' + 'space-separated list' }], -] : []), hasCrypto ? [ +] : [], hasCrypto ? [ ['OPENSSL_CONF', { helpText: 'load OpenSSL configuration from file' }], ['SSL_CERT_DIR', { helpText: 'sets OpenSSL\'s directory of trusted ' + 'certificates when used in conjunction with --use-openssl-ca' }], ['SSL_CERT_FILE', { helpText: 'sets OpenSSL\'s trusted certificate file ' + 'when used in conjunction with --use-openssl-ca' }], -] : []); +] : [])); function indent(text, depth) { diff --git a/test/parallel/test-cli-node-print-help.js b/test/parallel/test-cli-node-print-help.js index 84704be2104a..23752f92d8e1 100644 --- a/test/parallel/test-cli-node-print-help.js +++ b/test/parallel/test-cli-node-print-help.js @@ -9,6 +9,8 @@ const common = require('../common'); const assert = require('assert'); const { exec, spawn } = require('child_process'); const { once } = require('events'); +const { stripVTControlCharacters } = require('util'); +const { internalBinding } = require('internal/test/binding'); let stdOut; function startPrintHelpTest() { @@ -37,6 +39,26 @@ function validateNodePrintHelp() { ]; cliHelpOptions.forEach(testForSubstring); + + // Environment variables are listed at the start of a line in their own + // section. Matching on line starts avoids false positives from option help + // text that mentions them (e.g. --icu-data-dir mentions NODE_ICU_DATA). + const envSection = stripVTControlCharacters( + stdOut.slice(stdOut.indexOf('Environment variables:'))); + const { hasNodeOptions } = internalBinding('config'); + const envVars = [ + { compileConstant: HAVE_OPENSSL, + names: [ 'OPENSSL_CONF', 'SSL_CERT_DIR', 'SSL_CERT_FILE' ] }, + { compileConstant: NODE_HAVE_I18N_SUPPORT, names: [ 'NODE_ICU_DATA' ] }, + { compileConstant: hasNodeOptions, names: [ 'NODE_OPTIONS' ] }, + ]; + for (const { compileConstant, names } of envVars) { + for (const name of names) { + const listed = new RegExp(`^${name}\\s`, 'm').test(envSection); + assert.strictEqual(listed, Boolean(compileConstant), + `${name} listed: ${listed} in ${envSection}`); + } + } } function testForSubstring(options) { From 05fec774d35a738259208f0287274288a24d5e31 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Mon, 23 Nov 2026 01:06:12 +0000 Subject: [PATCH 2/4] src: group node --help options into sections The `node --help` output is a single alphabetical list of more than 200 options, which makes it hard to scan or to find related options. Add a required `HelpSection` argument to every `AddOption()` overload so that each option declares the section of the help output it belongs to where it is defined, and print the options grouped under those section headings. Sections are listed in node_options.h and are exposed to JavaScript through the `helpSections` binding property and a `helpSection` index on each `getCLIOptionsInfo()` entry. Assisted-by: Claude Signed-off-by: James M Snell --- lib/internal/main/print_help.js | 103 ++-- src/env_properties.h | 1 + src/node_options-inl.h | 17 + src/node_options.cc | 449 ++++++++++++++++-- src/node_options.h | 36 ++ .../test-cli-node-print-help-sections.js | 80 ++++ 6 files changed, 599 insertions(+), 87 deletions(-) create mode 100644 test/parallel/test-cli-node-print-help-sections.js diff --git a/lib/internal/main/print_help.js b/lib/internal/main/print_help.js index e8c0b3737f26..afe3ab5dee4d 100644 --- a/lib/internal/main/print_help.js +++ b/lib/internal/main/print_help.js @@ -2,6 +2,8 @@ const { ArrayPrototypeConcat, + ArrayPrototypeMap, + ArrayPrototypePush, ArrayPrototypeSort, Boolean, MathFloor, @@ -16,7 +18,7 @@ const { StringPrototypeTrimStart, } = primordials; -const { types } = internalBinding('options'); +const { helpSections, types } = internalBinding('options'); const hasCrypto = Boolean(process.versions.openssl); const { @@ -91,7 +93,7 @@ const envVars = new SafeMap(ArrayPrototypeConcat([ function indent(text, depth) { - return RegExpPrototypeSymbolReplace(/^/gm, text, StringPrototypeRepeat(' ', depth)); + return RegExpPrototypeSymbolReplace(/^(?!$)/gm, text, StringPrototypeRepeat(' ', depth)); } function fold(text, width) { @@ -121,12 +123,7 @@ function getArgDescription(type) { } } -function format( - { options, aliases = new SafeMap(), firstColumn, secondColumn, nameStyle = [] }, -) { - let text = ''; - let maxFirstColumnUsed = 0; - +function getEntries(options, aliases = new SafeMap()) { const sortedOptions = ArrayPrototypeSort( [...options.entries()], ({ 0: name1, 1: option1 }, { 0: name2, 1: option2 }) => { @@ -140,6 +137,7 @@ function format( }, ); + const entries = []; for (const { 0: name, 1: { helpText, type, defaultIsTrue }, } of sortedOptions) { @@ -181,29 +179,51 @@ function format( displayHelpText += ' (currently set)'; } + ArrayPrototypePush(entries, { displayName, helpText: displayHelpText }); + } + return entries; +} + +// Returns the width of the first column, shrunk to fit the longest name across +// all of the given entry lists so that every section lines up. +function fitFirstColumn(entryLists, firstColumn) { + let maxFirstColumnUsed = 0; + for (const entries of entryLists) { + for (const { displayName } of entries) { + maxFirstColumnUsed = MathMax(maxFirstColumnUsed, displayName.length); + } + } + // If we have more than 4 blank gap spaces, reduce first column width. + if (maxFirstColumnUsed < firstColumn - 4) + return maxFirstColumnUsed + 2; + return firstColumn; +} + +function format(entries, firstColumn, secondColumn, nameStyle) { + let text = ''; + for (const { displayName, helpText } of entries) { text += style(nameStyle, displayName); - maxFirstColumnUsed = MathMax(maxFirstColumnUsed, displayName.length); if (displayName.length >= firstColumn) text += '\n' + StringPrototypeRepeat(' ', firstColumn); else text += StringPrototypeRepeat(' ', firstColumn - displayName.length); text += StringPrototypeTrimStart( - indent(fold(displayHelpText, secondColumn), firstColumn)) + '\n'; + indent(fold(helpText, secondColumn), firstColumn)) + '\n'; } + return text; +} - if (maxFirstColumnUsed < firstColumn - 4) { - // If we have more than 4 blank gap spaces, reduce first column width. - return format({ - options, - aliases, - firstColumn: maxFirstColumnUsed + 2, - secondColumn, - nameStyle, - }); +// Splits the options into the --help sections that node_options.cc assigns +// them to, in the order they are defined in node_options.h. +function groupOptions(options) { + const grouped = ArrayPrototypeMap(helpSections, (title) => ({ + title, options: new SafeMap(), + })); + for (const { 0: name, 1: info } of options) { + grouped[info.helpSection].options.set(name, info); } - - return text; + return grouped; } function print(stream) { @@ -215,24 +235,37 @@ function print(stream) { const firstColumn = MathFloor(width * 0.4); const secondColumn = MathFloor(width * 0.57); + // These are handled by the argument parser rather than defined as options. + // Section 0 is HelpSection::kGeneral. options.set('-', { helpText: 'script read from stdin ' + '(default if no file name is provided, ' + - 'interactive mode if a tty)' }); - options.set('--', { helpText: 'indicate the end of node options' }); - let helpText = ( - style('bold', - 'Usage: node [options] [ script.js ] [arguments]\n' + - ' node inspect [options] [ script.js | host:port ] [arguments]') + - '\n\n' + style('bold', 'Options:') + '\n'); - helpText += (indent(format({ - options, aliases, firstColumn, secondColumn, nameStyle: ['bold', 'green'], - }), 2)); + 'interactive mode if a tty)', + helpSection: 0 }); + options.set('--', { helpText: 'indicate the end of node options', + helpSection: 0 }); + + const optionSections = []; + for (const { title, options: sectionOptions } of groupOptions(options)) { + const entries = getEntries(sectionOptions, aliases); + if (entries.length > 0) ArrayPrototypePush(optionSections, { title, entries }); + } + const optionsFirstColumn = fitFirstColumn( + ArrayPrototypeMap(optionSections, ({ entries }) => entries), firstColumn); + + let helpText = style('bold', + 'Usage: node [options] [ script.js ] [arguments]\n' + + ' node inspect [options] [ script.js | host:port ] [arguments]') + + '\n'; + for (const { title, entries } of optionSections) { + helpText += '\n' + style('bold', `${title}:`) + '\n'; + helpText += indent(format(entries, optionsFirstColumn, secondColumn, + ['bold', 'green']), 2); + } + const envEntries = getEntries(envVars); helpText += ('\n' + style('bold', 'Environment variables:') + '\n'); - - helpText += (format({ - options: envVars, firstColumn, secondColumn, nameStyle: ['bold', 'magenta'], - })); + helpText += format(envEntries, fitFirstColumn([envEntries], firstColumn), + secondColumn, ['bold', 'magenta']); helpText += ('\nDocumentation can be found at ' + style(['blue', 'underline'], 'https://nodejs.org/')); diff --git a/src/env_properties.h b/src/env_properties.h index 2f3d814ff497..18cfa42e198b 100644 --- a/src/env_properties.h +++ b/src/env_properties.h @@ -180,6 +180,7 @@ V(h2_string, "h2") \ V(handle_string, "handle") \ V(hash_algorithm_string, "hashAlgorithm") \ + V(help_section_string, "helpSection") \ V(help_text_string, "helpText") \ V(homedir_string, "homedir") \ V(host_string, "host") \ diff --git a/src/node_options-inl.h b/src/node_options-inl.h index dac206791c35..0e5710c71803 100644 --- a/src/node_options-inl.h +++ b/src/node_options-inl.h @@ -33,6 +33,7 @@ namespace options_parser { template void OptionsParser::AddOption(const char* name, const char* help_text, + HelpSection help_section, bool (*getter)(Options*), void (*setter)(Options*, bool), OptionEnvvarSettings env_setting, @@ -44,6 +45,7 @@ void OptionsParser::AddOption(const char* name, std::make_shared(getter, setter), env_setting, help_text, + help_section, default_is_true, NamespaceEnumToString(namespace_id)}); } @@ -51,6 +53,7 @@ void OptionsParser::AddOption(const char* name, template void OptionsParser::AddOption(const char* name, const char* help_text, + HelpSection help_section, uint64_t Options::*field, OptionEnvvarSettings env_setting, OptionNamespaces namespace_id, @@ -61,6 +64,7 @@ void OptionsParser::AddOption(const char* name, std::make_shared>(field), env_setting, help_text, + help_section, false, NamespaceEnumToString(namespace_id), strict}); @@ -69,6 +73,7 @@ void OptionsParser::AddOption(const char* name, template void OptionsParser::AddOption(const char* name, const char* help_text, + HelpSection help_section, int64_t Options::*field, OptionEnvvarSettings env_setting, OptionNamespaces namespace_id) { @@ -78,6 +83,7 @@ void OptionsParser::AddOption(const char* name, std::make_shared>(field), env_setting, help_text, + help_section, false, NamespaceEnumToString(namespace_id)}); } @@ -85,6 +91,7 @@ void OptionsParser::AddOption(const char* name, template void OptionsParser::AddOption(const char* name, const char* help_text, + HelpSection help_section, std::string Options::*field, OptionEnvvarSettings env_setting, OptionNamespaces namespace_id) { @@ -94,6 +101,7 @@ void OptionsParser::AddOption(const char* name, std::make_shared>(field), env_setting, help_text, + help_section, false, NamespaceEnumToString(namespace_id)}); } @@ -101,6 +109,7 @@ void OptionsParser::AddOption(const char* name, template void OptionsParser::AddOption(const char* name, const char* help_text, + HelpSection help_section, std::vector Options::*field, OptionEnvvarSettings env_setting, OptionNamespaces namespace_id) { @@ -111,6 +120,7 @@ void OptionsParser::AddOption(const char* name, std::make_shared>>(field), env_setting, help_text, + help_section, false, NamespaceEnumToString(namespace_id)}); } @@ -118,6 +128,7 @@ void OptionsParser::AddOption(const char* name, template void OptionsParser::AddOption(const char* name, const char* help_text, + HelpSection help_section, HostPort Options::*field, OptionEnvvarSettings env_setting, OptionNamespaces namespace_id) { @@ -127,6 +138,7 @@ void OptionsParser::AddOption(const char* name, std::make_shared>(field), env_setting, help_text, + help_section, false, NamespaceEnumToString(namespace_id)}); } @@ -134,6 +146,7 @@ void OptionsParser::AddOption(const char* name, template void OptionsParser::AddOption(const char* name, const char* help_text, + HelpSection help_section, NoOp no_op_tag, OptionEnvvarSettings env_setting, OptionNamespaces namespace_id) { @@ -142,6 +155,7 @@ void OptionsParser::AddOption(const char* name, nullptr, env_setting, help_text, + help_section, false, NamespaceEnumToString(namespace_id)}); } @@ -149,6 +163,7 @@ void OptionsParser::AddOption(const char* name, template void OptionsParser::AddOption(const char* name, const char* help_text, + HelpSection help_section, V8Option v8_option_tag, OptionEnvvarSettings env_setting, OptionNamespaces namespace_id) { @@ -157,6 +172,7 @@ void OptionsParser::AddOption(const char* name, nullptr, env_setting, help_text, + help_section, false, NamespaceEnumToString(namespace_id)}); } @@ -241,6 +257,7 @@ auto OptionsParser::Convert( Convert(original.field, get_child), original.env_setting, original.help_text, + original.help_section, original.default_is_true, original.namespace_id, original.strict}; diff --git a/src/node_options.cc b/src/node_options.cc index d0e34fd3d176..a1fb0c4ad0c1 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -23,6 +23,7 @@ #include #include +using v8::Array; using v8::Boolean; using v8::Context; using v8::FunctionCallbackInfo; @@ -658,35 +659,44 @@ void Parse( DebugOptionsParser::DebugOptionsParser() { AddOption("--inspect-port", "set host:port for inspector", + HelpSection::kDebugging, &DebugOptions::host_port, kAllowedInEnvvar); AddAlias("--debug-port", "--inspect-port"); AddOption("--inspect", "activate inspector on host:port (default: 127.0.0.1:9229)", + HelpSection::kDebugging, BOOL_FIELD(inspector_enabled), kAllowedInEnvvar); AddAlias("--inspect=", { "--inspect-port", "--inspect" }); - AddOption("--debug", "", BOOL_FIELD(deprecated_debug)); + AddOption( + "--debug", "", HelpSection::kDebugging, BOOL_FIELD(deprecated_debug)); AddAlias("--debug=", "--debug"); - AddOption("--debug-brk", "", BOOL_FIELD(deprecated_debug)); + AddOption( + "--debug-brk", "", HelpSection::kDebugging, BOOL_FIELD(deprecated_debug)); AddAlias("--debug-brk=", "--debug-brk"); AddOption("--inspect-brk", "activate inspector on host:port and break at start of user script", + HelpSection::kDebugging, BOOL_FIELD(break_first_line), kAllowedInEnvvar); Implies("--inspect-brk", "--inspect"); AddAlias("--inspect-brk=", { "--inspect-port", "--inspect-brk" }); - AddOption("--inspect-brk-node", "", BOOL_FIELD(break_node_first_line)); + AddOption("--inspect-brk-node", + "", + HelpSection::kDebugging, + BOOL_FIELD(break_node_first_line)); Implies("--inspect-brk-node", "--inspect"); AddAlias("--inspect-brk-node=", { "--inspect-port", "--inspect-brk-node" }); AddOption( "--inspect-wait", "activate inspector on host:port and wait for debugger to be attached", + HelpSection::kDebugging, BOOL_FIELD(inspect_wait), kAllowedInEnvvar); Implies("--inspect-wait", "--inspect"); @@ -695,6 +705,7 @@ DebugOptionsParser::DebugOptionsParser() { AddOption("--inspect-publish-uid", "comma separated list of destinations for inspector uid" "(default: stderr,http)", + HelpSection::kDebugging, &DebugOptions::inspect_publish_uid_string, kAllowedInEnvvar); } @@ -702,12 +713,14 @@ DebugOptionsParser::DebugOptionsParser() { EnvironmentOptionsParser::EnvironmentOptionsParser() { AddOption("--conditions", "additional user conditions for conditional exports and imports", + HelpSection::kModules, &EnvironmentOptions::conditions, kAllowedInEnvvar); AddAlias("-C", "--conditions"); AddOption("--experimental-detect-module", "when ambiguous modules fail to evaluate because they contain " "ES module syntax, try again to evaluate them as ES modules", + HelpSection::kModules, BOOL_FIELD(detect_module), kAllowedInEnvvar, true); @@ -716,15 +729,18 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { "is true, evaluate asynchronous graphs loaded by `require()` but " "do not run the microtasks, in order to find and print " "top-level await in the graph", + HelpSection::kModules, BOOL_FIELD(print_required_tla), kAllowedInEnvvar); AddOption("--require-module", "Allow loading synchronous ES Modules in require().", + HelpSection::kModules, BOOL_FIELD(require_module), kAllowedInEnvvar, true); AddOption("--experimental-require-module", "Legacy alias for --require-module", + HelpSection::kModules, BOOL_FIELD(require_module), kAllowedInEnvvar, true); @@ -732,10 +748,12 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { AddOption("--diagnostic-dir", "set dir for all output files" " (default: current working directory)", + HelpSection::kDiagnostics, &EnvironmentOptions::diagnostic_dir, kAllowedInEnvvar); AddOption("--disable-sigusr1", "Disable inspector thread to be listening for SIGUSR1 signal", + HelpSection::kDebugging, BOOL_FIELD(disable_sigusr1), kAllowedInEnvvar, false); @@ -745,77 +763,108 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { "'ipv6first' (IPv6 addresses are placed before IPv4 addresses) " "'verbatim' (addresses are in the order the DNS resolver " "returned)", + HelpSection::kNetworking, &EnvironmentOptions::dns_result_order, kAllowedInEnvvar); AddOption("--network-family-autoselection", "Disable network address family autodetection algorithm", + HelpSection::kNetworking, BOOL_FIELD(network_family_autoselection), kAllowedInEnvvar, true); AddOption("--network-family-autoselection-attempt-timeout", "Sets the default value for the network family autoselection " "attempt timeout.", + HelpSection::kNetworking, &EnvironmentOptions::network_family_autoselection_attempt_timeout, kAllowedInEnvvar); AddAlias("--enable-network-family-autoselection", "--network-family-autoselection"); AddOption("--enable-source-maps", "Source Map V3 support for stack traces", + HelpSection::kErrors, BOOL_FIELD(enable_source_maps), kAllowedInEnvvar); AddOption("--entry-url", "Treat the entrypoint as a URL", + HelpSection::kGeneral, BOOL_FIELD(entry_is_url), kAllowedInEnvvar); AddOption("--experimental-addon-modules", "experimental import support for addons", + HelpSection::kModules, BOOL_FIELD(experimental_addon_modules), kAllowedInEnvvar); AddOption("--experimental-bench", "experimental node:bench module and benchmark runner", + HelpSection::kBenchRunner, BOOL_FIELD(experimental_bench), kAllowedInEnvvar); - AddOption("--experimental-abortcontroller", "", NoOp{}, kAllowedInEnvvar); + AddOption("--experimental-abortcontroller", + "", + HelpSection::kBuiltinApis, + NoOp{}, + kAllowedInEnvvar); AddOption("--experimental-eventsource", "experimental EventSource API", + HelpSection::kBuiltinApis, BOOL_FIELD(experimental_eventsource), kAllowedInEnvvar, false); - AddOption("--experimental-fetch", "", NoOp{}, kAllowedInEnvvar); + AddOption("--experimental-fetch", + "", + HelpSection::kBuiltinApis, + NoOp{}, + kAllowedInEnvvar); #if HAVE_FFI AddOption("--experimental-ffi", "experimental node:ffi module", + HelpSection::kBuiltinApis, BOOL_FIELD(experimental_ffi), kAllowedInEnvvar, HAVE_FFI); #endif // HAVE_FFI AddOption("--experimental-web-worker", "experimental Web Worker API", + HelpSection::kBuiltinApis, BOOL_FIELD(experimental_web_worker), kAllowedInEnvvar, true); - AddOption("--experimental-websocket", "", NoOp{}, kAllowedInEnvvar); - AddOption("--experimental-global-customevent", "", NoOp{}, kAllowedInEnvvar); + AddOption("--experimental-websocket", + "", + HelpSection::kBuiltinApis, + NoOp{}, + kAllowedInEnvvar); + AddOption("--experimental-global-customevent", + "", + HelpSection::kBuiltinApis, + NoOp{}, + kAllowedInEnvvar); AddOption("--experimental-sqlite", "experimental node:sqlite module", + HelpSection::kBuiltinApis, BOOL_FIELD(experimental_sqlite), kAllowedInEnvvar, HAVE_SQLITE); AddOption("--experimental-stream-iter", "experimental iterable streams API (node:stream/iter)", + HelpSection::kBuiltinApis, BOOL_FIELD(experimental_stream_iter), kAllowedInEnvvar); AddOption("--experimental-dtls", #if HAVE_DTLS "experimental DTLS support", + HelpSection::kBuiltinApis, BOOL_FIELD(experimental_dtls), #else "" /* undocumented when no-op */, + HelpSection::kBuiltinApis, NoOp{}, #endif kAllowedInEnvvar); AddOption("--experimental-vfs", "experimental node:vfs module", + HelpSection::kModules, BOOL_FIELD(experimental_vfs), kAllowedInEnvvar, true); @@ -828,89 +877,121 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { "mount a directory or archive as a virtual file system and run the " "entry point and module resolution against it instead of the real " "file system (may be given once)", + HelpSection::kModules, &EnvironmentOptions::vfs_load_source, kDisallowedInEnvvar); - AddOption("[vfs_load_set]", "", BOOL_FIELD(vfs_load)); + AddOption("[vfs_load_set]", "", HelpSection::kModules, BOOL_FIELD(vfs_load)); Implies("--vfs-load", "[vfs_load_set]"); - AddOption("[sea_vfs]", "", BOOL_FIELD(sea_vfs)); + AddOption("[sea_vfs]", "", HelpSection::kSnapshots, BOOL_FIELD(sea_vfs)); AddOption("--experimental-quic", #ifndef OPENSSL_NO_QUIC "experimental QUIC support", + HelpSection::kBuiltinApis, BOOL_FIELD(experimental_quic), #else "" /* undocumented when no-op */, + HelpSection::kBuiltinApis, NoOp{}, #endif kAllowedInEnvvar); AddOption("--experimental-webstorage", "experimental Web Storage API", + HelpSection::kBuiltinApis, BOOL_FIELD(webstorage), kAllowedInEnvvar, HAVE_SQLITE); AddAlias("--webstorage", "--experimental-webstorage"); AddOption("--localstorage-file", "file used to persist localStorage data", + HelpSection::kBuiltinApis, &EnvironmentOptions::localstorage_file, kAllowedInEnvvar); AddOption("--experimental-global-navigator", "expose experimental Navigator API on the global scope", + HelpSection::kBuiltinApis, BOOL_FIELD(experimental_global_navigator), kAllowedInEnvvar, true); - AddOption("--experimental-global-webcrypto", "", NoOp{}, kAllowedInEnvvar); - AddOption("--experimental-json-modules", "", NoOp{}, kAllowedInEnvvar); - AddOption("--experimental-modules", "", NoOp{}, kAllowedInEnvvar); - AddOption("--experimental-wasm-modules", "", NoOp{}, kAllowedInEnvvar); + AddOption("--experimental-global-webcrypto", + "", + HelpSection::kBuiltinApis, + NoOp{}, + kAllowedInEnvvar); + AddOption("--experimental-json-modules", + "", + HelpSection::kModules, + NoOp{}, + kAllowedInEnvvar); + AddOption("--experimental-modules", + "", + HelpSection::kModules, + NoOp{}, + kAllowedInEnvvar); + AddOption("--experimental-wasm-modules", + "", + HelpSection::kModules, + NoOp{}, + kAllowedInEnvvar); AddOption("--experimental-import-text", "experimental support for importing source as text with import " "attributes", + HelpSection::kModules, BOOL_FIELD(experimental_import_text), kAllowedInEnvvar); AddOption("--experimental-import-meta-resolve", "experimental ES Module import.meta.resolve() parentURL support", + HelpSection::kModules, BOOL_FIELD(experimental_import_meta_resolve), kAllowedInEnvvar); AddOption("--permission", "enable the permission system", + HelpSection::kPermissions, BOOL_FIELD(permission), kAllowedInEnvvar, false, OptionNamespaces::kPermissionNamespace); AddOption("--permission-audit", "enable audit only for the permission system", + HelpSection::kPermissions, BOOL_FIELD(permission_audit), kAllowedInEnvvar, false); AddOption("--allow-env", "allow access to environment variables when any permissions are " "set", + HelpSection::kPermissions, &EnvironmentOptions::allow_env, kAllowedInEnvvar, OptionNamespaces::kPermissionNamespace); AddOption("--allow-fs-read", "allow permissions to read the filesystem", + HelpSection::kPermissions, &EnvironmentOptions::allow_fs_read, kAllowedInEnvvar, OptionNamespaces::kPermissionNamespace); AddOption("--allow-fs-write", "allow permissions to write in the filesystem", + HelpSection::kPermissions, &EnvironmentOptions::allow_fs_write, kAllowedInEnvvar, OptionNamespaces::kPermissionNamespace); AddOption("--allow-fs-vfs", "allow mounting a virtual file system when any permissions are set", + HelpSection::kPermissions, BOOL_FIELD(allow_fs_vfs), kAllowedInEnvvar, false, OptionNamespaces::kPermissionNamespace); AddOption("--allow-addons", "allow use of addons when any permissions are set", + HelpSection::kPermissions, BOOL_FIELD(allow_addons), kAllowedInEnvvar, false, OptionNamespaces::kPermissionNamespace); AddOption("--allow-child-process", "allow use of child process when any permissions are set", + HelpSection::kPermissions, BOOL_FIELD(allow_child_process), kAllowedInEnvvar, false, @@ -918,6 +999,7 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { #if HAVE_FFI AddOption("--allow-ffi", "allow use of FFI when any permissions are set", + HelpSection::kPermissions, BOOL_FIELD(allow_ffi), kAllowedInEnvvar, false, @@ -925,134 +1007,185 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { #endif // HAVE_FFI AddOption("--allow-inspector", "allow use of inspector when any permissions are set", + HelpSection::kPermissions, BOOL_FIELD(allow_inspector), kAllowedInEnvvar, false, OptionNamespaces::kPermissionNamespace); AddOption("--allow-net", "allow use of network when any permissions are set", + HelpSection::kPermissions, BOOL_FIELD(allow_net), kAllowedInEnvvar, false, OptionNamespaces::kPermissionNamespace); AddOption("--allow-wasi", "allow wasi when any permissions are set", + HelpSection::kPermissions, BOOL_FIELD(allow_wasi), kAllowedInEnvvar, false, OptionNamespaces::kPermissionNamespace); AddOption("--allow-worker", "allow worker threads when any permissions are set", + HelpSection::kPermissions, BOOL_FIELD(allow_worker_threads), kAllowedInEnvvar, false, OptionNamespaces::kPermissionNamespace); AddOption("--allow-openssl-store", "allow use of OpenSSL STORE loaders when any permissions are set", + HelpSection::kPermissions, BOOL_FIELD(allow_openssl_store), kAllowedInEnvvar, false, OptionNamespaces::kPermissionNamespace); - AddOption("--experimental-repl-await", "", NoOp{}, kAllowedInEnvvar); + AddOption("--experimental-repl-await", + "", + HelpSection::kGeneral, + NoOp{}, + kAllowedInEnvvar); AddOption("--experimental-vm-modules", "experimental ES Module support in vm module", + HelpSection::kModules, BOOL_FIELD(experimental_vm_modules), kAllowedInEnvvar); - AddOption("--experimental-worker", "", NoOp{}, kAllowedInEnvvar); - AddOption("--experimental-report", "", NoOp{}, kAllowedInEnvvar); - AddOption( - "--experimental-wasi-unstable-preview1", "", NoOp{}, kAllowedInEnvvar); - AddOption("--expose-gc", "expose gc extension", V8Option{}, kAllowedInEnvvar); - AddOption("--expose-internals", "", BOOL_FIELD(expose_internals)); + AddOption("--experimental-worker", + "", + HelpSection::kBuiltinApis, + NoOp{}, + kAllowedInEnvvar); + AddOption("--experimental-report", + "", + HelpSection::kDiagnostics, + NoOp{}, + kAllowedInEnvvar); + AddOption("--experimental-wasi-unstable-preview1", + "", + HelpSection::kBuiltinApis, + NoOp{}, + kAllowedInEnvvar); + AddOption("--expose-gc", + "expose gc extension", + HelpSection::kV8, + V8Option{}, + kAllowedInEnvvar); + AddOption("--expose-internals", + "", + HelpSection::kDiagnostics, + BOOL_FIELD(expose_internals)); AddOption("--frozen-intrinsics", "experimental frozen intrinsics support", + HelpSection::kSecurity, BOOL_FIELD(frozen_intrinsics), kAllowedInEnvvar); AddOption("--heapsnapshot-signal", "Generate heap snapshot on specified signal", + HelpSection::kDiagnostics, &EnvironmentOptions::heap_snapshot_signal, kAllowedInEnvvar); AddOption("--heapsnapshot-near-heap-limit", "Generate heap snapshots whenever V8 is approaching " "the heap limit. No more than the specified number of " "heap snapshots will be generated.", + HelpSection::kDiagnostics, &EnvironmentOptions::heap_snapshot_near_heap_limit, kAllowedInEnvvar); - AddOption("--http-parser", "", NoOp{}, kAllowedInEnvvar); + AddOption( + "--http-parser", "", HelpSection::kNetworking, NoOp{}, kAllowedInEnvvar); AddOption("--insecure-http-parser", "use an insecure HTTP parser that accepts invalid HTTP headers", + HelpSection::kNetworking, BOOL_FIELD(insecure_http_parser), kAllowedInEnvvar); AddOption("--input-type", "set module type for string input", + HelpSection::kGeneral, &EnvironmentOptions::input_type, kAllowedInEnvvar); - AddOption( - "--experimental-specifier-resolution", "", NoOp{}, kAllowedInEnvvar); + AddOption("--experimental-specifier-resolution", + "", + HelpSection::kModules, + NoOp{}, + kAllowedInEnvvar); AddAlias("--es-module-specifier-resolution", "--experimental-specifier-resolution"); AddOption("--deprecation", "silence deprecation warnings", + HelpSection::kErrors, BOOL_FIELD(deprecation), kAllowedInEnvvar, true); AddOption("--force-async-hooks-checks", "disable checks for async_hooks", + HelpSection::kDiagnostics, BOOL_FIELD(force_async_hooks_checks), kAllowedInEnvvar, true); AddOption( "--force-node-api-uncaught-exceptions-policy", "enforces 'uncaughtException' event on Node API asynchronous callbacks", + HelpSection::kErrors, BOOL_FIELD(force_node_api_uncaught_exceptions_policy), kAllowedInEnvvar, false); AddOption("--addons", "disable loading native addons", + HelpSection::kModules, BOOL_FIELD(allow_native_addons), kAllowedInEnvvar, true); AddOption("--global-search-paths", "disable global module search paths", + HelpSection::kModules, BOOL_FIELD(global_search_paths), kAllowedInEnvvar, true); AddOption("--warnings", "silence all process warnings", + HelpSection::kErrors, BOOL_FIELD(warnings), kAllowedInEnvvar, true); AddOption("--disable-warning", "silence specific process warnings", + HelpSection::kErrors, &EnvironmentOptions::disable_warnings, kAllowedInEnvvar); AddOption("--force-context-aware", "disable loading non-context-aware addons", + HelpSection::kModules, BOOL_FIELD(force_context_aware), kAllowedInEnvvar); AddOption("--pending-deprecation", "emit pending deprecation warnings", + HelpSection::kErrors, BOOL_FIELD(pending_deprecation), kAllowedInEnvvar); AddOption("--use-env-proxy", "parse proxy settings from HTTP_PROXY/HTTPS_PROXY/NO_PROXY" "environment variables and apply the setting in global HTTP/HTTPS " "clients", + HelpSection::kNetworking, BOOL_FIELD(use_env_proxy), kAllowedInEnvvar); AddOption("--preserve-symlinks", "preserve symbolic links when resolving", + HelpSection::kModules, BOOL_FIELD(preserve_symlinks), kAllowedInEnvvar); AddOption("--preserve-symlinks-main", "preserve symbolic links when resolving the main module", + HelpSection::kModules, BOOL_FIELD(preserve_symlinks_main), kAllowedInEnvvar); AddOption("--prof", "Generate V8 profiler output.", + HelpSection::kDiagnostics, V8Option{}); AddOption("--prof-process", "process V8 profiler output generated using --prof", + HelpSection::kDiagnostics, BOOL_FIELD(prof_process)); // Options after --prof-process are passed through to the prof processor. AddAlias("--prof-process", {"--prof-process", "--"}); @@ -1061,88 +1194,113 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { "Start the V8 CPU profiler on start up, and write the CPU profile " "to disk before exit. If --cpu-prof-dir is not specified, write " "the profile to the current working directory.", + HelpSection::kDiagnostics, BOOL_FIELD(cpu_prof), kAllowedInEnvvar); AddOption("--cpu-prof-name", "specified file name of the V8 CPU profile generated with " "--cpu-prof", + HelpSection::kDiagnostics, &EnvironmentOptions::cpu_prof_name, kAllowedInEnvvar); AddOption("--cpu-prof-interval", "specified sampling interval in microseconds for the V8 CPU " "profile generated with --cpu-prof. (default: 1000)", + HelpSection::kDiagnostics, &EnvironmentOptions::cpu_prof_interval, kAllowedInEnvvar); AddOption("--cpu-prof-dir", "Directory where the V8 profiles generated by --cpu-prof will be " "placed. Does not affect --prof.", + HelpSection::kDiagnostics, &EnvironmentOptions::cpu_prof_dir, kAllowedInEnvvar); AddOption("--experimental-network-inspection", "experimental network inspection support", + HelpSection::kDebugging, BOOL_FIELD(experimental_network_inspection)); AddOption("--experimental-storage-inspection", "experimental storage inspection support", + HelpSection::kDebugging, BOOL_FIELD(experimental_storage_inspection)); AddOption("--experimental-worker-inspection", "experimental worker inspection support", + HelpSection::kDebugging, BOOL_FIELD(experimental_worker_inspection)); AddOption("--experimental-inspector-network-resource", "experimental load network resources via the inspector", + HelpSection::kDebugging, BOOL_FIELD(experimental_inspector_network_resource)); AddOption( "--heap-prof", "Start the V8 heap profiler on start up, and write the heap profile " "to disk before exit. If --heap-prof-dir is not specified, write " "the profile to the current working directory.", + HelpSection::kDiagnostics, BOOL_FIELD(heap_prof), kAllowedInEnvvar); AddOption("--heap-prof-name", "specified file name of the V8 heap profile generated with " "--heap-prof", + HelpSection::kDiagnostics, &EnvironmentOptions::heap_prof_name, kAllowedInEnvvar); AddOption("--heap-prof-dir", "Directory where the V8 heap profiles generated by --heap-prof " "will be placed.", + HelpSection::kDiagnostics, &EnvironmentOptions::heap_prof_dir, kAllowedInEnvvar); AddOption("--heap-prof-interval", "specified sampling interval in bytes for the V8 heap " "profile generated with --heap-prof. (default: 512 * 1024)", + HelpSection::kDiagnostics, &EnvironmentOptions::heap_prof_interval, kAllowedInEnvvar); #endif // HAVE_INSPECTOR AddOption("--max-http-header-size", "set the maximum size of HTTP headers (default: 16384 (16KB))", + HelpSection::kNetworking, &EnvironmentOptions::max_http_header_size, kAllowedInEnvvar); AddOption("--redirect-warnings", "write warnings to file instead of stderr", + HelpSection::kErrors, &EnvironmentOptions::redirect_warnings, kAllowedInEnvvar); - AddOption("[has_env_file_string]", "", BOOL_FIELD(has_env_file_string)); + AddOption("[has_env_file_string]", + "", + HelpSection::kGeneral, + BOOL_FIELD(has_env_file_string)); AddOption("--env-file", "set environment variables from supplied file", + HelpSection::kGeneral, &EnvironmentOptions::env_file); Implies("--env-file", "[has_env_file_string]"); AddOption("--env-file-if-exists", "set environment variables from supplied file", + HelpSection::kGeneral, &EnvironmentOptions::optional_env_file); Implies("--env-file-if-exists", "[has_env_file_string]"); AddOption("--config-file", "set config file path", + HelpSection::kGeneral, &EnvironmentOptions::config_file_path, kDisallowedInEnvvar); AddAlias("--experimental-config-file", "--config-file"); AddAlias("--experimental-default-config-file", "--config-file"); AddOption("--experimental-package-map", "use the specified file for package map resolution", + HelpSection::kModules, &EnvironmentOptions::experimental_package_map_path, kAllowedInEnvvar); - AddOption("[has_bench_options]", "", BOOL_FIELD(has_bench_options)); + AddOption("[has_bench_options]", + "", + HelpSection::kBenchRunner, + BOOL_FIELD(has_bench_options)); AddOption("--bench", "launch benchmark runner on startup", + HelpSection::kBenchRunner, BOOL_FIELD(bench_runner), kDisallowedInEnvvar, false, @@ -1150,6 +1308,7 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { Implies("--bench", "[has_bench_options]"); AddOption("--bench-gc", "run garbage collection before measured benchmark samples", + HelpSection::kBenchRunner, &EnvironmentOptions::bench_gc, kAllowedInEnvvar, OptionNamespaces::kBenchRunnerNamespace); @@ -1157,40 +1316,52 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { AddOption("--bench-isolation", "configures the type of benchmark isolation used in the benchmark " "runner", + HelpSection::kBenchRunner, &EnvironmentOptions::bench_isolation, kAllowedInEnvvar, OptionNamespaces::kBenchRunnerNamespace); Implies("--bench-isolation", "[has_bench_options]"); AddOption("--bench-name-pattern", "run benchmarks whose name matches this regular expression", + HelpSection::kBenchRunner, &EnvironmentOptions::bench_name_pattern, kAllowedInEnvvar, OptionNamespaces::kBenchRunnerNamespace); Implies("--bench-name-pattern", "[has_bench_options]"); AddOption("--bench-reporter", "report benchmark output using the given reporter", + HelpSection::kBenchRunner, &EnvironmentOptions::bench_reporter, kAllowedInEnvvar, OptionNamespaces::kBenchRunnerNamespace); Implies("--bench-reporter", "[has_bench_options]"); AddOption("--bench-reporter-destination", "report the given benchmark reporter to the given destination", + HelpSection::kBenchRunner, &EnvironmentOptions::bench_reporter_destination, kAllowedInEnvvar, OptionNamespaces::kBenchRunnerNamespace); Implies("--bench-reporter-destination", "[has_bench_options]"); - AddOption("[has_bench_samples]", "", BOOL_FIELD(has_bench_samples)); + AddOption("[has_bench_samples]", + "", + HelpSection::kBenchRunner, + BOOL_FIELD(has_bench_samples)); AddOption("--bench-samples", "specify the number of measured benchmark samples", + HelpSection::kBenchRunner, &EnvironmentOptions::bench_samples, kAllowedInEnvvar, OptionNamespaces::kBenchRunnerNamespace, kStrictOptionParsing); Implies("--bench-samples", "[has_bench_options]"); Implies("--bench-samples", "[has_bench_samples]"); - AddOption("[has_bench_warmup]", "", BOOL_FIELD(has_bench_warmup)); + AddOption("[has_bench_warmup]", + "", + HelpSection::kBenchRunner, + BOOL_FIELD(has_bench_warmup)); AddOption("--bench-warmup", "specify the number of unreported benchmark warmup samples", + HelpSection::kBenchRunner, &EnvironmentOptions::bench_warmup, kAllowedInEnvvar, OptionNamespaces::kBenchRunnerNamespace, @@ -1199,55 +1370,65 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { Implies("--bench-warmup", "[has_bench_warmup]"); AddOption("--test", "launch test runner on startup", + HelpSection::kTestRunner, BOOL_FIELD(test_runner), kDisallowedInEnvvar, false, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-concurrency", "specify test runner concurrency", + HelpSection::kTestRunner, &EnvironmentOptions::test_runner_concurrency, kDisallowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-force-exit", "force test runner to exit upon completion", + HelpSection::kTestRunner, BOOL_FIELD(test_runner_force_exit), kDisallowedInEnvvar, false, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-timeout", "specify test runner timeout", + HelpSection::kTestRunner, &EnvironmentOptions::test_runner_timeout, kDisallowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-update-snapshots", "regenerate test snapshots", + HelpSection::kTestRunner, BOOL_FIELD(test_runner_update_snapshots), kDisallowedInEnvvar, false, OptionNamespaces::kTestRunnerNamespace); AddOption("--experimental-test-coverage", "enable code coverage in the test runner", + HelpSection::kTestRunner, BOOL_FIELD(test_runner_coverage), kDisallowedInEnvvar, false, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-coverage-branches", "the branch coverage minimum threshold", + HelpSection::kTestRunner, &EnvironmentOptions::test_coverage_branches, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-coverage-functions", "the function coverage minimum threshold", + HelpSection::kTestRunner, &EnvironmentOptions::test_coverage_functions, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-coverage-lines", "the line coverage minimum threshold", + HelpSection::kTestRunner, &EnvironmentOptions::test_coverage_lines, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-isolation", "configures the type of test isolation used in the test runner", + HelpSection::kTestRunner, &EnvironmentOptions::test_isolation, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); @@ -1255,137 +1436,167 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { AddAlias("--experimental-test-isolation", "--test-isolation"); AddOption("--experimental-test-module-mocks", "enable module mocking in the test runner", + HelpSection::kTestRunner, BOOL_FIELD(test_runner_module_mocks), kDisallowedInEnvvar, false, OptionNamespaces::kTestRunnerNamespace); AddOption("--experimental-test-snapshots", "", + HelpSection::kTestRunner, NoOp{}, kDisallowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-name-pattern", "run tests whose name matches this regular expression", + HelpSection::kTestRunner, &EnvironmentOptions::test_name_pattern, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-reporter", "report test output using the given reporter", + HelpSection::kTestRunner, &EnvironmentOptions::test_reporter, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-reporter-destination", "report given reporter to the given destination", + HelpSection::kTestRunner, &EnvironmentOptions::test_reporter_destination, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-only", "run tests with 'only' option set", + HelpSection::kTestRunner, BOOL_FIELD(test_only), kAllowedInEnvvar, false, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-forbid-only", "fail tests that use the 'only' option", + HelpSection::kTestRunner, BOOL_FIELD(test_forbid_only), kAllowedInEnvvar, false, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-shard", "run test at specific shard", + HelpSection::kTestRunner, &EnvironmentOptions::test_shard, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-skip-pattern", "run tests whose name do not match this regular expression", + HelpSection::kTestRunner, &EnvironmentOptions::test_skip_pattern, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--experimental-test-tag-filter", "run tests matching the given tag filter expression", + HelpSection::kTestRunner, &EnvironmentOptions::experimental_test_tag_filter, kDisallowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-coverage-include", "include files in coverage report that match this glob pattern", + HelpSection::kTestRunner, &EnvironmentOptions::coverage_include_pattern, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-coverage-include-all", "include source files that were never loaded in the coverage " "report", + HelpSection::kTestRunner, BOOL_FIELD(coverage_include_all), kAllowedInEnvvar, false, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-coverage-exclude", "exclude files from coverage report that match this glob pattern", + HelpSection::kTestRunner, &EnvironmentOptions::coverage_exclude_pattern, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-global-setup", "specifies the path to the global setup file", + HelpSection::kTestRunner, &EnvironmentOptions::test_global_setup_path, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-randomize", "run tests in a random order", + HelpSection::kTestRunner, BOOL_FIELD(test_randomize), kAllowedInEnvvar, false, OptionNamespaces::kTestRunnerNamespace); - AddOption("[has_test_random_seed]", "", BOOL_FIELD(has_test_random_seed)); + AddOption("[has_test_random_seed]", + "", + HelpSection::kTestRunner, + BOOL_FIELD(has_test_random_seed)); AddOption("--test-random-seed", "seed used to randomize test execution order", + HelpSection::kTestRunner, &EnvironmentOptions::test_random_seed, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); Implies("--test-random-seed", "[has_test_random_seed]"); AddOption("--test-rerun-failures", "specifies the path to the rerun state file", + HelpSection::kTestRunner, &EnvironmentOptions::test_rerun_failures_path, kAllowedInEnvvar, OptionNamespaces::kTestRunnerNamespace); AddOption("--test-udp-no-try-send", - "", // For testing only. + "", + HelpSection::kNetworking, // For testing only. BOOL_FIELD(test_udp_no_try_send), kDisallowedInEnvvar); AddOption("--throw-deprecation", "throw an exception on deprecations", + HelpSection::kErrors, BOOL_FIELD(throw_deprecation), kAllowedInEnvvar); AddOption("--trace-deprecation", "show stack traces on deprecations", + HelpSection::kErrors, BOOL_FIELD(trace_deprecation), kAllowedInEnvvar); AddOption("--trace-exit", "show stack trace when an environment exits", + HelpSection::kDiagnostics, BOOL_FIELD(trace_exit), kAllowedInEnvvar); AddOption("--trace-sync-io", "show stack trace when use of sync IO is detected after the " "first tick", + HelpSection::kDiagnostics, BOOL_FIELD(trace_sync_io), kAllowedInEnvvar); AddOption("--trace-tls", "prints TLS packet trace information to stderr", + HelpSection::kTlsCrypto, BOOL_FIELD(trace_tls), kAllowedInEnvvar); AddOption("--trace-uncaught", "show stack traces for the `throw` behind uncaught exceptions", + HelpSection::kErrors, BOOL_FIELD(trace_uncaught), kAllowedInEnvvar); AddOption("--trace-warnings", "show stack traces on process warnings", + HelpSection::kErrors, BOOL_FIELD(trace_warnings), kAllowedInEnvvar); AddOption("--trace-promises", "show stack traces on promise initialization and resolution", + HelpSection::kDiagnostics, BOOL_FIELD(trace_promises), kAllowedInEnvvar); AddOption("--trace-env", "Print accesses to the environment variables", + HelpSection::kDiagnostics, BOOL_FIELD(trace_env), kAllowedInEnvvar); Implies("--trace-env-js-stack", "--trace-env"); @@ -1393,17 +1604,20 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { AddOption("--trace-env-js-stack", "Print accesses to the environment variables and the JavaScript " "stack trace", + HelpSection::kDiagnostics, BOOL_FIELD(trace_env_js_stack), kAllowedInEnvvar); AddOption( "--trace-env-native-stack", "Print accesses to the environment variables and the native stack trace", + HelpSection::kDiagnostics, BOOL_FIELD(trace_env_native_stack), kAllowedInEnvvar); #if HAVE_OPENSSL AddOption("--use-system-ca", "use system's CA store", + HelpSection::kTlsCrypto, BOOL_FIELD(use_system_ca), kAllowedInEnvvar); #endif // HAVE_OPENSSL @@ -1412,11 +1626,13 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { "--trace-require-module", "Print access to require(esm). Options are 'all' (print all usage) and " "'no-node-modules' (excluding usage from the node_modules folder)", + HelpSection::kModules, &EnvironmentOptions::trace_require_module, kAllowedInEnvvar); AddOption("--extra-info-on-fatal-exception", "hide extra information on fatal exception that causes exit", + HelpSection::kErrors, BOOL_FIELD(extra_info_on_fatal_exception), kAllowedInEnvvar, true); @@ -1427,31 +1643,37 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { "(silence warnings), 'warn-with-error-code' (log a warning and set " "exit code 1 unless 'unhandledRejection' hook is set). (default: " "throw)", + HelpSection::kErrors, &EnvironmentOptions::unhandled_rejections, kAllowedInEnvvar); AddOption("--verify-base-objects", - "", /* undocumented, only for debugging */ + "", + HelpSection::kDiagnostics, /* undocumented, only for debugging */ BOOL_FIELD(verify_base_objects), kAllowedInEnvvar); AddOption("--watch", "run in watch mode", + HelpSection::kWatch, BOOL_FIELD(watch_mode), kAllowedInEnvvar, false, OptionNamespaces::kWatchNamespace); AddOption("--watch-path", "path to watch", + HelpSection::kWatch, &EnvironmentOptions::watch_mode_paths, kAllowedInEnvvar, OptionNamespaces::kWatchNamespace); AddOption("--watch-kill-signal", "kill signal to send to the process on watch mode restarts" "(default: SIGTERM)", + HelpSection::kWatch, &EnvironmentOptions::watch_mode_kill_signal, kAllowedInEnvvar, OptionNamespaces::kWatchNamespace); AddOption("--watch-preserve-output", "preserve outputs on watch mode restart", + HelpSection::kWatch, BOOL_FIELD(watch_mode_preserve_output), kAllowedInEnvvar, false, @@ -1459,6 +1681,7 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { Implies("--watch-path", "--watch"); AddOption("--check", "syntax check script without executing", + HelpSection::kGeneral, BOOL_FIELD(syntax_check_only)); AddAlias("-c", "--check"); // This option is only so that we can tell --eval with an empty string from @@ -1467,26 +1690,37 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { // TODO(addaleax): When moving --help over to something generated from the // programmatic descriptions, this will need some special care. // (See also [ssl_openssl_cert_store] below.) - AddOption("[has_eval_string]", "", BOOL_FIELD(has_eval_string)); - AddOption("--eval", "evaluate script", &EnvironmentOptions::eval_string); + AddOption("[has_eval_string]", + "", + HelpSection::kGeneral, + BOOL_FIELD(has_eval_string)); + AddOption("--eval", + "evaluate script", + HelpSection::kGeneral, + &EnvironmentOptions::eval_string); Implies("--eval", "[has_eval_string]"); - AddOption( - "--print", "evaluate script and print result", BOOL_FIELD(print_eval)); + AddOption("--print", + "evaluate script and print result", + HelpSection::kGeneral, + BOOL_FIELD(print_eval)); AddAlias("-e", "--eval"); AddAlias("--print ", "-pe"); AddAlias("-pe", { "--print", "--eval" }); AddAlias("-p", "--print"); AddOption("--require", "CommonJS module to preload (option can be repeated)", + HelpSection::kModules, &EnvironmentOptions::preload_cjs_modules, kAllowedInEnvvar); AddAlias("-r", "--require"); AddOption("--import", "ES module to preload (option can be repeated)", + HelpSection::kModules, &EnvironmentOptions::preload_esm_modules, kAllowedInEnvvar); AddOption("--strip-types", "Type-stripping for TypeScript files.", + HelpSection::kModules, BOOL_FIELD(strip_types), kAllowedInEnvvar, HAVE_AMARO); @@ -1494,39 +1728,48 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { AddOption("--experimental-strip-private-modules", "Type-stripping for TypeScript files under node_modules " "belonging to packages marked \"private\": true", + HelpSection::kModules, BOOL_FIELD(experimental_strip_private_modules), kAllowedInEnvvar); AddOption("--interactive", "always enter the REPL even if stdin does not appear " "to be a terminal", + HelpSection::kGeneral, BOOL_FIELD(force_repl)); AddAlias("-i", "--interactive"); - AddOption("--napi-modules", "", NoOp{}, kAllowedInEnvvar); + AddOption( + "--napi-modules", "", HelpSection::kModules, NoOp{}, kAllowedInEnvvar); AddOption("--tls-keylog", "log TLS decryption keys to named file for traffic analysis", + HelpSection::kTlsCrypto, &EnvironmentOptions::tls_keylog, kAllowedInEnvvar); AddOption("--tls-min-v1.0", "set default TLS minimum to TLSv1.0 (default: TLSv1.2)", + HelpSection::kTlsCrypto, BOOL_FIELD(tls_min_v1_0), kAllowedInEnvvar); AddOption("--tls-min-v1.1", "set default TLS minimum to TLSv1.1 (default: TLSv1.2)", + HelpSection::kTlsCrypto, BOOL_FIELD(tls_min_v1_1), kAllowedInEnvvar); AddOption("--tls-min-v1.2", "set default TLS minimum to TLSv1.2 (default: TLSv1.2)", + HelpSection::kTlsCrypto, BOOL_FIELD(tls_min_v1_2), kAllowedInEnvvar); AddOption("--tls-min-v1.3", "set default TLS minimum to TLSv1.3 (default: TLSv1.2)", + HelpSection::kTlsCrypto, BOOL_FIELD(tls_min_v1_3), kAllowedInEnvvar); AddOption("--tls-max-v1.2", "set default TLS maximum to TLSv1.2 (default: TLSv1.3)", + HelpSection::kTlsCrypto, BOOL_FIELD(tls_max_v1_2), kAllowedInEnvvar); // Current plan is: @@ -1535,17 +1778,20 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { // In either case, support both options they are uniformly available. AddOption("--tls-max-v1.3", "set default TLS maximum to TLSv1.3 (default: TLSv1.3)", + HelpSection::kTlsCrypto, BOOL_FIELD(tls_max_v1_3), kAllowedInEnvvar); AddOption("--report-exclude-env", "Exclude environment variables when generating report" " (default: false)", + HelpSection::kDiagnostics, BOOL_FIELD(report_exclude_env), kAllowedInEnvvar); AddOption("--report-exclude-network", "exclude network interface diagnostics." " (default: false)", + HelpSection::kDiagnostics, BOOL_FIELD(report_exclude_network), kAllowedInEnvvar); } @@ -1555,11 +1801,13 @@ PerIsolateOptionsParser::PerIsolateOptionsParser( AddOption("--worker-snapshot", "start worker threads from the bootstrapped context in the " "built-in startup snapshot", + HelpSection::kSnapshots, BOOL_FIELD(worker_snapshot), kAllowedInEnvvar, true); AddOption("--track-heap-objects", "track heap object allocations for heap snapshots", + HelpSection::kDiagnostics, BOOL_FIELD(track_heap_objects), kAllowedInEnvvar); @@ -1567,73 +1815,108 @@ PerIsolateOptionsParser::PerIsolateOptionsParser( AddOption("--abort-on-uncaught-exception", "aborting instead of exiting causes a core file to be generated " "for analysis", + HelpSection::kErrors, V8Option{}, kAllowedInEnvvar); AddOption("--interpreted-frames-native-stack", "help system profilers to translate JavaScript interpreted frames", + HelpSection::kDiagnostics, + V8Option{}, + kAllowedInEnvvar); + AddOption( + "--max-heap-size", "", HelpSection::kV8, V8Option{}, kAllowedInEnvvar); + AddOption("--max-old-space-size", + "", + HelpSection::kV8, V8Option{}, kAllowedInEnvvar); - AddOption("--max-heap-size", "", V8Option{}, kAllowedInEnvvar); - AddOption("--max-old-space-size", "", V8Option{}, kAllowedInEnvvar); AddOption("--max-old-space-size-percentage", "set V8's max old space size as a percentage of available memory " "(e.g., '50%'). Takes precedence over --max-old-space-size.", + HelpSection::kV8, &PerIsolateOptions::max_old_space_size_percentage, kAllowedInEnvvar); - AddOption("--max-semi-space-size", "", V8Option{}, kAllowedInEnvvar); - AddOption("--perf-basic-prof", "", V8Option{}, kAllowedInEnvvar); + AddOption("--max-semi-space-size", + "", + HelpSection::kV8, + V8Option{}, + kAllowedInEnvvar); AddOption( - "--perf-basic-prof-only-functions", "", V8Option{}, kAllowedInEnvvar); - AddOption("--perf-prof", "", V8Option{}, kAllowedInEnvvar); - AddOption("--perf-prof-unwinding-info", "", V8Option{}, kAllowedInEnvvar); + "--perf-basic-prof", "", HelpSection::kV8, V8Option{}, kAllowedInEnvvar); + AddOption("--perf-basic-prof-only-functions", + "", + HelpSection::kV8, + V8Option{}, + kAllowedInEnvvar); + AddOption("--perf-prof", "", HelpSection::kV8, V8Option{}, kAllowedInEnvvar); + AddOption("--perf-prof-unwinding-info", + "", + HelpSection::kV8, + V8Option{}, + kAllowedInEnvvar); AddOption("--stack-trace-limit", "", + HelpSection::kV8, &PerIsolateOptions::stack_trace_limit, kAllowedInEnvvar); AddOption("--disallow-code-generation-from-strings", "disallow eval and friends", + HelpSection::kSecurity, V8Option{}, kAllowedInEnvvar); AddOption("--jitless", "disable runtime allocation of executable memory", + HelpSection::kV8, V8Option{}, kAllowedInEnvvar); AddOption("--report-uncaught-exception", "generate diagnostic report on uncaught exceptions", + HelpSection::kDiagnostics, BOOL_FIELD(report_uncaught_exception), kAllowedInEnvvar); AddOption("--report-on-signal", "generate diagnostic report upon receiving signals", + HelpSection::kDiagnostics, BOOL_FIELD(report_on_signal), kAllowedInEnvvar); AddOption("--report-signal", "causes diagnostic report to be produced on provided signal," " unsupported in Windows. (default: SIGUSR2)", + HelpSection::kDiagnostics, &PerIsolateOptions::report_signal, kAllowedInEnvvar); Implies("--report-signal", "--report-on-signal"); AddOption("--enable-etw-stack-walking", "provides heap data to ETW Windows native tracing", + HelpSection::kDiagnostics, V8Option{}, kAllowedInEnvvar); - AddOption("--experimental-top-level-await", "", NoOp{}, kAllowedInEnvvar); + AddOption("--experimental-top-level-await", + "", + HelpSection::kModules, + NoOp{}, + kAllowedInEnvvar); AddOption("--experimental-shadow-realm", "", + HelpSection::kBuiltinApis, BOOL_FIELD(experimental_shadow_realm), kAllowedInEnvvar); - AddOption("--harmony-shadow-realm", "", V8Option{}); + AddOption( + "--harmony-shadow-realm", "", HelpSection::kBuiltinApis, V8Option{}); Implies("--experimental-shadow-realm", "--harmony-shadow-realm"); Implies("--harmony-shadow-realm", "--experimental-shadow-realm"); ImpliesNot("--no-harmony-shadow-realm", "--experimental-shadow-realm"); AddOption("--build-snapshot", "Generate a snapshot blob when the process exits.", + HelpSection::kSnapshots, BOOL_FIELD(build_snapshot), kDisallowedInEnvvar); AddOption("--build-snapshot-config", "Generate a snapshot blob when the process exits using a" "JSON configuration in the specified path.", + HelpSection::kSnapshots, &PerIsolateOptions::build_snapshot_config, kDisallowedInEnvvar); Implies("--build-snapshot-config", "--build-snapshot"); @@ -1645,83 +1928,107 @@ PerProcessOptionsParser::PerProcessOptionsParser( const PerIsolateOptionsParser& iop) { AddOption("--title", "the process title to use on startup", + HelpSection::kGeneral, &PerProcessOptions::title, kAllowedInEnvvar); AddOption("--trace-event-categories", "comma separated list of trace event categories to record", + HelpSection::kDiagnostics, &PerProcessOptions::trace_event_categories, kAllowedInEnvvar); AddOption("--trace-event-file-pattern", "Template string specifying the filepath for the trace-events " "data, it supports ${rotation} and ${pid}.", + HelpSection::kDiagnostics, &PerProcessOptions::trace_event_file_pattern, kAllowedInEnvvar); AddAlias("--trace-events-enabled", { "--trace-event-categories", "v8,node,node.async_hooks" }); AddOption("--v8-pool-size", "set V8's thread pool size", + HelpSection::kV8, &PerProcessOptions::v8_thread_pool_size, kAllowedInEnvvar); AddOption("--zero-fill-buffers", "automatically zero-fill all newly allocated Buffer instances", + HelpSection::kSecurity, BOOL_FIELD(zero_fill_all_buffers), kAllowedInEnvvar); AddOption("--debug-arraybuffer-allocations", - "", /* undocumented, only for debugging */ + "", + HelpSection::kDiagnostics, /* undocumented, only for debugging */ BOOL_FIELD(debug_arraybuffer_allocations), kAllowedInEnvvar); AddOption("--disable-proto", "disable Object.prototype.__proto__", + HelpSection::kSecurity, &PerProcessOptions::disable_proto, kAllowedInEnvvar); AddOption("--node-snapshot", - "", // It's a debug-only option. + "", + HelpSection::kSnapshots, // It's a debug-only option. BOOL_FIELD(node_snapshot), kAllowedInEnvvar); AddOption("--snapshot-blob", "Path to the snapshot blob that's either the result of snapshot" "building, or the blob that is used to restore the application " "state", + HelpSection::kSnapshots, &PerProcessOptions::snapshot_blob, kAllowedInEnvvar); // 12.x renamed this inadvertently, so alias it for consistency within the // release line, while using the original name for consistency with older // release lines. - AddOption("--security-revert", "", &PerProcessOptions::security_reverts); + AddOption("--security-revert", + "", + HelpSection::kSecurity, + &PerProcessOptions::security_reverts); AddAlias("--security-reverts", "--security-revert"); AddOption("--completion-bash", "print source-able bash completion script", + HelpSection::kGeneral, BOOL_FIELD(print_bash_completion)); - AddOption( - "--help", "print node command line options", BOOL_FIELD(print_help)); + AddOption("--help", + "print node command line options", + HelpSection::kGeneral, + BOOL_FIELD(print_help)); AddAlias("-h", "--help"); - AddOption("--version", "print Node.js version", BOOL_FIELD(print_version)); + AddOption("--version", + "print Node.js version", + HelpSection::kGeneral, + BOOL_FIELD(print_version)); AddAlias("-v", "--version"); AddOption("--v8-options", "print V8 command line options", + HelpSection::kV8, BOOL_FIELD(print_v8_help)); AddOption("--report-compact", "output compact single-line JSON", + HelpSection::kDiagnostics, BOOL_FIELD(report_compact), kAllowedInEnvvar); AddOption("--report-dir", "define custom report pathname." " (default: current working directory)", + HelpSection::kDiagnostics, &PerProcessOptions::report_directory, kAllowedInEnvvar); AddAlias("--report-directory", "--report-dir"); AddOption("--report-filename", "define custom report file name." " (default: YYYYMMDD.HHMMSS.PID.SEQUENCE#.txt)", + HelpSection::kDiagnostics, &PerProcessOptions::report_filename, kAllowedInEnvvar); AddOption("--report-on-fatalerror", "generate diagnostic report on fatal (internal) errors", + HelpSection::kDiagnostics, BOOL_FIELD(report_on_fatalerror), kAllowedInEnvvar); AddOption("--report-on-process-timeout", "generate diagnostic report when --process-timeout expires", + HelpSection::kDiagnostics, BOOL_FIELD(report_on_process_timeout)); #ifdef NODE_HAVE_I18N_SUPPORT @@ -1731,6 +2038,7 @@ PerProcessOptionsParser::PerProcessOptionsParser( " (note: linked-in ICU data is present)" #endif , + HelpSection::kGeneral, &PerProcessOptions::icu_data_dir, kAllowedInEnvvar); #endif @@ -1739,10 +2047,12 @@ PerProcessOptionsParser::PerProcessOptionsParser( AddOption("--openssl-config", "load OpenSSL configuration from the specified file " "(overrides OPENSSL_CONF)", + HelpSection::kTlsCrypto, &PerProcessOptions::openssl_config, kAllowedInEnvvar); AddOption("--tls-cipher-list", "use an alternative default TLS cipher list", + HelpSection::kTlsCrypto, &PerProcessOptions::tls_cipher_list, kAllowedInEnvvar); AddOption("--use-openssl-ca", @@ -1751,6 +2061,7 @@ PerProcessOptionsParser::PerProcessOptionsParser( " (default)" #endif , + HelpSection::kTlsCrypto, BOOL_FIELD(use_openssl_ca), kAllowedInEnvvar); AddOption("--use-bundled-ca", @@ -1759,39 +2070,49 @@ PerProcessOptionsParser::PerProcessOptionsParser( " (default)" #endif , + HelpSection::kTlsCrypto, BOOL_FIELD(use_bundled_ca), kAllowedInEnvvar); // Similar to [has_eval_string] above, except that the separation between // this and use_openssl_ca only exists for option validation after parsing. // This is not ideal. - AddOption("[ssl_openssl_cert_store]", "", BOOL_FIELD(ssl_openssl_cert_store)); + AddOption("[ssl_openssl_cert_store]", + "", + HelpSection::kTlsCrypto, + BOOL_FIELD(ssl_openssl_cert_store)); Implies("--use-openssl-ca", "[ssl_openssl_cert_store]"); ImpliesNot("--use-bundled-ca", "[ssl_openssl_cert_store]"); AddOption("--enable-fips", "enable FIPS crypto at startup", + HelpSection::kTlsCrypto, BOOL_FIELD(enable_fips_crypto), kAllowedInEnvvar); AddOption("--enable-fips-indicator-events", "publish FIPS indicator results to the " "crypto.fips.indicator diagnostics channel", + HelpSection::kTlsCrypto, BOOL_FIELD(enable_fips_indicator_events), kAllowedInEnvvar); AddOption("--force-fips", "force FIPS crypto (optional mode: provider or strict)", + HelpSection::kTlsCrypto, BOOL_FIELD(force_fips_crypto), kAllowedInEnvvar); AddOption("[force_fips_crypto_policy]", "", + HelpSection::kTlsCrypto, &PerProcessOptions::force_fips_crypto_policy, kAllowedInEnvvar); AddAlias("--force-fips=", {"[force_fips_crypto_policy]", "--force-fips"}); #ifndef V8_ENABLE_SANDBOX AddOption("--secure-heap", "total size of the OpenSSL secure heap", + HelpSection::kTlsCrypto, &PerProcessOptions::secure_heap, kAllowedInEnvvar); AddOption("--secure-heap-min", "minimum allocation size from the OpenSSL secure heap", + HelpSection::kTlsCrypto, &PerProcessOptions::secure_heap_min, kAllowedInEnvvar); #endif // V8_ENABLE_SANDBOX @@ -1799,10 +2120,12 @@ PerProcessOptionsParser::PerProcessOptionsParser( #if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL) AddOption("--openssl-legacy-provider", "enable OpenSSL's legacy provider", + HelpSection::kTlsCrypto, BOOL_FIELD(openssl_legacy_provider), kAllowedInEnvvar); AddOption("--openssl-shared-config", "enable OpenSSL shared configuration", + HelpSection::kTlsCrypto, BOOL_FIELD(openssl_shared_config), kAllowedInEnvvar); @@ -1811,23 +2134,27 @@ PerProcessOptionsParser::PerProcessOptionsParser( "This option is no longer supported and a no-op. It still accepts" " these values for compatibility: 'off' (default), 'on' (report a " "warning to stderr), or 'silent' (same as 'off').", + HelpSection::kV8, &PerProcessOptions::use_largepages, kAllowedInEnvvar); AddOption("--trace-sigint", "enable printing JavaScript stacktrace on SIGINT", + HelpSection::kDiagnostics, BOOL_FIELD(trace_sigint), kAllowedInEnvvar); AddOption("--process-timeout", "print why the process is still running and exit with code 124 " "if it has not exited after the given duration (e.g. 30s)", + HelpSection::kGeneral, &PerProcessOptions::process_timeout); Insert(iop, &PerProcessOptions::get_per_isolate_options); AddOption("--node-memory-debug", "Run with extra debug checks for memory leaks in Node.js itself", + HelpSection::kDiagnostics, NoOp{}, kAllowedInEnvvar); Implies("--node-memory-debug", "--debug-arraybuffer-allocations"); @@ -1836,21 +2163,25 @@ PerProcessOptionsParser::PerProcessOptionsParser( AddOption("--experimental-sea-config", "Generate a blob that can be embedded into the single executable " "application", + HelpSection::kSnapshots, &PerProcessOptions::experimental_sea_config); AddOption("--run", "Run a script specified in package.json", + HelpSection::kGeneral, &PerProcessOptions::run); AddOption( "--disable-wasm-trap-handler", "Disable trap-handler-based WebAssembly bound checks. V8 will insert " "inline bound checks when compiling WebAssembly which may slow down " "performance.", + HelpSection::kV8, BOOL_FIELD(disable_wasm_trap_handler), kAllowedInEnvvar); AddOption("--build-sea", "Build a Node.js single executable application", + HelpSection::kSnapshots, &PerProcessOptions::build_sea); } @@ -2178,15 +2509,17 @@ void GetCLIOptionsInfo(const FunctionCallbackInfo& args) { !ToV8Value(context, option_info.help_text).ToLocal(&help_text)) { return; } - constexpr size_t kInfoSize = 4; + constexpr size_t kInfoSize = 5; std::array, kInfoSize> names = { env->help_text_string(), + env->help_section_string(), env->env_var_settings_string(), env->type_string(), env->default_is_true_string(), }; std::array, kInfoSize> values = { help_text, + Integer::New(isolate, static_cast(option_info.help_section)), Integer::New(isolate, static_cast(option_info.env_setting)), Integer::New(isolate, static_cast(option_info.type)), Boolean::New(isolate, option_info.default_is_true), @@ -2535,6 +2868,18 @@ void Initialize(Local target, NODE_DEFINE_CONSTANT(types, kStringList); target->Set(context, FIXED_ONE_BYTE_STRING(isolate, "types"), types) .Check(); + + // Titles of the --help output sections, indexed by HelpSection. + Local help_sections[] = { +#define V(_, title) FIXED_ONE_BYTE_STRING(isolate, title), + OPTION_HELP_SECTION_LIST(V) +#undef V + }; + target + ->Set(context, + FIXED_ONE_BYTE_STRING(isolate, "helpSections"), + Array::New(isolate, help_sections, arraysize(help_sections))) + .Check(); } void RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_options.h b/src/node_options.h index 69d590802311..df183704f37e 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -534,6 +534,32 @@ inline const std::string NamespaceEnumToString(OptionNamespaces ns) { } } +// Sections of the `node --help` output, in the order they are printed. Every +// option is assigned to one of these by the AddOption() call that defines it. +// kGeneral must stay first: print_help.js places `-` and `--` in section 0. +#define OPTION_HELP_SECTION_LIST(V) \ + V(kGeneral, "General") \ + V(kModules, "Modules") \ + V(kBuiltinApis, "Built-in APIs") \ + V(kWatch, "Watch mode") \ + V(kTestRunner, "Test runner") \ + V(kBenchRunner, "Benchmark runner") \ + V(kDebugging, "Debugging and inspector") \ + V(kDiagnostics, "Diagnostics and profiling") \ + V(kErrors, "Errors and warnings") \ + V(kPermissions, "Permissions") \ + V(kSecurity, "Security hardening") \ + V(kNetworking, "Networking") \ + V(kTlsCrypto, "TLS and crypto") \ + V(kSnapshots, "Snapshots and single executables") \ + V(kV8, "V8 and memory") + +enum class HelpSection { +#define V(name, _) name, + OPTION_HELP_SECTION_LIST(V) +#undef V +}; + inline constexpr auto AllNamespaces() { return std::array{ #define V(name, _) OptionNamespaces::name, @@ -562,6 +588,7 @@ class OptionsParser { void AddOption( const char* name, const char* help_text, + HelpSection help_section, bool (*getter)(Options*), void (*setter)(Options*, bool), OptionEnvvarSettings env_setting = kDisallowedInEnvvar, @@ -569,6 +596,7 @@ class OptionsParser { OptionNamespaces namespace_id = OptionNamespaces::kNoNamespace); void AddOption(const char* name, const char* help_text, + HelpSection help_section, uint64_t Options::*field, OptionEnvvarSettings env_setting = kDisallowedInEnvvar, OptionNamespaces namespace_id = OptionNamespaces::kNoNamespace, @@ -576,36 +604,42 @@ class OptionsParser { void AddOption( const char* name, const char* help_text, + HelpSection help_section, int64_t Options::*field, OptionEnvvarSettings env_setting = kDisallowedInEnvvar, OptionNamespaces namespace_id = OptionNamespaces::kNoNamespace); void AddOption( const char* name, const char* help_text, + HelpSection help_section, std::string Options::*field, OptionEnvvarSettings env_setting = kDisallowedInEnvvar, OptionNamespaces namespace_id = OptionNamespaces::kNoNamespace); void AddOption( const char* name, const char* help_text, + HelpSection help_section, std::vector Options::*field, OptionEnvvarSettings env_setting = kDisallowedInEnvvar, OptionNamespaces namespace_id = OptionNamespaces::kNoNamespace); void AddOption( const char* name, const char* help_text, + HelpSection help_section, HostPort Options::*field, OptionEnvvarSettings env_setting = kDisallowedInEnvvar, OptionNamespaces namespace_id = OptionNamespaces::kNoNamespace); void AddOption( const char* name, const char* help_text, + HelpSection help_section, NoOp no_op_tag, OptionEnvvarSettings env_setting = kDisallowedInEnvvar, OptionNamespaces namespace_id = OptionNamespaces::kNoNamespace); void AddOption( const char* name, const char* help_text, + HelpSection help_section, V8Option v8_option_tag, OptionEnvvarSettings env_setting = kDisallowedInEnvvar, OptionNamespaces namespace_id = OptionNamespaces::kNoNamespace); @@ -731,11 +765,13 @@ class OptionsParser { // - The information of whether it may occur in an env var or not. // - A default value (if applicable). // - A namespace ID (optional) to allow for namespacing of options. + // - The section of the --help output that the option is listed in. struct OptionInfo { OptionType type; std::shared_ptr field; OptionEnvvarSettings env_setting; std::string help_text; + HelpSection help_section; bool default_is_true = false; std::string namespace_id; bool strict = false; diff --git a/test/parallel/test-cli-node-print-help-sections.js b/test/parallel/test-cli-node-print-help-sections.js new file mode 100644 index 000000000000..4f2af0f828b4 --- /dev/null +++ b/test/parallel/test-cli-node-print-help-sections.js @@ -0,0 +1,80 @@ +// Flags: --expose-internals +'use strict'; + +// Tests that `node --help` groups options into the sections that +// node_options.cc assigns them to. + +require('../common'); +const assert = require('assert'); +const { spawnSync } = require('child_process'); +const { internalBinding } = require('internal/test/binding'); +const { getCLIOptionsInfo } = require('internal/options'); + +const { + helpSections, + getNamespaceOptionsInputType, +} = internalBinding('options'); + +assert.ok(Array.isArray(helpSections)); +assert.ok(helpSections.length > 0); +// print_help.js puts `-` and `--` in section 0. +assert.strictEqual(helpSections[0], 'General'); +assert.strictEqual(new Set(helpSections).size, helpSections.length); + +const { options } = getCLIOptionsInfo(); +for (const [name, { helpSection }] of options) { + assert.ok(Number.isInteger(helpSection) && + helpSection >= 0 && helpSection < helpSections.length, + `${name} has invalid help section ${helpSection}`); +} + +// Options in a config file namespace belong in that namespace's section. +const namespaceSections = { + bench: 'Benchmark runner', + permission: 'Permissions', + test: 'Test runner', + watch: 'Watch mode', +}; +for (const [namespace, nsOptions] of getNamespaceOptionsInputType()) { + const expected = namespaceSections[namespace]; + assert.ok(expected, `no expected help section for namespace ${namespace}`); + for (const name of Object.keys(nsOptions)) { + assert.strictEqual(helpSections[options.get(name).helpSection], expected, + `${name} is in namespace ${namespace}`); + } +} + +// Every non-empty section is printed once, in order, and each documented +// option is listed under its own section. +const { stdout, status } = spawnSync(process.execPath, ['--help'], { + env: { ...process.env, NO_COLOR: '1', FORCE_COLOR: undefined }, + encoding: 'utf8', +}); +assert.strictEqual(status, 0); + +const printed = new Map(); // Section title -> text of that section. +let current; +for (const line of stdout.split('\n')) { + if (line === 'Environment variables:') break; + const heading = /^(\S.*):$/.exec(line); + if (heading && helpSections.includes(heading[1])) { + assert.ok(!printed.has(heading[1]), `${heading[1]} printed twice`); + current = heading[1]; + printed.set(current, ''); + } else if (current !== undefined) { + printed.set(current, printed.get(current) + line + '\n'); + } +} +assert.deepStrictEqual([...printed.keys()], + helpSections.filter((title) => printed.has(title))); + +for (const [name, { helpText, helpSection, defaultIsTrue }] of options) { + if (!helpText) continue; + const title = helpSections[helpSection]; + const shown = defaultIsTrue ? `--no-${name.slice(2)}` : name; + // Names are printed at the start of a line, possibly after aliases + // (e.g. `-e, --eval=...`). + const listed = new RegExp(`^ (?:\\S+, )*${RegExp.escape(shown)}(?:[=\\s\\[]|$)`, 'm'); + assert.match(printed.get(title) ?? '', listed, + `${shown} not listed under ${title}`); +} From 0ce036fc158e95d251382708689fdf30d2fce1c0 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Mon, 23 Nov 2026 01:21:51 +0000 Subject: [PATCH 3/4] doc: group cli.md options into help sections Group the options in doc/api/cli.md into the same sections as `node --help`, and check in test-cli-node-options-docs that each option is documented in its section. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/cli.md | 5318 +++++++++-------- .../test-cli-node-cli-manpage-options.mjs | 3 +- test/parallel/test-cli-node-options-docs.js | 55 +- 3 files changed, 2760 insertions(+), 2616 deletions(-) diff --git a/doc/api/cli.md b/doc/api/cli.md index a4e27926b00c..60f04a8037ae 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -63,7 +63,15 @@ passed more than once, then the last passed value is used. Options from the command line take precedence over options passed through the [`NODE_OPTIONS`][] environment variable. -### `-` +Options are grouped into the same sections as the output of `node --help`. + +### General + + + +#### `-` -Aborting instead of exiting causes a core file to be generated for post-mortem -analysis using a debugger (such as `lldb`, `gdb`, and `mdb`). - -If this flag is passed, the behavior can still be set to not abort through -[`process.setUncaughtExceptionCaptureCallback()`][] (and through usage of the -`node:domain` module that uses it). +Syntax check the script without executing. -### `--allow-addons` +#### `--completion-bash` -> Stability: 1.1 - Active development +Print source-able bash completion script for Node.js. -When using the [Permission Model][], the process will not be able to use -native addons by default. -Attempts to do so will throw an `ERR_DLOPEN_DISABLED` unless the -user explicitly passes the `--allow-addons` flag when starting Node.js. +```bash +node --completion-bash > node_bash_completion +source node_bash_completion +``` -Example: +#### `--config-file=path`, `--config-file` -```cjs -// Attempt to require an native addon -require('nodejs-addon-example'); -``` + -```console -$ node --permission --allow-fs-read=* index.js -node:internal/modules/cjs/loader:1319 - return process.dlopen(module, path.toNamespacedPath(filename)); - ^ +If present, Node.js will look for a configuration file at the specified path. +If the path is not specified, Node.js will look for a `node.config.json` file +in the current working directory. +To specify a custom path, use the `--config-file=path` form. +The space-separated `--config-file path` form is not supported. +Node.js will read the configuration file and apply the settings. The +configuration file should be a JSON file with the following structure. `vX.Y.Z` +in the `$schema` must be replaced with the version of Node.js you are using or +`latest-vX.x` for the latest version of that major release line. -Error: Cannot load native addon because loading addons is disabled. - at Module._extensions..node (node:internal/modules/cjs/loader:1319:18) - at Module.load (node:internal/modules/cjs/loader:1091:32) - at Module._load (node:internal/modules/cjs/loader:938:12) - at Module.require (node:internal/modules/cjs/loader:1115:19) - at require (node:internal/modules/helpers:130:18) - at Object. (/home/index.js:1:15) - at Module._compile (node:internal/modules/cjs/loader:1233:14) - at Module._extensions..js (node:internal/modules/cjs/loader:1287:10) - at Module.load (node:internal/modules/cjs/loader:1091:32) - at Module._load (node:internal/modules/cjs/loader:938:12) { - code: 'ERR_DLOPEN_DISABLED' +```json +{ + "$schema": "https://nodejs.org/dist/vX.Y.Z/docs/node-config-schema.json", + "nodeOptions": { + "import": [ + "amaro/strip" + ], + "watch-path": "src", + "watch-preserve-output": true + }, + "test": { + "test-isolation": "process" + }, + "watch": { + "watch-preserve-output": true + } } ``` -### `--allow-child-process` - - +The configuration file supports namespace-specific options: -> Stability: 1.1 - Active development +* The `nodeOptions` field contains CLI flags that are allowed in [`NODE_OPTIONS`][]. -When using the [Permission Model][], the process will not be able to spawn any -child process by default. -Attempts to do so will throw an `ERR_ACCESS_DENIED` unless the -user explicitly passes the `--allow-child-process` flag when starting Node.js. +* Namespace fields like `test`, `watch`, and `permission` contain configuration specific to that subsystem. -Example: +The configuration file can target a specific Node.js major version with +`nodeVersion`: -```js -const childProcess = require('node:child_process'); -// Attempt to bypass the permission -childProcess.spawn('node', ['-e', 'require("fs").writeFileSync("/new-file", "example")']); +```json +{ + "nodeVersion": 25, + "nodeOptions": { + "watch-path": "src" + } +} ``` -```console -$ node --permission --allow-fs-read=* index.js -node:internal/child_process:388 - const err = this._handle.spawn(options); - ^ -Error: Access to this API has been restricted - at ChildProcess.spawn (node:internal/child_process:388:28) - at node:internal/main/run_main_module:17:47 { - code: 'ERR_ACCESS_DENIED', - permission: 'ChildProcess' +To keep multiple version-specific configurations in the same file, use the +`configs` array. Node.js will use the first entry whose `nodeVersion` matches +the current Node.js major version: + +```json +{ + "$schema": "https://nodejs.org/dist/latest-v26.x/docs/node-config-schema.json", + "configs": [ + { + "nodeVersion": 25, + "config": { + "$schema": "https://nodejs.org/dist/latest-v25.x/docs/node-config-schema.json", + "nodeOptions": { + "watch-path": "src" + } + } + } + ] } ``` -The `child_process.fork()` API inherits the execution arguments from the -parent process. This means that if Node.js is started with the Permission -Model enabled and the `--allow-child-process` flag is set, any child process -created using `child_process.fork()` will automatically receive all relevant -Permission Model flags. +When `configs` is used, the top level may only contain `$schema` and +`configs`. Each `configs` item must define an integer `nodeVersion` and an +object `config`. A single top-level config does not require `nodeVersion`, but +if present it must match the current Node.js major version. -This behavior also applies to `child_process.spawn()`, but in that case, the -flags are propagated via the `NODE_OPTIONS` environment variable rather than -directly through the process arguments. +When a namespace is present in the +configuration file, Node.js automatically enables the corresponding flag +(e.g., `--test`, `--watch`, `--permission`). This allows you to configure +subsystem-specific options without explicitly passing the flag on the command line. -### `--allow-env` +For example: - +```json +{ + "test": { + "test-isolation": "process" + } +} +``` -> Stability: 1.1 - Active development +is equivalent to: -When using the [Permission Model][], the process starts without the environment -variables it has not been granted access to. At startup, every variable that -`--allow-env` does not match is removed from the process environment. Removed -variables are absent from `process.env`, from diagnostic reports, from native -code calling `getenv()`, and from the environment of child processes and worker -threads. +```bash +node --test --test-isolation=process +``` -The valid values are: +To disable the automatic flag while still using namespace options, you can +explicitly set the flag to `false` within the namespace: -* `*` - Grants access to every environment variable. -* A variable name, for example `--allow-env=DATABASE_URL`. -* A variable name prefix followed by `*`, for example `--allow-env=APP_*`. +```json +{ + "test": { + "test": false, + "test-isolation": "process" + } +} +``` -Multiple values can be passed by repeating the flag, or by separating them with -commas: `--allow-env=PORT,APP_*`. Variable names are case-insensitive on -Windows. +No-op flags are not supported. +Not all V8 flags are currently supported. -Example: +It is possible to use the [official JSON schema](../node-config-schema.json) +to validate the configuration file, which may vary depending on the Node.js version. +Each key in the configuration file corresponds to a flag that can be passed +as a command-line argument. The value of the key is the value that would be +passed to the flag. -```js -console.log(process.env.DATABASE_URL); -console.log(process.env.AWS_SECRET_ACCESS_KEY); -``` +For example, the configuration file above is equivalent to +the following command-line arguments: -```console -$ node --permission --allow-fs-read=* --allow-env=DATABASE_URL index.js -postgres://localhost/app -undefined -(node:1234) Warning: The permission model removed the environment variable "AWS_SECRET_ACCESS_KEY" at startup. Use --allow-env to manage permissions. +```bash +node --import amaro/strip --watch-path=src --watch-preserve-output --test-isolation=process ``` -The variables that Node.js and its bundled dependencies read, such as -`NODE_OPTIONS`, `PATH`, `HOME`, `TZ`, and `SSL_CERT_FILE`, are always kept, as -are the variables defined in [`--env-file`][] files. `NODE_ENV` is not kept -by default, so applications and libraries that read it need -`--allow-env=NODE_ENV`. See [Environment variable permissions][] for details. +The priority in configuration is as follows: -### `--allow-ffi` +1. NODE\_OPTIONS and command-line options +2. Dotenv NODE\_OPTIONS +3. Configuration file - +Values in the configuration file will not override the values in the environment +variables, command-line options, or the `NODE_OPTIONS` env file parsed by the +`--env-file` flag. -> Stability: 1.1 - Active development +Keys cannot be duplicated within the same or different namespaces. -When using the [Permission Model][], the process will not be able to use FFI -APIs by default. Attempts to use FFI APIs will throw an `ERR_ACCESS_DENIED` -exception unless the user explicitly passes the `--allow-ffi` flag when -starting Node.js. The [`node:ffi`][] module is only available in builds with -FFI support. - -Example: - -```js -const { DynamicLibrary, suffix } = require('node:ffi'); -const lib = new DynamicLibrary(`./mylib.${suffix}`); -``` +The configuration parser will throw an error if the configuration file contains +unknown keys or keys that cannot be used in a namespace. -```console -$ node --permission index.js -Error: Access to this API has been restricted. Use --allow-ffi to manage permissions. - at node:internal/main/run_main_module:17:47 { - code: 'ERR_ACCESS_DENIED', - permission: 'FFI' -} -``` +Node.js will not sanitize or perform validation on the user-provided configuration, +so **NEVER** use untrusted configuration files. -### `--allow-fs-read` +#### `--entry-url` -This flag configures file system read permissions using -the [Permission Model][]. - -The valid arguments for the `--allow-fs-read` flag are: - -* `*` - To allow all `FileSystemRead` operations. -* Multiple paths can be allowed using multiple `--allow-fs-read` flags. - Example `--allow-fs-read=/folder1/ --allow-fs-read=/folder2/` - -Examples can be found in the [File System Permissions][] documentation. +> Stability: 1 - Experimental -The initializer module and custom `--require` modules have an implicit -read permission. The entrypoint is granted as passed on the command line, -without the module loader's resolution; see the [File System Permissions][] -documentation for details. +When present, Node.js will interpret the entry point as a URL, rather than a +path. -```console -$ node --permission -r custom-require.js -r custom-require-2.js index.js -``` +Follows [ECMAScript module][] resolution rules. -* The `custom-require.js`, `custom-require-2.js`, and `index.js` will be - by default in the allowed read list. +Any query parameter or hash in the URL will be accessible via [`import.meta.url`][]. -```js -process.permission.has('fs.read', 'index.js'); // true -process.permission.has('fs.read', 'custom-require.js'); // true -process.permission.has('fs.read', 'custom-require-2.js'); // true +```bash +node --entry-url 'file:///path/to/file.js?queryparams=work#and-hashes-too' +node --entry-url 'file.ts?query#hash' +node --entry-url 'data:text/javascript,console.log("Hello")' ``` -### `--allow-fs-vfs` +#### `--env-file-if-exists=file` -> Stability: 1.1 - Active development - -When using the [Permission Model][], a [virtual file system][] cannot be -mounted by default: [`vfs.mount()`][] throws `ERR_INVALID_STATE` unless the -user explicitly passes the `--allow-fs-vfs` flag when starting Node.js. -In audit mode ([`--permission-audit`](#--permission-audit)), mounting is not -refused and no message is published to the diagnostics channel. - -A mounted VFS serves paths that the file system permissions do not describe, -so mounting one is gated on its own flag rather than on `--allow-fs-read` or -`--allow-fs-write`. - -```console -$ node --permission --allow-fs-vfs app.js -``` +Behavior is the same as [`--env-file`][], but an error is not thrown if the file +does not exist. -### `--allow-fs-write` +#### `--env-file=file` -This flag configures file system write permissions using -the [Permission Model][]. - -The valid arguments for the `--allow-fs-write` flag are: +Loads environment variables from a file relative to the current directory, +making them available to applications on `process.env`. The [environment +variables which configure Node.js][environment_variables], such as `NODE_OPTIONS`, +are parsed and applied. If the same variable is defined in the environment and +in the file, the value from the environment takes precedence. -* `*` - To allow all `FileSystemWrite` operations. -* Multiple paths can be allowed using multiple `--allow-fs-write` flags. - Example `--allow-fs-write=/folder1/ --allow-fs-write=/folder2/` +You can pass multiple `--env-file` arguments. Subsequent files override +pre-existing variables defined in previous files. -Paths delimited by comma (`,`) are no longer allowed. -When passing a single flag with a comma a warning will be displayed. +An error is thrown if the file does not exist. -Examples can be found in the [File System Permissions][] documentation. +```bash +node --env-file=.env --env-file=.development.env index.js +``` -### `--allow-inspector` +The format of the file should be one line per key-value pair of environment +variable name and value separated by `=`: - +```text +PORT=3000 +``` -> Stability: 1.0 - Early development +Any text after a `#` is treated as a comment: -When using the [Permission Model][], the process will not be able to connect -through inspector protocol. +```text +# This is a comment +PORT=3000 # This is also a comment +``` -Attempts to do so will throw an `ERR_ACCESS_DENIED` unless the -user explicitly passes the `--allow-inspector` flag when starting Node.js. +Values can start and end with the following quotes: `` ` ``, `"` or `'`. +They are omitted from the values. -Example: +```text +USERNAME="nodejs" # will result in `nodejs` as the value. +``` -```js -const { Session } = require('node:inspector/promises'); +Multi-line values are supported: -const session = new Session(); -session.connect(); +```text +MULTI_LINE="THIS IS +A MULTILINE" +# will result in `THIS IS\nA MULTILINE` as the value. ``` -```console -$ node --permission index.js -Error: connect ERR_ACCESS_DENIED Access to this API has been restricted. Use --allow-inspector to manage permissions. - code: 'ERR_ACCESS_DENIED', -} +Export keyword before a key is ignored: + +```text +export USERNAME="nodejs" # will result in `nodejs` as the value. ``` -### `--allow-net` +If you want to load environment variables from a file that may not exist, you +can use the [`--env-file-if-exists`][] flag instead. + +#### `-e`, `--eval "script"` -> Stability: 1.1 - Active development - -When using the [Permission Model][], the process will not be able to access -network by default. -Attempts to do so will throw an `ERR_ACCESS_DENIED` unless the -user explicitly passes the `--allow-net` flag when starting Node.js. - -Example: +Evaluate the following argument as JavaScript. The modules which are +predefined in the REPL can also be used in `script`. -```js -const http = require('node:http'); -// Attempt to bypass the permission -const req = http.get('http://example.com', () => {}); +If `script` starts with `-`, pass it using `=` (for example, +`node --print --eval=-42`) so it is parsed as the value of `--eval`. -req.on('error', (err) => { - console.log('err', err); -}); -``` +On Windows, using `cmd.exe` a single quote will not work correctly because it +only recognizes double `"` for quoting. In Powershell or Git bash, both `'` +and `"` are usable. -```console -$ node --permission index.js -Error: connect ERR_ACCESS_DENIED Access to this API has been restricted. Use --allow-net to manage permissions. - code: 'ERR_ACCESS_DENIED', -} -``` +It is possible to run code containing inline types unless the +[`--no-strip-types`][] flag is provided. -### `--allow-openssl-store` +#### `-h`, `--help` -> Stability: 1.1 - Active development - -When using the [Permission Model][], the process will not be able to use -OpenSSL STORE loaders by default, for example to load a private key from a -{URL} passed to [`crypto.createPrivateKey()`][]. Attempts to do so will throw -an `ERR_ACCESS_DENIED` unless the user explicitly passes the -`--allow-openssl-store` flag. This permission can be dropped at runtime via -[`permission.drop()`][]. - -This flag grants broad authority to configured OpenSSL STORE loaders. A loader -may access files, devices, tokens, or the network. Access performed by a loader -is not constrained by the `fs.read`, `fs.write`, or `net` permission scopes. - -Loaders and the modules they load are subject to [`--allow-env`][], however. -Environment variables they rely on, such as `SOFTHSM2_CONF` for SoftHSM, are -removed at startup unless they are granted explicitly with `--allow-env`. See -[Environment variable permissions][] for details. +Print node command-line options. +The output of this option is less detailed than this document. -### `--allow-wasi` +#### `--icu-data-dir=file` -> Stability: 1.1 - Active development - -When using the [Permission Model][], the process will not be capable of creating -any WASI instances by default. -For security reasons, the call will throw an `ERR_ACCESS_DENIED` unless the -user explicitly passes the flag `--allow-wasi` in the main Node.js process. +Specify ICU data load path. (Overrides `NODE_ICU_DATA`.) -Example: +#### `--input-type=type` -```js -const { WASI } = require('node:wasi'); -// Attempt to bypass the permission -new WASI({ - version: 'preview1', - // Attempt to mount the whole filesystem - preopens: { - '/': '/', - }, -}); -``` + -```console -$ node --permission --allow-fs-read=* index.js +This configures Node.js to interpret `--eval` or `STDIN` input as CommonJS or +as an ES module. Valid values are `"commonjs"`, `"module"`, `"module-typescript"` and `"commonjs-typescript"`. +The `"-typescript"` values are not available with the flag `--no-strip-types`. +The default is no value, or `"commonjs"` if `--no-experimental-detect-module` is passed. -Error: Access to this API has been restricted - at node:internal/main/run_main_module:30:49 { - code: 'ERR_ACCESS_DENIED', - permission: 'WASI', -} -``` +If `--input-type` is not provided, +Node.js will try to detect the syntax with the following steps: -### `--allow-worker` +1. Run the input as CommonJS. +2. If step 1 fails, run the input as an ES module. +3. If step 2 fails with a SyntaxError, strip the types. +4. If step 3 fails with an error code [`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`][] + or [`ERR_INVALID_TYPESCRIPT_SYNTAX`][], + throw the error from step 2, including the TypeScript error in the message, + else run as CommonJS. +5. If step 4 fails, run the input as an ES module. - +To avoid the delay of multiple syntax detection passes, the `--input-type=type` flag can be used to specify +how the `--eval` input should be interpreted. -> Stability: 1.1 - Active development +The REPL does not support this option. Usage of `--input-type=module` with +[`--print`][] will throw an error, as `--print` does not support ES module +syntax. -When using the [Permission Model][], the process will not be able to create any -worker threads by default. -For security reasons, the call will throw an `ERR_ACCESS_DENIED` unless the -user explicitly pass the flag `--allow-worker` in the main Node.js process. +#### `-i`, `--interactive` -Example: + -```js -const { Worker } = require('node:worker_threads'); -// Attempt to bypass the permission -new Worker(__filename); -``` +Opens the REPL even if stdin does not appear to be a terminal. -```console -$ node --permission --allow-fs-read=* index.js +#### `-p`, `--print "script"` -Error: Access to this API has been restricted - at node:internal/main/run_main_module:17:47 { - code: 'ERR_ACCESS_DENIED', - permission: 'WorkerThreads' -} -``` + -### `--bench` +Identical to `-e` but prints the result. + +#### `--process-timeout=duration` -> Stability: 1 - Experimental +> Stability: 2 - Stable -Starts the Node.js command-line benchmark runner. At least one explicit file or -glob pattern is required: +Exits the process with code `124` if it is still running after `duration`, +measured from the start of the process. `duration` is a positive integer +followed by a unit: `ms`, `s`, `m`, or `h`, for example `500ms`, `30s`, `5m`, or +`1h`. The exit code matches the one used by the `timeout(1)` command. + +Before exiting, Node.js prints what the main thread was doing and which +resources were keeping the event loop alive to stderr: ```console -node --experimental-bench --bench benchmark.mjs -node --experimental-bench --bench 'benchmarks/**/*.js' +$ node --process-timeout=5s server.js +(node:25418) Process timed out after 5s (--process-timeout). Exiting with code 124. +Main thread was not executing JavaScript. +Resources keeping the event loop alive: + TCPServerWrap (listening on [::]:3000, fd 20) + Timeout x2 (next due in 2931ms) ``` -The `--experimental-bench` flag is required to use this flag or any other -`--bench-*` option. +If the main thread was executing JavaScript, its stack trace is printed instead. +Use [`--report-on-process-timeout`][] to also generate a [diagnostic report][]. -Quote glob patterns to prevent expansion by the shell. Matching files are -sorted and executed serially. By default, each file runs in a separate child -process. Benchmark files declare benchmarks using `node:bench`; they must not -call `run()` themselves. See the [benchmark runner][] documentation for more -details. +The process exits without emitting the `'beforeExit'` and `'exit'` events, as +the JavaScript code may be what keeps the process running. Code coverage and +profiles, such as those enabled with [`NODE_V8_COVERAGE=dir`][] or +[`--cpu-prof`][], are still written. -This flag cannot be combined with `--test`, `--watch`, `--watch-path`, -`--check`, `--eval`, or `--interactive`. +If the main thread does not respond within two seconds, for example because it +is blocked in a synchronous operation such as [`child_process.execSync()`][], +Node.js exits immediately without printing the stack trace and resources. + +This option is not allowed in [`NODE_OPTIONS`][], and it cannot be combined +with the options that enable the inspector, such as `--inspect`, +`--inspect-brk`, `--inspect-wait`, `--inspect-port`, and +`--inspect-publish-uid`, nor with `node inspect`, `--run`, or +`--build-snapshot`. While it is in effect, [`inspector.open()`][] and +[`session.connectToMainThread()`][] throw, and requests to activate the +inspector with `SIGUSR1` are ignored. + +Child processes that inherit `process.execArgv`, such as those created with +[`child_process.fork()`][], apply the timeout from their own start. With +[`--watch`][], the timeout applies to each run of the application rather than +to the process that watches for changes. When +[running tests from the command line][], the test runner process applies the +timeout to the whole run, and each test file that runs in its own process +applies it as well. -### `--bench-gc=mode` +#### `--run` -> Stability: 1 - Experimental +This runs a specified command from a package.json's `"scripts"` object. +If a missing `"command"` is provided, it will list the available scripts. -Overrides the garbage collection mode for every selected benchmark. When `mode` -is `'once'`, a full garbage collection runs before the first measured sample. -When `mode` is `'sample'`, a full garbage collection runs before every measured -sample. When `mode` is `'none'`, no garbage collection is forced. Without this -option, each benchmark uses its own `gc` value, which defaults to `'none'`. +Passing `--run` without a command lists the available scripts and exits +with a non-zero exit code: -Forcing garbage collection requires the `--expose-gc` flag. With process -isolation, `--expose-gc` is added to benchmark child processes automatically -when `mode` is `'once'` or `'sample'`. With `--bench-isolation=none`, -`--expose-gc` must be passed explicitly. +```console +$ node --run +Available scripts are: + test: node --test +``` -### `--bench-isolation=mode` +`--run` will traverse up to the root directory and finds a `package.json` +file to run the command from. - +`--run` prepends `./node_modules/.bin` for each ancestor of +the current directory, to the `PATH` in order to execute the binaries from +different folders where multiple `node_modules` directories are present, if +`ancestor-folder/node_modules/.bin` is a directory. -> Stability: 1 - Experimental +`--run` executes the command in the directory containing the related `package.json`. -Configures benchmark file isolation. When `mode` is `'process'`, each matching -file runs in a separate child process. This is the default. Files are still run -serially so their measured work does not overlap. +For example, the following command will run the `test` script of +the `package.json` in the current folder: -When `mode` is `'none'`, all matching files and benchmarks run serially in the -benchmark runner process. This reduces startup overhead but allows module, -heap, and process state to carry between files. User writes to stdout or stderr -also share destinations with benchmark reporters in this mode. +```console +$ node --run test +``` -The supported modes are `'process'` and `'none'`. +You can also pass arguments to the command. Any argument after `--` will +be appended to the script: -### `--bench-name-pattern=pattern` +```console +$ node --run test -- --verbose +``` - +##### Intentional limitations -> Stability: 1 - Experimental +`node --run` is not meant to match the behaviors of `npm run` or of the `run` +commands of other package managers. The Node.js implementation is intentionally +more limited, in order to focus on top performance for the most common use +cases. +Some features of other `run` implementations that are intentionally excluded +are: -Only runs benchmarks whose full hierarchical name matches the JavaScript -regular expression `pattern`. Non-matching benchmarks are reported as skipped. +* Running `pre` or `post` scripts in addition to the specified script. +* Defining package manager-specific environment variables. -### `--bench-reporter-destination=destination` +##### Environment variables - +The following environment variables are set when running a script with `--run`: -> Stability: 1 - Experimental +* `NODE_RUN_SCRIPT_NAME`: The name of the script being run. For example, if + `--run` is used to run `test`, the value of this variable will be `test`. +* `NODE_RUN_PACKAGE_JSON_PATH`: The path to the `package.json` that is being + processed. -Specifies the destination for the corresponding benchmark reporter. The value -can be `stdout`, `stderr`, or a file path. A single reporter defaults to -`stdout` when no destination is specified. +Environment variables loaded from a file with [`--env-file`][] are not applied +to the command executed by `--run`. -### `--bench-reporter=reporter` +#### `--title=title` -> Stability: 1 - Experimental +Set `process.title` on startup. -Specifies a benchmark reporter. The built-in reporters are `spec` and `json`. -The `json` reporter emits newline-delimited JSON. A custom reporter can be -specified using a module specifier resolved from the current working directory. +#### `-v`, `--version` -This option can be repeated. When multiple reporters are specified, each must -have a corresponding `--bench-reporter-destination`. The default reporter is -`spec`. + + +Print node's version. -### `--bench-samples=count` +### Modules -> Stability: 1 - Experimental - -Overrides the maximum number of measured callback invocations for every -selected benchmark. A benchmark may finish earlier by calling -`context.done()`. `count` must be an integer between `1` and `4294967295`. - -### `--bench-warmup=count` +#### `-C condition`, `--conditions=condition` -> Stability: 1 - Experimental +Provide custom [conditional exports][] resolution conditions. -Overrides the number of unreported warmup callback invocations for every -selected benchmark. `count` must be an integer between `0` and `4294967295`. -Without this option, each benchmark uses its own `warmup` value, which defaults -to `10`. +Any number of custom string condition names are permitted. + +The default Node.js conditions of `"node"`, `"default"`, `"import"`, and +`"require"` will always apply as defined. + +For example, to run a module with "development" resolutions: + +```bash +node -C development app.js +``` -### `--build-sea=config` +#### `--experimental-addon-modules` -> Stability: 1.1 - Active development - -Generates a [single executable application][] from a JSON -configuration file. The argument must be a path to the configuration file. If -the path is not absolute, it is resolved relative to the current working -directory. +> Stability: 1.2 - Release candidate -For configuration fields, cross-platform notes, and asset APIs, see -the [single executable application][] documentation. +Enable experimental import support for `.node` addons. -### `--build-snapshot` +#### `--experimental-import-meta-resolve` -Generates a snapshot blob when the process exits and writes it to -disk, which can be loaded later with `--snapshot-blob`. +Enable experimental `import.meta.resolve()` parent URL support, which allows +passing a second `parentURL` argument for contextual resolution. -When building the snapshot, if `--snapshot-blob` is not specified, -the generated blob will be written, by default, to `snapshot.blob` -in the current working directory. Otherwise it will be written to -the path specified by `--snapshot-blob`. +Previously gated the entire `import.meta.resolve` feature. -```console -$ echo "globalThis.foo = 'I am from the snapshot'" > snapshot.js +#### `--experimental-import-text` -# Run snapshot.js to initialize the application and snapshot the -# state of it into snapshot.blob. -$ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js + -$ echo "console.log(globalThis.foo)" > index.js +> Stability: 1.0 - Early development -# Load the generated snapshot and start the application from index.js. -$ node --snapshot-blob snapshot.blob index.js -I am from the snapshot -``` +Enable experimental support for importing modules with +`with { type: 'text' }`. -The [`v8.startupSnapshot` API][] can be used to specify an entry point at -snapshot building time, thus avoiding the need of an additional entry -script at deserialization time: +#### `--experimental-package-map=` -```console -$ echo "require('v8').startupSnapshot.setDeserializeMainFunction(() => console.log('I am from the snapshot'))" > snapshot.js -$ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js -$ node --snapshot-blob snapshot.blob -I am from the snapshot -``` + -For more information, check out the [`v8.startupSnapshot` API][] documentation. +> Stability: 1 - Experimental -The snapshot currently only supports loading a single entrypoint during the -snapshot building process, which can load built-in modules, but not additional user-land modules. -Users can bundle their applications into a single script with their bundler -of choice before building a snapshot. +Enable experimental package map resolution. The `path` argument specifies the +location of a JSON configuration file that defines package resolution mappings. -As it's complicated to ensure the serializablility of all built-in modules, -which are also growing over time, only a subset of the built-in modules are -well tested to be serializable during the snapshot building process. -The Node.js core test suite checks that a few fairly complex applications -can be snapshotted. The list of built-in modules being -[captured by the built-in snapshot of Node.js][] is considered supported. -When the snapshot builder encounters a built-in module that cannot be -serialized, it may crash the snapshot building process. In that case a typical -workaround would be to delay loading that module until -runtime, using either [`v8.startupSnapshot.setDeserializeMainFunction()`][] or -[`v8.startupSnapshot.addDeserializeCallback()`][]. If serialization for -an additional module during the snapshot building process is needed, -please file a request in the [Node.js issue tracker][] and link to it in the -[tracking issue for user-land snapshots][]. +```bash +node --experimental-package-map=./package-map.json app.js +``` -During snapshot building, a debugger cannot be attached to the process. -`--build-snapshot` cannot be used together with `--inspect`, `--inspect-brk` or -`--inspect-wait`. +When enabled, bare specifier resolution consults the package map for resolution. +This allows explicit control over which packages can import which dependencies. -### `--build-snapshot-config` +See [Package maps][] for details on the configuration file format and +resolution algorithm. + +#### `--experimental-print-required-tla` -Specifies the path to a JSON configuration file which configures snapshot -creation behavior. +If the ES module graph cannot be `require()`'d because it contains any top-level `await`, +this flag allows Node.js to locate and print their locations. -The following options are currently supported: +#### `--experimental-strip-private-modules` -* `builder` {string} Required. Provides the name to the script that is executed - before building the snapshot, as if [`--build-snapshot`][] had been passed - with `builder` as the main script name. -* `withoutCodeCache` {boolean} Optional. Including the code cache reduces the - time spent on compiling functions included in the snapshot at the expense - of a bigger snapshot size and potentially breaking portability of the - snapshot. + -When using this flag, additional script files provided on the command line will -not be executed and instead be interpreted as regular command line arguments. +> Stability: 1 - Experimental + +By default, Node.js refuses to strip types from TypeScript files inside +folders under a `node_modules` path. This flag enables type stripping for +such files when they belong to a package whose `package.json` contains +`"private": true`. Files belonging to non-private packages still throw +[`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`][]. +The limitation to private packages should never be lifted, +as publishing packages with TypeScript sources +is highly discouraged. +Stripping types inside `node_modules` is intended only +for local development. -### `-c`, `--check` +#### `--experimental-vm-modules` -Syntax check the script without executing. +Enable experimental ES Module support in the `node:vm` module. -### `--completion-bash` +#### `--force-context-aware` -Print source-able bash completion script for Node.js. - -```bash -node --completion-bash > node_bash_completion -source node_bash_completion -``` +Disable loading native addons that are not [context-aware][]. -### `-C condition`, `--conditions=condition` +#### `--import=module` -Provide custom [conditional exports][] resolution conditions. +> Stability: 1 - Experimental -Any number of custom string condition names are permitted. +Preload the specified module at startup. If the flag is provided several times, +each module will be executed sequentially in the order they appear, starting +with the ones provided in [`NODE_OPTIONS`][]. -The default Node.js conditions of `"node"`, `"default"`, `"import"`, and -`"require"` will always apply as defined. +Follows [ECMAScript module][] resolution rules. +Use [`--require`][] to load a [CommonJS module][]. +Modules preloaded with `--require` will run before modules preloaded with `--import`. -For example, to run a module with "development" resolutions: +Modules are preloaded into the main thread as well as any worker threads, +forked processes, or clustered processes. -```bash -node -C development app.js -``` +#### `--no-addons` + + -### `--config-file=path`, `--config-file` +Disable the `node-addons` exports condition as well as disable loading +native addons. When `--no-addons` is specified, calling `process.dlopen` or +requiring a native C++ addon will fail and throw an exception. + +#### `--no-experimental-detect-module` -If present, Node.js will look for a configuration file at the specified path. -If the path is not specified, Node.js will look for a `node.config.json` file -in the current working directory. -To specify a custom path, use the `--config-file=path` form. -The space-separated `--config-file path` form is not supported. -Node.js will read the configuration file and apply the settings. The -configuration file should be a JSON file with the following structure. `vX.Y.Z` -in the `$schema` must be replaced with the version of Node.js you are using or -`latest-vX.x` for the latest version of that major release line. +Disable using [syntax detection][] to determine module type. -```json -{ - "$schema": "https://nodejs.org/dist/vX.Y.Z/docs/node-config-schema.json", - "nodeOptions": { - "import": [ - "amaro/strip" - ], - "watch-path": "src", - "watch-preserve-output": true - }, - "test": { - "test-isolation": "process" - }, - "watch": { - "watch-preserve-output": true - } -} -``` +#### `--no-experimental-require-module` -The configuration file supports namespace-specific options: + -* The `nodeOptions` field contains CLI flags that are allowed in [`NODE_OPTIONS`][]. +> Stability: 3 - Legacy: Use [`--no-require-module`][] instead. -* Namespace fields like `test`, `watch`, and `permission` contain configuration specific to that subsystem. +Legacy alias for [`--no-require-module`][]. -The configuration file can target a specific Node.js major version with -`nodeVersion`: +#### `--no-experimental-vfs` -```json -{ - "nodeVersion": 25, - "nodeOptions": { - "watch-path": "src" - } -} -``` + -To keep multiple version-specific configurations in the same file, use the -`configs` array. Node.js will use the first entry whose `nodeVersion` matches -the current Node.js major version: +Disable the experimental [`node:vfs`][] module and `--vfs-load`. -```json -{ - "$schema": "https://nodejs.org/dist/latest-v26.x/docs/node-config-schema.json", - "configs": [ - { - "nodeVersion": 25, - "config": { - "$schema": "https://nodejs.org/dist/latest-v25.x/docs/node-config-schema.json", - "nodeOptions": { - "watch-path": "src" - } - } - } - ] -} -``` +#### `--no-global-search-paths` -When `configs` is used, the top level may only contain `$schema` and -`configs`. Each `configs` item must define an integer `nodeVersion` and an -object `config`. A single top-level config does not require `nodeVersion`, but -if present it must match the current Node.js major version. + -When a namespace is present in the -configuration file, Node.js automatically enables the corresponding flag -(e.g., `--test`, `--watch`, `--permission`). This allows you to configure -subsystem-specific options without explicitly passing the flag on the command line. +Do not search modules from global paths like `$HOME/.node_modules` and +`$NODE_PATH`. -For example: +#### `--no-require-module` -```json -{ - "test": { - "test-isolation": "process" - } -} -``` + -is equivalent to: +Disable support for loading a synchronous ES module graph in `require()`. -```bash -node --test --test-isolation=process -``` +See [Loading ECMAScript modules using `require()`][]. -To disable the automatic flag while still using namespace options, you can -explicitly set the flag to `false` within the namespace: +#### `--no-strip-types` -```json -{ - "test": { - "test": false, - "test-isolation": "process" - } -} -``` + -No-op flags are not supported. -Not all V8 flags are currently supported. +Disable type-stripping for TypeScript files. +For more information, see the [TypeScript type-stripping][] documentation. -It is possible to use the [official JSON schema](../node-config-schema.json) -to validate the configuration file, which may vary depending on the Node.js version. -Each key in the configuration file corresponds to a flag that can be passed -as a command-line argument. The value of the key is the value that would be -passed to the flag. +#### `--preserve-symlinks` -For example, the configuration file above is equivalent to -the following command-line arguments: + -```bash -node --import amaro/strip --watch-path=src --watch-preserve-output --test-isolation=process +Instructs the module loader to preserve symbolic links when resolving and +caching modules. + +By default, when Node.js loads a module from a path that is symbolically linked +to a different on-disk location, Node.js will dereference the link and use the +actual on-disk "real path" of the module as both an identifier and as a root +path to locate other dependency modules. In most cases, this default behavior +is acceptable. However, when using symbolically linked peer dependencies, as +illustrated in the example below, the default behavior causes an exception to +be thrown if `moduleA` attempts to require `moduleB` as a peer dependency: + +```text +{appDir} + ├── app + │ ├── index.js + │ └── node_modules + │ ├── moduleA -> {appDir}/moduleA + │ └── moduleB + │ ├── index.js + │ └── package.json + └── moduleA + ├── index.js + └── package.json ``` -The priority in configuration is as follows: +The `--preserve-symlinks` command-line flag instructs Node.js to use the +symlink path for modules as opposed to the real path, allowing symbolically +linked peer dependencies to be found. + +Note, however, that using `--preserve-symlinks` can have other side effects. +Specifically, symbolically linked _native_ modules can fail to load if those +are linked from more than one location in the dependency tree (Node.js would +see those as two separate modules and would attempt to load the module multiple +times, causing an exception to be thrown). + +The `--preserve-symlinks` flag does not apply to the main module, which allows +`node --preserve-symlinks node_module/.bin/` to work. To apply the same +behavior for the main module, also use `--preserve-symlinks-main`. + +#### `--preserve-symlinks-main` + + + +Instructs the module loader to preserve symbolic links when resolving and +caching the main module (`require.main`). + +This flag exists so that the main module can be opted-in to the same behavior +that `--preserve-symlinks` gives to all other imports; they are separate flags, +however, for backward compatibility with older Node.js versions. + +`--preserve-symlinks-main` does not imply `--preserve-symlinks`; use +`--preserve-symlinks-main` in addition to +`--preserve-symlinks` when it is not desirable to follow symlinks before +resolving relative paths. + +See [`--preserve-symlinks`][] for more information. + +#### `-r`, `--require module` + + + +Preload the specified module at startup. + +Follows `require()`'s module resolution +rules. `module` may be either a path to a file, or a node module name. + +Modules preloaded with `--require` will run before modules preloaded with `--import`. + +Modules are preloaded into the main thread as well as any worker threads, +forked processes, or clustered processes. + +#### `--trace-require-module=mode` + + + +Prints information about usage of [Loading ECMAScript modules using `require()`][]. + +When `mode` is `all`, all usage is printed. When `mode` is `no-node-modules`, usage +from the `node_modules` folder is excluded. + +#### `--vfs-load=source` -1. NODE\_OPTIONS and command-line options -2. Dotenv NODE\_OPTIONS -3. Configuration file + -Values in the configuration file will not override the values in the environment -variables, command-line options, or the `NODE_OPTIONS` env file parsed by the -`--env-file` flag. +* `source` {string} A directory or an archive file to mount and run. -Keys cannot be duplicated within the same or different namespaces. +May be given at most once. -The configuration parser will throw an error if the configuration file contains -unknown keys or keys that cannot be used in a namespace. +Mounts `source` as a virtual file system ([`node:vfs`][]), and runs the entry +point and all subsequent `require()`/`import` resolution against that mount +rather than the real file system. This option is unavailable when +`--no-experimental-vfs` disables [`node:vfs`][]. The mount is placed at a +reserved mount point +assigned by Node.js, so it never shadows real paths and no target can be +chosen. The entry point is taken from the mount the same way `node ` +takes one: the mount's own `package.json` `"main"`, or `index.js`. Any +positional command-line argument is the program's own (available from +`process.argv[2]` onward), never an entry-point override. -Node.js will not sanitize or perform validation on the user-provided configuration, -so **NEVER** use untrusted configuration files. +`process.argv[1]` reports `source` rather than the reserved mount point, since +the mount point is an opaque implementation detail. -### `--cpu-prof` +The provider backing a source is chosen from the source itself rather than from +its file name: - +* A directory is mounted with a [`RealFSProvider`][] rooted there. +* A file whose bytes are a ZIP archive is mounted with a [`ZipProvider`][], so + an archive can carry any name. -Starts the V8 CPU profiler on start up, and writes the CPU profile to disk -before exit. +Providers registered with `vfs.registerProvider()` (typically from a module +preloaded with [`--require`][] or [`--import`][]) are consulted first, in +reverse registration order, and may claim directories as well as files. If no +provider claims the source, Node.js exits with an error. -If `--cpu-prof-dir` is not specified, the generated profile is placed -in the current working directory. +In worker threads `--vfs-load` mounts but does not load: a worker inherits the +mount and runs its own entry point, which may itself live in the mount. -If `--cpu-prof-name` is not specified, the generated profile is -named `CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile`. +The source is mounted at the same reserved mount point in every thread that +mounts it, whatever else that thread mounts, so a path into the mount means the +same thing in all of them. -```console -$ node --cpu-prof index.js -$ ls *.cpuprofile -CPU.20190409.202950.15293.0.0.cpuprofile -``` +A worker created with its own `execArgv` inherits none of the parent's options, +and so does not mount the source at all. To run a script from the mount, such a +worker must be given `--vfs-load` again; without it, that thread has no mount +for the script to come from, and the worker fails to load it. [`node:vfs`][] is +available to worker code without an experimental flag. A worker whose script +comes from anywhere else, such as the real file system, needs nothing added. -If `--cpu-prof-name` is specified, the provided value is used as a template -for the file name. The following placeholder is supported and will be -substituted at runtime: +`--vfs-load` is not permitted in [`NODE_OPTIONS`][]: which entry point runs is +the command line's decision, and the environment must not be able to redirect +it. -* `${pid}` — the current process ID +`--vfs-load` cannot be used in a [single executable application][]: its entry +point is the `"main"` it was built with, and with `"useVfs"` its own virtual +file system is mounted at the mount point reserved for `--vfs-load`. ```console -$ node --cpu-prof --cpu-prof-name 'CPU.${pid}.cpuprofile' index.js -$ ls *.cpuprofile -CPU.15293.cpuprofile +$ node --vfs-load=app.zip ``` -### `--cpu-prof-dir` +### Built-in APIs -Specify the directory where the CPU profiles generated by `--cpu-prof` will -be placed. - -The default value is controlled by the -[`--diagnostic-dir`][] command-line option. - -### `--cpu-prof-interval` +#### `--experimental-dtls` -Specify the sampling interval in microseconds for the CPU profiles generated -by `--cpu-prof`. The default is 1000 microseconds. +> Stability: 1 - Experimental + +Enable experimental support for the DTLS protocol. See the +[dtls documentation][] for details. -### `--cpu-prof-name` +#### `--experimental-eventsource` -Specify the file name of the CPU profile generated by `--cpu-prof`. +Enable exposition of [EventSource Web API][] on the global scope. -### `--diagnostic-dir=directory` +#### `--experimental-quic` -Set the directory to which all diagnostic output files are written. -Defaults to current working directory. + -Affects the default output directory of: +> Stability: 1.1 - Active development -* [`--cpu-prof-dir`][] -* [`--heap-prof-dir`][] -* [`--redirect-warnings`][] +Enable experimental support for the QUIC protocol. -### `--disable-proto=mode` +#### `--experimental-shadow-realm` -Disable the `Object.prototype.__proto__` property. If `mode` is `delete`, the -property is removed entirely. If `mode` is `throw`, accesses to the -property throw an exception with the code `ERR_PROTO_ACCESS`. +Use this flag to enable [ShadowRealm][] support. -### `--disable-sigusr1` +#### `--experimental-stream-iter` -Disable the ability of starting a debugging session by sending a -`SIGUSR1` signal to the process. +> Stability: 1 - Experimental -### `--disable-warning=code-or-type` +Enable the experimental [`node:stream/iter`][] module. + +#### `--experimental-wasi-unstable-preview1` -> Stability: 2 - Stable - -Disable specific process warnings by `code` or `type`. - -Warnings emitted from [`process.emitWarning()`][emit_warning] may contain a -`code` and a `type`. This option will not-emit warnings that have a matching -`code` or `type`. - -List of [deprecation warnings][]. - -The Node.js core warning types are: `DeprecationWarning` and -`ExperimentalWarning` - -For example, the following script will not emit -[DEP0025 `require('node:sys')`][DEP0025 warning] when executed with -`node --disable-warning=DEP0025`: - -```mjs -import sys from 'node:sys'; -``` - -```cjs -const sys = require('node:sys'); -``` - -For example, the following script will emit the -[DEP0025 `require('node:sys')`][DEP0025 warning], but not any Experimental -Warnings (such as -[ExperimentalWarning: `vm.measureMemory` is an experimental feature][] -in <=v21) when executed with `node --disable-warning=ExperimentalWarning`: - -```mjs -import sys from 'node:sys'; -import vm from 'node:vm'; - -vm.measureMemory(); -``` - -```cjs -const sys = require('node:sys'); -const vm = require('node:vm'); - -vm.measureMemory(); -``` +Enable experimental WebAssembly System Interface (WASI) support. -### `--disable-wasm-trap-handler` +#### `--localstorage-file=file` -Node.js enables V8's trap-handler-based WebAssembly bound checks on 64-bit platforms, -which significantly improves WebAssembly performance by eliminating the need for -inline bound checks. This optimization requires allocating a large virtual memory -cage per WebAssembly memory instance (currently typically 8GB for 32-bit WebAssembly memory, -16GB for 64-bit WebAssembly memory) to trap out-of-bound accesses. On most 64-bit -platforms, the virtual memory address space is usually large enough (around 128TB) -to accommodate typical WebAssembly usages, but if the machine has manual limits -on virtual memory (e.g. through `ulimit -v`), WebAssembly memory allocation is -more likely to fail with `WebAssembly.Memory(): could not allocate memory`. - -At startup, Node.js automatically checks whether there is enough virtual memory -available to allocate at least one cage, and if not, the trap-handler optimization -is automatically disabled so that WebAssembly can still run using inline -bound checks (with less optimal performance). But if the application needs to create -many WebAssembly memory instances and the machine still configures a relatively high -limit on virtual memory, allocation of WebAssembly memory instances may still fail -more quickly than expected due to the raised virtual memory usage. +> Stability: 1.2 - Release candidate. -`--disable-wasm-trap-handler` fully disables this optimization so that WebAssembly memory -instances always use inline bound checks instead of reserving large virtual memory cages. -This allows more instances to be created when the virtual memory address space available -to the Node.js process is limited. +The file used to store `localStorage` data. If the file does not exist, it is +created the first time `localStorage` is accessed. The same file may be shared +between multiple Node.js processes concurrently. -### `--disallow-code-generation-from-strings` +#### `--no-experimental-ffi` -Make built-in language features like `eval` and `new Function` that generate -code from strings throw an exception instead. This does not affect the Node.js -`node:vm` module. +> Stability: 1 - Experimental + +Disable the experimental [`node:ffi`][] module. + +This flag is only available in builds with FFI support. -### `--dns-result-order=order` +#### `--no-experimental-global-navigator` -Set the default value of `order` in [`dns.lookup()`][] and -[`dnsPromises.lookup()`][]. The value could be: - -* `ipv4first`: sets default `order` to `ipv4first`. -* `ipv6first`: sets default `order` to `ipv6first`. -* `verbatim`: sets default `order` to `verbatim`. +> Stability: 1 - Experimental -The default is `verbatim` and [`dns.setDefaultResultOrder()`][] have higher -priority than `--dns-result-order`. +Disable exposition of [Navigator API][] on the global scope. -### `--enable-fips` +#### `--no-experimental-sqlite` -Enable [FIPS mode][] at startup by adding `fips=yes` to OpenSSL's default -property query. This does not load or validate a FIPS provider or run its -self-tests. Configure OpenSSL to load the provider separately. +Disable the [`node:sqlite`][] module. -### `--enable-fips-indicator-events` +#### `--no-experimental-web-worker` -Publish OpenSSL FIPS indicator results to the -[`'crypto.fips.indicator'`][] diagnostics channel. This option requires OpenSSL -3.4 or later. It does not enable [FIPS mode][] or change whether an operation -is permitted. +> Stability: 1.1 - Active Development + +Disable support for the Web Worker API. -### `--enable-source-maps` +#### `--no-experimental-webstorage` -Enable [Source Map][] support for stack traces. - -When using a transpiler, such as TypeScript, stack traces thrown by an -application reference the transpiled code, not the original source position. -`--enable-source-maps` enables caching of Source Maps and makes a best -effort to report stack traces relative to the original source file. +> Stability: 1.2 - Release candidate. -Overriding `Error.prepareStackTrace` may prevent `--enable-source-maps` from -modifying the stack trace. Call and return the results of the original -`Error.prepareStackTrace` in the overriding function to modify the stack trace -with source maps. +Disable [`Web Storage`][] support. -```js -const originalPrepareStackTrace = Error.prepareStackTrace; -Error.prepareStackTrace = (error, trace) => { - // Modify error and trace and format stack trace with - // original Error.prepareStackTrace. - return originalPrepareStackTrace(error, trace); -}; -``` +### Watch mode -Note, enabling source maps can introduce latency to your application -when `Error.stack` is accessed. If you access `Error.stack` frequently -in your application, take into account the performance implications -of `--enable-source-maps`. + -### `--entry-url` +#### `--watch` -> Stability: 1 - Experimental - -When present, Node.js will interpret the entry point as a URL, rather than a -path. +Starts Node.js in watch mode. +When in watch mode, changes in the watched files cause the Node.js process to +restart. +By default, watch mode will watch the entry point +and any required or imported module. +Use `--watch-path` to specify what paths to watch. -Follows [ECMAScript module][] resolution rules. +This flag cannot be combined with +`--check`, `--eval`, `--interactive`, or the REPL. -Any query parameter or hash in the URL will be accessible via [`import.meta.url`][]. +Note: The `--watch` flag requires a file path as an argument and is incompatible +with `--run` or inline script input, as `--run` takes precedence and ignores watch +mode. If no file is provided, Node.js will exit with status code `9`. ```bash -node --entry-url 'file:///path/to/file.js?queryparams=work#and-hashes-too' -node --entry-url 'file.ts?query#hash' -node --entry-url 'data:text/javascript,console.log("Hello")' +node --watch index.js ``` -### `--env-file-if-exists=file` +#### `--watch-kill-signal` -Behavior is the same as [`--env-file`][], but an error is not thrown if the file -does not exist. +> Stability: 1.1 - Active Development + +Customizes the signal sent to the process on watch mode restarts. + +```bash +node --watch --watch-kill-signal SIGINT test.js +``` -### `--env-file=file` +#### `--watch-path` -Loads environment variables from a file relative to the current directory, -making them available to applications on `process.env`. The [environment -variables which configure Node.js][environment_variables], such as `NODE_OPTIONS`, -are parsed and applied. If the same variable is defined in the environment and -in the file, the value from the environment takes precedence. +Starts Node.js in watch mode and specifies what paths to watch. +When in watch mode, changes in the watched paths cause the Node.js process to +restart. +This will turn off watching of required or imported modules, even when used in +combination with `--watch`. -You can pass multiple `--env-file` arguments. Subsequent files override -pre-existing variables defined in previous files. +This flag cannot be combined with +`--check`, `--eval`, `--interactive`, `--test`, or the REPL. -An error is thrown if the file does not exist. +Note: Using `--watch-path` implicitly enables `--watch`, which requires a file path +and is incompatible with `--run`, as `--run` takes precedence and ignores watch mode. ```bash -node --env-file=.env --env-file=.development.env index.js -``` - -The format of the file should be one line per key-value pair of environment -variable name and value separated by `=`: - -```text -PORT=3000 -``` - -Any text after a `#` is treated as a comment: - -```text -# This is a comment -PORT=3000 # This is also a comment +node --watch-path=./src --watch-path=./tests index.js ``` -Values can start and end with the following quotes: `` ` ``, `"` or `'`. -They are omitted from the values. +#### `--watch-preserve-output` -```text -USERNAME="nodejs" # will result in `nodejs` as the value. -``` + -Multi-line values are supported: +Disable the clearing of the console when watch mode restarts the process. -```text -MULTI_LINE="THIS IS -A MULTILINE" -# will result in `THIS IS\nA MULTILINE` as the value. +```bash +node --watch --watch-preserve-output test.js ``` -Export keyword before a key is ignored: - -```text -export USERNAME="nodejs" # will result in `nodejs` as the value. -``` +### Test runner -If you want to load environment variables from a file that may not exist, you -can use the [`--env-file-if-exists`][] flag instead. + -### `-e`, `--eval "script"` +#### `--experimental-test-coverage` -Evaluate the following argument as JavaScript. The modules which are -predefined in the REPL can also be used in `script`. - -If `script` starts with `-`, pass it using `=` (for example, -`node --print --eval=-42`) so it is parsed as the value of `--eval`. - -On Windows, using `cmd.exe` a single quote will not work correctly because it -only recognizes double `"` for quoting. In Powershell or Git bash, both `'` -and `"` are usable. - -It is possible to run code containing inline types unless the -[`--no-strip-types`][] flag is provided. +When used in conjunction with the `node:test` module, a code coverage report is +generated as part of the test runner output. If no tests are run, a coverage +report is not generated. See the documentation on +[collecting code coverage from tests][] for more details. -### `--experimental-addon-modules` +#### `--experimental-test-module-mocks` -> Stability: 1.2 - Release candidate +> Stability: 1.0 - Early development -Enable experimental import support for `.node` addons. +Enable module mocking in the test runner. + +This feature requires `--allow-worker` if used with the [Permission Model][]. -### `--experimental-bench` +#### `--experimental-test-tag-filter=''` -> Stability: 1 - Experimental - -Enable the experimental `node:bench` module and command-line benchmark runner. +> Stability: 1.0 - Early development -### `--experimental-dtls` +Run only tests that match the provided boolean tag-filter expression. Tests +declare tags via the `tags` option on `test()`, `it()`, `suite()`, or +`describe()`. Tags inherit from suites to nested tests by union. - +The expression supports boolean operators (`and`/`&&`, `or`/`||`, +`not`/`!`), parentheses for grouping, and `*` wildcards inside identifiers. +Standard precedence applies: `not` binds tighter than `and`, which binds +tighter than `or`. See [Test tags][] for the full grammar and behavior. -> Stability: 1 - Experimental +The flag may be specified more than once; multiple expressions are combined +with AND, so a test must satisfy every expression to run. -Enable experimental support for the DTLS protocol. See the -[dtls documentation][] for details. +A malformed expression causes the test runner to exit with a non-zero status +before running any tests. -### `--experimental-eventsource` +#### `--test` -Enable exposition of [EventSource Web API][] on the global scope. +Starts the Node.js command line test runner. This flag cannot be combined with +`--watch-path`, `--check`, `--eval`, `--interactive`, or the inspector. +See the documentation on [running tests from the command line][] +for more details. -### `--experimental-import-meta-resolve` +#### `--test-concurrency` -Enable experimental `import.meta.resolve()` parent URL support, which allows -passing a second `parentURL` argument for contextual resolution. - -Previously gated the entire `import.meta.resolve` feature. +The maximum number of test files that the test runner CLI will execute +concurrently. If `--test-isolation` is set to `'none'`, this flag is ignored and +concurrency is one. Otherwise, concurrency defaults to +`os.availableParallelism() - 1`. -### `--experimental-import-text` +#### `--test-coverage-branches=threshold` -> Stability: 1.0 - Early development +> Stability: 1 - Experimental -Enable experimental support for importing modules with -`with { type: 'text' }`. +Require a minimum percent of covered branches. If code coverage does not reach +the threshold specified, the process will exit with code `1`. -### `--experimental-inspector-network-resource` +#### `--test-coverage-exclude` -> Stability: 1.1 - Active Development +> Stability: 1 - Experimental -Enable experimental support for inspector network resources. +Excludes specific files from code coverage using a glob pattern, which can match +both absolute and relative file paths. + +This option may be specified multiple times to exclude multiple glob patterns. + +If both `--test-coverage-exclude` and `--test-coverage-include` are provided, +files must meet **both** criteria to be included in the coverage report. + +By default all the matching test files are excluded from the coverage report. +Specifying this option will override the default behavior. -### `--experimental-network-inspection` +#### `--test-coverage-functions=threshold` > Stability: 1 - Experimental -Enable experimental support for the network inspection with Chrome DevTools. +Require a minimum percent of covered functions. If code coverage does not reach +the threshold specified, the process will exit with code `1`. -### `--experimental-package-map=` +#### `--test-coverage-include` > Stability: 1 - Experimental -Enable experimental package map resolution. The `path` argument specifies the -location of a JSON configuration file that defines package resolution mappings. - -```bash -node --experimental-package-map=./package-map.json app.js -``` +Includes specific files in code coverage using a glob pattern, which can match +both absolute and relative file paths. -When enabled, bare specifier resolution consults the package map for resolution. -This allows explicit control over which packages can import which dependencies. +This option may be specified multiple times to include multiple glob patterns. -See [Package maps][] for details on the configuration file format and -resolution algorithm. +If both `--test-coverage-exclude` and `--test-coverage-include` are provided, +files must meet **both** criteria to be included in the coverage report. -### `--experimental-print-required-tla` +#### `--test-coverage-include-all` -If the ES module graph cannot be `require()`'d because it contains any top-level `await`, -this flag allows Node.js to locate and print their locations. +> Stability: 1 - Experimental -### `--experimental-quic` +Includes source files that were never loaded by the test run in the coverage +report, where they are reported as having zero coverage. + +Candidate files are searched for in the current working directory, and are +subject to the same `--test-coverage-include` and `--test-coverage-exclude` +filtering as the rest of the report. + +#### `--test-coverage-lines=threshold` -> Stability: 1.1 - Active development +> Stability: 1 - Experimental -Enable experimental support for the QUIC protocol. +Require a minimum percent of covered lines. If code coverage does not reach +the threshold specified, the process will exit with code `1`. -### `--experimental-sea-config` +#### `--test-forbid-only` -> Stability: 1 - Experimental +Fails the test run if a test or suite is declared with `only: true`, including +the `test.only()`, `it.only()`, `suite.only()`, and `describe.only()` shorthands, +or if `testContext.runOnly(true)` is called. This is useful in CI to prevent +accidentally committing exclusive tests that exclude the rest of a test suite. -Use this flag to generate a blob that can be injected into the Node.js -binary to produce a [single executable application][]. See the documentation -about [this configuration][`--experimental-sea-config`] for details. +This option applies with either test isolation mode and takes precedence over +`--test-only`. Name filtering, TODO markers, and expected failures do not suppress +detected violations. Only declarations evaluated during the run are checked; +code inside a skipped test callback is not evaluated. -### `--experimental-shadow-realm` +#### `--test-force-exit` -Use this flag to enable [ShadowRealm][] support. +Configures the test runner to exit the process once all known tests have +finished executing even if the event loop would otherwise remain active. -### `--experimental-storage-inspection` +#### `--test-global-setup=module` -> Stability: 1.1 - Active Development +> Stability: 1.0 - Early development -Enable experimental support for storage inspection +Specify a module that will be evaluated before all tests are executed and +can be used to setup global state or fixtures for tests. + +See the documentation on [global setup and teardown][] for more details. -### `--experimental-stream-iter` +#### `--test-isolation=mode` -> Stability: 1 - Experimental - -Enable the experimental [`node:stream/iter`][] module. +Configures the type of test isolation used in the test runner. When `mode` is +`'process'`, each test file is run in a separate child process. When `mode` is +`'none'`, all test files run in the same process as the test runner. The default +isolation mode is `'process'`. This flag is ignored if the `--test` flag is not +present. See the [test runner execution model][] section for more information. -### `--experimental-strip-private-modules` +#### `--test-name-pattern` -> Stability: 1 - Experimental +A regular expression that configures the test runner to only execute tests +whose name matches the provided pattern. See the documentation on +[filtering tests by name][] for more details. -By default, Node.js refuses to strip types from TypeScript files inside -folders under a `node_modules` path. This flag enables type stripping for -such files when they belong to a package whose `package.json` contains -`"private": true`. Files belonging to non-private packages still throw -[`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`][]. -The limitation to private packages should never be lifted, -as publishing packages with TypeScript sources -is highly discouraged. -Stripping types inside `node_modules` is intended only -for local development. +If both `--test-name-pattern` and `--test-skip-pattern` are supplied, +tests must satisfy **both** requirements in order to be executed. -### `--experimental-test-coverage` +#### `--test-only` -When used in conjunction with the `node:test` module, a code coverage report is -generated as part of the test runner output. If no tests are run, a coverage -report is not generated. See the documentation on -[collecting code coverage from tests][] for more details. - -### `--experimental-test-module-mocks` +Configures the test runner to only execute top level tests that have the `only` +option set. This flag is not necessary when test isolation is disabled. + +#### `--test-random-seed` -> Stability: 1.0 - Early development +Set the seed used to randomize test execution order. This applies to both test +file execution order and queued tests within each file. Providing this flag +enables randomization implicitly, even without `--test-randomize`. -Enable module mocking in the test runner. +The value must be an integer between `0` and `4294967295`. -This feature requires `--allow-worker` if used with the [Permission Model][]. +This flag cannot be used with `--watch` or `--test-rerun-failures`. -### `--experimental-test-tag-filter=''` +#### `--test-randomize` -> Stability: 1.0 - Early development - -Run only tests that match the provided boolean tag-filter expression. Tests -declare tags via the `tags` option on `test()`, `it()`, `suite()`, or -`describe()`. Tags inherit from suites to nested tests by union. +Randomize test execution order. This applies to both test file execution order +and queued tests within each file. This can help detect tests that rely on +shared state or execution order. -The expression supports boolean operators (`and`/`&&`, `or`/`||`, -`not`/`!`), parentheses for grouping, and `*` wildcards inside identifiers. -Standard precedence applies: `not` binds tighter than `and`, which binds -tighter than `or`. See [Test tags][] for the full grammar and behavior. +The seed used for randomization is printed in the test summary and can be +reused with `--test-random-seed`. -The flag may be specified more than once; multiple expressions are combined -with AND, so a test must satisfy every expression to run. +For detailed behavior and examples, see +[randomizing tests execution order][]. -A malformed expression causes the test runner to exit with a non-zero status -before running any tests. +This flag cannot be used with `--watch` or `--test-rerun-failures`. -### `--experimental-vm-modules` +#### `--test-reporter` -Enable experimental ES Module support in the `node:vm` module. +A test reporter to use when running tests. See the documentation on +[test reporters][] for more details. -### `--experimental-wasi-unstable-preview1` +#### `--test-reporter-destination` -Enable experimental WebAssembly System Interface (WASI) support. +The destination for the corresponding test reporter. See the documentation on +[test reporters][] for more details. -### `--experimental-worker-inspection` +#### `--test-rerun-failures` -> Stability: 1.1 - Active Development - -Enable experimental support for the worker inspection with Chrome DevTools. +A path to a file allowing the test runner to persist the state of the test +suite between runs. The test runner will use this file to determine which tests +have already succeeded or failed, allowing for re-running of failed tests +without having to re-run the entire test suite. The test runner will create this +file if it does not exist. +See the documentation on [test reruns][] for more details. -### `--force-context-aware` +#### `--test-shard` -Disable loading native addons that are not [context-aware][]. - -### `--force-fips[=mode]` - - +Test suite shard to execute in a format of `/`, where -Enable [FIPS mode][] at startup and prevent it from being disabled from script -code. This changes the default property query as described for -[`--enable-fips`][]. +* `index` is a positive integer, index of divided parts. +* `total` is a positive integer, total of divided part. -An optional mode can be specified using `--force-fips=mode`: +This command will divide all tests files into `total` equal parts, +and will run only those that happen to be in an `index` part. -* `provider`: Preserve the OpenSSL FIPS provider's configured handling of - non-approved operations. This is the current default when the mode is - omitted. -* `strict`: Reject non-approved operations reported through the OpenSSL FIPS - indicator callback. This mode requires OpenSSL 3.4 or later. +For example, to split your tests suite into three parts, use this: -The `strict` mode only covers operations reported through the callback for -OpenSSL's default library context. It does not cover native addons that use -another `OSSL_LIB_CTX` or another copy of `libcrypto`, nor operation-specific -indicators that do not invoke the callback. +```bash +node --test --test-shard=1/3 +node --test --test-shard=2/3 +node --test --test-shard=3/3 +``` -### `--force-node-api-uncaught-exceptions-policy` +#### `--test-skip-pattern` -Enforces `uncaughtException` event on Node-API asynchronous callbacks. +A regular expression that configures the test runner to skip tests +whose name matches the provided pattern. See the documentation on +[filtering tests by name][] for more details. -To prevent from an existing add-on from crashing the process, this flag is not -enabled by default. In the future, this flag will be enabled by default to -enforce the correct behavior. +If both `--test-name-pattern` and `--test-skip-pattern` are supplied, +tests must satisfy **both** requirements in order to be executed. -### `--frozen-intrinsics` +#### `--test-timeout` -> Stability: 1 - Experimental +A number of milliseconds the test execution will fail after. If unspecified, +subtests inherit this value from their parent. The default value is `Infinity`. -Enable experimental frozen intrinsics like `Array` and `Object`. +#### `--test-update-snapshots` -Only the root context is supported. There is no guarantee that -`globalThis.Array` is indeed the default intrinsic reference. Code may break -under this flag. + -To allow polyfills to be added, -[`--require`][] and [`--import`][] both run before freezing intrinsics. +Regenerates the snapshot files used by the test runner for [snapshot testing][]. -### `--heap-prof` +### Benchmark runner -Starts the V8 heap profiler on start up, and writes the heap profile to disk -before exit. +#### `--bench` -If `--heap-prof-dir` is not specified, the generated profile is placed -in the current working directory. + -If `--heap-prof-name` is not specified, the generated profile is -named `Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile`. +> Stability: 1 - Experimental + +Starts the Node.js command-line benchmark runner. At least one explicit file or +glob pattern is required: ```console -$ node --heap-prof index.js -$ ls *.heapprofile -Heap.20190409.202950.15293.0.001.heapprofile +node --experimental-bench --bench benchmark.mjs +node --experimental-bench --bench 'benchmarks/**/*.js' ``` -### `--heap-prof-dir` +The `--experimental-bench` flag is required to use this flag or any other +`--bench-*` option. + +Quote glob patterns to prevent expansion by the shell. Matching files are +sorted and executed serially. By default, each file runs in a separate child +process. Benchmark files declare benchmarks using `node:bench`; they must not +call `run()` themselves. See the [benchmark runner][] documentation for more +details. + +This flag cannot be combined with `--test`, `--watch`, `--watch-path`, +`--check`, `--eval`, or `--interactive`. + +#### `--bench-gc=mode` -Specify the directory where the heap profiles generated by `--heap-prof` will -be placed. +> Stability: 1 - Experimental -The default value is controlled by the -[`--diagnostic-dir`][] command-line option. +Overrides the garbage collection mode for every selected benchmark. When `mode` +is `'once'`, a full garbage collection runs before the first measured sample. +When `mode` is `'sample'`, a full garbage collection runs before every measured +sample. When `mode` is `'none'`, no garbage collection is forced. Without this +option, each benchmark uses its own `gc` value, which defaults to `'none'`. + +Forcing garbage collection requires the `--expose-gc` flag. With process +isolation, `--expose-gc` is added to benchmark child processes automatically +when `mode` is `'once'` or `'sample'`. With `--bench-isolation=none`, +`--expose-gc` must be passed explicitly. -### `--heap-prof-interval` +#### `--bench-isolation=mode` -Specify the average sampling interval in bytes for the heap profiles generated -by `--heap-prof`. The default is 512 \* 1024 bytes. +> Stability: 1 - Experimental + +Configures benchmark file isolation. When `mode` is `'process'`, each matching +file runs in a separate child process. This is the default. Files are still run +serially so their measured work does not overlap. + +When `mode` is `'none'`, all matching files and benchmarks run serially in the +benchmark runner process. This reduces startup overhead but allows module, +heap, and process state to carry between files. User writes to stdout or stderr +also share destinations with benchmark reporters in this mode. + +The supported modes are `'process'` and `'none'`. -### `--heap-prof-name` +#### `--bench-name-pattern=pattern` -Specify the file name of the heap profile generated by `--heap-prof`. +> Stability: 1 - Experimental + +Only runs benchmarks whose full hierarchical name matches the JavaScript +regular expression `pattern`. Non-matching benchmarks are reported as skipped. -### `--heapsnapshot-near-heap-limit=max_count` +#### `--bench-reporter-destination=destination` -Writes a V8 heap snapshot to disk when the V8 heap usage is approaching the -heap limit. `count` should be a non-negative integer (in which case -Node.js will write no more than `max_count` snapshots to disk). +> Stability: 1 - Experimental -When generating snapshots, garbage collection may be triggered and bring -the heap usage down. Therefore multiple snapshots may be written to disk -before the Node.js instance finally runs out of memory. These heap snapshots -can be compared to determine what objects are being allocated during the -time consecutive snapshots are taken. It's not guaranteed that Node.js will -write exactly `max_count` snapshots to disk, but it will try -its best to generate at least one and up to `max_count` snapshots before the -Node.js instance runs out of memory when `max_count` is greater than `0`. +Specifies the destination for the corresponding benchmark reporter. The value +can be `stdout`, `stderr`, or a file path. A single reporter defaults to +`stdout` when no destination is specified. -Generating V8 snapshots takes time and memory (both memory managed by the -V8 heap and native memory outside the V8 heap). The bigger the heap is, -the more resources it needs. Node.js will adjust the V8 heap to accommodate -the additional V8 heap memory overhead, and try its best to avoid using up -all the memory available to the process. When the process uses -more memory than the system deems appropriate, the process may be terminated -abruptly by the system, depending on the system configuration. +#### `--bench-reporter=reporter` -```console -$ node --max-old-space-size=100 --heapsnapshot-near-heap-limit=3 index.js -Wrote snapshot to Heap.20200430.100036.49580.0.001.heapsnapshot -Wrote snapshot to Heap.20200430.100037.49580.0.002.heapsnapshot -Wrote snapshot to Heap.20200430.100038.49580.0.003.heapsnapshot + -<--- Last few GCs ---> +> Stability: 1 - Experimental -[49580:0x110000000] 4826 ms: Mark-sweep 130.6 (147.8) -> 130.5 (147.8) MB, 27.4 / 0.0 ms (average mu = 0.126, current mu = 0.034) allocation failure scavenge might not succeed -[49580:0x110000000] 4845 ms: Mark-sweep 130.6 (147.8) -> 130.6 (147.8) MB, 18.8 / 0.0 ms (average mu = 0.088, current mu = 0.031) allocation failure scavenge might not succeed +Specifies a benchmark reporter. The built-in reporters are `spec` and `json`. +The `json` reporter emits newline-delimited JSON. A custom reporter can be +specified using a module specifier resolved from the current working directory. + +This option can be repeated. When multiple reporters are specified, each must +have a corresponding `--bench-reporter-destination`. The default reporter is +`spec`. +#### `--bench-samples=count` -<--- JS stacktrace ---> + -FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory -.... -``` +> Stability: 1 - Experimental + +Overrides the maximum number of measured callback invocations for every +selected benchmark. A benchmark may finish earlier by calling +`context.done()`. `count` must be an integer between `1` and `4294967295`. -### `--heapsnapshot-signal=signal` +#### `--bench-warmup=count` -Enables a signal handler that causes the Node.js process to write a heap dump -when the specified signal is received. `signal` must be a valid signal name. -Disabled by default. +> Stability: 1 - Experimental -```console -$ node --heapsnapshot-signal=SIGUSR2 index.js & -$ ps aux -USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND -node 1 5.5 6.1 787252 247004 ? Ssl 16:43 0:02 node --heapsnapshot-signal=SIGUSR2 index.js -$ kill -USR2 1 -$ ls -Heap.20190718.133405.15554.0.001.heapsnapshot -``` +Overrides the number of unreported warmup callback invocations for every +selected benchmark. `count` must be an integer between `0` and `4294967295`. +Without this option, each benchmark uses its own `warmup` value, which defaults +to `10`. -### `-h`, `--help` +#### `--experimental-bench` -Print node command-line options. -The output of this option is less detailed than this document. +> Stability: 1 - Experimental + +Enable the experimental `node:bench` module and command-line benchmark runner. -### `--icu-data-dir=file` +### Debugging and inspector -Specify ICU data load path. (Overrides `NODE_ICU_DATA`.) - -### `--import=module` +#### `--disable-sigusr1` -> Stability: 1 - Experimental +Disable the ability of starting a debugging session by sending a +`SIGUSR1` signal to the process. -Preload the specified module at startup. If the flag is provided several times, -each module will be executed sequentially in the order they appear, starting -with the ones provided in [`NODE_OPTIONS`][]. +#### `--experimental-inspector-network-resource` -Follows [ECMAScript module][] resolution rules. -Use [`--require`][] to load a [CommonJS module][]. -Modules preloaded with `--require` will run before modules preloaded with `--import`. + -Modules are preloaded into the main thread as well as any worker threads, -forked processes, or clustered processes. +> Stability: 1.1 - Active Development + +Enable experimental support for inspector network resources. -### `--input-type=type` +#### `--experimental-network-inspection` -This configures Node.js to interpret `--eval` or `STDIN` input as CommonJS or -as an ES module. Valid values are `"commonjs"`, `"module"`, `"module-typescript"` and `"commonjs-typescript"`. -The `"-typescript"` values are not available with the flag `--no-strip-types`. -The default is no value, or `"commonjs"` if `--no-experimental-detect-module` is passed. +> Stability: 1 - Experimental -If `--input-type` is not provided, -Node.js will try to detect the syntax with the following steps: +Enable experimental support for the network inspection with Chrome DevTools. -1. Run the input as CommonJS. -2. If step 1 fails, run the input as an ES module. -3. If step 2 fails with a SyntaxError, strip the types. -4. If step 3 fails with an error code [`ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`][] - or [`ERR_INVALID_TYPESCRIPT_SYNTAX`][], - throw the error from step 2, including the TypeScript error in the message, - else run as CommonJS. -5. If step 4 fails, run the input as an ES module. +#### `--experimental-storage-inspection` -To avoid the delay of multiple syntax detection passes, the `--input-type=type` flag can be used to specify -how the `--eval` input should be interpreted. + -The REPL does not support this option. Usage of `--input-type=module` with -[`--print`][] will throw an error, as `--print` does not support ES module -syntax. +> Stability: 1.1 - Active Development + +Enable experimental support for storage inspection -### `--insecure-http-parser` +#### `--experimental-worker-inspection` -Enable leniency flags on the HTTP parser. This may allow -interoperability with non-conformant HTTP implementations. - -When enabled, the parser will accept the following: - -* Invalid HTTP headers values. -* Invalid HTTP versions. -* Allow message containing both `Transfer-Encoding` - and `Content-Length` headers. -* Allow extra data after message when `Connection: close` is present. -* Allow extra transfer encodings after `chunked` has been provided. -* Allow `\n` to be used as token separator instead of `\r\n`. -* Allow `\r\n` not to be provided after a chunk. -* Allow spaces to be present after a chunk size and before `\r\n`. +> Stability: 1.1 - Active Development -All the above will expose your application to request smuggling -or poisoning attack. Avoid using this option. +Enable experimental support for the worker inspection with Chrome DevTools. -### `--inspect-brk[=[host:]port]` +#### `--inspect-brk[=[host:]port]` + +#### `--cpu-prof` + + + +Starts the V8 CPU profiler on start up, and writes the CPU profile to disk +before exit. + +If `--cpu-prof-dir` is not specified, the generated profile is placed +in the current working directory. + +If `--cpu-prof-name` is not specified, the generated profile is +named `CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile`. + +```console +$ node --cpu-prof index.js +$ ls *.cpuprofile +CPU.20190409.202950.15293.0.0.cpuprofile +``` + +If `--cpu-prof-name` is specified, the provided value is used as a template +for the file name. The following placeholder is supported and will be +substituted at runtime: + +* `${pid}` — the current process ID + +```console +$ node --cpu-prof --cpu-prof-name 'CPU.${pid}.cpuprofile' index.js +$ ls *.cpuprofile +CPU.15293.cpuprofile +``` + +#### `--cpu-prof-dir` + + + +Specify the directory where the CPU profiles generated by `--cpu-prof` will +be placed. + +The default value is controlled by the +[`--diagnostic-dir`][] command-line option. + +#### `--cpu-prof-interval` + + -Opens the REPL even if stdin does not appear to be a terminal. +Specify the sampling interval in microseconds for the CPU profiles generated +by `--cpu-prof`. The default is 1000 microseconds. -### `--jitless` +#### `--cpu-prof-name` -> Stability: 1 - Experimental. This flag is inherited from V8 and is subject to -> change upstream. - -Disable [runtime allocation of executable memory][jitless]. This may be -required on some platforms for security reasons. It can also reduce attack -surface on other platforms, but the performance impact may be severe. - -When WebAssembly is unavailable in this mode, TypeScript parsing and WebAssembly -module imports throw [`ERR_WEBASSEMBLY_NOT_SUPPORTED`][]. Node.js does not -guarantee alternative implementations of features that require WebAssembly or -runtime allocation of executable memory when those capabilities are unavailable. - -This flag controls V8's runtime code generation. It does not impose an -operating-system restriction on executable memory allocated by native addons or -[`node:ffi`][]. FFI operations that require unavailable executable memory can -throw [`ERR_RX_MEMORY_NOT_SUPPORTED`][]. +Specify the file name of the CPU profile generated by `--cpu-prof`. -### `--localstorage-file=file` +#### `--diagnostic-dir=directory` - +Set the directory to which all diagnostic output files are written. +Defaults to current working directory. -> Stability: 1.2 - Release candidate. +Affects the default output directory of: -The file used to store `localStorage` data. If the file does not exist, it is -created the first time `localStorage` is accessed. The same file may be shared -between multiple Node.js processes concurrently. +* [`--cpu-prof-dir`][] +* [`--heap-prof-dir`][] +* [`--redirect-warnings`][] -### `--max-http-header-size=size` +#### `--heap-prof` -Specify the maximum size, in bytes, of HTTP headers. Defaults to 16 KiB. - -### `--max-old-space-size-percentage=percentage` - -Sets the maximum memory size of V8's old memory section as a percentage of available system memory. -This flag takes precedence over `--max-old-space-size` when both are specified. - -The `percentage` parameter must be a number greater than 0 and up to 100, representing the percentage -of available system memory to allocate to the V8 heap. +Starts the V8 heap profiler on start up, and writes the heap profile to disk +before exit. -**Note:** This flag utilizes `--max-old-space-size`, which may be unreliable on 32-bit platforms due to -integer overflow issues. +If `--heap-prof-dir` is not specified, the generated profile is placed +in the current working directory. -```bash -# Using 50% of available system memory -node --max-old-space-size-percentage=50 index.js +If `--heap-prof-name` is not specified, the generated profile is +named `Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile`. -# Using 75% of available system memory -node --max-old-space-size-percentage=75 index.js +```console +$ node --heap-prof index.js +$ ls *.heapprofile +Heap.20190409.202950.15293.0.001.heapprofile ``` -### `--network-family-autoselection-attempt-timeout` +#### `--heap-prof-dir` -Sets the default value for the network family autoselection attempt timeout. -For more information, see [`net.getDefaultAutoSelectFamilyAttemptTimeout()`][]. +Specify the directory where the heap profiles generated by `--heap-prof` will +be placed. -### `--no-addons` +The default value is controlled by the +[`--diagnostic-dir`][] command-line option. + +#### `--heap-prof-interval` -Disable the `node-addons` exports condition as well as disable loading -native addons. When `--no-addons` is specified, calling `process.dlopen` or -requiring a native C++ addon will fail and throw an exception. +Specify the average sampling interval in bytes for the heap profiles generated +by `--heap-prof`. The default is 512 \* 1024 bytes. -### `--no-deprecation` +#### `--heap-prof-name` -Silence deprecation warnings. +Specify the file name of the heap profile generated by `--heap-prof`. -### `--no-experimental-detect-module` +#### `--heapsnapshot-near-heap-limit=max_count` -Disable using [syntax detection][] to determine module type. - -### `--no-experimental-ffi` +Writes a V8 heap snapshot to disk when the V8 heap usage is approaching the +heap limit. `count` should be a non-negative integer (in which case +Node.js will write no more than `max_count` snapshots to disk). - +When generating snapshots, garbage collection may be triggered and bring +the heap usage down. Therefore multiple snapshots may be written to disk +before the Node.js instance finally runs out of memory. These heap snapshots +can be compared to determine what objects are being allocated during the +time consecutive snapshots are taken. It's not guaranteed that Node.js will +write exactly `max_count` snapshots to disk, but it will try +its best to generate at least one and up to `max_count` snapshots before the +Node.js instance runs out of memory when `max_count` is greater than `0`. -> Stability: 1 - Experimental +Generating V8 snapshots takes time and memory (both memory managed by the +V8 heap and native memory outside the V8 heap). The bigger the heap is, +the more resources it needs. Node.js will adjust the V8 heap to accommodate +the additional V8 heap memory overhead, and try its best to avoid using up +all the memory available to the process. When the process uses +more memory than the system deems appropriate, the process may be terminated +abruptly by the system, depending on the system configuration. -Disable the experimental [`node:ffi`][] module. +```console +$ node --max-old-space-size=100 --heapsnapshot-near-heap-limit=3 index.js +Wrote snapshot to Heap.20200430.100036.49580.0.001.heapsnapshot +Wrote snapshot to Heap.20200430.100037.49580.0.002.heapsnapshot +Wrote snapshot to Heap.20200430.100038.49580.0.003.heapsnapshot -This flag is only available in builds with FFI support. +<--- Last few GCs ---> -### `--no-experimental-global-navigator` +[49580:0x110000000] 4826 ms: Mark-sweep 130.6 (147.8) -> 130.5 (147.8) MB, 27.4 / 0.0 ms (average mu = 0.126, current mu = 0.034) allocation failure scavenge might not succeed +[49580:0x110000000] 4845 ms: Mark-sweep 130.6 (147.8) -> 130.6 (147.8) MB, 18.8 / 0.0 ms (average mu = 0.088, current mu = 0.031) allocation failure scavenge might not succeed - -> Stability: 1 - Experimental +<--- JS stacktrace ---> -Disable exposition of [Navigator API][] on the global scope. +FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory +.... +``` -### `--no-experimental-require-module` +#### `--heapsnapshot-signal=signal` -> Stability: 3 - Legacy: Use [`--no-require-module`][] instead. +Enables a signal handler that causes the Node.js process to write a heap dump +when the specified signal is received. `signal` must be a valid signal name. +Disabled by default. -Legacy alias for [`--no-require-module`][]. +```console +$ node --heapsnapshot-signal=SIGUSR2 index.js & +$ ps aux +USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND +node 1 5.5 6.1 787252 247004 ? Ssl 16:43 0:02 node --heapsnapshot-signal=SIGUSR2 index.js +$ kill -USR2 1 +$ ls +Heap.20190718.133405.15554.0.001.heapsnapshot +``` -### `--no-experimental-sqlite` +#### `--no-force-async-hooks-checks` -Disable the [`node:sqlite`][] module. +Disables runtime checks for `async_hooks`. These will still be enabled +dynamically when `async_hooks` is enabled. -### `--no-experimental-vfs` +#### `--node-memory-debug` -Disable the experimental [`node:vfs`][] module and `--vfs-load`. +Enable extra debug checks for memory leaks in Node.js internals. This is +usually only useful for developers debugging Node.js itself. -### `--no-experimental-web-worker` +#### `--prof` -> Stability: 1.1 - Active Development - -Disable support for the Web Worker API. +Generate V8 profiler output. -### `--no-experimental-webstorage` +#### `--prof-process` -> Stability: 1.2 - Release candidate. - -Disable [`Web Storage`][] support. +Process V8 profiler output generated using the V8 option `--prof`. -### `--no-extra-info-on-fatal-exception` +#### `--report-compact` -Hide extra information on fatal exception that causes exit. +Write reports in a compact format, single-line JSON, more easily consumable +by log processing systems than the default multi-line format designed for +human consumption. -### `--no-force-async-hooks-checks` +#### `--report-dir=directory`, `--report-directory=directory` -Disables runtime checks for `async_hooks`. These will still be enabled -dynamically when `async_hooks` is enabled. +Location at which the report will be generated. -### `--no-global-search-paths` +#### `--report-exclude-env` -Do not search modules from global paths like `$HOME/.node_modules` and -`$NODE_PATH`. +When `--report-exclude-env` is passed the diagnostic report generated will not +contain the `environmentVariables` data. -### `--no-network-family-autoselection` +#### `--report-exclude-network` -Disables the family autoselection algorithm unless connection options explicitly -enables it. - - +Exclude `header.networkInterfaces` from the diagnostic report. By default +this is not set and the network interfaces are included. -### `--no-require-module` +#### `--report-filename=filename` -Disable support for loading a synchronous ES module graph in `require()`. +Name of the file to which the report will be written. -See [Loading ECMAScript modules using `require()`][]. +If the filename is set to `'stdout'` or `'stderr'`, the report is written to +the stdout or stderr of the process respectively. -### `--no-strip-types` +#### `--report-on-fatalerror` -Disable type-stripping for TypeScript files. -For more information, see the [TypeScript type-stripping][] documentation. +Enables the report to be triggered on fatal errors (internal errors within +the Node.js runtime such as out of memory) that lead to termination of the +application. Useful to inspect various diagnostic data elements such as heap, +stack, event loop state, resource consumption etc. to reason about the fatal +error. -### `--no-warnings` +#### `--report-on-process-timeout` -Silence all process warnings (including deprecations). +> Stability: 2 - Stable + +Enables the report to be generated when [`--process-timeout`][] expires, in +addition to the summary printed to stderr. Useful to inspect the JavaScript +and native stacks, the event loop state, and resource consumption to reason +about why the process did not exit. Requires [`--process-timeout`][]. + +Worker threads that do not provide their part of the report within two +seconds, for example because they are blocked in a synchronous operation such +as [`child_process.execSync()`][], are left out of it. -### `--no-worker-snapshot` +#### `--report-on-signal` -> Stability: 1 - Experimental - -Start worker threads by running the internal bootstrap from scratch instead of -deserializing the bootstrapped context from the built-in startup snapshot. +Enables report to be generated upon receiving the specified (or predefined) +signal to the running Node.js process. The signal to trigger the report is +specified through `--report-signal`. -### `--node-memory-debug` +#### `--report-signal=signal` -Enable extra debug checks for memory leaks in Node.js internals. This is -usually only useful for developers debugging Node.js itself. +Sets or resets the signal for report generation (not supported on Windows). +Default signal is `SIGUSR2`. -### `--openssl-config=file` +#### `--report-uncaught-exception` -Load an OpenSSL configuration file on startup. The file can activate an -OpenSSL FIPS provider. See [FIPS mode][]. - -This option takes precedence over the `OPENSSL_CONF` environment variable. +Enables report to be generated when the process exits due to an uncaught +exception. Useful when inspecting the JavaScript stack in conjunction with +native stack and other runtime environment data. -### `--openssl-legacy-provider` +#### `--trace-env` -Enable OpenSSL's legacy provider. For more information please see -[OSSL\_PROVIDER-legacy][OSSL_PROVIDER-legacy]. +Print information about any access to environment variables done in the current Node.js +instance to stderr, including: -### `--openssl-shared-config` +* The environment variable reads that Node.js does internally. +* Writes in the form of `process.env.KEY = "SOME VALUE"`. +* Reads in the form of `process.env.KEY`. +* Definitions in the form of `Object.defineProperty(process.env, 'KEY', {...})`. +* Queries in the form of `Object.hasOwn(process.env, 'KEY')`, + `process.env.hasOwnProperty('KEY')` or `'KEY' in process.env`. +* Deletions in the form of `delete process.env.KEY`. +* Enumerations inf the form of `...process.env` or `Object.keys(process.env)`. - +Only the names of the environment variables being accessed are printed. The values are not printed. -Enable OpenSSL default configuration section, `openssl_conf` to be read from -the OpenSSL configuration file. The default configuration file is named -`openssl.cnf` but this can be changed using the environment variable -`OPENSSL_CONF`, or by using the command line option `--openssl-config`. -The location of the default OpenSSL configuration file depends on how OpenSSL -is being linked to Node.js. Sharing the OpenSSL configuration may have unwanted -implications and it is recommended to use a configuration section specific to -Node.js which is `nodejs_conf` and is default when this option is not used. +To print the stack trace of the access, use `--trace-env-js-stack` and/or +`--trace-env-native-stack`. -### `--pending-deprecation` +#### `--trace-env-js-stack` -Emit pending deprecation warnings. - -Pending deprecations are generally identical to a runtime deprecation with the -notable exception that they are turned _off_ by default and will not be emitted -unless either the `--pending-deprecation` command-line flag, or the -`NODE_PENDING_DEPRECATION=1` environment variable, is set. Pending deprecations -are used to provide a kind of selective "early warning" mechanism that -developers may leverage to detect deprecated API usage. +In addition to what `--trace-env` does, this prints the JavaScript stack trace of the access. -### `--permission` +#### `--trace-env-native-stack` -Enable the Permission Model for current process. When enabled, the -following permissions are restricted: +In addition to what `--trace-env` does, this prints the native stack trace of the access. -> See also [`--permission-audit`](#--permission-audit) for an audit-only mode -> that logs violations without denying access. +#### `--trace-event-categories` -* File System - manageable through - [`--allow-fs-read`][], [`--allow-fs-write`][] flags -* Network - manageable through [`--allow-net`][] flag -* Environment variables - manageable through [`--allow-env`][] flag -* Child Process - manageable through [`--allow-child-process`][] flag -* Worker Threads - manageable through [`--allow-worker`][] flag -* WASI - manageable through [`--allow-wasi`][] flag -* Addons - manageable through [`--allow-addons`][] flag -* FFI - manageable through [`--allow-ffi`](#--allow-ffi) flag -* OpenSSL STORE loaders - manageable through [`--allow-openssl-store`][] flag + + +A comma separated list of categories that should be traced when trace event +tracing is enabled using `--trace-events-enabled`. -### `--permission-audit` +#### `--trace-event-file-pattern` -Enable audit mode for the permission model. When enabled, permission checks -are performed but access is **not** denied — no `ERR_ACCESS_DENIED` error is -thrown. Instead, each permission violation is published through the -`node:diagnostics_channel` module, and execution continues normally. +Template string specifying the filepath for the trace event data, it +supports `${rotation}` and `${pid}`. -This flag does not require [`--permission`](#--permission) to be specified. The -`--allow-*` flags are not needed in audit mode, since no -access is denied. +#### `--trace-events-enabled` -Audit mode is useful for discovering what permissions your application -requires before deploying with [`--permission`](#--permission). See the -[Permission Model][] documentation for the list of diagnostics channel names -and the message format. + -If both [`--permission`](#--permission) and `--permission-audit` are specified, -`--permission` takes precedence and the Permission Model runs in enforce mode. +Enables the collection of trace event tracing information. -### `--preserve-symlinks` +#### `--trace-exit` -Instructs the module loader to preserve symbolic links when resolving and -caching modules. +Prints a stack trace whenever an environment is exited proactively, +i.e. invoking `process.exit()`. -By default, when Node.js loads a module from a path that is symbolically linked -to a different on-disk location, Node.js will dereference the link and use the -actual on-disk "real path" of the module as both an identifier and as a root -path to locate other dependency modules. In most cases, this default behavior -is acceptable. However, when using symbolically linked peer dependencies, as -illustrated in the example below, the default behavior causes an exception to -be thrown if `moduleA` attempts to require `moduleB` as a peer dependency: +#### `--trace-sigint` -```text -{appDir} - ├── app - │ ├── index.js - │ └── node_modules - │ ├── moduleA -> {appDir}/moduleA - │ └── moduleB - │ ├── index.js - │ └── package.json - └── moduleA - ├── index.js - └── package.json -``` + -The `--preserve-symlinks` command-line flag instructs Node.js to use the -symlink path for modules as opposed to the real path, allowing symbolically -linked peer dependencies to be found. +Prints a stack trace on SIGINT. -Note, however, that using `--preserve-symlinks` can have other side effects. -Specifically, symbolically linked _native_ modules can fail to load if those -are linked from more than one location in the dependency tree (Node.js would -see those as two separate modules and would attempt to load the module multiple -times, causing an exception to be thrown). +#### `--trace-sync-io` -The `--preserve-symlinks` flag does not apply to the main module, which allows -`node --preserve-symlinks node_module/.bin/` to work. To apply the same -behavior for the main module, also use `--preserve-symlinks-main`. + + +Prints a stack trace whenever synchronous I/O is detected after the first turn +of the event loop. -### `--preserve-symlinks-main` +#### `--track-heap-objects` -Instructs the module loader to preserve symbolic links when resolving and -caching the main module (`require.main`). - -This flag exists so that the main module can be opted-in to the same behavior -that `--preserve-symlinks` gives to all other imports; they are separate flags, -however, for backward compatibility with older Node.js versions. +Track heap object allocations for heap snapshots. -`--preserve-symlinks-main` does not imply `--preserve-symlinks`; use -`--preserve-symlinks-main` in addition to -`--preserve-symlinks` when it is not desirable to follow symlinks before -resolving relative paths. +### Errors and warnings -See [`--preserve-symlinks`][] for more information. + -### `-p`, `--print "script"` +#### `--abort-on-uncaught-exception` -Identical to `-e` but prints the result. +Aborting instead of exiting causes a core file to be generated for post-mortem +analysis using a debugger (such as `lldb`, `gdb`, and `mdb`). + +If this flag is passed, the behavior can still be set to not abort through +[`process.setUncaughtExceptionCaptureCallback()`][] (and through usage of the +`node:domain` module that uses it). -### `--process-timeout=duration` +#### `--disable-warning=code-or-type` > Stability: 2 - Stable -Exits the process with code `124` if it is still running after `duration`, -measured from the start of the process. `duration` is a positive integer -followed by a unit: `ms`, `s`, `m`, or `h`, for example `500ms`, `30s`, `5m`, or -`1h`. The exit code matches the one used by the `timeout(1)` command. +Disable specific process warnings by `code` or `type`. -Before exiting, Node.js prints what the main thread was doing and which -resources were keeping the event loop alive to stderr: +Warnings emitted from [`process.emitWarning()`][emit_warning] may contain a +`code` and a `type`. This option will not-emit warnings that have a matching +`code` or `type`. -```console -$ node --process-timeout=5s server.js -(node:25418) Process timed out after 5s (--process-timeout). Exiting with code 124. -Main thread was not executing JavaScript. -Resources keeping the event loop alive: - TCPServerWrap (listening on [::]:3000, fd 20) - Timeout x2 (next due in 2931ms) -``` +List of [deprecation warnings][]. -If the main thread was executing JavaScript, its stack trace is printed instead. -Use [`--report-on-process-timeout`][] to also generate a [diagnostic report][]. +The Node.js core warning types are: `DeprecationWarning` and +`ExperimentalWarning` -The process exits without emitting the `'beforeExit'` and `'exit'` events, as -the JavaScript code may be what keeps the process running. Code coverage and -profiles, such as those enabled with [`NODE_V8_COVERAGE=dir`][] or -[`--cpu-prof`][], are still written. +For example, the following script will not emit +[DEP0025 `require('node:sys')`][DEP0025 warning] when executed with +`node --disable-warning=DEP0025`: -If the main thread does not respond within two seconds, for example because it -is blocked in a synchronous operation such as [`child_process.execSync()`][], -Node.js exits immediately without printing the stack trace and resources. +```mjs +import sys from 'node:sys'; +``` -This option is not allowed in [`NODE_OPTIONS`][], and it cannot be combined -with the options that enable the inspector, such as `--inspect`, -`--inspect-brk`, `--inspect-wait`, `--inspect-port`, and -`--inspect-publish-uid`, nor with `node inspect`, `--run`, or -`--build-snapshot`. While it is in effect, [`inspector.open()`][] and -[`session.connectToMainThread()`][] throw, and requests to activate the -inspector with `SIGUSR1` are ignored. +```cjs +const sys = require('node:sys'); +``` -Child processes that inherit `process.execArgv`, such as those created with -[`child_process.fork()`][], apply the timeout from their own start. With -[`--watch`][], the timeout applies to each run of the application rather than -to the process that watches for changes. When -[running tests from the command line][], the test runner process applies the -timeout to the whole run, and each test file that runs in its own process -applies it as well. +For example, the following script will emit the +[DEP0025 `require('node:sys')`][DEP0025 warning], but not any Experimental +Warnings (such as +[ExperimentalWarning: `vm.measureMemory` is an experimental feature][] +in <=v21) when executed with `node --disable-warning=ExperimentalWarning`: -### `--prof` +```mjs +import sys from 'node:sys'; +import vm from 'node:vm'; - +vm.measureMemory(); +``` -Generate V8 profiler output. +```cjs +const sys = require('node:sys'); +const vm = require('node:vm'); + +vm.measureMemory(); +``` -### `--prof-process` +#### `--enable-source-maps` -Process V8 profiler output generated using the V8 option `--prof`. +Enable [Source Map][] support for stack traces. -### `--redirect-warnings=file` +When using a transpiler, such as TypeScript, stack traces thrown by an +application reference the transpiled code, not the original source position. +`--enable-source-maps` enables caching of Source Maps and makes a best +effort to report stack traces relative to the original source file. - +Overriding `Error.prepareStackTrace` may prevent `--enable-source-maps` from +modifying the stack trace. Call and return the results of the original +`Error.prepareStackTrace` in the overriding function to modify the stack trace +with source maps. -Write process warnings to the given file instead of printing to stderr. The -file will be created if it does not exist, and will be appended to if it does. -If an error occurs while attempting to write the warning to the file, the -warning will be written to stderr instead. +```js +const originalPrepareStackTrace = Error.prepareStackTrace; +Error.prepareStackTrace = (error, trace) => { + // Modify error and trace and format stack trace with + // original Error.prepareStackTrace. + return originalPrepareStackTrace(error, trace); +}; +``` -The `file` name may be an absolute path. If it is not, the default directory it -will be written to is controlled by the -[`--diagnostic-dir`][] command-line option. +Note, enabling source maps can introduce latency to your application +when `Error.stack` is accessed. If you access `Error.stack` frequently +in your application, take into account the performance implications +of `--enable-source-maps`. -### `--report-compact` +#### `--force-node-api-uncaught-exceptions-policy` -Write reports in a compact format, single-line JSON, more easily consumable -by log processing systems than the default multi-line format designed for -human consumption. +Enforces `uncaughtException` event on Node-API asynchronous callbacks. + +To prevent from an existing add-on from crashing the process, this flag is not +enabled by default. In the future, this flag will be enabled by default to +enforce the correct behavior. -### `--report-dir=directory`, `--report-directory=directory` +#### `--no-deprecation` -Location at which the report will be generated. +Silence deprecation warnings. -### `--report-exclude-env` +#### `--no-extra-info-on-fatal-exception` -When `--report-exclude-env` is passed the diagnostic report generated will not -contain the `environmentVariables` data. +Hide extra information on fatal exception that causes exit. -### `--report-exclude-network` +#### `--no-warnings` -Exclude `header.networkInterfaces` from the diagnostic report. By default -this is not set and the network interfaces are included. +Silence all process warnings (including deprecations). -### `--report-filename=filename` +#### `--pending-deprecation` -Name of the file to which the report will be written. +Emit pending deprecation warnings. -If the filename is set to `'stdout'` or `'stderr'`, the report is written to -the stdout or stderr of the process respectively. +Pending deprecations are generally identical to a runtime deprecation with the +notable exception that they are turned _off_ by default and will not be emitted +unless either the `--pending-deprecation` command-line flag, or the +`NODE_PENDING_DEPRECATION=1` environment variable, is set. Pending deprecations +are used to provide a kind of selective "early warning" mechanism that +developers may leverage to detect deprecated API usage. -### `--report-on-fatalerror` +#### `--redirect-warnings=file` -Enables the report to be triggered on fatal errors (internal errors within -the Node.js runtime such as out of memory) that lead to termination of the -application. Useful to inspect various diagnostic data elements such as heap, -stack, event loop state, resource consumption etc. to reason about the fatal -error. +Write process warnings to the given file instead of printing to stderr. The +file will be created if it does not exist, and will be appended to if it does. +If an error occurs while attempting to write the warning to the file, the +warning will be written to stderr instead. + +The `file` name may be an absolute path. If it is not, the default directory it +will be written to is controlled by the +[`--diagnostic-dir`][] command-line option. -### `--report-on-process-timeout` +#### `--throw-deprecation` -> Stability: 2 - Stable - -Enables the report to be generated when [`--process-timeout`][] expires, in -addition to the summary printed to stderr. Useful to inspect the JavaScript -and native stacks, the event loop state, and resource consumption to reason -about why the process did not exit. Requires [`--process-timeout`][]. - -Worker threads that do not provide their part of the report within two -seconds, for example because they are blocked in a synchronous operation such -as [`child_process.execSync()`][], are left out of it. +Throw errors for deprecations. -### `--report-on-signal` +#### `--trace-deprecation` -Enables report to be generated upon receiving the specified (or predefined) -signal to the running Node.js process. The signal to trigger the report is -specified through `--report-signal`. +Print stack traces for deprecations. -### `--report-signal=signal` +#### `--trace-uncaught` -Sets or resets the signal for report generation (not supported on Windows). -Default signal is `SIGUSR2`. +Print stack traces for uncaught exceptions; usually, the stack trace associated +with the creation of an `Error` is printed, whereas this makes Node.js also +print the stack trace associated with throwing the value (which does not need +to be an `Error` instance). -### `--report-uncaught-exception` +Enabling this option may affect garbage collection behavior negatively. + +#### `--trace-warnings` -Enables report to be generated when the process exits due to an uncaught -exception. Useful when inspecting the JavaScript stack in conjunction with -native stack and other runtime environment data. +Print stack traces for process warnings (including deprecations). -### `-r`, `--require module` +#### `--unhandled-rejections=mode` -Preload the specified module at startup. - -Follows `require()`'s module resolution -rules. `module` may be either a path to a file, or a node module name. +Using this flag allows to change what should happen when an unhandled rejection +occurs. One of the following modes can be chosen: -Modules preloaded with `--require` will run before modules preloaded with `--import`. +* `throw`: Emit [`unhandledRejection`][]. If this hook is not set, raise the + unhandled rejection as an uncaught exception. This is the default. +* `strict`: Raise the unhandled rejection as an uncaught exception. If the + exception is handled, [`unhandledRejection`][] is emitted. +* `warn`: Always trigger a warning, no matter if the [`unhandledRejection`][] + hook is set or not but do not print the deprecation warning. +* `warn-with-error-code`: Emit [`unhandledRejection`][]. If this hook is not + set, trigger a warning, and set the process exit code to 1. +* `none`: Silence all warnings. -Modules are preloaded into the main thread as well as any worker threads, -forked processes, or clustered processes. +If a rejection happens during the command line entry point's ES module static +loading phase, it will always raise it as an uncaught exception. -### `--run` +### Permissions -This runs a specified command from a package.json's `"scripts"` object. -If a missing `"command"` is provided, it will list the available scripts. - -Passing `--run` without a command lists the available scripts and exits -with a non-zero exit code: +#### `--allow-addons` -```console -$ node --run -Available scripts are: - test: node --test -``` + -`--run` will traverse up to the root directory and finds a `package.json` -file to run the command from. +> Stability: 1.1 - Active development -`--run` prepends `./node_modules/.bin` for each ancestor of -the current directory, to the `PATH` in order to execute the binaries from -different folders where multiple `node_modules` directories are present, if -`ancestor-folder/node_modules/.bin` is a directory. +When using the [Permission Model][], the process will not be able to use +native addons by default. +Attempts to do so will throw an `ERR_DLOPEN_DISABLED` unless the +user explicitly passes the `--allow-addons` flag when starting Node.js. -`--run` executes the command in the directory containing the related `package.json`. +Example: -For example, the following command will run the `test` script of -the `package.json` in the current folder: +```cjs +// Attempt to require an native addon +require('nodejs-addon-example'); +``` ```console -$ node --run test +$ node --permission --allow-fs-read=* index.js +node:internal/modules/cjs/loader:1319 + return process.dlopen(module, path.toNamespacedPath(filename)); + ^ + +Error: Cannot load native addon because loading addons is disabled. + at Module._extensions..node (node:internal/modules/cjs/loader:1319:18) + at Module.load (node:internal/modules/cjs/loader:1091:32) + at Module._load (node:internal/modules/cjs/loader:938:12) + at Module.require (node:internal/modules/cjs/loader:1115:19) + at require (node:internal/modules/helpers:130:18) + at Object. (/home/index.js:1:15) + at Module._compile (node:internal/modules/cjs/loader:1233:14) + at Module._extensions..js (node:internal/modules/cjs/loader:1287:10) + at Module.load (node:internal/modules/cjs/loader:1091:32) + at Module._load (node:internal/modules/cjs/loader:938:12) { + code: 'ERR_DLOPEN_DISABLED' +} ``` -You can also pass arguments to the command. Any argument after `--` will -be appended to the script: +#### `--allow-child-process` -```console -$ node --run test -- --verbose -``` + -#### Intentional limitations +> Stability: 1.1 - Active development -`node --run` is not meant to match the behaviors of `npm run` or of the `run` -commands of other package managers. The Node.js implementation is intentionally -more limited, in order to focus on top performance for the most common use -cases. -Some features of other `run` implementations that are intentionally excluded -are: +When using the [Permission Model][], the process will not be able to spawn any +child process by default. +Attempts to do so will throw an `ERR_ACCESS_DENIED` unless the +user explicitly passes the `--allow-child-process` flag when starting Node.js. -* Running `pre` or `post` scripts in addition to the specified script. -* Defining package manager-specific environment variables. +Example: -#### Environment variables +```js +const childProcess = require('node:child_process'); +// Attempt to bypass the permission +childProcess.spawn('node', ['-e', 'require("fs").writeFileSync("/new-file", "example")']); +``` -The following environment variables are set when running a script with `--run`: +```console +$ node --permission --allow-fs-read=* index.js +node:internal/child_process:388 + const err = this._handle.spawn(options); + ^ +Error: Access to this API has been restricted + at ChildProcess.spawn (node:internal/child_process:388:28) + at node:internal/main/run_main_module:17:47 { + code: 'ERR_ACCESS_DENIED', + permission: 'ChildProcess' +} +``` -* `NODE_RUN_SCRIPT_NAME`: The name of the script being run. For example, if - `--run` is used to run `test`, the value of this variable will be `test`. -* `NODE_RUN_PACKAGE_JSON_PATH`: The path to the `package.json` that is being - processed. +The `child_process.fork()` API inherits the execution arguments from the +parent process. This means that if Node.js is started with the Permission +Model enabled and the `--allow-child-process` flag is set, any child process +created using `child_process.fork()` will automatically receive all relevant +Permission Model flags. -Environment variables loaded from a file with [`--env-file`][] are not applied -to the command executed by `--run`. +This behavior also applies to `child_process.spawn()`, but in that case, the +flags are propagated via the `NODE_OPTIONS` environment variable rather than +directly through the process arguments. -### `--secure-heap-min=n` +#### `--allow-env` -When using `--secure-heap`, the `--secure-heap-min` flag specifies the -minimum allocation from the secure heap. The minimum value is `2`. -The maximum value is the lesser of `--secure-heap` or `2147483647`. -The value given must be a power of two. +> Stability: 1.1 - Active development -### `--secure-heap=n` +When using the [Permission Model][], the process starts without the environment +variables it has not been granted access to. At startup, every variable that +`--allow-env` does not match is removed from the process environment. Removed +variables are absent from `process.env`, from diagnostic reports, from native +code calling `getenv()`, and from the environment of child processes and worker +threads. - +The valid values are: -Initializes an OpenSSL secure heap of `n` bytes. When initialized, the -secure heap is used for selected types of allocations within OpenSSL -during key generation and other operations. This is useful, for instance, -to prevent sensitive information from leaking due to pointer overruns -or underruns. +* `*` - Grants access to every environment variable. +* A variable name, for example `--allow-env=DATABASE_URL`. +* A variable name prefix followed by `*`, for example `--allow-env=APP_*`. -The secure heap is a fixed size and cannot be resized at runtime so, -if used, it is important to select a large enough heap to cover all -application uses. +Multiple values can be passed by repeating the flag, or by separating them with +commas: `--allow-env=PORT,APP_*`. Variable names are case-insensitive on +Windows. -The heap size given must be a power of two. Any value less than 2 -will disable the secure heap. +Example: -The secure heap is disabled by default. +```js +console.log(process.env.DATABASE_URL); +console.log(process.env.AWS_SECRET_ACCESS_KEY); +``` -The secure heap is not available on Windows. +```console +$ node --permission --allow-fs-read=* --allow-env=DATABASE_URL index.js +postgres://localhost/app +undefined +(node:1234) Warning: The permission model removed the environment variable "AWS_SECRET_ACCESS_KEY" at startup. Use --allow-env to manage permissions. +``` -See [`CRYPTO_secure_malloc_init`][] for more details. +The variables that Node.js and its bundled dependencies read, such as +`NODE_OPTIONS`, `PATH`, `HOME`, `TZ`, and `SSL_CERT_FILE`, are always kept, as +are the variables defined in [`--env-file`][] files. `NODE_ENV` is not kept +by default, so applications and libraries that read it need +`--allow-env=NODE_ENV`. See [Environment variable permissions][] for details. -### `--snapshot-blob=path` +#### `--allow-ffi` -> Stability: 1 - Experimental - -When used with `--build-snapshot`, `--snapshot-blob` specifies the path -where the generated snapshot blob is written to. If not specified, the -generated blob is written to `snapshot.blob` in the current working directory. +> Stability: 1.1 - Active development -When used without `--build-snapshot`, `--snapshot-blob` specifies the -path to the blob that is used to restore the application state. +When using the [Permission Model][], the process will not be able to use FFI +APIs by default. Attempts to use FFI APIs will throw an `ERR_ACCESS_DENIED` +exception unless the user explicitly passes the `--allow-ffi` flag when +starting Node.js. The [`node:ffi`][] module is only available in builds with +FFI support. -When loading a snapshot, Node.js checks that: +Example: -1. The version, architecture, and platform of the running Node.js binary - are exactly the same as that of the binary that generates the snapshot. -2. The V8 flags and CPU features are compatible with that of the binary - that generates the snapshot. +```js +const { DynamicLibrary, suffix } = require('node:ffi'); +const lib = new DynamicLibrary(`./mylib.${suffix}`); +``` -If they don't match, Node.js refuses to load the snapshot and exits with -status code 1. +```console +$ node --permission index.js +Error: Access to this API has been restricted. Use --allow-ffi to manage permissions. + at node:internal/main/run_main_module:17:47 { + code: 'ERR_ACCESS_DENIED', + permission: 'FFI' +} +``` -### `--test` +#### `--allow-fs-read` -Starts the Node.js command line test runner. This flag cannot be combined with -`--watch-path`, `--check`, `--eval`, `--interactive`, or the inspector. -See the documentation on [running tests from the command line][] -for more details. +This flag configures file system read permissions using +the [Permission Model][]. -### `--test-concurrency` +The valid arguments for the `--allow-fs-read` flag are: - +* `*` - To allow all `FileSystemRead` operations. +* Multiple paths can be allowed using multiple `--allow-fs-read` flags. + Example `--allow-fs-read=/folder1/ --allow-fs-read=/folder2/` -The maximum number of test files that the test runner CLI will execute -concurrently. If `--test-isolation` is set to `'none'`, this flag is ignored and -concurrency is one. Otherwise, concurrency defaults to -`os.availableParallelism() - 1`. +Examples can be found in the [File System Permissions][] documentation. -### `--test-coverage-branches=threshold` +The initializer module and custom `--require` modules have an implicit +read permission. The entrypoint is granted as passed on the command line, +without the module loader's resolution; see the [File System Permissions][] +documentation for details. - +```console +$ node --permission -r custom-require.js -r custom-require-2.js index.js +``` -> Stability: 1 - Experimental +* The `custom-require.js`, `custom-require-2.js`, and `index.js` will be + by default in the allowed read list. -Require a minimum percent of covered branches. If code coverage does not reach -the threshold specified, the process will exit with code `1`. +```js +process.permission.has('fs.read', 'index.js'); // true +process.permission.has('fs.read', 'custom-require.js'); // true +process.permission.has('fs.read', 'custom-require-2.js'); // true +``` -### `--test-coverage-exclude` +#### `--allow-fs-vfs` -> Stability: 1 - Experimental - -Excludes specific files from code coverage using a glob pattern, which can match -both absolute and relative file paths. +> Stability: 1.1 - Active development -This option may be specified multiple times to exclude multiple glob patterns. +When using the [Permission Model][], a [virtual file system][] cannot be +mounted by default: [`vfs.mount()`][] throws `ERR_INVALID_STATE` unless the +user explicitly passes the `--allow-fs-vfs` flag when starting Node.js. +In audit mode ([`--permission-audit`](#--permission-audit)), mounting is not +refused and no message is published to the diagnostics channel. -If both `--test-coverage-exclude` and `--test-coverage-include` are provided, -files must meet **both** criteria to be included in the coverage report. +A mounted VFS serves paths that the file system permissions do not describe, +so mounting one is gated on its own flag rather than on `--allow-fs-read` or +`--allow-fs-write`. -By default all the matching test files are excluded from the coverage report. -Specifying this option will override the default behavior. +```console +$ node --permission --allow-fs-vfs app.js +``` -### `--test-coverage-functions=threshold` +#### `--allow-fs-write` -> Stability: 1 - Experimental - -Require a minimum percent of covered functions. If code coverage does not reach -the threshold specified, the process will exit with code `1`. - -### `--test-coverage-include` - - +This flag configures file system write permissions using +the [Permission Model][]. -> Stability: 1 - Experimental +The valid arguments for the `--allow-fs-write` flag are: -Includes specific files in code coverage using a glob pattern, which can match -both absolute and relative file paths. +* `*` - To allow all `FileSystemWrite` operations. +* Multiple paths can be allowed using multiple `--allow-fs-write` flags. + Example `--allow-fs-write=/folder1/ --allow-fs-write=/folder2/` -This option may be specified multiple times to include multiple glob patterns. +Paths delimited by comma (`,`) are no longer allowed. +When passing a single flag with a comma a warning will be displayed. -If both `--test-coverage-exclude` and `--test-coverage-include` are provided, -files must meet **both** criteria to be included in the coverage report. +Examples can be found in the [File System Permissions][] documentation. -### `--test-coverage-include-all` +#### `--allow-inspector` -> Stability: 1 - Experimental +> Stability: 1.0 - Early development -Includes source files that were never loaded by the test run in the coverage -report, where they are reported as having zero coverage. +When using the [Permission Model][], the process will not be able to connect +through inspector protocol. -Candidate files are searched for in the current working directory, and are -subject to the same `--test-coverage-include` and `--test-coverage-exclude` -filtering as the rest of the report. +Attempts to do so will throw an `ERR_ACCESS_DENIED` unless the +user explicitly passes the `--allow-inspector` flag when starting Node.js. -### `--test-coverage-lines=threshold` +Example: - +```js +const { Session } = require('node:inspector/promises'); -> Stability: 1 - Experimental +const session = new Session(); +session.connect(); +``` -Require a minimum percent of covered lines. If code coverage does not reach -the threshold specified, the process will exit with code `1`. +```console +$ node --permission index.js +Error: connect ERR_ACCESS_DENIED Access to this API has been restricted. Use --allow-inspector to manage permissions. + code: 'ERR_ACCESS_DENIED', +} +``` -### `--test-forbid-only` +#### `--allow-net` -Fails the test run if a test or suite is declared with `only: true`, including -the `test.only()`, `it.only()`, `suite.only()`, and `describe.only()` shorthands, -or if `testContext.runOnly(true)` is called. This is useful in CI to prevent -accidentally committing exclusive tests that exclude the rest of a test suite. +> Stability: 1.1 - Active development -This option applies with either test isolation mode and takes precedence over -`--test-only`. Name filtering, TODO markers, and expected failures do not suppress -detected violations. Only declarations evaluated during the run are checked; -code inside a skipped test callback is not evaluated. +When using the [Permission Model][], the process will not be able to access +network by default. +Attempts to do so will throw an `ERR_ACCESS_DENIED` unless the +user explicitly passes the `--allow-net` flag when starting Node.js. -### `--test-force-exit` +Example: - +```js +const http = require('node:http'); +// Attempt to bypass the permission +const req = http.get('http://example.com', () => {}); -Configures the test runner to exit the process once all known tests have -finished executing even if the event loop would otherwise remain active. +req.on('error', (err) => { + console.log('err', err); +}); +``` + +```console +$ node --permission index.js +Error: connect ERR_ACCESS_DENIED Access to this API has been restricted. Use --allow-net to manage permissions. + code: 'ERR_ACCESS_DENIED', +} +``` -### `--test-global-setup=module` +#### `--allow-openssl-store` -> Stability: 1.0 - Early development +> Stability: 1.1 - Active development -Specify a module that will be evaluated before all tests are executed and -can be used to setup global state or fixtures for tests. +When using the [Permission Model][], the process will not be able to use +OpenSSL STORE loaders by default, for example to load a private key from a +{URL} passed to [`crypto.createPrivateKey()`][]. Attempts to do so will throw +an `ERR_ACCESS_DENIED` unless the user explicitly passes the +`--allow-openssl-store` flag. This permission can be dropped at runtime via +[`permission.drop()`][]. -See the documentation on [global setup and teardown][] for more details. +This flag grants broad authority to configured OpenSSL STORE loaders. A loader +may access files, devices, tokens, or the network. Access performed by a loader +is not constrained by the `fs.read`, `fs.write`, or `net` permission scopes. + +Loaders and the modules they load are subject to [`--allow-env`][], however. +Environment variables they rely on, such as `SOFTHSM2_CONF` for SoftHSM, are +removed at startup unless they are granted explicitly with `--allow-env`. See +[Environment variable permissions][] for details. -### `--test-isolation=mode` +#### `--allow-wasi` -Configures the type of test isolation used in the test runner. When `mode` is -`'process'`, each test file is run in a separate child process. When `mode` is -`'none'`, all test files run in the same process as the test runner. The default -isolation mode is `'process'`. This flag is ignored if the `--test` flag is not -present. See the [test runner execution model][] section for more information. +> Stability: 1.1 - Active development -### `--test-name-pattern` +When using the [Permission Model][], the process will not be capable of creating +any WASI instances by default. +For security reasons, the call will throw an `ERR_ACCESS_DENIED` unless the +user explicitly passes the flag `--allow-wasi` in the main Node.js process. - +Example: -A regular expression that configures the test runner to only execute tests -whose name matches the provided pattern. See the documentation on -[filtering tests by name][] for more details. +```js +const { WASI } = require('node:wasi'); +// Attempt to bypass the permission +new WASI({ + version: 'preview1', + // Attempt to mount the whole filesystem + preopens: { + '/': '/', + }, +}); +``` -If both `--test-name-pattern` and `--test-skip-pattern` are supplied, -tests must satisfy **both** requirements in order to be executed. +```console +$ node --permission --allow-fs-read=* index.js -### `--test-only` +Error: Access to this API has been restricted + at node:internal/main/run_main_module:30:49 { + code: 'ERR_ACCESS_DENIED', + permission: 'WASI', +} +``` + +#### `--allow-worker` -Configures the test runner to only execute top level tests that have the `only` -option set. This flag is not necessary when test isolation is disabled. +> Stability: 1.1 - Active development -### `--test-random-seed` +When using the [Permission Model][], the process will not be able to create any +worker threads by default. +For security reasons, the call will throw an `ERR_ACCESS_DENIED` unless the +user explicitly pass the flag `--allow-worker` in the main Node.js process. - +Example: -Set the seed used to randomize test execution order. This applies to both test -file execution order and queued tests within each file. Providing this flag -enables randomization implicitly, even without `--test-randomize`. +```js +const { Worker } = require('node:worker_threads'); +// Attempt to bypass the permission +new Worker(__filename); +``` -The value must be an integer between `0` and `4294967295`. +```console +$ node --permission --allow-fs-read=* index.js -This flag cannot be used with `--watch` or `--test-rerun-failures`. +Error: Access to this API has been restricted + at node:internal/main/run_main_module:17:47 { + code: 'ERR_ACCESS_DENIED', + permission: 'WorkerThreads' +} +``` -### `--test-randomize` +#### `--permission` -Randomize test execution order. This applies to both test file execution order -and queued tests within each file. This can help detect tests that rely on -shared state or execution order. - -The seed used for randomization is printed in the test summary and can be -reused with `--test-random-seed`. +Enable the Permission Model for current process. When enabled, the +following permissions are restricted: -For detailed behavior and examples, see -[randomizing tests execution order][]. +> See also [`--permission-audit`](#--permission-audit) for an audit-only mode +> that logs violations without denying access. -This flag cannot be used with `--watch` or `--test-rerun-failures`. +* File System - manageable through + [`--allow-fs-read`][], [`--allow-fs-write`][] flags +* Network - manageable through [`--allow-net`][] flag +* Environment variables - manageable through [`--allow-env`][] flag +* Child Process - manageable through [`--allow-child-process`][] flag +* Worker Threads - manageable through [`--allow-worker`][] flag +* WASI - manageable through [`--allow-wasi`][] flag +* Addons - manageable through [`--allow-addons`][] flag +* FFI - manageable through [`--allow-ffi`](#--allow-ffi) flag +* OpenSSL STORE loaders - manageable through [`--allow-openssl-store`][] flag -### `--test-reporter` +#### `--permission-audit` -A test reporter to use when running tests. See the documentation on -[test reporters][] for more details. +Enable audit mode for the permission model. When enabled, permission checks +are performed but access is **not** denied — no `ERR_ACCESS_DENIED` error is +thrown. Instead, each permission violation is published through the +`node:diagnostics_channel` module, and execution continues normally. + +This flag does not require [`--permission`](#--permission) to be specified. The +`--allow-*` flags are not needed in audit mode, since no +access is denied. + +Audit mode is useful for discovering what permissions your application +requires before deploying with [`--permission`](#--permission). See the +[Permission Model][] documentation for the list of diagnostics channel names +and the message format. + +If both [`--permission`](#--permission) and `--permission-audit` are specified, +`--permission` takes precedence and the Permission Model runs in enforce mode. -### `--test-reporter-destination` +### Security hardening -The destination for the corresponding test reporter. See the documentation on -[test reporters][] for more details. - -### `--test-rerun-failures` +#### `--disable-proto=mode` -A path to a file allowing the test runner to persist the state of the test -suite between runs. The test runner will use this file to determine which tests -have already succeeded or failed, allowing for re-running of failed tests -without having to re-run the entire test suite. The test runner will create this -file if it does not exist. -See the documentation on [test reruns][] for more details. +Disable the `Object.prototype.__proto__` property. If `mode` is `delete`, the +property is removed entirely. If `mode` is `throw`, accesses to the +property throw an exception with the code `ERR_PROTO_ACCESS`. -### `--test-shard` +#### `--disallow-code-generation-from-strings` -Test suite shard to execute in a format of `/`, where +Make built-in language features like `eval` and `new Function` that generate +code from strings throw an exception instead. This does not affect the Node.js +`node:vm` module. -* `index` is a positive integer, index of divided parts. -* `total` is a positive integer, total of divided part. +#### `--frozen-intrinsics` -This command will divide all tests files into `total` equal parts, -and will run only those that happen to be in an `index` part. + -For example, to split your tests suite into three parts, use this: +> Stability: 1 - Experimental -```bash -node --test --test-shard=1/3 -node --test --test-shard=2/3 -node --test --test-shard=3/3 -``` +Enable experimental frozen intrinsics like `Array` and `Object`. + +Only the root context is supported. There is no guarantee that +`globalThis.Array` is indeed the default intrinsic reference. Code may break +under this flag. + +To allow polyfills to be added, +[`--require`][] and [`--import`][] both run before freezing intrinsics. -### `--test-skip-pattern` +#### `--zero-fill-buffers` -A regular expression that configures the test runner to skip tests -whose name matches the provided pattern. See the documentation on -[filtering tests by name][] for more details. - -If both `--test-name-pattern` and `--test-skip-pattern` are supplied, -tests must satisfy **both** requirements in order to be executed. +Automatically zero-fills all newly allocated [`Buffer`][] instances. -### `--test-timeout` +### Networking -A number of milliseconds the test execution will fail after. If unspecified, -subtests inherit this value from their parent. The default value is `Infinity`. - -### `--test-update-snapshots` +#### `--dns-result-order=order` -Regenerates the snapshot files used by the test runner for [snapshot testing][]. - -### `--throw-deprecation` +Set the default value of `order` in [`dns.lookup()`][] and +[`dnsPromises.lookup()`][]. The value could be: - +* `ipv4first`: sets default `order` to `ipv4first`. +* `ipv6first`: sets default `order` to `ipv6first`. +* `verbatim`: sets default `order` to `verbatim`. -Throw errors for deprecations. +The default is `verbatim` and [`dns.setDefaultResultOrder()`][] have higher +priority than `--dns-result-order`. -### `--title=title` +#### `--insecure-http-parser` -Set `process.title` on startup. +Enable leniency flags on the HTTP parser. This may allow +interoperability with non-conformant HTTP implementations. -### `--tls-cipher-list=list` +When enabled, the parser will accept the following: - +* Invalid HTTP headers values. +* Invalid HTTP versions. +* Allow message containing both `Transfer-Encoding` + and `Content-Length` headers. +* Allow extra data after message when `Connection: close` is present. +* Allow extra transfer encodings after `chunked` has been provided. +* Allow `\n` to be used as token separator instead of `\r\n`. +* Allow `\r\n` not to be provided after a chunk. +* Allow spaces to be present after a chunk size and before `\r\n`. -Specify an alternative default TLS cipher list. Requires Node.js to be built -with crypto support (default). +All the above will expose your application to request smuggling +or poisoning attack. Avoid using this option. -### `--tls-keylog=file` +#### `--max-http-header-size=size` -Log TLS key material to a file. The key material is in NSS `SSLKEYLOGFILE` -format and can be used by software (such as Wireshark) to decrypt the TLS -traffic. +Specify the maximum size, in bytes, of HTTP headers. Defaults to 16 KiB. -### `--tls-max-v1.2` +#### `--network-family-autoselection-attempt-timeout` -Set [`tls.DEFAULT_MAX_VERSION`][] to 'TLSv1.2'. Use to disable support for -TLSv1.3. +Sets the default value for the network family autoselection attempt timeout. +For more information, see [`net.getDefaultAutoSelectFamilyAttemptTimeout()`][]. -### `--tls-max-v1.3` +#### `--no-network-family-autoselection` -Set default [`tls.DEFAULT_MAX_VERSION`][] to 'TLSv1.3'. Use to enable support -for TLSv1.3. +Disables the family autoselection algorithm unless connection options explicitly +enables it. + + -### `--tls-min-v1.0` +#### `--use-env-proxy` -Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1'. Use for compatibility with -old TLS clients or servers. +> Stability: 1.1 - Active Development + +When enabled, Node.js parses the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` +environment variables during startup, and routes requests through the +specified proxy. + +Use this only with proxies that are trusted and authorized for the deployment. +Proxy support is intended for reaching external networks through authorized +proxy servers, for example when a firewall requires one. It is not for hiding +traffic or evading network policy. See [Built-in Proxy Support][]. -### `--tls-min-v1.1` +This is equivalent to setting the [`NODE_USE_ENV_PROXY=1`][] environment variable. +When both are set, `--use-env-proxy` takes precedence. + +### TLS and crypto -Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.1'. Use for compatibility -with old TLS clients or servers. +#### `--enable-fips` + + -### `--tls-min-v1.2` +Enable [FIPS mode][] at startup by adding `fips=yes` to OpenSSL's default +property query. This does not load or validate a FIPS provider or run its +self-tests. Configure OpenSSL to load the provider separately. + +#### `--enable-fips-indicator-events` -Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.2'. This is the default for -12.x and later, but the option is supported for compatibility with older Node.js -versions. +Publish OpenSSL FIPS indicator results to the +[`'crypto.fips.indicator'`][] diagnostics channel. This option requires OpenSSL +3.4 or later. It does not enable [FIPS mode][] or change whether an operation +is permitted. -### `--tls-min-v1.3` +#### `--force-fips[=mode]` -Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.3'. Use to disable support -for TLSv1.2, which is not as secure as TLSv1.3. +Enable [FIPS mode][] at startup and prevent it from being disabled from script +code. This changes the default property query as described for +[`--enable-fips`][]. + +An optional mode can be specified using `--force-fips=mode`: + +* `provider`: Preserve the OpenSSL FIPS provider's configured handling of + non-approved operations. This is the current default when the mode is + omitted. +* `strict`: Reject non-approved operations reported through the OpenSSL FIPS + indicator callback. This mode requires OpenSSL 3.4 or later. + +The `strict` mode only covers operations reported through the callback for +OpenSSL's default library context. It does not cover native addons that use +another `OSSL_LIB_CTX` or another copy of `libcrypto`, nor operation-specific +indicators that do not invoke the callback. -### `--trace-deprecation` +#### `--openssl-config=file` -Print stack traces for deprecations. +Load an OpenSSL configuration file on startup. The file can activate an +OpenSSL FIPS provider. See [FIPS mode][]. + +This option takes precedence over the `OPENSSL_CONF` environment variable. -### `--trace-env` +#### `--openssl-legacy-provider` -Print information about any access to environment variables done in the current Node.js -instance to stderr, including: +Enable OpenSSL's legacy provider. For more information please see +[OSSL\_PROVIDER-legacy][OSSL_PROVIDER-legacy]. -* The environment variable reads that Node.js does internally. -* Writes in the form of `process.env.KEY = "SOME VALUE"`. -* Reads in the form of `process.env.KEY`. -* Definitions in the form of `Object.defineProperty(process.env, 'KEY', {...})`. -* Queries in the form of `Object.hasOwn(process.env, 'KEY')`, - `process.env.hasOwnProperty('KEY')` or `'KEY' in process.env`. -* Deletions in the form of `delete process.env.KEY`. -* Enumerations inf the form of `...process.env` or `Object.keys(process.env)`. +#### `--openssl-shared-config` -Only the names of the environment variables being accessed are printed. The values are not printed. + -To print the stack trace of the access, use `--trace-env-js-stack` and/or -`--trace-env-native-stack`. +Enable OpenSSL default configuration section, `openssl_conf` to be read from +the OpenSSL configuration file. The default configuration file is named +`openssl.cnf` but this can be changed using the environment variable +`OPENSSL_CONF`, or by using the command line option `--openssl-config`. +The location of the default OpenSSL configuration file depends on how OpenSSL +is being linked to Node.js. Sharing the OpenSSL configuration may have unwanted +implications and it is recommended to use a configuration section specific to +Node.js which is `nodejs_conf` and is default when this option is not used. -### `--trace-env-js-stack` +#### `--secure-heap-min=n` -In addition to what `--trace-env` does, this prints the JavaScript stack trace of the access. +When using `--secure-heap`, the `--secure-heap-min` flag specifies the +minimum allocation from the secure heap. The minimum value is `2`. +The maximum value is the lesser of `--secure-heap` or `2147483647`. +The value given must be a power of two. -### `--trace-env-native-stack` +#### `--secure-heap=n` -In addition to what `--trace-env` does, this prints the native stack trace of the access. - -### `--trace-event-categories` +Initializes an OpenSSL secure heap of `n` bytes. When initialized, the +secure heap is used for selected types of allocations within OpenSSL +during key generation and other operations. This is useful, for instance, +to prevent sensitive information from leaking due to pointer overruns +or underruns. - +The secure heap is a fixed size and cannot be resized at runtime so, +if used, it is important to select a large enough heap to cover all +application uses. -A comma separated list of categories that should be traced when trace event -tracing is enabled using `--trace-events-enabled`. +The heap size given must be a power of two. Any value less than 2 +will disable the secure heap. -### `--trace-event-file-pattern` +The secure heap is disabled by default. - +The secure heap is not available on Windows. -Template string specifying the filepath for the trace event data, it -supports `${rotation}` and `${pid}`. +See [`CRYPTO_secure_malloc_init`][] for more details. -### `--trace-events-enabled` +#### `--tls-cipher-list=list` -Enables the collection of trace event tracing information. +Specify an alternative default TLS cipher list. Requires Node.js to be built +with crypto support (default). -### `--trace-exit` +#### `--tls-keylog=file` -Prints a stack trace whenever an environment is exited proactively, -i.e. invoking `process.exit()`. - -### `--trace-require-module=mode` - - - -Prints information about usage of [Loading ECMAScript modules using `require()`][]. - -When `mode` is `all`, all usage is printed. When `mode` is `no-node-modules`, usage -from the `node_modules` folder is excluded. +Log TLS key material to a file. The key material is in NSS `SSLKEYLOGFILE` +format and can be used by software (such as Wireshark) to decrypt the TLS +traffic. -### `--trace-sigint` +#### `--tls-max-v1.2` -Prints a stack trace on SIGINT. +Set [`tls.DEFAULT_MAX_VERSION`][] to 'TLSv1.2'. Use to disable support for +TLSv1.3. -### `--trace-sync-io` +#### `--tls-max-v1.3` -Prints a stack trace whenever synchronous I/O is detected after the first turn -of the event loop. +Set default [`tls.DEFAULT_MAX_VERSION`][] to 'TLSv1.3'. Use to enable support +for TLSv1.3. -### `--trace-tls` +#### `--tls-min-v1.0` -Prints TLS packet trace information to `stderr`. This can be used to debug TLS -connection problems. +Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1'. Use for compatibility with +old TLS clients or servers. -### `--trace-uncaught` +#### `--tls-min-v1.1` -Print stack traces for uncaught exceptions; usually, the stack trace associated -with the creation of an `Error` is printed, whereas this makes Node.js also -print the stack trace associated with throwing the value (which does not need -to be an `Error` instance). - -Enabling this option may affect garbage collection behavior negatively. +Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.1'. Use for compatibility +with old TLS clients or servers. -### `--trace-warnings` +#### `--tls-min-v1.2` -Print stack traces for process warnings (including deprecations). +Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.2'. This is the default for +12.x and later, but the option is supported for compatibility with older Node.js +versions. -### `--track-heap-objects` +#### `--tls-min-v1.3` -Track heap object allocations for heap snapshots. +Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.3'. Use to disable support +for TLSv1.2, which is not as secure as TLSv1.3. -### `--unhandled-rejections=mode` +#### `--trace-tls` -Using this flag allows to change what should happen when an unhandled rejection -occurs. One of the following modes can be chosen: - -* `throw`: Emit [`unhandledRejection`][]. If this hook is not set, raise the - unhandled rejection as an uncaught exception. This is the default. -* `strict`: Raise the unhandled rejection as an uncaught exception. If the - exception is handled, [`unhandledRejection`][] is emitted. -* `warn`: Always trigger a warning, no matter if the [`unhandledRejection`][] - hook is set or not but do not print the deprecation warning. -* `warn-with-error-code`: Emit [`unhandledRejection`][]. If this hook is not - set, trigger a warning, and set the process exit code to 1. -* `none`: Silence all warnings. - -If a rejection happens during the command line entry point's ES module static -loading phase, it will always raise it as an uncaught exception. +Prints TLS packet trace information to `stderr`. This can be used to debug TLS +connection problems. -### `--use-bundled-ca`, `--use-openssl-ca` +#### `--use-bundled-ca`, `--use-openssl-ca` - -> Stability: 1.1 - Active Development - -When enabled, Node.js parses the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` -environment variables during startup, and routes requests through the -specified proxy. - -Use this only with proxies that are trusted and authorized for the deployment. -Proxy support is intended for reaching external networks through authorized -proxy servers, for example when a firewall requires one. It is not for hiding -traffic or evading network policy. See [Built-in Proxy Support][]. - -This is equivalent to setting the [`NODE_USE_ENV_PROXY=1`][] environment variable. -When both are set, `--use-env-proxy` takes precedence. - -### `--use-largepages=mode` - - - -This option is no longer supported and a no-op. It used to re-map the Node.js -static code to large memory pages at startup. - -It still accepts the following values for compatibility: - -* `off`: No mapping will be attempted. This is the default. -* `on`: No mapping will be attempted and a message will be printed to - standard error stating it's no longer supported. -* `silent`: Same as `off`. - -### `--use-system-ca` +#### `--use-system-ca` + +#### `--build-sea=config` + + + +> Stability: 1.1 - Active development + +Generates a [single executable application][] from a JSON +configuration file. The argument must be a path to the configuration file. If +the path is not absolute, it is resolved relative to the current working +directory. + +For configuration fields, cross-platform notes, and asset APIs, see +the [single executable application][] documentation. + +#### `--build-snapshot` + + -Print V8 command-line options. +Generates a snapshot blob when the process exits and writes it to +disk, which can be loaded later with `--snapshot-blob`. + +When building the snapshot, if `--snapshot-blob` is not specified, +the generated blob will be written, by default, to `snapshot.blob` +in the current working directory. Otherwise it will be written to +the path specified by `--snapshot-blob`. + +```console +$ echo "globalThis.foo = 'I am from the snapshot'" > snapshot.js + +# Run snapshot.js to initialize the application and snapshot the +# state of it into snapshot.blob. +$ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js + +$ echo "console.log(globalThis.foo)" > index.js + +# Load the generated snapshot and start the application from index.js. +$ node --snapshot-blob snapshot.blob index.js +I am from the snapshot +``` + +The [`v8.startupSnapshot` API][] can be used to specify an entry point at +snapshot building time, thus avoiding the need of an additional entry +script at deserialization time: + +```console +$ echo "require('v8').startupSnapshot.setDeserializeMainFunction(() => console.log('I am from the snapshot'))" > snapshot.js +$ node --snapshot-blob snapshot.blob --build-snapshot snapshot.js +$ node --snapshot-blob snapshot.blob +I am from the snapshot +``` + +For more information, check out the [`v8.startupSnapshot` API][] documentation. + +The snapshot currently only supports loading a single entrypoint during the +snapshot building process, which can load built-in modules, but not additional user-land modules. +Users can bundle their applications into a single script with their bundler +of choice before building a snapshot. + +As it's complicated to ensure the serializablility of all built-in modules, +which are also growing over time, only a subset of the built-in modules are +well tested to be serializable during the snapshot building process. +The Node.js core test suite checks that a few fairly complex applications +can be snapshotted. The list of built-in modules being +[captured by the built-in snapshot of Node.js][] is considered supported. +When the snapshot builder encounters a built-in module that cannot be +serialized, it may crash the snapshot building process. In that case a typical +workaround would be to delay loading that module until +runtime, using either [`v8.startupSnapshot.setDeserializeMainFunction()`][] or +[`v8.startupSnapshot.addDeserializeCallback()`][]. If serialization for +an additional module during the snapshot building process is needed, +please file a request in the [Node.js issue tracker][] and link to it in the +[tracking issue for user-land snapshots][]. + +During snapshot building, a debugger cannot be attached to the process. +`--build-snapshot` cannot be used together with `--inspect`, `--inspect-brk` or +`--inspect-wait`. -### `--v8-pool-size=num` +#### `--build-snapshot-config` -Set V8's thread pool size which will be used to allocate background jobs. +Specifies the path to a JSON configuration file which configures snapshot +creation behavior. -If set to `0` then Node.js will choose an appropriate size of the thread pool -based on an estimate of the amount of parallelism. +The following options are currently supported: -The amount of parallelism refers to the number of computations that can be -carried out simultaneously in a given machine. In general, it's the same as the -amount of CPUs, but it may diverge in environments such as VMs or containers. +* `builder` {string} Required. Provides the name to the script that is executed + before building the snapshot, as if [`--build-snapshot`][] had been passed + with `builder` as the main script name. +* `withoutCodeCache` {boolean} Optional. Including the code cache reduces the + time spent on compiling functions included in the snapshot at the expense + of a bigger snapshot size and potentially breaking portability of the + snapshot. + +When using this flag, additional script files provided on the command line will +not be executed and instead be interpreted as regular command line arguments. -### `-v`, `--version` +#### `--experimental-sea-config` -Print node's version. +> Stability: 1 - Experimental + +Use this flag to generate a blob that can be injected into the Node.js +binary to produce a [single executable application][]. See the documentation +about [this configuration][`--experimental-sea-config`] for details. -### `--vfs-load=source` +#### `--no-worker-snapshot` -* `source` {string} A directory or an archive file to mount and run. - -May be given at most once. +> Stability: 1 - Experimental -Mounts `source` as a virtual file system ([`node:vfs`][]), and runs the entry -point and all subsequent `require()`/`import` resolution against that mount -rather than the real file system. This option is unavailable when -`--no-experimental-vfs` disables [`node:vfs`][]. The mount is placed at a -reserved mount point -assigned by Node.js, so it never shadows real paths and no target can be -chosen. The entry point is taken from the mount the same way `node ` -takes one: the mount's own `package.json` `"main"`, or `index.js`. Any -positional command-line argument is the program's own (available from -`process.argv[2]` onward), never an entry-point override. +Start worker threads by running the internal bootstrap from scratch instead of +deserializing the bootstrapped context from the built-in startup snapshot. -`process.argv[1]` reports `source` rather than the reserved mount point, since -the mount point is an opaque implementation detail. +#### `--snapshot-blob=path` -The provider backing a source is chosen from the source itself rather than from -its file name: + -* A directory is mounted with a [`RealFSProvider`][] rooted there. -* A file whose bytes are a ZIP archive is mounted with a [`ZipProvider`][], so - an archive can carry any name. +> Stability: 1 - Experimental -Providers registered with `vfs.registerProvider()` (typically from a module -preloaded with [`--require`][] or [`--import`][]) are consulted first, in -reverse registration order, and may claim directories as well as files. If no -provider claims the source, Node.js exits with an error. +When used with `--build-snapshot`, `--snapshot-blob` specifies the path +where the generated snapshot blob is written to. If not specified, the +generated blob is written to `snapshot.blob` in the current working directory. -In worker threads `--vfs-load` mounts but does not load: a worker inherits the -mount and runs its own entry point, which may itself live in the mount. +When used without `--build-snapshot`, `--snapshot-blob` specifies the +path to the blob that is used to restore the application state. -The source is mounted at the same reserved mount point in every thread that -mounts it, whatever else that thread mounts, so a path into the mount means the -same thing in all of them. +When loading a snapshot, Node.js checks that: -A worker created with its own `execArgv` inherits none of the parent's options, -and so does not mount the source at all. To run a script from the mount, such a -worker must be given `--vfs-load` again; without it, that thread has no mount -for the script to come from, and the worker fails to load it. [`node:vfs`][] is -available to worker code without an experimental flag. A worker whose script -comes from anywhere else, such as the real file system, needs nothing added. +1. The version, architecture, and platform of the running Node.js binary + are exactly the same as that of the binary that generates the snapshot. +2. The V8 flags and CPU features are compatible with that of the binary + that generates the snapshot. -`--vfs-load` is not permitted in [`NODE_OPTIONS`][]: which entry point runs is -the command line's decision, and the environment must not be able to redirect -it. +If they don't match, Node.js refuses to load the snapshot and exits with +status code 1. -`--vfs-load` cannot be used in a [single executable application][]: its entry -point is the `"main"` it was built with, and with `"useVfs"` its own virtual -file system is mounted at the mount point reserved for `--vfs-load`. +### V8 and memory -```console -$ node --vfs-load=app.zip -``` + -### `--watch` +#### `--disable-wasm-trap-handler` -Starts Node.js in watch mode. -When in watch mode, changes in the watched files cause the Node.js process to -restart. -By default, watch mode will watch the entry point -and any required or imported module. -Use `--watch-path` to specify what paths to watch. - -This flag cannot be combined with -`--check`, `--eval`, `--interactive`, or the REPL. +Node.js enables V8's trap-handler-based WebAssembly bound checks on 64-bit platforms, +which significantly improves WebAssembly performance by eliminating the need for +inline bound checks. This optimization requires allocating a large virtual memory +cage per WebAssembly memory instance (currently typically 8GB for 32-bit WebAssembly memory, +16GB for 64-bit WebAssembly memory) to trap out-of-bound accesses. On most 64-bit +platforms, the virtual memory address space is usually large enough (around 128TB) +to accommodate typical WebAssembly usages, but if the machine has manual limits +on virtual memory (e.g. through `ulimit -v`), WebAssembly memory allocation is +more likely to fail with `WebAssembly.Memory(): could not allocate memory`. -Note: The `--watch` flag requires a file path as an argument and is incompatible -with `--run` or inline script input, as `--run` takes precedence and ignores watch -mode. If no file is provided, Node.js will exit with status code `9`. +At startup, Node.js automatically checks whether there is enough virtual memory +available to allocate at least one cage, and if not, the trap-handler optimization +is automatically disabled so that WebAssembly can still run using inline +bound checks (with less optimal performance). But if the application needs to create +many WebAssembly memory instances and the machine still configures a relatively high +limit on virtual memory, allocation of WebAssembly memory instances may still fail +more quickly than expected due to the raised virtual memory usage. -```bash -node --watch index.js -``` +`--disable-wasm-trap-handler` fully disables this optimization so that WebAssembly memory +instances always use inline bound checks instead of reserving large virtual memory cages. +This allows more instances to be created when the virtual memory address space available +to the Node.js process is limited. -### `--watch-kill-signal` +#### `--jitless` -> Stability: 1.1 - Active Development +> Stability: 1 - Experimental. This flag is inherited from V8 and is subject to +> change upstream. -Customizes the signal sent to the process on watch mode restarts. +Disable [runtime allocation of executable memory][jitless]. This may be +required on some platforms for security reasons. It can also reduce attack +surface on other platforms, but the performance impact may be severe. + +When WebAssembly is unavailable in this mode, TypeScript parsing and WebAssembly +module imports throw [`ERR_WEBASSEMBLY_NOT_SUPPORTED`][]. Node.js does not +guarantee alternative implementations of features that require WebAssembly or +runtime allocation of executable memory when those capabilities are unavailable. + +This flag controls V8's runtime code generation. It does not impose an +operating-system restriction on executable memory allocated by native addons or +[`node:ffi`][]. FFI operations that require unavailable executable memory can +throw [`ERR_RX_MEMORY_NOT_SUPPORTED`][]. + +#### `--max-old-space-size-percentage=percentage` + +Sets the maximum memory size of V8's old memory section as a percentage of available system memory. +This flag takes precedence over `--max-old-space-size` when both are specified. + +The `percentage` parameter must be a number greater than 0 and up to 100, representing the percentage +of available system memory to allocate to the V8 heap. + +**Note:** This flag utilizes `--max-old-space-size`, which may be unreliable on 32-bit platforms due to +integer overflow issues. ```bash -node --watch --watch-kill-signal SIGINT test.js +# Using 50% of available system memory +node --max-old-space-size-percentage=50 index.js + +# Using 75% of available system memory +node --max-old-space-size-percentage=75 index.js ``` -### `--watch-path` +#### `--use-largepages=mode` -Starts Node.js in watch mode and specifies what paths to watch. -When in watch mode, changes in the watched paths cause the Node.js process to -restart. -This will turn off watching of required or imported modules, even when used in -combination with `--watch`. - -This flag cannot be combined with -`--check`, `--eval`, `--interactive`, `--test`, or the REPL. +This option is no longer supported and a no-op. It used to re-map the Node.js +static code to large memory pages at startup. -Note: Using `--watch-path` implicitly enables `--watch`, which requires a file path -and is incompatible with `--run`, as `--run` takes precedence and ignores watch mode. +It still accepts the following values for compatibility: -```bash -node --watch-path=./src --watch-path=./tests index.js -``` +* `off`: No mapping will be attempted. This is the default. +* `on`: No mapping will be attempted and a message will be printed to + standard error stating it's no longer supported. +* `silent`: Same as `off`. -### `--watch-preserve-output` +#### `--v8-options` -Disable the clearing of the console when watch mode restarts the process. - -```bash -node --watch --watch-preserve-output test.js -``` +Print V8 command-line options. -### `--zero-fill-buffers` +#### `--v8-pool-size=num` -Automatically zero-fills all newly allocated [`Buffer`][] instances. +Set V8's thread pool size which will be used to allocate background jobs. + +If set to `0` then Node.js will choose an appropriate size of the thread pool +based on an estimate of the amount of parallelism. + +The amount of parallelism refers to the number of computations that can be +carried out simultaneously in a given machine. In general, it's the same as the +amount of CPUs, but it may diverge in environments such as VMs or containers. ## Environment variables diff --git a/test/parallel/test-cli-node-cli-manpage-options.mjs b/test/parallel/test-cli-node-cli-manpage-options.mjs index 9fd536a71542..e62722d9acab 100644 --- a/test/parallel/test-cli-node-cli-manpage-options.mjs +++ b/test/parallel/test-cli-node-cli-manpage-options.mjs @@ -23,7 +23,8 @@ const rl = createInterface({ input: cliMdContentsStream, }); -const isOptionLineRegex = /^###(?: `[^`]*`,?)*$/; +// Options are `####` entries inside the `###` help sections. +const isOptionLineRegex = /^####(?: `[^`]*`,?)*$/; for await (const line of rl) { if (line.startsWith('## ')) { diff --git a/test/parallel/test-cli-node-options-docs.js b/test/parallel/test-cli-node-options-docs.js index 80caa29d4263..c7d3a0d3584e 100644 --- a/test/parallel/test-cli-node-options-docs.js +++ b/test/parallel/test-cli-node-options-docs.js @@ -32,6 +32,16 @@ const deprecated = [ ]; +const nodeOptionsH = fs.readFileSync(path.resolve(rootDir, 'src', 'node_options.h'), 'utf8'); +const helpSectionList = nodeOptionsH.slice( + nodeOptionsH.indexOf('#define OPTION_HELP_SECTION_LIST'), + nodeOptionsH.indexOf('enum class HelpSection')); +const helpSectionTitles = new Map( + Array.from(helpSectionList.matchAll(/\bV\((k\w+), "([^"]+)"\)/g), (m) => [m[1], m[2]])); +assert.ok(helpSectionTitles.size > 0); +// Option name -> title of the --help section node_options.cc assigns it to. +const optionHelpSections = new Map(); + const manPagesOptions = new Set(); for (const [, envVar] of manPageText.matchAll(/\.It Fl (-[a-zA-Z0-9._-]+)/g)) { @@ -43,6 +53,10 @@ for (const [, envVar, config] of nodeOptionsCC.matchAll(addOptionRE)) { const isInNodeOption = config.includes('kAllowedInEnvvar') && !config.includes('kDisallowedInEnvvar'); const isV8Option = config.includes('V8Option{}'); const isNoOp = config.includes('NoOp{}'); + const helpSection = /HelpSection::(k\w+)/.exec(config)?.[1]; + assert.ok(helpSectionTitles.has(helpSection), + `${envVar} has unknown help section ${helpSection}`); + optionHelpSections.set(envVar, helpSectionTitles.get(helpSection)); if ( envVar.startsWith('[') || @@ -106,8 +120,10 @@ for (const [, envVar, config] of nodeOptionsCC.matchAll(addOptionRE)) { } { - const sections = /^## (.+)$/mg; - const cliOptionPattern = /^### (?:`-\w.*`, )?`([^`]+)`/mg; + // Entries are sorted within each `##` section, and within each `###` group + // of entries (such as the option sections under `## Options`). + const sections = /^(?:## |### (?!`))(.+)$/mg; + const cliOptionPattern = /^####? (?:`-\w.*`, )?`([^`]+)`/mg; let match; let previousIndex = 0; do { @@ -120,6 +136,41 @@ for (const [, envVar, config] of nodeOptionsCC.matchAll(addOptionRE)) { } while (match); } +// Options under `## Options` are grouped into `###` sections that match the +// --help sections node_options.cc assigns them to. Each section heading +// carries its label as `help-section` YAML metadata. +{ + const lines = cliText.split('\n'); + const optionsLines = lines.slice(lines.indexOf('## Options'), + lines.indexOf('## Environment variables')); + const knownTitles = new Set(helpSectionTitles.values()); + let section; + for (const [index, line] of optionsLines.entries()) { + const [, depth, heading] = /^(###|####) (.+)$/.exec(line) ?? []; + if (depth === undefined) continue; + if (depth === '###') { + const yaml = optionsLines.slice(index + 1, index + 5).join('\n'); + const label = /^/m.exec(yaml)?.[1]; + assert.strictEqual(label, heading, + `doc/api/cli.md section "${heading}" needs help-section: ${heading} YAML`); + assert.ok(knownTitles.has(label), + `doc/api/cli.md section "${label}" is not a help section in src/node_options.h`); + section = label; + continue; + } + assert.ok(section, `doc/api/cli.md ${heading} is not inside a section`); + for (const [, flag] of heading.matchAll(/`(-[-\w.]*)/g)) { + const expected = optionHelpSections.get(flag) ?? + optionHelpSections.get(flag.replace(/^--no-/, '--')); + if (expected === undefined) continue; + assert.strictEqual(section, expected, + `doc/api/cli.md documents ${flag} under "${section}", ` + + `but src/node_options.cc puts it in "${expected}"`); + break; + } + } +} + // add alias handling manPagesOptions.delete('-trace-events-enabled'); From 794c5f6fc1a86bb5915542390a7e552cf428f8de Mon Sep 17 00:00:00 2001 From: James M Snell Date: Mon, 23 Nov 2026 01:32:30 +0000 Subject: [PATCH 4/4] lib,doc: list run modes in node --help usage The usage section of `node --help` and the synopsis in doc/api/cli.md only listed running a script and `node inspect`. Also list the other top-level run modes: `-e`, `-p`, `--run`, `--watch`, `--test` and `--bench`. Assisted-by: Claude Signed-off-by: James M Snell --- doc/api/cli.md | 14 ++++++++++++-- lib/internal/main/print_help.js | 10 +++++++++- test/parallel/test-cli-node-print-help.js | 14 ++++++++++++++ 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/doc/api/cli.md b/doc/api/cli.md index 60f04a8037ae..f1b7e394cfd3 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -11,15 +11,25 @@ To view this documentation as a manual page in a terminal, run `man node`. ## Synopsis -`node [options] [V8 options] [ | -e "script" | -] [--] [arguments]` +`node [options] [V8 options] [ | -e "script" | -p "script" | -] [--] [arguments]` `node inspect [ | -e "script" | :] …` +`node --run [