Node.js v25.3.0 文档


命令行 API#>

【Command-line API】

Node.js 提供了多种命令行选项。这些选项提供了内置调试、多种执行脚本的方式以及其他有用的运行时选项。

【Node.js comes with a variety of CLI options. These options expose built-in debugging, multiple ways to execute scripts, and other helpful runtime options.】

要在终端中将此文档作为手册页查看,请运行 man node

【To view this documentation as a manual page in a terminal, run man node.】

概要#>

【Synopsis】

node [options] [V8 options] [<program-entry-point> | -e "script" | -] [--] [arguments]

node inspect [<program-entry-point> | -e "script" | <host>:<port>] …

node --v8-options

无需参数即可启动 REPL

【Execute without arguments to start the REPL.】

有关 node inspect 的更多信息,请参阅 调试器 文档。

【For more info about node inspect, see the debugger documentation.】

程序入口点#>

【Program entry point】

程序的入口点是一个类似指定符的字符串。如果该字符串不是绝对路径,它将被解析为相对于当前工作目录的路径。然后,该路径由 CommonJS 模块加载器解析。如果找不到对应的文件,将抛出错误。

【The program entry point is a specifier-like string. If the string is not an absolute path, it's resolved as a relative path from the current working directory. That path is then resolved by CommonJS module loader. If no corresponding file is found, an error is thrown.】

如果找到文件,其路径将在以下任何情况下传递给 ES 模块加载器

【If a file is found, its path will be passed to the ES module loader under any of the following conditions:】

  • 该程序是通过命令行标志启动的,该标志强制入口点使用 ECMAScript 模块加载器加载,例如 --import
  • 该文件具有 .mjs.wasm 扩展名。
  • 该文件没有 .cjs 扩展名,并且最近的父级 package.json 文件包含一个顶层 "type" 字段,其值为 "module"。

否则,文件将使用 CommonJS 模块加载器加载。更多详情请参阅 模块加载器

【Otherwise, the file is loaded using the CommonJS module loader. See Modules loaders for more details.】

ECMAScript 模块加载器入口点警告#>

【ECMAScript modules loader entry point caveat】

在加载时,ES 模块加载器 会加载程序入口点,node 命令仅接受扩展名为 .js.mjs.cjs 的文件作为输入。使用以下标志,可启用其他文件扩展名:

【When loading, the ES module loader loads the program entry point, the node command will accept as input only files with .js, .mjs, or .cjs extensions. With the following flags, additional file extensions are enabled:】

选项#>

【Options】

所有选项,包括 V8 选项,都允许单词通过连字符(-)或下划线(_)分隔。例如,--pending-deprecation 等同于 --pending_deprecation

【All options, including V8 options, allow words to be separated by both dashes (-) or underscores (_). For example, --pending-deprecation is equivalent to --pending_deprecation.】

如果一个只接受单个值的选项(例如 --max-http-header-size)被多次传递,则使用最后传递的值。命令行中的选项优先于通过 NODE_OPTIONS 环境变量传递的选项。

【If an option that takes a single value (such as --max-http-header-size) is 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.】

-#>

stdin 的别名。类似于其他命令行工具中使用 - 的方式,表示脚本从 stdin 读取,其余选项传递给该脚本。

【Alias for stdin. Analogous to the use of - in other command-line utilities, meaning that the script is read from stdin, and the rest of the options are passed to that script.】

--#>

指示节点选项的结束。将其余的参数传递给脚本。如果在此之前没有提供脚本文件名或 eval/print 脚本,则下一个参数将作为脚本文件名使用。

【Indicate the end of node options. Pass the rest of the arguments to the script. If no script filename or eval/print script is supplied prior to this, then the next argument is used as a script filename.】

--abort-on-uncaught-exception#>

中止而不是退出会生成一个核心文件,用于使用调试器(如 lldbgdbmdb)进行事后分析。

【Aborting instead of exiting causes a core file to be generated for post-mortem analysis using a debugger (such as lldb, gdb, and mdb).】

如果传递了此标志,行为仍然可以通过 process.setUncaughtExceptionCaptureCallback()(以及通过使用依赖它的 node:domain 模块)设置为不终止。

【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).】

--allow-addons#>

稳定性: 1.1 - 处于活跃开发中

在使用 权限模型 时,默认情况下该进程将无法使用本地插件。除非用户在启动 Node.js 时显式传递 --allow-addons 标志,否则尝试使用本地插件将抛出 ERR_DLOPEN_DISABLED 错误。

【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.】

示例:

【Example:】

// Attempt to require an native addon
require('nodejs-addon-example'); 
$ 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.<anonymous> (/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'
} 

--allow-child-process#>

稳定性: 1.1 - 处于活跃开发中

在使用 权限模型 时,默认情况下该进程无法生成任何子进程。尝试这样做将抛出 ERR_ACCESS_DENIED,除非用户在启动 Node.js 时显式传递 --allow-child-process 标志。

【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.】

示例:

【Example:】

const childProcess = require('node:child_process');
// Attempt to bypass the permission
childProcess.spawn('node', ['-e', 'require("fs").writeFileSync("/new-file", "example")']); 
$ 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'
} 

child_process.fork() API 会继承父进程的执行参数。这意味着,如果 Node.js 在启用权限模型的情况下启动,并且设置了 --allow-child-process 标志,那么使用 child_process.fork() 创建的任何子进程都会自动接收所有相关的权限模型标志。

【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.】

这种行为同样适用于 child_process.spawn(),但在这种情况下,标志是通过 NODE_OPTIONS 环境变量传递的,而不是直接通过进程参数。

【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.】

--allow-fs-read#>

该标志使用 权限模型 配置文件系统读取权限。

【This flag configures file system read permissions using the Permission Model.】

--allow-fs-read 标志的有效参数是:

【The valid arguments for the --allow-fs-read flag are:】

  • * - 允许所有 FileSystemRead 操作。
  • 可以使用多个 --allow-fs-read 标志来允许多个路径。例如 --allow-fs-read=/folder1/ --allow-fs-read=/folder1/

示例可以在 文件系统权限 文档中找到。

【Examples can be found in the File System Permissions documentation.】

初始化模块和自定义 --require 模块具有隐式读取权限。

【The initializer module and custom --require modules has a implicit read permission.】

$ node --permission -r custom-require.js -r custom-require-2.js index.js 
  • custom-require.jscustom-require-2.jsindex.js 默认情况下将包含在允许读取的列表中。
process.has('fs.read', 'index.js'); // true
process.has('fs.read', 'custom-require.js'); // true
process.has('fs.read', 'custom-require-2.js'); // true 

--allow-fs-write#>

该标志使用 权限模型 配置文件系统写入权限。

【This flag configures file system write permissions using the Permission Model.】

--allow-fs-write 标志的有效参数是:

【The valid arguments for the --allow-fs-write flag are:】

  • * - 允许所有 FileSystemWrite 操作。
  • 可以使用多个 --allow-fs-write 标志来允许多个路径。例如 --allow-fs-write=/folder1/ --allow-fs-write=/folder1/

不再允许使用逗号(,)分隔的路径。传递带有逗号的单个标志时,将显示警告。

【Paths delimited by comma (,) are no longer allowed. When passing a single flag with a comma a warning will be displayed.】

示例可以在 文件系统权限 文档中找到。

【Examples can be found in the File System Permissions documentation.】

--allow-inspector#>

稳定性: 1.0 - 早期开发

使用 权限模型 时,该过程将无法通过检查器协议进行连接。

【When using the Permission Model, the process will not be able to connect through inspector protocol.】

除非用户在启动 Node.js 时显式传递 --allow-inspector 标志,否则尝试这样做会抛出 ERR_ACCESS_DENIED

【Attempts to do so will throw an ERR_ACCESS_DENIED unless the user explicitly passes the --allow-inspector flag when starting Node.js.】

示例:

【Example:】

const { Session } = require('node:inspector/promises');

const session = new Session();
session.connect(); 
$ 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',
} 

--allow-net#>

稳定性: 1.1 - 处于活跃开发中

使用 权限模型 时,默认情况下该进程将无法访问网络。除非用户在启动 Node.js 时显式传递 --allow-net 标志,否则尝试访问网络将抛出 ERR_ACCESS_DENIED 错误。

【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:】

const http = require('node:http');
// Attempt to bypass the permission
const req = http.get('http://example.com', () => {});

req.on('error', (err) => {
  console.log('err', err);
}); 
$ 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',
} 

--allow-wasi#>

稳定性: 1.1 - 处于活跃开发中

在使用 权限模型 时,该进程默认无法创建任何 WASI 实例。出于安全原因,除非用户在主 Node.js 进程中显式传递 --allow-wasi 标志,否则调用将抛出 ERR_ACCESS_DENIED

【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:】

const { WASI } = require('node:wasi');
// Attempt to bypass the permission
new WASI({
  version: 'preview1',
  // Attempt to mount the whole filesystem
  preopens: {
    '/': '/',
  },
}); 
$ node --permission --allow-fs-read=* index.js

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#>

稳定性: 1.1 - 处于活跃开发中

在使用 权限模型 时,默认情况下该进程无法创建任何工作线程。出于安全原因,除非用户在主 Node.js 进程中显式传递 --allow-worker 标志,否则调用会抛出 ERR_ACCESS_DENIED

【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:】

const { Worker } = require('node:worker_threads');
// Attempt to bypass the permission
new Worker(__filename); 
$ node --permission --allow-fs-read=* index.js

Error: Access to this API has been restricted
    at node:internal/main/run_main_module:17:47 {
  code: 'ERR_ACCESS_DENIED',
  permission: 'WorkerThreads'
} 

--build-snapshot#>

稳定性: 1 - 实验性

在进程退出时生成快照二进制文件并写入磁盘,之后可以使用 --snapshot-blob 加载。

【Generates a snapshot blob when the process exits and writes it to disk, which can be loaded later with --snapshot-blob.】

在构建快照时,如果未指定 --snapshot-blob,生成的 blob 默认会写入当前工作目录下的 snapshot.blob。否则,它将写入由 --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.】

$ 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 

v8.startupSnapshot API 可以在快照构建时指定入口点,从而避免在反序列化时需要额外的入口脚本:

【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:】

$ 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 

欲了解更多信息,请查看 v8.startupSnapshot API 文档。

【For more information, check out the v8.startupSnapshot API documentation.】

目前对运行时快照的支持是实验性的:

【Currently the support for run-time snapshot is experimental in that:】

  1. 快照中尚不支持用户级模块,因此一次只能生成单个文件的快照。不过,用户可以在构建快照之前使用自己选择的打包工具将应用打包成单个脚本。
  2. 只有内置模块的一个子集在快照中可用,尽管 Node.js 核心测试套件会检查一些相当复杂的应用是否可以被快照。更多模块的支持正在添加中。如果在构建快照时发生任何崩溃或错误行为,请在 Node.js 问题跟踪器 中提交报告,并在 用户空间快照的跟踪问题 中链接该报告。

--build-snapshot-config#>

稳定性: 1 - 实验性

指定 JSON 配置文件的路径,该文件用于配置快照创建行为。

【Specifies the path to a JSON configuration file which configures snapshot creation behavior.】

目前支持以下选项:

【The following options are currently supported:】

  • builder <string> 必填。提供在构建快照之前执行的脚本名称,就像使用 builder 作为主脚本名称传递了 --build-snapshot 一样。
  • withoutCodeCache <boolean> 可选。包含代码缓存可以减少对快照中包含的函数进行编译所花费的时间,但代价是快照体积更大,且可能会破坏快照的可移植性。

使用此标志时,命令行中提供的额外脚本文件将不会被执行,而是被解释为普通的命令行参数。

【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.】

-c--check#>

-c, --check

语法检查脚本而不执行。

【Syntax check the script without executing.】

--completion-bash#>

为 Node.js 打印可源代码的 bash 完成脚本。

【Print source-able bash completion script for Node.js.】

node --completion-bash > node_bash_completion
source node_bash_completion 

-C 条件, --conditions=条件#>

-C condition, --conditions=condition

提供自定义 条件导出 分辨率条件。

【Provide custom conditional exports resolution conditions.】

允许任意数量的自定义字符串条件名称。

【Any number of custom string condition names are permitted.】

默认的 Node.js 条件 "node""default""import""require" 将始终按定义应用。

【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:】

node -C development app.js 

--cpu-prof#>

在启动时启动 V8 CPU 分析器,并在退出前将 CPU 分析结果写入磁盘。

【Starts the V8 CPU profiler on start up, and writes the CPU profile to disk before exit.】

如果未指定 --cpu-prof-dir,生成的性能分析文件将放在当前工作目录中。

【If --cpu-prof-dir is not specified, the generated profile is placed in the current working directory.】

如果未指定 --cpu-prof-name,生成的配置文件将命名为 CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile

【If --cpu-prof-name is not specified, the generated profile is named CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile.】

$ node --cpu-prof index.js
$ ls *.cpuprofile
CPU.20190409.202950.15293.0.0.cpuprofile 

如果指定了 --cpu-prof-name,提供的值将用作文件名的模板。支持以下占位符,并将在运行时进行替换:

【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} — 当前进程 ID
$ node --cpu-prof --cpu-prof-name 'CPU.${pid}.cpuprofile' index.js
$ ls *.cpuprofile
CPU.15293.cpuprofile 

--cpu-prof-dir#>

指定由 --cpu-prof 生成的 CPU 分析文件将放置的目录。

【Specify the directory where the CPU profiles generated by --cpu-prof will be placed.】

默认值由 --diagnostic-dir 命令行选项控制。

【The default value is controlled by the --diagnostic-dir command-line option.】

--cpu-prof-interval#>

指定由 --cpu-prof 生成的 CPU 配置文件的采样间隔(微秒)。默认值是 1000 微秒。

【Specify the sampling interval in microseconds for the CPU profiles generated by --cpu-prof. The default is 1000 microseconds.】

--cpu-prof-name#>

指定由 --cpu-prof 生成的 CPU 配置文件的文件名。

【Specify the file name of the CPU profile generated by --cpu-prof.】

--diagnostic-dir=directory#>

设置所有诊断输出文件写入的目录。默认是当前工作目录。

【Set the directory to which all diagnostic output files are written. Defaults to current working directory.】

影响默认输出目录:

【Affects the default output directory of:】

--disable-proto=mode#>

禁用 Object.prototype.__proto__ 属性。如果 modedelete,则该属性将被完全移除。如果 modethrow,访问该属性会抛出代码为 ERR_PROTO_ACCESS 的异常。

【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.】

--disable-sigusr1#>

禁止通过向进程发送 SIGUSR1 信号来启动调试会话的功能。

【Disable the ability of starting a debugging session by sending a SIGUSR1 signal to the process.】

--disable-warning=code-or-type#>

稳定性: 1.1 - 处于活跃开发中

通过 codetype 禁用特定的进程警告。

【Disable specific process warnings by code or type.】

process.emitWarning() 发出的警告可能包含 codetype。此选项不会发出具有匹配 codetype 的警告。

【Warnings emitted from process.emitWarning() may contain a code and a type. This option will not-emit warnings that have a matching code or type.】

弃用警告 列表。

【List of deprecation warnings.】

Node.js 核心警告类型有:DeprecationWarningExperimentalWarning

【The Node.js core warning types are: DeprecationWarning and ExperimentalWarning

例如,以下脚本在使用 node --disable-warning=DEP0025 执行时不会发出 DEP0025 require('node:sys')

【For example, the following script will not emit DEP0025 require('node:sys') when executed with node --disable-warning=DEP0025:】

import sys from 'node:sys';const sys = require('node:sys');

例如,以下脚本将在使用 node --disable-warning=ExperimentalWarning 执行时发出 DEP0025 require('node:sys'),但不会发出任何实验性警告(例如 <=v21 中的 实验性警告:vm.measureMemory 是一个实验性功能):

【For example, the following script will emit the DEP0025 require('node:sys'), but not any Experimental Warnings (such as ExperimentalWarning: vm.measureMemory is an experimental feature in <=v21) when executed with node --disable-warning=ExperimentalWarning:】

import sys from 'node:sys';
import vm from 'node:vm';

vm.measureMemory();const sys = require('node:sys');
const vm = require('node:vm');

vm.measureMemory();

--disable-wasm-trap-handler#>

默认情况下,Node.js 启用了基于陷阱处理程序的 WebAssembly 边界检查。因此,V8 不需要在从 WebAssembly 编译的代码中插入内联边界检查,这可能显著加快 WebAssembly 的执行速度,但此优化需要分配一个大的虚拟内存区(当前为 10GB)。如果由于系统配置或硬件限制,Node.js 进程无法访问足够大的虚拟内存地址空间,用户将无法运行涉及在此虚拟内存区分配的任何 WebAssembly,并会看到内存不足的错误。

【By default, Node.js enables trap-handler-based WebAssembly bound checks. As a result, V8 does not need to insert inline bound checks int the code compiled from WebAssembly which may speedup WebAssembly execution significantly, but this optimization requires allocating a big virtual memory cage (currently 10GB). If the Node.js process does not have access to a large enough virtual memory address space due to system configurations or hardware limitations, users won't be able to run any WebAssembly that involves allocation in this virtual memory cage and will see an out-of-memory error.】

$ ulimit -v 5000000
$ node -p "new WebAssembly.Memory({ initial: 10, maximum: 100 });"
[eval]:1
new WebAssembly.Memory({ initial: 10, maximum: 100 });
^

RangeError: WebAssembly.Memory(): could not allocate memory
    at [eval]:1:1
    at runScriptInThisContext (node:internal/vm:209:10)
    at node:internal/process/execution:118:14
    at [eval]-wrapper:6:24
    at runScript (node:internal/process/execution:101:62)
    at evalScript (node:internal/process/execution:136:3)
    at node:internal/main/eval_string:49:3
 

--disable-wasm-trap-handler 禁用此优化,以便用户至少能够运行 WebAssembly(性能较低),当他们的 Node.js 进程可用的虚拟内存地址空间低于 V8 WebAssembly 内存隔离所需的空间时。

--disallow-code-generation-from-strings#>

让像 evalnew Function 这样的内置语言特性在从字符串生成代码时抛出异常。这不会影响 Node.js 的 node:vm 模块。

【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.】

--dns-result-order=order#>

dns.lookup()dnsPromises.lookup() 中设置 order 的默认值。该值可以是:

【Set the default value of order in dns.lookup() and dnsPromises.lookup(). The value could be:】

  • ipv4first:将默认 order 设置为 ipv4first
  • ipv6first:将默认 order 设置为 ipv6first
  • verbatim:将默认 order 设置为 verbatim

默认是 verbatim,并且 dns.setDefaultResultOrder() 的优先级高于 --dns-result-order

【The default is verbatim and dns.setDefaultResultOrder() have higher priority than --dns-result-order.】

--enable-fips#>

在启动时启用符合 FIPS 的加密。(需要使用支持 FIPS 的 OpenSSL 构建 Node.js。)

【Enable FIPS-compliant crypto at startup. (Requires Node.js to be built against FIPS-compatible OpenSSL.)】

--enable-network-family-autoselection#>

启用家庭自动选择算法,除非连接选项明确禁用它。

【Enables the family autoselection algorithm unless connection options explicitly disables it.】

--enable-source-maps#>

启用 源映射 支持堆栈跟踪。

【Enable Source Map support for stack traces.】

当使用像 TypeScript 这样的转译器时,应用抛出的堆栈跟踪会引用转译后的代码,而不是原始源代码位置。--enable-source-maps 启用源映射的缓存,并尽最大努力报告相对于原始源文件的堆栈跟踪。

【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.】

重写 Error.prepareStackTrace 可能会阻止 --enable-source-maps 修改堆栈跟踪。在重写函数中调用并返回原始 Error.prepareStackTrace 的结果,以便使用源映射修改堆栈跟踪。

【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.】

const originalPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = (error, trace) => {
  // Modify error and trace and format stack trace with
  // original Error.prepareStackTrace.
  return originalPrepareStackTrace(error, trace);
}; 

注意,启用源映射可能会在访问 Error.stack 时增加应用的延迟。如果你的应用中频繁访问 Error.stack,请考虑 --enable-source-maps 的性能影响。

【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#>

稳定性: 1 - 实验性

当存在时,Node.js 会将入口点解释为 URL,而不是路径。

【When present, Node.js will interpret the entry point as a URL, rather than a path.】

遵循 ECMAScript 模块 分辨率规则。

【Follows ECMAScript module resolution rules.】

URL 中的任何查询参数或哈希都可以通过 import.meta.url 访问。

【Any query parameter or hash in the URL will be accessible via import.meta.url.】

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")' 

--env-file-if-exists=file#>

行为与 --env-file 相同,但如果文件不存在,则不会抛出错误。

【Behavior is the same as --env-file, but an error is not thrown if the file does not exist.】

--env-file=file#>

从相对于当前目录的文件加载环境变量,使它们在 process.env 中可供应用使用。配置 Node.js 的环境变量,例如 NODE_OPTIONS,会被解析和应用。如果同一个变量在环境中和文件中都有定义,则优先使用环境中的值。

【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, 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.】

你可以传递多个 --env-file 参数。后续的文件会覆盖先前文件中已定义的变量。

【You can pass multiple --env-file arguments. Subsequent files override pre-existing variables defined in previous files.】

如果文件不存在,则会引发错误。

【An error is thrown if the file does not exist.】

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 =:】

PORT=3000 

# 后面的任何文本都被视为注释:

【Any text after a # is treated as a comment:】

# This is a comment
PORT=3000 # This is also a comment 

值可以以以下引号开始和结束:`"'。 它们会从值中省略。

【Values can start and end with the following quotes: `, " or '. They are omitted from the values.】

USERNAME="nodejs" # will result in `nodejs` as the value. 

支持多行值:

【Multi-line values are supported:】

MULTI_LINE="THIS IS
A MULTILINE"
# will result in `THIS IS\nA MULTILINE` as the value. 

在忽略某个键之前导出关键字:

【Export keyword before a key is ignored:】

export USERNAME="nodejs" # will result in `nodejs` as the value. 

如果你想从可能不存在的文件中加载环境变量,你可以改用 --env-file-if-exists 标志。

【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 "脚本"#>

-e, --eval "script"

将以下参数作为 JavaScript 进行评估。在 REPL 中预定义的模块也可以在 script 中使用。

【Evaluate the following argument as JavaScript. The modules which are predefined in the REPL can also be used in script.】

在 Windows 上,使用 cmd.exe 时,单引号无法正确工作,因为它只识别双引号 " 作为引用。在 Powershell 或 Git bash 中,单引号 ' 和双引号 " 都可以使用。

【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.】

除非提供 --no-experimental-strip-types 标志,否则可以运行包含内联类型的代码。

【It is possible to run code containing inline types unless the --no-experimental-strip-types flag is provided.】

--experimental-addon-modules#>

稳定性: 1.0 - 早期开发

启用对 .node 插件的实验性导入支持。

【Enable experimental import support for .node addons.】

--experimental-config-file=config#>

稳定性: 1.0 - 早期开发

如果存在,Node.js 将在指定路径查找配置文件。Node.js 将读取该配置文件并应用设置。配置文件应为具有以下结构的 JSON 文件。在 $schema 中的 vX.Y.Z 必须替换为你正在使用的 Node.js 版本。

【If present, Node.js will look for a configuration file at the specified path. 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.】

{
  "$schema": "https://nodejs.cn/dist/vX.Y.Z/docs/node-config-schema.json",
  "nodeOptions": {
    "import": [
      "amaro/strip"
    ],
    "watch-path": "src",
    "watch-preserve-output": true
  },
  "testRunner": {
    "test-isolation": "process"
  }
} 

配置文件支持特定于命名空间的选项:

【The configuration file supports namespace-specific options:】

  • nodeOptions 字段包含在 NODE_OPTIONS 中允许的 CLI 标志。
  • testRunner 这样的命名空间字段包含特定于该子系统的配置。

不支持无操作标志。当前并非所有 V8 标志都被支持。

【No-op flags are not supported. Not all V8 flags are currently supported.】

可以使用官方 JSON 模式来验证配置文件,这可能会根据 Node.js 版本的不同而有所变化。配置文件中的每个键都对应一个可以作为命令行参数传递的标志。该键的值就是将传递给该标志的值。

【It is possible to use the official JSON schema 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.】

例如,上面的配置文件等同于以下命令行参数:

【For example, the configuration file above is equivalent to the following command-line arguments:】

node --import amaro/strip --watch-path=src --watch-preserve-output --test-isolation=process 

配置中的优先级如下:

【The priority in configuration is as follows:】

  1. NODE_OPTIONS 和命令行选项
  2. 配置文件
  3. Dotenv NODE_OPTIONS

配置文件中的值不会覆盖环境变量和命令行选项中的值,但会覆盖通过 --env-file 标志解析的 NODE_OPTIONS 环境文件中的值。

【Values in the configuration file will not override the values in the environment variables and command-line options, but will override the values in the NODE_OPTIONS env file parsed by the --env-file flag.】

键不能在相同或不同的命名空间内重复。

【Keys cannot be duplicated within the same or different namespaces.】

如果配置文件包含未知的键或不能在命名空间中使用的键,配置解析器将抛出错误。

【The configuration parser will throw an error if the configuration file contains unknown keys or keys that cannot be used in a namespace.】

Node.js 不会对用户提供的配置进行清理或验证, 所以 绝对不要 使用不可信的配置文件。

【Node.js will not sanitize or perform validation on the user-provided configuration, so NEVER use untrusted configuration files.】

--experimental-default-config-file#>

稳定性: 1.0 - 早期开发

如果存在 --experimental-default-config-file 标志,Node.js 将在当前工作目录中查找 node.config.json 文件,并将其作为配置文件加载。

【If the --experimental-default-config-file flag is present, Node.js will look for a node.config.json file in the current working directory and load it as a as configuration file.】

--experimental-eventsource#>

在全局范围内启用 EventSource 网络 API 的公开显示。

【Enable exposition of EventSource Web API on the global scope.】

--experimental-import-meta-resolve#>

启用实验性的 import.meta.resolve() 父 URL 支持,允许传递第二个 parentURL 参数以进行上下文解析。

【Enable experimental import.meta.resolve() parent URL support, which allows passing a second parentURL argument for contextual resolution.】

之前对整个 import.meta.resolve 功能进行了限制。

【Previously gated the entire import.meta.resolve feature.】

--experimental-inspector-network-resource#>

稳定性: 1.1 - 处于活跃开发中

启用对检查器网络资源的实验性支持。

【Enable experimental support for inspector network resources.】

--experimental-loader=module#>

不建议使用此标志,可能会在 Node.js 的未来版本中被移除。 请改用 --importregister()

指定包含导出 模块自定义钩子modulemodule 可以是任何被 import 说明符 接受的字符串。

【Specify the module containing exported module customization hooks. module may be any string accepted as an import specifier.】

如果与 权限模型 一起使用此功能,则需要 --allow-worker

【This feature requires --allow-worker if used with the Permission Model.】

--experimental-network-inspection#>

稳定性: 1 - 实验性

使用 Chrome DevTools 启用对网络检查的实验性支持。

【Enable experimental support for the network inspection with Chrome DevTools.】

--experimental-print-required-tla#>

如果被 require() 的 ES 模块包含顶层 await,此标志允许 Node.js 评估该模块,尝试定位顶层 await,并打印它们的位置以帮助用户找到它们。

【If the ES module being require()'d contains top-level await, this flag allows Node.js to evaluate the module, try to locate the top-level awaits, and print their location to help users find them.】

--experimental-quic#>

稳定性: 1.1 - 处于活跃开发中

启用对 QUIC 协议的实验性支持。

【Enable experimental support for the QUIC protocol.】

--experimental-require-module#>

稳定性: 1.1 - 处于活跃开发中

支持在 require() 中加载同步 ES 模块图。

【Supports loading a synchronous ES module graph in require().】

使用 require() 加载 ECMAScript 模块

【See Loading ECMAScript modules using require().】

--experimental-sea-config#>

稳定性: 1 - 实验性

使用此标志生成一个可以注入到 Node.js 二进制文件中的 blob,以生成 单个可执行应用。有关 这个配置 的详细信息,请参阅文档。

【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 for details.】

--experimental-shadow-realm#>

使用此标志以启用 影子字段 支持。

【Use this flag to enable ShadowRealm support.】

--experimental-test-coverage#>

当与 node:test 模块结合使用时,会在测试运行器输出中生成代码覆盖率报告。如果没有运行任何测试,则不会生成覆盖率报告。有关更多详细信息,请参阅 从测试中收集代码覆盖率 的文档。

【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#>

稳定性: 1.0 - 早期开发

在测试运行器中启用模块模拟。

【Enable module mocking in the test runner.】

如果与 权限模型 一起使用此功能,则需要 --allow-worker

【This feature requires --allow-worker if used with the Permission Model.】

--experimental-transform-types#>

稳定性: 1.2 - 发布候选版

启用将仅 TypeScript 的语法转换为 JavaScript 代码。意味着 --enable-source-maps

【Enables the transformation of TypeScript-only syntax into JavaScript code. Implies --enable-source-maps.】

--experimental-vm-modules#>

node:vm 模块中启用实验性的 ES 模块支持。

【Enable experimental ES Module support in the node:vm module.】

--experimental-wasi-unstable-preview1#>

启用实验性 WebAssembly 系统接口 (WASI) 支持。

【Enable experimental WebAssembly System Interface (WASI) support.】

--experimental-worker-inspection#>

稳定性: 1.1 - 处于活跃开发中

启用对使用 Chrome DevTools 检查工作器 (worker) 的实验性支持。

【Enable experimental support for the worker inspection with Chrome DevTools.】

--expose-gc#>

稳定性: 1 - 实验性。此标志继承自 V8,可能会在上游发生变化。

此标志将公开 V8 的 gc 扩展。

【This flag will expose the gc extension from V8.】

if (globalThis.gc) {
  globalThis.gc();
} 

--force-context-aware#>

禁用加载非 上下文感知 的本地插件。

【Disable loading native addons that are not context-aware.】

--force-fips#>

在启动时强制使用 FIPS 兼容的加密。(无法从脚本代码中禁用。) (与 --enable-fips 的要求相同。)

【Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.) (Same requirements as --enable-fips.)】

--force-node-api-uncaught-exceptions-policy#>

在 Node-API 异步回调上强制触发 uncaughtException 事件。

【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.】

--frozen-intrinsics#>

稳定性: 1 - 实验性

启用实验性的冻结内置对象,如 ArrayObject

【Enable experimental frozen intrinsics like Array and Object.】

仅支持根上下文。无法保证 globalThis.Array 确实是默认的内在引用。在此标志下代码可能会出错。

【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.】

为了允许添加填充,--require--import 都会在冻结内置对象之前运行。

【To allow polyfills to be added, --require and --import both run before freezing intrinsics.】

--heap-prof#>

在启动时启动 V8 堆分析器,并在退出前将堆分析结果写入磁盘。

【Starts the V8 heap profiler on start up, and writes the heap profile to disk before exit.】

如果未指定 --heap-prof-dir,生成的配置文件将放置在当前工作目录中。

【If --heap-prof-dir is not specified, the generated profile is placed in the current working directory.】

如果未指定 --heap-prof-name,生成的配置文件将被命名为 Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile

【If --heap-prof-name is not specified, the generated profile is named Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile.】

$ node --heap-prof index.js
$ ls *.heapprofile
Heap.20190409.202950.15293.0.001.heapprofile 

--heap-prof-dir#>

指定由 --heap-prof 生成的堆分析文件将被放置的目录。

【Specify the directory where the heap profiles generated by --heap-prof will be placed.】

默认值由 --diagnostic-dir 命令行选项控制。

【The default value is controlled by the --diagnostic-dir command-line option.】

--heap-prof-interval#>

指定生成堆配置文件的平均采样间隔(字节) 由“--堆-教授”编写。默认是512 * 1024字节。

【Specify the average sampling interval in bytes for the heap profiles generated by --heap-prof. The default is 512 * 1024 bytes.】

--heap-prof-name#>

指定由 --heap-prof 生成的堆分析文件的文件名。

【Specify the file name of the heap profile generated by --heap-prof.】

--heapsnapshot-near-heap-limit=max_count#>

稳定性: 1 - 实验性

当 V8 堆使用量接近堆限制时,将 V8 堆快照写入磁盘。count 应该是一个非负整数(在这种情况下,Node.js 不会将超过 max_count 个快照写入磁盘)。

【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).】

在生成快照时,可能会触发垃圾回收,从而降低堆的使用量。因此,在 Node.js 实例最终耗尽内存之前,可能会将多个快照写入磁盘。这些堆快照可以进行比较,以确定在连续快照拍摄期间正在分配哪些对象。不能保证 Node.js 会正好将 max_count 个快照写入磁盘,但它会尽力在 Node.js 实例耗尽内存之前生成至少一个、最多 max_count 个快照,当 max_count 大于 0 时。

【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.】

生成 V8 快照需要时间和内存(包括 V8 堆管理的内存以及 V8 堆之外的本地内存)。堆越大,需要的资源就越多。Node.js 会调整 V8 堆以适应额外的 V8 堆内存开销,并尽量避免耗尽进程可用的所有内存。当进程使用的内存超过系统认为合适的范围时,根据系统配置,进程可能会被系统突然终止。

【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.】

$ 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 --->

[49580:0x110000000]     4826 毫秒:标记-清除 130.6 (147.8) -> 130.5 (147.8) MB,27.4 / 0.0 毫秒(平均 mu = 0.126,当前 mu = 0.034)分配失败,清理可能不成功
[49580:0x110000000]     4845 毫秒:标记-清除 130.6 (147.8) -> 130.6 (147.8) MB,18.8 / 0.0 毫秒(平均 mu = 0.088,当前 mu = 0.031)分配失败,清理可能不成功



<--- JS stacktrace --->

致命错误:在堆边界附近的标记压缩无效,分配失败 - JavaScript 堆内存不足
....

【FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
....】
 

--heapsnapshot-signal=signal#>

启用一个信号处理程序,当收到指定信号时,使 Node.js 进程写入堆转储。signal 必须是有效的信号名称。默认情况下为禁用。

【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.】

$ 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 

-h--help#>

-h, --help

打印节点命令行选项。该选项的输出不如本文档详细。

【Print node command-line options. The output of this option is less detailed than this document.】

--icu-data-dir=file#>

指定 ICU 数据加载路径。(会覆盖 NODE_ICU_DATA。)

【Specify ICU data load path. (Overrides NODE_ICU_DATA.)】

--import=module#>

稳定性: 1 - 实验性

在启动时预加载指定的模块。如果该标志被多次提供,每个模块将按它们出现的顺序依次执行,首先是 NODE_OPTIONS 中提供的模块。

【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.】

遵循 ECMAScript 模块 分辨率规则。 使用 --require 加载 CommonJS 模块。 使用 --require 预加载的模块将在使用 --import 预加载的模块之前运行。

【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.】

--input-type=type#>

这将配置 Node.js 将 --evalSTDIN 输入解释为 CommonJS 或 ES 模块。有效值为 "commonjs""module""module-typescript""commonjs-typescript"。带有 "-typescript" 的值在使用 --no-experimental-strip-types 标志时不可用。默认情况下没有值,或者如果传递了 --no-experimental-detect-module,则默认为 "commonjs"

【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-experimental-strip-types. The default is no value, or "commonjs" if --no-experimental-detect-module is passed.】

如果未提供 --input-type,Node.js 将尝试通过以下步骤来检测语法:

【If --input-type is not provided, Node.js will try to detect the syntax with the following steps:】

  1. 以 CommonJS 方式运行输入。
  2. 如果步骤 1 失败,请将输入作为 ES 模块运行。
  3. 如果步骤 2 由于语法错误失败,请去掉类型。
  4. 如果步骤 3 出现错误代码 ERR_UNSUPPORTED_TYPESCRIPT_SYNTAXERR_INVALID_TYPESCRIPT_SYNTAX,则抛出步骤 2 的错误,并在消息中包含 TypeScript 错误,否则以 CommonJS 方式运行。
  5. 如果第4步失败,请将输入作为ES模块运行。

为了避免多次语法检测带来的延迟,可以使用 --input-type=type 标志来指定 --eval 输入的解释方式。

【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.】

REPL 不支持此选项。在 --print 中使用 --input-type=module 会导致错误,因为 --print 不支持 ES 模块语法。

【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.】

--insecure-http-parser#>

在 HTTP 解析器上启用宽松标志。这可能允许与不符合标准的 HTTP 实现进行互操作。

【Enable leniency flags on the HTTP parser. This may allow interoperability with non-conformant HTTP implementations.】

启用后,解析器将接受以下内容:

【When enabled, the parser will accept the following:】

  • 无效的 HTTP 头部值。
  • 无效的 HTTP 版本。
  • 允许消息同时包含 Transfer-EncodingContent-Length 头。
  • 当存在 Connection: close 时,允许消息后有额外数据。
  • 在提供 chunked 之后允许额外的传输编码。
  • 允许使用 作为标记分隔符,而不是
  • 允许在一个块之后不提供
  • 允许在块大小后和 之前存在空格。

以上所有情况都可能使你的应用暴露于请求走私或注入攻击。避免使用此选项。

【All the above will expose your application to request smuggling or poisoning attack. Avoid using this option.】

警告:将检查器绑定到公共 IP:端口组合是不安全的#>

【Warning: binding inspector to a public IP:port combination is insecure】

将检查器绑定到带有开放端口的公共 IP(包括 0.0.0.0)是不安全的,因为它允许外部主机连接到检查器并执行 远程代码执行 攻击。

【Binding the inspector to a public IP (including 0.0.0.0) with an open port is insecure, as it allows external hosts to connect to the inspector and perform a remote code execution attack.】

如果指定主机,请确保:

【If specifying a host, make sure that either:】

  • 该主机无法从公共网络访问。
  • 防火墙阻止端口上的不受欢迎连接。

更具体地说,如果端口(默认是 9229)没有防火墙保护,--inspect=0.0.0.0 是不安全的。

有关更多信息,请参阅 调试的安全影响 部分。

【See the debugging security implications section for more information.】

--inspect-brk[=[host:]port]#>

host:port 上激活检查器,并在用户脚本开始处中断。默认的 host:port127.0.0.1:9229。如果指定端口为 0,将使用一个随机可用端口。

【Activate inspector on host:port and break at start of user script. Default host:port is 127.0.0.1:9229. If port 0 is specified, a random available port will be used.】

有关 Node.js 调试器的更多说明,请参见 Node.js 的 V8 检查器集成

【See V8 Inspector integration for Node.js for further explanation on Node.js debugger.】

--inspect-port=[host:]port#>

设置在激活检查器时使用的 host:port。在通过发送 SIGUSR1 信号激活检查器时很有用。除非传递了 --disable-sigusr1

【Set the host:port to be used when the inspector is activated. Useful when activating the inspector by sending the SIGUSR1 signal. Except when --disable-sigusr1 is passed.】

默认主机是 127.0.0.1。如果指定端口 0,将使用一个随机可用端口。

【Default host is 127.0.0.1. If port 0 is specified, a random available port will be used.】

请参见下面关于 host 参数使用的 安全警告

【See the security warning below regarding the host parameter usage.】

--inspect-publish-uid=stderr,http#>

指定检查器网络套接字网址的暴露方式。

【Specify ways of the inspector web socket url exposure.】

默认情况下,检查器的 websocket URL 可以在标准错误输出(stderr)中找到,也可以通过 http://host:port/json/list/json/list 端点访问。

【By default inspector websocket url is available in stderr and under /json/list endpoint on http://host:port/json/list.】

--inspect-wait[=[host:]port]#>

host:port 上激活检查器并等待调试器附加。默认的 host:port127.0.0.1:9229。如果指定端口为 0,将使用一个随机的可用端口。

【Activate inspector on host:port and wait for debugger to be attached. Default host:port is 127.0.0.1:9229. If port 0 is specified, a random available port will be used.】

有关 Node.js 调试器的更多说明,请参见 Node.js 的 V8 检查器集成

【See V8 Inspector integration for Node.js for further explanation on Node.js debugger.】

--inspect[=[host:]port]#>

host:port 上激活检查器。默认值是 127.0.0.1:9229。如果指定端口为 0,将使用一个随机可用端口。

【Activate inspector on host:port. Default is 127.0.0.1:9229. If port 0 is specified, a random available port will be used.】

V8 检查器集成允许诸如 Chrome DevTools 和 IDE 等工具调试和分析 Node.js 实例。这些工具通过 TCP 端口附加到 Node.js 实例并使用 Chrome 开发者工具协议 进行通信。有关 Node.js 调试器的更多说明,请参阅 Node.js 的 V8 检查器集成

【V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug and profile Node.js instances. The tools attach to Node.js instances via a tcp port and communicate using the Chrome DevTools Protocol. See V8 Inspector integration for Node.js for further explanation on Node.js debugger.】

-i--interactive#>

-i, --interactive

即使标准输入似乎不是终端,也会打开交互式解释器。

【Opens the REPL even if stdin does not appear to be a terminal.】

--jitless#>

稳定性: 1 - 实验性。此标志继承自 V8,可能会在上游发生变化。

禁用 可执行内存的运行时分配。这在某些平台上可能出于安全原因是必需的。在其他平台上,它也可以减少攻击面,但性能影响可能很严重。

【Disable runtime allocation of executable memory. 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.】

--localstorage-file=file#>

用于存储 localStorage 数据的文件。如果文件不存在,当第一次访问 localStorage 时会创建该文件。多个 Node.js 进程可以同时共享同一个文件。如果 Node.js 是使用 --no-webstorage(或 --no-experimental-webstorage)标志启动的,则此标志无效。

【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. This flag is a no-op if Node.js is started with the --no-webstorage (or --no-experimental-webstorage) flag.】

--max-http-header-size=size#>

指定 HTTP 请求头的最大大小(以字节为单位)。默认值为 16 KiB。

【Specify the maximum size, in bytes, of HTTP headers. Defaults to 16 KiB.】

--max-old-space-size-percentage=percentage#>

将 V8 的旧内存区的最大内存大小设置为可用系统内存的百分比。当同时指定此标志和 --max-old-space-size 时,此标志优先。

【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.】

percentage 参数必须是大于 0 且不超过 100 的数字,表示要分配给 V8 堆的可用系统内存百分比。

【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.】

注意: 此标志使用了 --max-old-space-size,在 32 位平台上可能不可靠,因为存在整数溢出问题。

# 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 

--napi-modules#>

此选项无任何操作。它保留是为了兼容性。

【This option is a no-op. It is kept for compatibility.】

--network-family-autoselection-attempt-timeout#>

设置网络类型自动选择尝试超时的默认值。有关更多信息,请参见 net.getDefaultAutoSelectFamilyAttemptTimeout()

【Sets the default value for the network family autoselection attempt timeout. For more information, see net.getDefaultAutoSelectFamilyAttemptTimeout().】

--no-addons#>

禁用 node-addons 导出条件,同时禁用加载本地插件。当指定 --no-addons 时,调用 process.dlopen 或加载本地 C++ 插件将会失败并抛出异常。

【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-async-context-frame#>

禁用由 AsyncContextFrame 支持的 AsyncLocalStorage,并使用以前依赖 async_hooks 的实现。保留以前的模型是为了与 Electron 兼容以及应对上下文流可能不同的情况。然而,如果发现流有差异,请报告。

【Disables the use of AsyncLocalStorage backed by AsyncContextFrame and uses the prior implementation which relied on async_hooks. The previous model is retained for compatibility with Electron and for cases where the context flow may differ. However, if a difference in flow is found please report it.】

--no-deprecation#>

静默弃用警告。

【Silence deprecation warnings.】

--no-experimental-detect-module#>

禁用使用 语法检测 来确定模块类型。

【Disable using syntax detection to determine module type.】

--no-experimental-global-navigator#>

稳定性: 1 - 实验性

在全局范围内禁用 导航器 API 的公开显示。

【Disable exposition of Navigator API on the global scope.】

--no-experimental-repl-await#>

使用此标志在交互式解释器中禁用顶层等待。

【Use this flag to disable top-level await in REPL.】

--no-experimental-require-module#>

稳定性: 1.1 - 处于活跃开发中

禁用在 require() 中加载同步 ES 模块图的支持。

【Disable support for loading a synchronous ES module graph in require().】

使用 require() 加载 ECMAScript 模块

【See Loading ECMAScript modules using require().】

--no-experimental-sqlite#>

禁用实验性的node:sqlite模块。

【Disable the experimental node:sqlite module.】

--no-experimental-strip-types#>

稳定性: 1.2 - 发布候选版

禁用 TypeScript 文件的实验性类型剥离。有关更多信息,请参阅 TypeScript 类型剥离 文档。

【Disable experimental type-stripping for TypeScript files. For more information, see the TypeScript type-stripping documentation.】

--no-experimental-websocket#>

禁用 WebSocket 在全局范围内的展示。

【Disable exposition of WebSocket on the global scope.】

--no-extra-info-on-fatal-exception#>

隐藏导致退出的致命异常的额外信息。

【Hide extra information on fatal exception that causes exit.】

--no-force-async-hooks-checks#>

禁用 async_hooks 的运行时检查。当启用 async_hooks 时,这些检查仍会动态启用。

【Disables runtime checks for async_hooks. These will still be enabled dynamically when async_hooks is enabled.】

--no-global-search-paths#>

不要从全局路径如 $HOME/.node_modules$NODE_PATH 搜索模块。

【Do not search modules from global paths like $HOME/.node_modules and $NODE_PATH.】

--no-network-family-autoselection#>

除非连接选项明确启用,否则禁用家庭自动选择算法。

【Disables the family autoselection algorithm unless connection options explicitly enables it.】

--no-warnings#>

静默所有进程警告(包括弃用的)。

【Silence all process warnings (including deprecations).】

--no-webstorage#>

禁用Web Storage支持。

【Disable Web Storage support.】

--node-memory-debug#>

启用针对 Node.js 内部的额外内存泄漏调试检查。这通常只对调试 Node.js 本身的开发者有用。

【Enable extra debug checks for memory leaks in Node.js internals. This is usually only useful for developers debugging Node.js itself.】

--openssl-config=file#>

在启动时加载 OpenSSL 配置文件。除其他用途外,如果 Node.js 是针对启用 FIPS 的 OpenSSL 构建的,这可以用于启用符合 FIPS 的加密。

【Load an OpenSSL configuration file on startup. Among other uses, this can be used to enable FIPS-compliant crypto if Node.js is built against FIPS-enabled OpenSSL.】

--openssl-legacy-provider#>

启用 OpenSSL 3.0 传统提供程序。更多信息请参见 OSSL_提供者-传统

【Enable OpenSSL 3.0 legacy provider. For more information please see OSSL_PROVIDER-legacy.】

--openssl-shared-config#>

启用 OpenSSL 默认配置部分 openssl_conf,以便从 OpenSSL 配置文件中读取。默认的配置文件名为 openssl.cnf,但可以通过环境变量 OPENSSL_CONF 或命令行选项 --openssl-config 更改。默认 OpenSSL 配置文件的位置取决于 OpenSSL 如何与 Node.js 进行链接。共享 OpenSSL 配置可能会带来不希望的影响,建议使用专用于 Node.js 的配置部分 nodejs_conf,当不使用此选项时,该部分为默认配置。

【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.】

--pending-deprecation#>

触发挂起的弃用警告。

【Emit pending deprecation warnings.】

待弃用通常与运行时弃用完全相同,其显著区别在于,默认情况下它们是关闭的,并且不会被触发,除非设置了 --pending-deprecation 命令行标志或 NODE_PENDING_DEPRECATION=1 环境变量。待弃用用于提供一种选择性的“提前警告”机制,开发者可以利用它来检测已弃用的 API 使用情况。

【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.】

--permission#>

为当前进程启用权限模型。启用后,以下权限将受到限制:

【Enable the Permission Model for current process. When enabled, the following permissions are restricted:】

--preserve-symlinks#>

指示模块加载器在解析和缓存模块时保留符号链接。

【Instructs the module loader to preserve symbolic links when resolving and caching modules.】

默认情况下,当 Node.js 从符号链接到不同磁盘位置的路径加载模块时,Node.js 会取消引用该链接,并使用模块的实际磁盘“真实路径”作为标识符,以及作为定位其他依赖模块的根路径。在大多数情况下,这种默认行为是可接受的。然而,当使用符号链接的对等依赖时,如下面的示例所示,如果 moduleA 尝试将 moduleB 作为对等依赖来 require,默认行为会导致抛出异常:

【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:】

{appDir}
 ├── app
 │   ├── index.js
 │   └── node_modules
 │       ├── moduleA -> {appDir}/moduleA
 │       └── moduleB
 │           ├── index.js
 │           └── package.json
 └── moduleA
     ├── index.js
     └── package.json 

--preserve-symlinks 命令行标志指示 Node.js 使用模块的符号链接路径而不是真实路径,从而允许找到符号链接的同级依赖。

【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.】

请注意,使用 --preserve-symlinks 可能会有其他副作用。具体来说,如果符号链接的 原生 模块从依赖树中的多个位置链接,可能会加载失败(Node.js 会将它们视为两个独立的模块,并尝试多次加载该模块,从而导致抛出异常)。

【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).】

--preserve-symlinks 标志不适用于主模块,这使得 node --preserve-symlinks node_module/.bin/<foo> 能够工作。要在主模块上应用相同的行为,还需要使用 --preserve-symlinks-main

【The --preserve-symlinks flag does not apply to the main module, which allows node --preserve-symlinks node_module/.bin/<foo> to work. To apply the same behavior for the main module, also use --preserve-symlinks-main.】

--preserve-symlinks-main#>

指示模块加载器在解析和缓存主模块(require.main)时保留符号链接。

【Instructs the module loader to preserve symbolic links when resolving and caching the main module (require.main).】

这个标志存在是为了让主模块可以选择采用 --preserve-symlinks 对所有其他导入所提供的相同行为;不过,它们是单独的标志,以便向旧版本的 Node.js 保持向后兼容。

【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 并不意味着 --preserve-symlinks;当不希望在解析相对路径之前跟随符号链接时,应将 --preserve-symlinks-main--preserve-symlinks 一起使用。

有关更多信息,请参见--preserve-symlinks

【See --preserve-symlinks for more information.】

-p--print "script"#>

-p, --print "script"

-e 相同,但会打印结果。

【Identical to -e but prints the result.】

--prof#>

生成 V8 分析器输出。

【Generate V8 profiler output.】

--prof-process#>

处理使用 V8 选项 --prof 生成的 V8 分析器输出。

【Process V8 profiler output generated using the V8 option --prof.】

--redirect-warnings=file#>

将进程警告写入指定文件,而不是打印到标准错误。如果文件不存在,将创建该文件;如果文件已存在,将在其末尾追加内容。如果在尝试将警告写入文件时发生错误,警告将改为写入标准错误。

【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.】

file 名称可以是绝对路径。如果不是,文件将被写入的默认目录由 --diagnostic-dir 命令行选项控制。

【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-compact#>

以紧凑格式编写报告,单行 JSON,比为人类阅读设计的默认多行格式更易被日志处理系统消费。

【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.】

--report-dir=目录report-directory=目录#>

--report-dir=directory, report-directory=directory

生成报告的位置。

【Location at which the report will be generated.】

--report-exclude-env#>

当传入 --report-exclude-env 时,生成的诊断报告将不包含 environmentVariables 数据。

【When --report-exclude-env is passed the diagnostic report generated will not contain the environmentVariables data.】

--report-exclude-network#>

从诊断报告中排除 header.networkInterfaces。默认情况下,此项未设置,网络接口会被包括在内。

【Exclude header.networkInterfaces from the diagnostic report. By default this is not set and the network interfaces are included.】

--report-filename=filename#>

将写入报告的文件的名称。

【Name of the file to which the report will be written.】

如果文件名设置为 'stdout''stderr',报告将分别写入进程的标准输出或标准错误。

【If the filename is set to 'stdout' or 'stderr', the report is written to the stdout or stderr of the process respectively.】

--report-on-fatalerror#>

启用在致命错误(Node.js 运行时的内部错误,例如内存耗尽)发生时触发报告的功能,这些错误会导致应用终止。可用于检查各种诊断数据元素,如堆、堆栈、事件循环状态、资源消耗等,以分析致命错误的原因。

【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.】

--report-on-signal#>

在接收到发送到正在运行的 Node.js 进程的指定(或预定义)信号时,启用生成报告。触发报告的信号通过 --report-signal 指定。

【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.】

--report-signal=signal#>

设置或重置报告生成的信号(Windows 不支持)。 默认信号是 SIGUSR2

【Sets or resets the signal for report generation (not supported on Windows). Default signal is SIGUSR2.】

--report-uncaught-exception#>

当进程因未捕获的异常退出时,允许生成报告。在结合本地堆栈和其他运行时环境数据检查 JavaScript 堆栈时非常有用。

【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.】

-r--require 模块#>

-r, --require module

在启动时预加载指定的模块。

【Preload the specified module at startup.】

遵循 require() 的模块解析规则。module 可以是文件路径,也可以是节点模块名称。

【Follows require()'s module resolution rules. module may be either a path to a file, or a node module name.】

使用 --require 预加载的模块会在使用 --import 预加载的模块之前运行。

【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.】

--run#>

这会从 package.json 的 "scripts" 对象中运行指定的命令。如果提供了一个不存在的 "command",它将列出可用的脚本。

【This runs a specified command from a package.json's "scripts" object. If a missing "command" is provided, it will list the available scripts.】

--run 将向上遍历到根目录,并找到一个 package.json 文件来运行命令。

--run 会将每个当前目录的祖级目录下的 ./node_modules/.bin 添加到 PATH 中,以便在存在多个 node_modules 目录的不同文件夹中执行二进制文件,如果 ancestor-folder/node_modules/.bin 是一个目录。

--run 在包含相关 package.json 的目录中执行命令。

例如,以下命令将在当前文件夹中运行 package.jsontest 脚本:

【For example, the following command will run the test script of the package.json in the current folder:】

$ node --run test 

你也可以向命令传递参数。-- 之后的任何参数都会被追加到脚本中:

【You can also pass arguments to the command. Any argument after -- will be appended to the script:】

$ node --run test -- --verbose 

故意限制#>

【Intentional limitations】

node --run 并不是用来模仿 npm run 或其他包管理器的 run 命令的行为。Node.js 的实现故意更为有限,以便专注于最常见用例的高性能。其他 run 实现中被故意排除的一些功能有:

  • 除了指定的脚本之外,还会运行 prepost 脚本。
  • 定义特定于包管理器的环境变量。

环境变量#>

【Environment variables】

在使用 --run 运行脚本时,会设置以下环境变量:

【The following environment variables are set when running a script with --run:】

  • NODE_RUN_SCRIPT_NAME:正在运行的脚本名称。例如,如果使用 --run 来运行 test,则该变量的值将是 test
  • NODE_RUN_PACKAGE_JSON_PATH:正在处理的 package.json 的路径。

--secure-heap-min=n#>

在使用 --secure-heap 时,--secure-heap-min 参数指定从安全堆分配的最小值。最小值为 2。最大值为 --secure-heap2147483647 中的较小者。指定的值必须是二的幂。

【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.】

--secure-heap=n#>

初始化一个大小为 n 字节的 OpenSSL 安全堆。初始化后,安全堆会在 OpenSSL 中的某些分配类型中使用,例如在密钥生成和其他操作期间。这非常有用,例如可以防止由于指针越界或下溢导致的敏感信息泄露。

【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.】

指定的堆大小必须是二的幂。小于 2 的任意值将禁用安全堆。

【The heap size given must be a power of two. Any value less than 2 will disable the secure heap.】

默认情况下禁用安全堆。

【The secure heap is disabled by default.】

安全堆在 Windows 上不可用。

【The secure heap is not available on Windows.】

有关详细信息,请参见CRYPTO_secure_malloc_init

【See CRYPTO_secure_malloc_init for more details.】

--snapshot-blob=path#>

稳定性: 1 - 实验性

当与 --build-snapshot 一起使用时,--snapshot-blob 指定生成的快照二进制文件的写入路径。如果未指定,生成的二进制文件将写入当前工作目录下的 snapshot.blob

【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.】

当不使用 --build-snapshot 时,--snapshot-blob 指定用于恢复应用状态的 blob 的路径。

【When used without --build-snapshot, --snapshot-blob specifies the path to the blob that is used to restore the application state.】

加载快照时,Node.js 检查:

【When loading a snapshot, Node.js checks that:】

  1. 正在运行的 Node.js 二进制文件的版本、架构和平台与生成快照的二进制文件完全相同。
  2. V8 标志和 CPU 特性与生成快照的二进制文件兼容。

如果它们不匹配,Node.js 将拒绝加载快照并以状态码 1 退出。

【If they don't match, Node.js refuses to load the snapshot and exits with status code 1.】

--test#>

启动 Node.js 命令行测试运行器。此标志不能与 --watch-path--check--eval--interactive 或检查器一起使用。有关更多详情,请参阅 从命令行运行测试 文档。

【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.】

--test-concurrency#>

测试运行器 CLI 可以并发执行的最大测试文件数。如果 --test-isolation 设置为 'none',则忽略此标志,并且并发数为一。否则,并发数默认为 os.availableParallelism() - 1

【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.】

--test-coverage-branches=threshold#>

稳定性: 1 - 实验性

要求覆盖的分支达到最低百分比。如果代码覆盖率未达到指定的阈值,进程将以代码 1 退出。

【Require a minimum percent of covered branches. If code coverage does not reach the threshold specified, the process will exit with code 1.】

--test-coverage-exclude#>

稳定性: 1 - 实验性

使用通配符模式从代码覆盖中排除特定文件,该模式可以匹配绝对和相对文件路径。

【Excludes specific files from code coverage using a glob pattern, which can match both absolute and relative file paths.】

可以多次指定此选项以排除多个 glob 模式。

【This option may be specified multiple times to exclude multiple glob patterns.】

如果同时提供了 --test-coverage-exclude--test-coverage-include,文件必须同时满足两个条件才能被包含在覆盖率报告中。

【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.】

--test-coverage-functions=threshold#>

稳定性: 1 - 实验性

要求覆盖的函数达到最低百分比。如果代码覆盖率未达到指定的阈值,进程将以代码 1 退出。

【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#>

稳定性: 1 - 实验性

使用全局模式在代码覆盖中包含特定文件,该模式可以匹配绝对路径和相对路径。

【Includes specific files in code coverage using a glob pattern, which can match both absolute and relative file paths.】

可以多次指定此选项以包含多个 glob 模式。

【This option may be specified multiple times to include multiple glob patterns.】

如果同时提供了 --test-coverage-exclude--test-coverage-include,文件必须同时满足两个条件才能被包含在覆盖率报告中。

【If both --test-coverage-exclude and --test-coverage-include are provided, files must meet both criteria to be included in the coverage report.】

--test-coverage-lines=threshold#>

稳定性: 1 - 实验性

要求覆盖的代码行达到最低百分比。如果代码覆盖率未达到指定的阈值,进程将以代码 1 退出。

【Require a minimum percent of covered lines. If code coverage does not reach the threshold specified, the process will exit with code 1.】

--test-force-exit#>

配置测试运行器以在所有已知测试执行完毕后退出进程,即使事件循环本来会继续保持活动状态。

【Configures the test runner to exit the process once all known tests have finished executing even if the event loop would otherwise remain active.】

--test-global-setup=module#>

稳定性: 1.0 - 早期开发

指定一个模块,该模块将在所有测试执行之前进行评估,并可用于设置测试的全局状态或夹具。

【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.】

--test-isolation=mode#>

配置测试运行器中使用的测试隔离类型。当 mode'process' 时,每个测试文件将在单独的子进程中运行。当 mode'none' 时,所有测试文件将在与测试运行器相同的进程中运行。默认的隔离模式是 'process'。如果未使用 --test 标志,则此标志会被忽略。有关更多信息,请参阅 测试运行器执行模型 部分。

【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.】

--test-name-pattern#>

一个正则表达式,用于配置测试运行器,只执行名称与提供的模式匹配的测试。有关更多详细信息,请参阅 按名称筛选测试 的文档。

【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.】

如果同时提供了 --test-name-pattern--test-skip-pattern,测试必须满足两个条件才能执行。

【If both --test-name-pattern and --test-skip-pattern are supplied, tests must satisfy both requirements in order to be executed.】

--test-only#>

配置测试运行器仅执行设置了 only 选项的顶层测试。当测试隔离被禁用时,此标志不是必须的。

【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-reporter#>

在运行测试时使用的测试报告工具。有关详细信息,请参见 测试报告器 的文档。

【A test reporter to use when running tests. See the documentation on test reporters for more details.】

--test-reporter-destination#>

相应测试报告的目标位置。有关更多详细信息,请参阅 测试报告器 的文档。

【The destination for the corresponding test reporter. See the documentation on test reporters for more details.】

--test-rerun-failures#>

一个指向文件的路径,允许测试运行器在多次运行之间保持测试套件的状态。测试运行器将使用此文件来确定哪些测试已经成功或失败,从而可以重新运行失败的测试,而无需重新运行整个测试套件。如果该文件不存在,测试运行器将创建它。有关更多详细信息,请参阅 测试重跑 的文档。

【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.】

--test-shard#>

要执行的测试套件分片,格式为 <index>/<total>,其中

【Test suite shard to execute in a format of <index>/<total>, where】

  • index 是一个正整数,表示分割部分的索引。
  • total 是一个正整数,表示分割部分的总和。

此命令将把所有测试文件分成 total 等份,并且只运行位于第 index 部分的测试文件。

【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:】

node --test --test-shard=1/3
node --test --test-shard=2/3
node --test --test-shard=3/3 

--test-skip-pattern#>

一个正则表达式,用于配置测试运行器跳过名称与提供的模式匹配的测试。更多细节请参阅关于 按名称筛选测试 的文档。

【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.】

如果同时提供了 --test-name-pattern--test-skip-pattern,测试必须满足两个条件才能执行。

【If both --test-name-pattern and --test-skip-pattern are supplied, tests must satisfy both requirements in order to be executed.】

--test-timeout#>

测试执行将在若干毫秒后失败。如果未指定,子测试将继承其父测试的此值。默认值为 Infinity

【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#>

重新生成测试运行器用于 快照测试 的快照文件。

【Regenerates the snapshot files used by the test runner for snapshot testing.】

--throw-deprecation#>

为弃用抛出错误。

【Throw errors for deprecations.】

--title=title#>

在启动时设置 process.title

【Set process.title on startup.】

--tls-cipher-list=list#>

指定一个备用的默认 TLS 密码套件列表。需要 Node.js 在构建时启用加密支持(默认)。

【Specify an alternative default TLS cipher list. Requires Node.js to be built with crypto support (default).】

--tls-keylog=file#>

将 TLS 密钥材料记录到文件中。密钥材料采用 NSS SSLKEYLOGFILE 格式,可被软件(如 Wireshark)用来解密 TLS 流量。

【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.】

--tls-max-v1.2#>

tls.DEFAULT_MAX_VERSION 设置为 'TLSv1.2'。用于禁用对 TLSv1.3 的支持。

【Set tls.DEFAULT_MAX_VERSION to 'TLSv1.2'. Use to disable support for TLSv1.3.】

--tls-max-v1.3#>

将默认 tls.DEFAULT_MAX_VERSION 设置为 'TLSv1.3'。用于启用对 TLSv1.3 的支持。

【Set default tls.DEFAULT_MAX_VERSION to 'TLSv1.3'. Use to enable support for TLSv1.3.】

--tls-min-v1.0#>

将默认 tls.DEFAULT_MIN_VERSION 设置为 'TLSv1'。用于与旧版 TLS 客户端或服务器兼容。

【Set default tls.DEFAULT_MIN_VERSION to 'TLSv1'. Use for compatibility with old TLS clients or servers.】

--tls-min-v1.1#>

将默认 tls.DEFAULT_MIN_VERSION 设置为 'TLSv1.1'。用于与旧版 TLS 客户端或服务器的兼容性。

【Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.1'. Use for compatibility with old TLS clients or servers.】

--tls-min-v1.2#>

将默认 tls.DEFAULT_MIN_VERSION 设置为 'TLSv1.2'。这是 12.x 及更高版本的默认设置,但该选项可用于与较旧的 Node.js 版本兼容。

【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.】

--tls-min-v1.3#>

将默认 tls.DEFAULT_MIN_VERSION 设置为 'TLSv1.3'。用于禁用对 TLSv1.2 的支持,因为它不如 TLSv1.3 安全。

【Set default tls.DEFAULT_MIN_VERSION to 'TLSv1.3'. Use to disable support for TLSv1.2, which is not as secure as TLSv1.3.】

--trace-deprecation#>

打印弃用的堆栈跟踪。

【Print stack traces for deprecations.】

--trace-env#>

将当前 Node.js 实例中对环境变量的任何访问信息打印到标准错误,包括:

【Print information about any access to environment variables done in the current Node.js instance to stderr, including:】

  • 环境变量读取的是 Node.js 内部处理的内容。
  • process.env.KEY = "SOME VALUE" 的形式书写。
  • process.env.KEY 的形式读取。
  • Object.defineProperty(process.env, 'KEY', {...}) 形式的定义。
  • Object.hasOwn(process.env, 'KEY')process.env.hasOwnProperty('KEY')'KEY' in process.env 形式的查询。
  • delete process.env.KEY 形式进行删除。
  • ...process.envObject.keys(process.env) 形式的枚举。

只会打印正在访问的环境变量的名称,其值不会被打印。

【Only the names of the environment variables being accessed are printed. The values are not printed.】

要打印访问的堆栈跟踪,请使用 --trace-env-js-stack 和/或 --trace-env-native-stack

【To print the stack trace of the access, use --trace-env-js-stack and/or --trace-env-native-stack.】

--trace-env-js-stack#>

除了 --trace-env 的功能外,这还会打印访问的 JavaScript 堆栈追踪。

【In addition to what --trace-env does, this prints the JavaScript stack trace of the access.】

--trace-env-native-stack#>

除了 --trace-env 的功能之外,这还会打印访问的本地堆栈跟踪。

【In addition to what --trace-env does, this prints the native stack trace of the access.】

--trace-event-categories#>

使用 --trace-events-enabled 启用跟踪事件追踪时,应该被追踪的类别的逗号分隔列表。

【A comma separated list of categories that should be traced when trace event tracing is enabled using --trace-events-enabled.】

--trace-event-file-pattern#>

指定跟踪事件数据文件路径的模板字符串,它支持 ${rotation}${pid}

【Template string specifying the filepath for the trace event data, it supports ${rotation} and ${pid}.】

--trace-events-enabled#>

启用跟踪事件跟踪信息的收集。

【Enables the collection of trace event tracing information.】

--trace-exit#>

每当主动退出环境时,即调用 process.exit(),都会打印堆栈跟踪。

【Prints a stack trace whenever an environment is exited proactively, i.e. invoking process.exit().】

--trace-require-module=mode#>

打印有关 使用 require() 加载 ECMAScript 模块 使用的信息。

【Prints information about usage of Loading ECMAScript modules using require().】

modeall 时,会打印所有用法。当 modeno-node-modules 时,会排除来自 node_modules 文件夹的用法。

【When mode is all, all usage is printed. When mode is no-node-modules, usage from the node_modules folder is excluded.】

--trace-sigint#>

在 SIGINT 上打印堆栈跟踪。

【Prints a stack trace on SIGINT.】

--trace-sync-io#>

在事件循环的第一次循环之后检测到同步 I/O 时打印堆栈跟踪。

【Prints a stack trace whenever synchronous I/O is detected after the first turn of the event loop.】

--trace-tls#>

将 TLS 数据包跟踪信息打印到 stderr。这可用于调试 TLS 连接问题。

【Prints TLS packet trace information to stderr. This can be used to debug TLS connection problems.】

--trace-uncaught#>

打印未捕获异常的堆栈跟踪;通常会打印与创建 Error 相关的堆栈跟踪,而此选项会让 Node.js 还打印与抛出值相关的堆栈跟踪(抛出的值不必是 Error 实例)。

【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.】

--trace-warnings#>

打印进程警告的堆栈跟踪(包括弃用)。

【Print stack traces for process warnings (including deprecations).】

--track-heap-objects#>

跟踪堆快照的堆对象分配。

【Track heap object allocations for heap snapshots.】

--unhandled-rejections=mode#>

使用此标志可以更改在发生未处理的拒绝时应发生的操作。可以选择以下模式之一:

【Using this flag allows to change what should happen when an unhandled rejection occurs. One of the following modes can be chosen:】

  • throw:发出 unhandledRejection。如果未设置此钩子,则将未处理的拒绝作为未捕获异常抛出。这是默认行为。
  • strict:将未处理的拒绝作为未捕获异常抛出。如果异常被处理,将触发 unhandledRejection
  • warn:始终触发警告,无论 unhandledRejection 钩子是否设置,但不要打印弃用警告。
  • warn-with-error-code:发出 unhandledRejection。如果未设置此钩子,则触发警告,并将进程退出码设置为 1。
  • none:静音所有警告。

如果在命令行入口点的 ES 模块静态加载阶段发生拒绝,它将始终将其作为未捕获的异常引发。

【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.】

--use-bundled-ca--use-openssl-ca#>

--use-bundled-ca, --use-openssl-ca

使用当前 Node.js 版本提供的打包 Mozilla CA 存储,或使用 OpenSSL 的默认 CA 存储。默认存储可在构建时选择。

【Use bundled Mozilla CA store as supplied by current Node.js version or use OpenSSL's default CA store. The default store is selectable at build-time.】

由 Node.js 提供的打包 CA 证书库是 Mozilla CA 证书库在发布时的快照。在所有支持的平台上都是相同的。

【The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store that is fixed at release time. It is identical on all supported platforms.】

使用 OpenSSL 存储允许对存储进行外部修改。对于大多数 Linux 和 BSD 发行版,该存储由发行版维护者和系统管理员维护。OpenSSL CA 存储的位置取决于 OpenSSL 库的配置,但可以在运行时使用环境变量进行更改。

【Using OpenSSL store allows for external modifications of the store. For most Linux and BSD distributions, this store is maintained by the distribution maintainers and system administrators. OpenSSL CA store location is dependent on configuration of the OpenSSL library but this can be altered at runtime using environment variables.】

请参见 SSL_CERT_DIRSSL_CERT_FILE

【See SSL_CERT_DIR and SSL_CERT_FILE.】

--use-env-proxy#>

稳定性: 1.1 - 处于活跃开发中

启用时,Node.js 会在启动时解析 HTTP_PROXYHTTPS_PROXYNO_PROXY 环境变量,并通过指定的代理隧道传输请求。

【When enabled, Node.js parses the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables during startup, and tunnels requests over the specified proxy.】

这相当于设置 NODE_USE_ENV_PROXY=1 环境变量。当两者都设置时,--use-env-proxy 优先。

【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#>

在启动时将 Node.js 静态代码重新映射到大内存页。如果目标系统支持,这将导致 Node.js 静态代码被移动到 2 MiB 页而不是 4 KiB 页上。

【Re-map the Node.js static code to large memory pages at startup. If supported on the target system, this will cause the Node.js static code to be moved onto 2 MiB pages instead of 4 KiB pages.】

mode 的以下值是有效的:

【The following values are valid for mode:】

  • off:不会尝试映射。这是默认设置。
  • on:如果操作系统支持,将尝试进行映射。映射失败将被忽略,并且消息会打印到标准错误输出。
  • silent:如果操作系统支持,将尝试映射。映射失败将被忽略,不会报告。

--use-system-ca#>

Node.js 使用系统存储中受信任的 CA 证书,并可以配合 --use-bundled-ca 选项和 NODE_EXTRA_CA_CERTS 环境变量使用。在 Windows 和 macOS 以外的平台上,它会从 OpenSSL 信任的目录和文件中加载证书,类似于 --use-openssl-ca,不同之处在于它在首次加载后会缓存证书。

【Node.js uses the trusted CA certificates present in the system store along with the --use-bundled-ca option and the NODE_EXTRA_CA_CERTS environment variable. On platforms other than Windows and macOS, this loads certificates from the directory and file trusted by OpenSSL, similar to --use-openssl-ca, with the difference being that it caches the certificates after first load.】

在 Windows 和 macOS 上,证书信任策略计划遵循 Chromium 本地信任证书的策略

【On Windows and macOS, the certificate trust policy is planned to follow Chromium's policy for locally trusted certificates:】

在 macOS 上,遵循以下设置:

【On macOS, the following settings are respected:】

  • 默认钥匙串和系统钥匙串
    • 信任:
      • 任何将“使用此证书时”标志设置为“始终信任”的证书,或
      • 任何将“安全套接字层(SSL)”标志设置为“始终信任”的证书。
    • 不信任:
      • 任何“使用此证书时”标志设置为“永不信任”的证书,或
      • 任何将“安全套接字层(SSL)”标志设置为“永不信任”的证书。

在 Windows 上,将遵循以下设置(与 Chromium 的策略不同,目前不支持不信任和中间 CA):

【On Windows, the following settings are respected (unlike Chromium's policy, distrust and intermediate CA are not currently supported):】

  • 本地计算机(通过 certlm.msc 访问)
    • 信任:
      • 受信任的根证书颁发机构
      • 可信赖的人
      • 企业信任 -> 企业 -> 受信任的根证书颁发机构
      • 企业信任 -> 企业 -> 可信人员
      • 企业信任 -> 组策略 -> 受信任的根证书颁发机构
      • 企业信任 -> 组策略 -> 受信任的人员
  • 当前用户(通过 certmgr.msc 访问)
    • 信任:
      • 受信任的根证书颁发机构
      • 企业信任 -> 组策略 -> 受信任的根证书颁发机构

在 Windows 和 macOS 上,Node.js 会在使用证书之前检查用户的证书设置,确保这些设置没有禁止其用于 TLS 服务器身份验证。

【On Windows and macOS, Node.js would check that the user settings for the certificates do not forbid them for TLS server authentication before using them.】

在其他系统上,Node.js 会从默认证书文件(通常是 /etc/ssl/cert.pem)和默认证书目录(通常是 /etc/ssl/certs)加载证书,这些位置是 Node.js 所链接的 OpenSSL 版本所遵循的。通常,这在主要的 Linux 发行版和其他类 Unix 系统上都能正常工作。如果设置了覆盖 OpenSSL 的环境变量(通常是 SSL_CERT_FILESSL_CERT_DIR,具体取决于 Node.js 所链接的 OpenSSL 的配置),则会使用指定的路径来加载证书。如果 Node.js 所链接的 OpenSSL 版本使用的常规路径与用户的系统配置不一致,这些环境变量可以作为一种解决方法。

【On other systems, Node.js loads certificates from the default certificate file (typically /etc/ssl/cert.pem) and default certificate directory (typically /etc/ssl/certs) that the version of OpenSSL that Node.js links to respects. This typically works with the convention on major Linux distributions and other Unix-like systems. If the overriding OpenSSL environment variables (typically SSL_CERT_FILE and SSL_CERT_DIR, depending on the configuration of the OpenSSL that Node.js links to) are set, the specified paths will be used to load certificates instead. These environment variables can be used as workarounds if the conventional paths used by the version of OpenSSL Node.js links to are not consistent with the system configuration that the users have for some reason.】

--v8-options#>

打印 V8 命令行选项。

【Print V8 command-line options.】

--v8-pool-size=num#>

设置 V8 的线程池大小,用于分配后台作业。

【Set V8's thread pool size which will be used to allocate background jobs.】

如果设置为 0,那么 Node.js 将根据对并行量的估算选择合适的线程池大小。

【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.】

并行度是指在给定机器中可以同时执行的计算数量。一般来说,它与 CPU 的数量相同,但在虚拟机或容器等环境中可能会有所不同。

【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.】

-v--version#>

-v, --version

打印 node 的版本。

【Print node's version.】

--watch#>

以监视模式启动 Node.js。 在监视模式下,被监视的文件发生更改会导致 Node.js 进程重启。 默认情况下,监视模式会监视入口点以及所有所需或导入的模块。 使用 --watch-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.】

此标志不能与 --check--eval--interactive 或 REPL 一起使用。

【This flag cannot be combined with --check, --eval, --interactive, or the REPL.】

注意:--watch 标志需要一个文件路径作为参数,并且与 --run 或内联脚本输入不兼容,因为 --run 优先,会忽略监听模式。如果未提供文件,Node.js 将以状态码 9 退出。

【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.】

node --watch index.js 

--watch-kill-signal#>

稳定性: 1.1 - 处于活跃开发中

自定义在监视模式重启时发送给进程的信号。

【Customizes the signal sent to the process on watch mode restarts.】

node --watch --watch-kill-signal SIGINT test.js 

--watch-path#>

以监视模式启动 Node.js,并指定要监视的路径。 在监视模式下,被监视路径的更改会导致 Node.js 进程重新启动。 这将关闭对所需或导入模块的监视,即使与 --watch 结合使用也一样。

【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.】

此标志不能与 --check--eval--interactive--test 或 REPL 组合使用。

【This flag cannot be combined with --check, --eval, --interactive, --test, or the REPL.】

注意:使用 --watch-path 会隐式启用 --watch,它需要一个文件路径,并且与 --run 不兼容,因为 --run 优先,会忽略监听模式。

【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.】

node --watch-path=./src --watch-path=./tests index.js 

此选项仅在 macOS 和 Windows 上受支持。
在不支持该选项的平台上使用时,将抛出 ERR_FEATURE_UNAVAILABLE_ON_PLATFORM 异常。

【This option is only supported on macOS and Windows. An ERR_FEATURE_UNAVAILABLE_ON_PLATFORM exception will be thrown when the option is used on a platform that does not support it.】

--watch-preserve-output#>

当监视模式重新启动进程时禁用控制台的清除。

【Disable the clearing of the console when watch mode restarts the process.】

node --watch --watch-preserve-output test.js 

--zero-fill-buffers#>

自动将所有新分配的 Buffer 实例填充为零。

【Automatically zero-fills all newly allocated Buffer instances.】

环境变量#>

【Environment variables】

FORCE_COLOR=[1, 2, 3]#>

FORCE_COLOR 环境变量用于启用 ANSI 彩色输出。其值可以是:

【The FORCE_COLOR environment variable is used to enable ANSI colorized output. The value may be:】

  • 1true 或空字符串 '' 表示支持 16 色。
  • 2 表示支持 256 色,或者
  • 3 表示支持 1600 万色。

当使用 FORCE_COLOR 并设置为支持的值时,NO_COLORNODE_DISABLE_COLORS 环境变量将被忽略。

【When FORCE_COLOR is used and set to a supported value, both the NO_COLOR, and NODE_DISABLE_COLORS environment variables are ignored.】

任何其他值都会导致彩色输出被禁用。

【Any other value will result in colorized output being disabled.】

NODE_COMPILE_CACHE=dir#>

稳定性: 1.1 - 处于活跃开发中

为 Node.js 实例启用 模块编译缓存。具体详情请参阅 模块编译缓存 的文档。

【Enable the module compile cache for the Node.js instance. See the documentation of module compile cache for details.】

NODE_COMPILE_CACHE_PORTABLE=1#>

设置为 1 时,只要模块相对于缓存目录的布局保持不变,模块编译缓存 就可以在不同的目录位置重复使用。

【When set to 1, the module compile cache can be reused across different directory locations as long as the module layout relative to the cache directory remains the same.】

NODE_DEBUG=module[,…]#>

',' 分隔的核心模块列表,这些模块应该打印调试信息。

NODE_DEBUG_NATIVE=module[,…]#>

应打印调试信息的核心 C++ 模块的,分隔列表。

NODE_DISABLE_COLORS=1#>

当设置时,颜色将不会在交互式解释器中使用。

【When set, colors will not be used in the REPL.】

NODE_DISABLE_COMPILE_CACHE=1#>

稳定性: 1.1 - 处于活跃开发中

禁用 Node.js 实例的 模块编译缓存。具体详情请参阅 模块编译缓存 的文档。

【Disable the module compile cache for the Node.js instance. See the documentation of module compile cache for details.】

NODE_EXTRA_CA_CERTS=file#>

设置后,知名的“根”证书颁发机构(如 VeriSign)将会使用 file 中的额外证书进行扩展。该文件应包含一个或多个 PEM 格式的受信任证书。如果文件缺失或格式错误,将会(仅一次)发出 process.emitWarning() 消息,但其他任何错误将被忽略。

【When set, the well known "root" CAs (like VeriSign) will be extended with the extra certificates in file. The file should consist of one or more trusted certificates in PEM format. A message will be emitted (once) with process.emitWarning() if the file is missing or malformed, but any errors are otherwise ignored.】

当为 TLS 或 HTTPS 客户端或服务器显式指定 ca 选项属性时,既不会使用知名证书,也不会使用额外证书。

【Neither the well known nor extra certificates are used when the ca options property is explicitly specified for a TLS or HTTPS client or server.】

node 以 setuid root 运行或设置了 Linux 文件能力时,此环境变量将被忽略。

【This environment variable is ignored when node runs as setuid root or has Linux file capabilities set.】

NODE_EXTRA_CA_CERTS 环境变量只在 Node.js 进程首次启动时读取。运行时使用 process.env.NODE_EXTRA_CA_CERTS 更改其值不会影响当前进程。

【The NODE_EXTRA_CA_CERTS environment variable is only read when the Node.js process is first launched. Changing the value at runtime using process.env.NODE_EXTRA_CA_CERTS has no effect on the current process.】

NODE_ICU_DATA=file#>

ICU(Intl 对象)数据的数据路径。在使用 small-icu 支持编译时,将扩展已链接的数据。

【Data path for ICU (Intl object) data. Will extend linked-in data when compiled with small-icu support.】

NODE_NO_WARNINGS=1#>

设置为 1 时,进程警告将被静音。

【When set to 1, process warnings are silenced.】

NODE_OPTIONS=options...#>

以空格分隔的命令行选项列表。options... 会在命令行选项之前被解析,因此命令行选项将会覆盖或在 options... 的基础上叠加。如果使用了环境中不允许的选项,例如 -p 或脚本文件,Node.js 将会报错并退出。

【A space-separated list of command-line options. options... are interpreted before command-line options, so command-line options will override or compound after anything in options.... Node.js will exit with an error if an option that is not allowed in the environment is used, such as -p or a script file.】

如果选项值包含空格,则可以使用双引号转义:

【If an option value contains a space, it can be escaped using double quotes:】

NODE_OPTIONS='--require "./my path/file.js"' 

作为命令行选项传递的单例标志将覆盖传入 NODE_OPTIONS 的相同标志:

【A singleton flag passed as a command-line option will override the same flag passed into NODE_OPTIONS:】

# The inspector will be available on port 5555
NODE_OPTIONS='--inspect=localhost:4444' node --inspect=localhost:5555 

可以多次传递的标志将被视为先传递其 NODE_OPTIONS 实例,然后再传递其命令行实例:

【A flag that can be passed multiple times will be treated as if its NODE_OPTIONS instances were passed first, and then its command-line instances afterwards:】

NODE_OPTIONS='--require "./a.js"' node --require "./b.js"
# is equivalent to:
node --require "./a.js" --require "./b.js" 

允许的 Node.js 选项如下列所示。如果一个选项同时支持 --XX 和 --no-XX 变体,它们都被支持,但下面的列表中仅包含其中一个。

【Node.js options that are allowed are in the following list. If an option supports both --XX and --no-XX variants, they are both supported but only one is included in the list below.】

  • --allow-addons
  • --allow-child-process
  • --allow-fs-read
  • --allow-fs-write
  • --allow-inspector
  • --allow-net
  • --allow-wasi
  • --allow-worker
  • --conditions-C
  • --cpu-prof-dir
  • --cpu-prof-interval
  • --cpu-prof-name
  • --cpu-prof
  • --diagnostic-dir
  • --disable-proto
  • --disable-sigusr1
  • --disable-warning
  • --disable-wasm-trap-handler
  • --dns-result-order
  • --enable-fips
  • --enable-network-family-autoselection
  • --enable-source-maps
  • --entry-url
  • --experimental-abortcontroller
  • --experimental-addon-modules
  • --experimental-detect-module
  • --experimental-eventsource
  • --experimental-import-meta-resolve
  • --experimental-json-modules
  • --experimental-loader
  • --experimental-modules
  • --experimental-print-required-tla
  • --experimental-quic
  • --experimental-require-module
  • --experimental-shadow-realm
  • --experimental-specifier-resolution
  • --experimental-test-isolation
  • --experimental-top-level-await
  • --experimental-transform-types
  • --experimental-vm-modules
  • --experimental-wasi-unstable-preview1
  • --force-context-aware
  • --force-fips
  • --force-node-api-uncaught-exceptions-policy
  • --frozen-intrinsics
  • --heap-prof-dir
  • --heap-prof-interval
  • --heap-prof-name
  • --heap-prof
  • --heapsnapshot-near-heap-limit
  • --heapsnapshot-signal
  • --http-parser
  • --icu-data-dir
  • --import
  • --input-type
  • --insecure-http-parser
  • --inspect-brk
  • --inspect-port--debug-port
  • --inspect-publish-uid
  • --inspect-wait
  • --inspect
  • --localstorage-file
  • --max-http-header-size
  • --max-old-space-size-percentage
  • --napi-modules
  • --network-family-autoselection-attempt-timeout
  • --no-addons
  • --no-async-context-frame
  • --no-deprecation
  • --no-experimental-global-navigator
  • --no-experimental-repl-await
  • --no-experimental-sqlite
  • --no-experimental-strip-types
  • --no-experimental-websocket
  • --no-experimental-webstorage
  • --no-extra-info-on-fatal-exception
  • --no-force-async-hooks-checks
  • --no-global-search-paths
  • --no-network-family-autoselection
  • --no-warnings
  • --no-webstorage
  • --node-memory-debug
  • --openssl-config
  • --openssl-legacy-provider
  • --openssl-shared-config
  • --pending-deprecation
  • --permission
  • --preserve-symlinks-main
  • --preserve-symlinks
  • --prof-process
  • --redirect-warnings
  • --report-compact
  • --report-dir--report-directory
  • --report-exclude-env
  • --report-exclude-network
  • --report-filename
  • --report-on-fatalerror
  • --report-on-signal
  • --report-signal
  • --report-uncaught-exception
  • --require-r
  • --secure-heap-min
  • --secure-heap
  • --snapshot-blob
  • --test-coverage-branches
  • --test-coverage-exclude
  • --test-coverage-functions
  • --test-coverage-include
  • --test-coverage-lines
  • --test-global-setup
  • --test-isolation
  • --test-name-pattern
  • --test-only
  • --test-reporter-destination
  • --test-reporter
  • --test-rerun-failures
  • --test-shard
  • --test-skip-pattern
  • --throw-deprecation
  • --title
  • --tls-cipher-list
  • --tls-keylog
  • --tls-max-v1.2
  • --tls-max-v1.3
  • --tls-min-v1.0
  • --tls-min-v1.1
  • --tls-min-v1.2
  • --tls-min-v1.3
  • --trace-deprecation
  • --trace-env-js-stack
  • --trace-env-native-stack
  • --trace-env
  • --trace-event-categories
  • --trace-event-file-pattern
  • --trace-events-enabled
  • --trace-exit
  • --trace-require-module
  • --trace-sigint
  • --trace-sync-io
  • --trace-tls
  • --trace-uncaught
  • --trace-warnings
  • --track-heap-objects
  • --unhandled-rejections
  • --use-bundled-ca
  • --use-env-proxy
  • --use-largepages
  • --use-openssl-ca
  • --use-system-ca
  • --v8-pool-size
  • --watch-kill-signal
  • --watch-path
  • --watch-preserve-output
  • --watch
  • --zero-fill-buffers

允许的 V8 选项是:

【V8 options that are allowed are:】

  • --abort-on-uncaught-exception
  • --disallow-code-generation-from-strings
  • --enable-etw-stack-walking
  • --expose-gc
  • --interpreted-frames-native-stack
  • --jitless
  • --max-old-space-size
  • --max-semi-space-size
  • --perf-basic-prof-only-functions
  • --perf-basic-prof
  • --perf-prof-unwinding-info
  • --perf-prof
  • --stack-trace-limit

--perf-basic-prof-only-functions--perf-basic-prof--perf-prof-unwinding-info--perf-prof 仅在 Linux 上可用。

--enable-etw-stack-walking 仅在 Windows 上可用。

NODE_PATH=path[:…]#>

':' 分隔的目录列表,前缀到模块搜索路径。

在 Windows 上,这反而是一个用 ';' 分隔的列表。

【On Windows, this is a ';'-separated list instead.】

NODE_PENDING_DEPRECATION=1#>

设置为 1 时,会发出待定弃用警告。

【When set to 1, emit pending deprecation warnings.】

待弃用通常与运行时弃用完全相同,其显著区别在于,默认情况下它们是关闭的,并且不会被触发,除非设置了 --pending-deprecation 命令行标志或 NODE_PENDING_DEPRECATION=1 环境变量。待弃用用于提供一种选择性的“提前警告”机制,开发者可以利用它来检测已弃用的 API 使用情况。

【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.】

NODE_PENDING_PIPE_INSTANCES=instances#>

设置管道服务器等待连接时的挂起管道实例句柄数量。此设置仅适用于 Windows。

【Set the number of pending pipe instance handles when the pipe server is waiting for connections. This setting applies to Windows only.】

NODE_PRESERVE_SYMLINKS=1#>

当设置为 1 时,指示模块加载器在解析和缓存模块时保留符号链接。

【When set to 1, instructs the module loader to preserve symbolic links when resolving and caching modules.】

NODE_REDIRECT_WARNINGS=file#>

设置后,进程警告将输出到指定文件,而不是打印到标准错误。若文件不存在,将会创建该文件;若文件已存在,则会追加内容。如果在尝试将警告写入文件时发生错误,警告将改为写入标准错误。这相当于使用 --redirect-warnings=file 命令行选项。

【When set, process warnings will be emitted 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. This is equivalent to using the --redirect-warnings=file command-line flag.】

NODE_REPL_EXTERNAL_MODULE=file#>

Node.js 模块的路径,该模块将在内置 REPL 的位置加载。将此值覆盖为空字符串('')将使用内置 REPL。

【Path to a Node.js module which will be loaded in place of the built-in REPL. Overriding this value to an empty string ('') will use the built-in REPL.】

NODE_REPL_HISTORY=file#>

用于存储持久 REPL 历史记录的文件路径。默认路径是 ~/.node_repl_history,可以被此变量覆盖。将该值设置为空字符串(''' ')将禁用持久 REPL 历史记录。

【Path to the file used to store the persistent REPL history. The default path is ~/.node_repl_history, which is overridden by this variable. Setting the value to an empty string ('' or ' ') disables persistent REPL history.】

NODE_SKIP_PLATFORM_CHECK=value#>

如果 value 等于 '1',在 Node.js 启动期间将跳过对支持平台的检查。Node.js 可能无法正确执行。在不支持的平台上遇到的任何问题都不会得到修复。

【If value equals '1', the check for a supported platform is skipped during Node.js startup. Node.js might not execute correctly. Any issues encountered on unsupported platforms will not be fixed.】

NODE_TEST_CONTEXT=value#>

如果 value 等于 'child',测试报告程序选项将被覆盖,测试输出将以 TAP 格式发送到标准输出(stdout)。如果提供了其他值,Node.js 不保证报告程序使用的格式或其稳定性。

【If value equals 'child', test reporter options will be overridden and test output will be sent to stdout in the TAP format. If any other value is provided, Node.js makes no guarantees about the reporter format used or its stability.】

NODE_TLS_REJECT_UNAUTHORIZED=value#>

如果 value 等于 '0',TLS 连接的证书验证将被禁用。这会使 TLS 以及 HTTPS 的安全性降低。强烈不建议使用此环境变量。

【If value equals '0', certificate validation is disabled for TLS connections. This makes TLS, and HTTPS by extension, insecure. The use of this environment variable is strongly discouraged.】

NODE_USE_ENV_PROXY=1#>

稳定性: 1.1 - 处于活跃开发中

启用时,Node.js 会在启动时解析 HTTP_PROXYHTTPS_PROXYNO_PROXY 环境变量,并通过指定的代理隧道传输请求。

【When enabled, Node.js parses the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables during startup, and tunnels requests over the specified proxy.】

这也可以通过 --use-env-proxy 命令行标志来启用。当两者都设置时,--use-env-proxy 会优先。

【This can also be enabled using the --use-env-proxy command-line flag. When both are set, --use-env-proxy takes precedence.】

NODE_USE_SYSTEM_CA=1#>

Node.js 使用系统存储中的受信任 CA 证书,同时可以配合 --use-bundled-ca 选项和 NODE_EXTRA_CA_CERTS 环境变量使用。

【Node.js uses the trusted CA certificates present in the system store along with the --use-bundled-ca option and the NODE_EXTRA_CA_CERTS environment variable.】

这也可以通过 --use-system-ca 命令行标志启用。当两者都设置时,--use-system-ca 优先。

【This can also be enabled using the --use-system-ca command-line flag. When both are set, --use-system-ca takes precedence.】

NODE_V8_COVERAGE=dir#>

设置后,Node.js 将开始将 V8 JavaScript 代码覆盖率源映射 数据输出到作为参数提供的目录(覆盖信息以 JSON 形式写入以 coverage 为前缀的文件)。

【When set, Node.js will begin outputting V8 JavaScript code coverage and Source Map data to the directory provided as an argument (coverage information is written as JSON to files with a coverage prefix).】

NODE_V8_COVERAGE 会自动传递到子进程,使得对调用 child_process.spawn() 系列函数的应用进行检测更加容易。NODE_V8_COVERAGE 可以设置为空字符串,以防止传播。

覆盖输出#>

【Coverage output】

覆盖率作为一个包含 脚本覆盖 个对象的数组输出,在顶层键 result 下:

【Coverage is output as an array of ScriptCoverage objects on the top-level key result:】

{
  "result": [
    {
      "scriptId": "67",
      "url": "internal/tty.js",
      "functions": []
    }
  ]
} 

源映射缓存#>

【Source map cache】

稳定性: 1 - 实验性

如果找到,源映射数据会被添加到 JSON 覆盖对象的顶层键 source-map-cache 中。

【If found, source map data is appended to the top-level key source-map-cache on the JSON coverage object.】

source-map-cache 是一个对象,其键表示提取源映射的文件,值包括原始的源映射 URL(在键 url 中)、解析后的 Source Map v3 信息(在键 data 中)以及源文件的行长度(在键 lineLengths 中)。

{
  "result": [
    {
      "scriptId": "68",
      "url": "file:///absolute/path/to/source.js",
      "functions": []
    }
  ],
  "source-map-cache": {
    "file:///absolute/path/to/source.js": {
      "url": "./path-to-map.json",
      "data": {
        "version": 3,
        "sources": [
          "file:///absolute/path/to/original.js"
        ],
        "names": [
          "Foo",
          "console",
          "info"
        ],
        "mappings": "MAAMA,IACJC,YAAaC",
        "sourceRoot": "./"
      },
      "lineLengths": [
        13,
        62,
        38,
        27
      ]
    }
  }
} 

NO_COLOR=<any>#>

NO_COLORNODE_DISABLE_COLORS 的别名。该环境变量的值是任意的。

OPENSSL_CONF=file#>

在启动时加载 OpenSSL 配置文件。除了其他用途外,如果 Node.js 是使用 ./configure --openssl-fips 构建的,这可以用来启用符合 FIPS 的加密。

【Load an OpenSSL configuration file on startup. Among other uses, this can be used to enable FIPS-compliant crypto if Node.js is built with ./configure --openssl-fips.】

如果使用 --openssl-config 命令行选项,则会忽略该环境变量。

【If the --openssl-config command-line option is used, the environment variable is ignored.】

SSL_CERT_DIR=dir#>

如果启用了 --use-openssl-ca,或者在 macOS 和 Windows 之外的平台启用了 --use-system-ca,这将覆盖并设置 OpenSSL 的受信任证书目录。

【If --use-openssl-ca is enabled, or if --use-system-ca is enabled on platforms other than macOS and Windows, this overrides and sets OpenSSL's directory containing trusted certificates.】

请注意,除非显式设置子环境,否则此环境变量将被任何子进程继承,如果它们使用 OpenSSL,可能会导致它们信任与 Node 相同的证书颁发机构。

【Be aware that unless the child environment is explicitly set, this environment variable will be inherited by any child processes, and if they use OpenSSL, it may cause them to trust the same CAs as node.】

SSL_CERT_FILE=file#>

如果启用了 --use-openssl-ca,或者在 macOS 和 Windows 之外的平台启用了 --use-system-ca,这将覆盖并设置包含受信任证书的 OpenSSL 文件。

【If --use-openssl-ca is enabled, or if --use-system-ca is enabled on platforms other than macOS and Windows, this overrides and sets OpenSSL's file containing trusted certificates.】

请注意,除非显式设置子环境,否则此环境变量将被任何子进程继承,如果它们使用 OpenSSL,可能会导致它们信任与 Node 相同的证书颁发机构。

【Be aware that unless the child environment is explicitly set, this environment variable will be inherited by any child processes, and if they use OpenSSL, it may cause them to trust the same CAs as node.】

TZ#>

TZ 环境变量用于指定时区配置。

【The TZ environment variable is used to specify the timezone configuration.】

虽然 Node.js 并不支持所有类型的 在其他环境中处理 TZ 的方式,但它确实支持基本的 时区 ID(例如 'Etc/UTC''Europe/Paris''America/New_York')。 它可能支持其他一些缩写或别名,但这些强烈不推荐使用,也无法保证可用。

【While Node.js does not support all of the various ways that TZ is handled in other environments, it does support basic timezone IDs (such as 'Etc/UTC', 'Europe/Paris', or 'America/New_York'). It may support a few other abbreviations or aliases, but these are strongly discouraged and not guaranteed.】

$ TZ=Europe/Dublin node -pe "new Date().toString()"
Wed May 12 2021 20:30:48 GMT+0100 (Irish Standard Time) 

UV_THREADPOOL_SIZE=size#>

将 libuv 线程池中使用的线程数设置为 size 个线程。

【Set the number of threads used in libuv's threadpool to size threads.】

Node.js 尽可能使用异步系统 API,但在这些 API 不存在的情况下,会使用 libuv 的线程池基于同步系统 API 创建异步 Node API。使用线程池的 Node.js API 有:

【Asynchronous system APIs are used by Node.js whenever possible, but where they do not exist, libuv's threadpool is used to create asynchronous node APIs based on synchronous system APIs. Node.js APIs that use the threadpool are:】

  • 除文件监视器 API 和那些显式同步的 API 外,所有 fs API
  • 异步加密 API,例如 crypto.pbkdf2()crypto.scrypt()crypto.randomBytes()crypto.randomFill()crypto.generateKeyPair()
  • dns.lookup()
  • 所有 zlib API,除了那些明确为同步的 API

由于 libuv 的线程池大小是固定的,这意味着如果这些 API 中的任何一个由于某种原因运行时间很长,其他在 libuv 线程池中运行的(看似无关的)API 的性能也会受到影响。为了解决这个问题,一种潜在的方案是通过将 'UV_THREADPOOL_SIZE' 环境变量设置为大于 4(其当前默认值)的值来增加 libuv 线程池的大小。然而,从进程内部使用 process.env.UV_THREADPOOL_SIZE=size 来设置并不能保证有效,因为线程池会在运行时初始化时创建,早于用户代码的运行。更多信息,请参见 libuv 线程池文档

【Because libuv's threadpool has a fixed size, it means that if for whatever reason any of these APIs takes a long time, other (seemingly unrelated) APIs that run in libuv's threadpool will experience degraded performance. In order to mitigate this issue, one potential solution is to increase the size of libuv's threadpool by setting the 'UV_THREADPOOL_SIZE' environment variable to a value greater than 4 (its current default value). However, setting this from inside the process using process.env.UV_THREADPOOL_SIZE=size is not guranteed to work as the threadpool would have been created as part of the runtime initialisation much before user code is run. For more information, see the libuv threadpool documentation.】

有用的 V8 选项#>

【Useful V8 options】

V8 有自己的一套命令行选项。任何提供给 node 的 V8 CLI 选项都会传递给 V8 处理。V8 的选项不保证稳定性。V8 团队本身也不认为它们是正式 API 的一部分,并保留随时更改的权利。同样,它们不在 Node.js 的稳定性保证范围内。很多 V8 选项仅对 V8 开发者有用。尽管如此,仍有一小部分 V8 选项在 Node.js 中广泛适用,并在此进行了文档说明:

【V8 has its own set of CLI options. Any V8 CLI option that is provided to node will be passed on to V8 to handle. V8's options have no stability guarantee. The V8 team themselves don't consider them to be part of their formal API, and reserve the right to change them at any time. Likewise, they are not covered by the Node.js stability guarantees. Many of the V8 options are of interest only to V8 developers. Despite this, there is a small set of V8 options that are widely applicable to Node.js, and they are documented here:】

--abort-on-uncaught-exception#>

--disallow-code-generation-from-strings#>

--enable-etw-stack-walking#>

--expose-gc#>

--harmony-shadow-realm#>

--interpreted-frames-native-stack#>

--jitless#>

--max-old-space-size=SIZE(以 MiB 为单位)#>

--max-old-space-size=SIZE (in MiB)】

设置 V8 旧生代内存区域的最大内存大小。当内存使用接近上限时,V8 将花更多时间进行垃圾回收,以尝试释放未使用的内存。

【Sets the max memory size of V8's old memory section. As memory consumption approaches the limit, V8 will spend more time on garbage collection in an effort to free unused memory.】

在一台拥有 2 GiB 内存的机器上,可以考虑将此设置为 1536(1.5 GiB),以为其他用途留出一些内存并避免交换。

【On a machine with 2 GiB of memory, consider setting this to 1536 (1.5 GiB) to leave some memory for other uses and avoid swapping.】

node --max-old-space-size=1536 index.js 

--max-semi-space-size=SIZE(以兆字节为单位)#>

--max-semi-space-size=SIZE (in MiB)】

设置 V8 的 清理垃圾收集器 的最大 半空格 大小,单位为 MiB(兆二进制字节)。 增加半空间的最大大小可能会提高 Node.js 的吞吐量,但代价是更多的内存消耗。

【Sets the maximum semi-space size for V8's scavenge garbage collector in MiB (mebibytes). Increasing the max size of a semi-space may improve throughput for Node.js at the cost of more memory consumption.】

由于 V8 堆的年轻代大小是半空间的三倍(参见 V8 中的 YoungGenerationSizeFromSemiSpaceSize),每增加 1 MiB 的半空间,会应用到三个独立的半空间,因此堆大小将增加 3 MiB。吞吐量的提高取决于你的工作负载(参见 #42511)。

【Since the young generation size of the V8 heap is three times (see YoungGenerationSizeFromSemiSpaceSize in V8) the size of the semi-space, an increase of 1 MiB to semi-space applies to each of the three individual semi-spaces and causes the heap size to increase by 3 MiB. The throughput improvement depends on your workload (see #42511).】

默认值取决于内存限制。例如,在内存限制为 512 MiB 的 64 位系统上,半空间的最大大小默认为 1 MiB。对于内存限制最高为 2 GiB 的系统,在 64 位系统上半空间的默认最大大小将小于 16 MiB。

【The default value depends on the memory limit. For example, on 64-bit systems with a memory limit of 512 MiB, the max size of a semi-space defaults to 1 MiB. For memory limits up to and including 2GiB, the default max size of a semi-space will be less than 16 MiB on 64-bit systems.】

为了获得你应用的最佳配置,你在运行应用基准测试时应该尝试不同的 max-semi-space-size 值。

【To get the best configuration for your application, you should try different max-semi-space-size values when running benchmarks for your application.】

例如,在 64 位系统上进行基准测试:

【For example, benchmark on a 64-bit systems:】

for MiB in 16 32 64 128; do
    node --max-semi-space-size=$MiB index.js
done 

--perf-basic-prof#>

--perf-basic-prof-only-functions#>

--perf-prof#>

--perf-prof-unwinding-info#>

--prof#>

--security-revert#>

--stack-trace-limit=limit#>

在错误的堆栈跟踪中要收集的最大堆栈帧数。将其设置为 0 将禁用堆栈跟踪收集。默认值为 10。

【The maximum number of stack frames to collect in an error's stack trace. Setting it to 0 disables stack trace collection. The default value is 10.】

node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12 
Node.js 中文网 - 粤ICP备13048890号