Node.js v20.11.1 文档


命令行 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 的更多信息,请参阅 debugger 文档。

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

程序入口点#

¥Program entry point

程序入口点是类似说明符的字符串。如果字符串不是绝对路径,则解析为当前工作目录的相对路径。然后,该路径由 CommonJS 模块加载器解析,或者如果通过了 --experimental-default-type=module,则由 ES 模块加载器 解析。如果没有找到对应的文件,则抛出错误。

¥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, or by the ES module loader if --experimental-default-type=module is passed. 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--experimental-default-type=module

    ¥The program was started with a command-line flag that forces the entry point to be loaded with ECMAScript module loader, such as --import or --experimental-default-type=module.

  • 该文件的扩展名为 .mjs

    ¥The file has an .mjs extension.

  • 该文件没有 .cjs 扩展名,并且最近的父 package.json 文件包含值为 "module" 的顶层 "type" 字段。

    ¥The file does not have a .cjs extension, and the nearest parent package.json file contains a top-level "type" field with a value of "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 扩展名的文件作为输入;当启用 --experimental-wasm-modules 时,具有 .wasm 分机;并且当 --experimental-default-type=module 通过时没有扩展。

¥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 .wasm extensions when --experimental-wasm-modules is enabled; and with no extension when --experimental-default-type=module is passed.

选项#

¥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.

-#

标准输入的别名。类似于在其他命令行工具中使用 -,这意味着脚本是从标准输入读取的,其余的选项将传给该脚本。

¥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.

--#

指示 node 选项的结束。将其余参数传给脚本。如果在此之前没有提供脚本文件名或评估/打印脚本,则下一个参数用作脚本文件名。

¥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-child-process#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active development

使用 权限模型 时,默认情况下该进程将无法生成任何子进程。尝试这样做将抛出 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 --experimental-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 Object.spawn (node:child_process:723:9)
    at Object.<anonymous> (/home/index.js:3:14)
    at Module._compile (node:internal/modules/cjs/loader:1120:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1174:10)
    at Module.load (node:internal/modules/cjs/loader:998:32)
    at Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'ERR_ACCESS_DENIED',
  permission: 'ChildProcess'
} 

--allow-fs-read#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active development

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

¥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 操作。

    ¥* - To allow all FileSystemRead operations.

  • 使用多个 --allow-fs-read 标志可以允许多个路径。示例 --allow-fs-read=/folder1/ --allow-fs-read=/folder1/

    ¥Multiple paths can be allowed using multiple --allow-fs-read flags. Example --allow-fs-read=/folder1/ --allow-fs-read=/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.

CLI 标志尚不支持相对路径。

¥Relative paths are NOT yet supported by the CLI flag.

初始化模块也需要被允许。考虑以下示例:

¥The initializer module also needs to be allowed. Consider the following example:

$ node --experimental-permission t.js
node:internal/modules/cjs/loader:162
  const result = internalModuleStat(filename);
                 ^

Error: Access to this API has been restricted
    at stat (node:internal/modules/cjs/loader:162:18)
    at Module._findPath (node:internal/modules/cjs/loader:640:16)
    at resolveMainPath (node:internal/modules/run_main:15:25)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:53:24)
    at node:internal/main/run_main_module:23:47 {
  code: 'ERR_ACCESS_DENIED',
  permission: 'FileSystemRead',
  resource: '/Users/rafaelgss/repos/os/node/t.js'
} 

该进程需要访问 index.js 模块:

¥The process needs to have access to the index.js module:

node --experimental-permission --allow-fs-read=/path/to/index.js index.js 

--allow-fs-write#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active development

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

¥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 操作。

    ¥* - To allow all FileSystemWrite operations.

  • 使用多个 --allow-fs-read 标志可以允许多个路径。示例 --allow-fs-read=/folder1/ --allow-fs-read=/folder1/

    ¥Multiple paths can be allowed using multiple --allow-fs-read flags. Example --allow-fs-read=/folder1/ --allow-fs-read=/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.

CLI 标志不支持相对路径。

¥Relative paths are NOT supported through the CLI flag.

--allow-worker#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active development

使用 权限模型 时,进程默认无法创建任何工作线程。出于安全原因,除非用户在主 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 --experimental-permission --allow-fs-read=* index.js
node:internal/worker:188
    this[kHandle] = new WorkerImpl(url,
                    ^

Error: Access to this API has been restricted
    at new Worker (node:internal/worker:188:21)
    at Object.<anonymous> (/home/index.js.js:3:1)
    at Module._compile (node:internal/modules/cjs/loader:1120:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1174:10)
    at Module.load (node:internal/modules/cjs/loader:998:32)
    at Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'ERR_ACCESS_DENIED',
  permission: 'WorkerThreads'
} 

--build-snapshot#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

进程退出时生成快照 blob 并将其写入磁盘,稍后可以使用 --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. 快照尚不支持用户级模块,因此只能对一个文件进行快照。但是,用户可以在构建快照之前使用他们选择的打包器将他们的应用打包到一个脚本中。

    ¥User-land modules are not yet supported in the snapshot, so only one single file can be snapshotted. Users can bundle their applications into a single script with their bundler of choice before building a snapshot, however.

  2. 只有一部分内置模块在快照中工作,尽管 Node.js 核心测试套件会检查一些相当复杂的应用是否可以被快照。正在添加对更多模块的支持。如果在构建快照时发生任何崩溃或错误行为,请在 Node.js 问题跟踪器 中提交报告并在 用户态快照的跟踪问题 中链接到它。

    ¥Only a subset of the built-in modules work in the snapshot, though the Node.js core test suite checks that a few fairly complex applications can be snapshotted. Support for more modules are being added. If any crashes or buggy behaviors occur when building a snapshot, please file a report in the Node.js issue tracker and link to it in the tracking issue for user-land snapshots.

-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 condition, --conditions=condition#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

启用对自定义 条件导出 解析条件的实验支持。

¥Enable experimental support for custom conditional exports resolution conditions.

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

¥Any number of custom string condition names are permitted.

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

¥The default Node.js conditions of "node", "default", "import", and "require" will always apply as defined.

例如,要运行具有 "development" 解析的模块:

¥For example, to run a module with "development" resolutions:

node -C development app.js 

--cpu-prof#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

启动时开始 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-dir#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

指定放置 --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#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

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

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

指定 --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-warning=code-or-type#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active development

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=ExperimentalWarnings 执行时,以下脚本将触发 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=ExperimentalWarnings:

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

--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() 中设置 verbatim 的默认值。该值可能是:

¥Set the default value of verbatim in dns.lookup() and dnsPromises.lookup(). The value could be:

  • ipv4first:设置默认的 verbatimfalse

    ¥ipv4first: sets default verbatim false.

  • verbatim:设置默认的 verbatimtrue

    ¥verbatim: sets default verbatim true.

默认为 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-source-maps#

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

¥Enable Source Map v3 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 修改堆栈跟踪。

¥Overriding Error.prepareStackTrace prevents --enable-source-maps from modifying the stack 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.

--env-file=config#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active development

从相对于当前目录的文件加载环境变量,使它们可供 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.

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. 

-e, --eval "script"#

将以下参数作为 JavaScript 评估。交互式解释器中预定义的模块也可以在 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.

--experimental-default-type=type#

稳定性: 1.0 - 早期开发

¥Stability: 1.0 - Early development

定义用于以下目的的模块系统 modulecommonjs

¥Define which module system, module or commonjs, to use for the following:

  • 如果未指定 --input-type,则通过 --eval 或 STDIN 提供字符串输入。

    ¥String input provided via --eval or STDIN, if --input-type is unspecified.

  • 如果同一文件夹或任何父文件夹中不存在 package.json 文件,则以 .js 结尾或没有扩展名的文件。

    ¥Files ending in .js or with no extension, if there is no package.json file present in the same folder or any parent folder.

  • 如果最近的父 package.json 字段缺少 "type" 字段,则以 .js 结尾或没有扩展名的文件;除非 package.json 文件夹或任何父文件夹位于 node_modules 文件夹内。

    ¥Files ending in .js or with no extension, if the nearest parent package.json field lacks a "type" field; unless the package.json folder or any parent folder is inside a node_modules folder.

换句话说,--experimental-default-type=module 将 Node.js 当前默认为 CommonJS 的所有位置翻转为默认为 ECMAScript 模块(node_modules 以下的文件夹和子文件夹除外),以实现向后兼容性。

¥In other words, --experimental-default-type=module flips all the places where Node.js currently defaults to CommonJS to instead default to ECMAScript modules, with the exception of folders and subfolders below node_modules, for backward compatibility.

--experimental-default-type=module--experimental-wasm-modules 下,没有扩展名的文件如果以 WebAssembly 幻数 (\0asm) 开头,将被视为 WebAssembly;否则它们将被视为 ES 模块 JavaScript。

¥Under --experimental-default-type=module and --experimental-wasm-modules, files with no extension will be treated as WebAssembly if they begin with the WebAssembly magic number (\0asm); otherwise they will be treated as ES module JavaScript.

--experimental-detect-module#

稳定性: 1.0 - 早期开发

¥Stability: 1.0 - Early development

Node.js 会检查不明确输入的源代码以确定其是否包含 ES 模块语法;如果检测到这样的语法,输入将被视为 ES 模块。

¥Node.js will inspect the source code of ambiguous input to determine whether it contains ES module syntax; if such syntax is detected, the input will be treated as an ES module.

不明确的输入定义为:

¥Ambiguous input is defined as:

  • 带有 .js 扩展名或没有扩展名的文件;并且要么没有控制 package.json 文件,要么缺少 type 字段;且未指定 --experimental-default-type

    ¥Files with a .js extension or no extension; and either no controlling package.json file or one that lacks a type field; and --experimental-default-type is not specified.

  • 当未指定 --input-type--experimental-default-type 时,字符串输入(--eval 或 STDIN)。

    ¥String input (--eval or STDIN) when neither --input-type nor --experimental-default-type are specified.

ES 模块语法被定义为当评估为 CommonJS 时会抛出异常的语法。这包括 importexport 声明以及 import.meta 引用。它不包括在 CommonJS 中有效的 import() 表达式。

¥ES module syntax is defined as syntax that would throw when evaluated as CommonJS. This includes import and export statements and import.meta references. It does not include import() expressions, which are valid in CommonJS.

--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-loader=module#

不鼓励使用此标志,并且可能会在 Node.js 的未来版本中将其删除。请改用 --importregister()

¥This flag is discouraged and may be removed in a future version of Node.js. Please use --import with register() instead.

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

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

--experimental-network-imports#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

import 说明符中启用对 https: 协议的实验性支持。

¥Enable experimental support for the https: protocol in import specifiers.

--experimental-permission#

稳定性: 1.1 - 积极开发

¥Stability: 1.1 - Active development

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

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

--experimental-policy#

使用指定的文件作为安全策略。

¥Use the specified file as a security policy.

--experimental-sea-config#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

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

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

使用此标志启用 ShadowRealm 支持。

¥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-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-wasm-modules#

启用实验性 WebAssembly 模块支持。

¥Enable experimental WebAssembly module support.

--experimental-websocket#

启用实验性 WebSocket 支持。

¥Enable experimental WebSocket support.

--force-context-aware#

禁止加载非 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 - 实验性的

¥Stability: 1 - Experimental

启用像 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.

为了允许添加 polyfill,--require--import 都在冻结内部函数之前运行。

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

--heap-prof#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

在启动时开始 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#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

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

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

指定 --heap-prof 生成的堆分析文件的平均采样间隔(以字节为单位)。默认为 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#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

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

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

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

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

当 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 个快照写入磁盘,但是当 max_count 大于 0 时,它会尽量在 Node.js 实例耗尽内存之前生成至少一个和最多 max_count 个快照。

¥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 ms: Mark-sweep 130.6 (147.8) -> 130.5 (147.8) MB, 27.4 / 0.0 ms  (average mu = 0.126, current mu = 0.034) allocation failure scavenge might not succeed
[49580:0x110000000]     4845 ms: Mark-sweep 130.6 (147.8) -> 130.6 (147.8) MB, 18.8 / 0.0 ms  (average mu = 0.088, current mu = 0.031) allocation failure scavenge might not succeed


<--- JS stacktrace --->

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#

打印 node 命令行选项。此选项的输出不如本文档详细。

¥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 - 实验性的

¥Stability: 1 - Experimental

在启动时预加载指定的模块。如果多次提供该标志,则每个模块将按照它们出现的顺序依次执行,从 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.

--input-type=type#

这将 Node.js 配置为将字符串输入解释为 CommonJS 或 ES 模块。字符串输入是通过 --eval--printSTDIN 输入的。

¥This configures Node.js to interpret string input as CommonJS or as an ES module. String input is input via --eval, --print, or STDIN.

有效值为 "commonjs""module"。默认为 "commonjs"

¥Valid values are "commonjs" and "module". The default is "commonjs".

REPL 不支持此选项。

¥The REPL does not support this option.

--insecure-http-parser#

使用接受无效 HTTP 标头的不安全 HTTP 解析器。这可能允许与不一致的 HTTP 实现的互操作性。它还可能允许请求走私和其他依赖于接受无效标头的 HTTP 攻击。避免使用此选项。

¥Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow interoperability with non-conformant HTTP implementations. It may also allow request smuggling and other HTTP attacks that rely on invalid headers being accepted. Avoid using this option.

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

host:port 上激活检查器。默认为 127.0.0.1:9229

¥Activate inspector on host:port. Default is 127.0.0.1:9229.

V8 检查器集成允许 Chrome 开发者工具和 IDE 等工具调试和分析 Node.js 实例。这些工具通过 tcp 端口连接到 Node.js 实例,并使用 Chrome DevTools 协议 进行通信。

¥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.

警告:将检查器绑定到公共 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:

  • 无法从公共网络访问该主机。

    ¥The host is not accessible from public networks.

  • 防火墙不允许端口上不需要的连接。

    ¥A firewall disallows unwanted connections on the port.

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

¥More specifically, --inspect=0.0.0.0 is insecure if the port (9229 by default) is not firewall-protected.

有关详细信息,请参阅 调试安全隐患 部分。

¥See the debugging security implications section for more information.

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

host:port 上激活检查器并在用户脚本开始时中断。默认 host:port127.0.0.1:9229

¥Activate inspector on host:port and break at start of user script. Default host:port is 127.0.0.1:9229.

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

设置检查器激活时使用的 host:port。在通过发送 SIGUSR1 信号激活检查器时很有用。

¥Set the host:port to be used when the inspector is activated. Useful when activating the inspector by sending the SIGUSR1 signal.

默认主机是 127.0.0.1

¥Default host is 127.0.0.1.

有关 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.

默认情况下,检查器网络套接字网址在标准错误和 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.

-i, --interactive#

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

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

--jitless#

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

¥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.

此标志是从 V8 继承的,可能会在上游发生变化。它可能会在非语义化主版本中消失。

¥This flag is inherited from V8 and is subject to change upstream. It may disappear in a non-semver-major release.

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

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

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

--napi-modules#

此选项为空操作。它是为了兼容性而保留的。

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

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

静默弃用警告。

¥Silence deprecation warnings.

--no-experimental-fetch#

禁用对 Fetch API 的实验性支持。

¥Disable experimental support for the Fetch API.

--no-experimental-global-customevent#

在全局作用域内禁用 CustomEvent Web API 的说明。

¥Disable exposition of CustomEvent Web API on the global scope.

--no-experimental-global-webcrypto#

在全局作用域内禁用 网络加密 API 的说明。

¥Disable exposition of Web Crypto API on the global scope.

--no-experimental-repl-await#

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

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

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

--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_PROVIDER-legacy

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

--openssl-shared-config#

启用 OpenSSL 默认配置部分,从 OpenSSL 配置文件中读取 openssl_conf。默认配置文件名为 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.

--policy-integrity=sri#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

如果策略不具有指定的完整性,则指示 Node.js 在运行任何代码之前出错。它需要一个 子资源完整性 字符串作为参数。

¥Instructs Node.js to error prior to running any code if the policy does not have the specified integrity. It expects a Subresource Integrity string as a parameter.

--preserve-symlinks#

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

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

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

¥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 之外还使用 --preserve-symlinks-main

¥--preserve-symlinks-main does not imply --preserve-symlinks; use --preserve-symlinks-main in addition to --preserve-symlinks when it is not desirable to follow symlinks before resolving relative paths.

有关详细信息,请参阅 --preserve-symlinks

¥See --preserve-symlinks for more information.

-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=directory, report-directory=directory#

生成报告的位置。

¥Location at which the report will be generated.

--report-filename=filename#

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

¥Name of the file to which the report will be written.

如果文件名设置为 'stdout''stderr',则报告分别写入进程的 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 module#

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

¥Preload the specified module at startup.

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

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

仅支持 CommonJS 模块。使用 --import 预加载 ECMAScript 模块。预加载 --require 的模块将在预加载 --import 的模块之前运行。

¥Only CommonJS modules are supported. Use --import to preload an ECMAScript module. Modules preloaded with --require will run before modules preloaded with --import.

--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 的幂。任何小于 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.

--secure-heap-min=n#

当使用 --secure-heap 时,--secure-heap-min 标志指定安全堆的最小分配。最小值为 2。最大值是 --secure-heap2147483647 中的较小者。给定的值必须是 2 的幂。

¥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.

--snapshot-blob=path#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

--build-snapshot 一起使用时,--snapshot-blob 指定写入生成的快照 blob 的路径。如果不指定,生成的 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 二进制文件的版本、体系结构和平台与生成快照的二进制文件完全相同。

    ¥The version, architecture, and platform of the running Node.js binary are exactly the same as that of the binary that generates the snapshot.

  2. V8 标志和 CPU 功能与生成快照的二进制文件兼容。

    ¥The V8 flags and CPU features are compatible with that of the binary that generates the snapshot.

如果它们不匹配,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 将同时执行的测试文件的最大数量。默认值为 os.availableParallelism() - 1

¥The maximum number of test files that the test runner CLI will execute concurrently. The default value is os.availableParallelism() - 1.

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

将测试运行器配置为仅执行设置了 only 选项的顶层测试。

¥Configures the test runner to only execute top level tests that have the only option set.

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

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

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

index 是一个正整数,划分部分的索引 total 是一个正整数,划分部分的总数 该命令将所有测试文件划分为 total 个相等的部分,并且仅运行那些恰好位于 index 部分的文件。

¥index is a positive integer, index of divided parts total is a positive integer, total of divided part 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-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.

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

稳定性: 0 - 已弃用

¥Stability: 0 - Deprecated

Atomics.wait() 调用的简短摘要打印到标准错误。输出可能如下所示:

¥Print short summaries of calls to Atomics.wait() to stderr. The output could look like this:

(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 1, inf) started
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 1, inf) did not wait because the values mismatched
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 0, 10) started
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 0, 0, 10) timed out
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 4, 0, inf) started
(node:15701) [Thread 1] Atomics.wait(&lt;address> + 4, -1, inf) started
(node:15701) [Thread 0] Atomics.wait(&lt;address> + 4, 0, inf) was woken up by another thread
(node:15701) [Thread 1] Atomics.wait(&lt;address> + 4, -1, inf) was woken up by another thread 

这里的字段对应于:

¥The fields here correspond to:

  • worker_threads.threadId 给定的线程标识

    ¥The thread id as given by worker_threads.threadId

  • 有问题的 SharedArrayBuffer 的基地址,以及传给 Atomics.wait() 的索引对应的字节偏移量

    ¥The base address of the SharedArrayBuffer in question, as well as the byte offset corresponding to the index passed to Atomics.wait()

  • 传给 Atomics.wait() 的期望值

    ¥The expected value that was passed to Atomics.wait()

  • 传给 Atomics.wait 的超时

    ¥The timeout passed to Atomics.wait

--trace-deprecation#

打印弃用的堆栈跟踪。

¥Print stack traces for deprecations.

--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-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。如果未设置此钩子,则将未处理的拒绝上升为未捕获的异常。这是默认值。

    ¥throw: Emit unhandledRejection. If this hook is not set, raise the unhandled rejection as an uncaught exception. This is the default.

  • strict:上升未处理的拒绝作为未捕获的异常。如果处理了异常,则触发 unhandledRejection

    ¥strict: Raise the unhandled rejection as an uncaught exception. If the exception is handled, unhandledRejection is emitted.

  • warn:始终触发警告,无论是否设置了 unhandledRejection 钩子,但不打印弃用警告。

    ¥warn: Always trigger a warning, no matter if the unhandledRejection hook is set or not but do not print the deprecation warning.

  • warn-with-error-code:触发 unhandledRejection。如果未设置此钩子,则触发警告,并将进程退出码设置为 1。

    ¥warn-with-error-code: Emit unhandledRejection. If this hook is not set, trigger a warning, and set the process exit code to 1.

  • none:静默所有警告。

    ¥none: Silence all warnings.

如果在命令行入口点的 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#

使用当前 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-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:不会尝试映射。这是默认值。

    ¥off: No mapping will be attempted. This is the default.

  • on:如果操作系统支持,则将尝试映射。映射失败将被忽略,并且将向标准错误打印消息。

    ¥on: If supported by the OS, mapping will be attempted. Failure to map will be ignored and a message will be printed to standard error.

  • silent:如果操作系统支持,则将尝试映射。映射失败将被忽略,并且不会被报告。

    ¥silent: If supported by the OS, mapping will be attempted. Failure to map will be ignored and will not be reported.

--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 数量相同,但在 VM 或容器等环境中可能会有所不同。

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

打印 node 的版本。

¥Print node's version.

--watch#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

以监视模式启动 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.

node --watch index.js 

--watch-path#

稳定性: 1 - 实验性的

¥Stability: 1 - Experimental

以监视模式启动 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.

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#

自动零填充所有新分配的 BufferSlowBuffer 实例。

¥Automatically zero-fills all newly allocated Buffer and SlowBuffer 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 色,

    ¥1, true, or the empty string '' indicate 16-color support,

  • 2 表示支持 256 色,或

    ¥2 to indicate 256-color support, or

  • 3 表示支持 1600 万色。

    ¥3 to indicate 16 million-color support.

当使用 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.

NO_COLOR=<any>#

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

¥NO_COLOR is an alias for NODE_DISABLE_COLORS. The value of the environment variable is arbitrary.

NODE_DEBUG=module[,…]#

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

¥','-separated list of core modules that should print debug information.

NODE_DEBUG_NATIVE=module[,…]#

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

¥','-separated list of core C++ modules that should print debug information.

NODE_DISABLE_COLORS=1#

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

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

NODE_EXTRA_CA_CERTS=file#

设置后,众所周知的 "root" CA(如 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 选项是:

¥Node.js options that are allowed are:

  • --allow-child-process

  • --allow-fs-read

  • --allow-fs-write

  • --allow-worker

  • --conditions, -C

  • --diagnostic-dir

  • --disable-proto

  • --disable-warning

  • --dns-result-order

  • --enable-fips

  • --enable-network-family-autoselection

  • --enable-source-maps

  • --experimental-abortcontroller

  • --experimental-default-type

  • --experimental-detect-module

  • --experimental-import-meta-resolve

  • --experimental-json-modules

  • --experimental-loader

  • --experimental-modules

  • --experimental-network-imports

  • --experimental-permission

  • --experimental-policy

  • --experimental-shadow-realm

  • --experimental-specifier-resolution

  • --experimental-top-level-await

  • --experimental-vm-modules

  • --experimental-wasi-unstable-preview1

  • --experimental-wasm-modules

  • --experimental-websocket

  • --force-context-aware

  • --force-fips

  • --force-node-api-uncaught-exceptions-policy

  • --frozen-intrinsics

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

  • --max-http-header-size

  • --napi-modules

  • --no-addons

  • --no-deprecation

  • --no-experimental-fetch

  • --no-experimental-global-customevent

  • --no-experimental-global-webcrypto

  • --no-experimental-repl-await

  • --no-extra-info-on-fatal-exception

  • --no-force-async-hooks-checks

  • --no-global-search-paths

  • --no-network-family-autoselection

  • --no-warnings

  • --node-memory-debug

  • --openssl-config

  • --openssl-legacy-provider

  • --openssl-shared-config

  • --pending-deprecation

  • --policy-integrity

  • --preserve-symlinks-main

  • --preserve-symlinks

  • --prof-process

  • --redirect-warnings

  • --report-compact

  • --report-dir, --report-directory

  • --report-filename

  • --report-on-fatalerror

  • --report-on-signal

  • --report-signal

  • --report-uncaught-exception

  • --require, -r

  • --secure-heap-min

  • --secure-heap

  • --snapshot-blob

  • --test-only

  • --test-reporter-destination

  • --test-reporter

  • --test-shard

  • --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-atomics-wait

  • --trace-deprecation

  • --trace-event-categories

  • --trace-event-file-pattern

  • --trace-events-enabled

  • --trace-exit

  • --trace-sigint

  • --trace-sync-io

  • --trace-tls

  • --trace-uncaught

  • --trace-warnings

  • --track-heap-objects

  • --unhandled-rejections

  • --use-bundled-ca

  • --use-largepages

  • --use-openssl-ca

  • --v8-pool-size

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

  • --huge-max-old-generation-size

  • --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 上可用。

¥--perf-basic-prof-only-functions, --perf-basic-prof, --perf-prof-unwinding-info, and --perf-prof are only available on Linux.

--enable-etw-stack-walking 仅适用于 Windows。

¥--enable-etw-stack-walking is only available on Windows.

NODE_PATH=path[:…]#

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

¥':'-separated list of directories prefixed to the module search 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 模块的路径,该模块将代替内置交互式解释器加载。将此值覆盖为空字符串 ('') ,则将使用内置的交互式解释器。

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

用于存储持久的交互式解释器历史的文件路径。默认路径是 ~/.node_repl_history,会被此变量覆盖。将值设置为空字符串(''' ')会禁用持久的交互式解释器历史记录。

¥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 格式发送到标准输出。如果提供任何其他值,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_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 可以设置为空字符串,防止传播。

¥NODE_V8_COVERAGE will automatically propagate to subprocesses, making it easier to instrument applications that call the child_process.spawn() family of functions. NODE_V8_COVERAGE can be set to an empty string, to prevent propagation.

覆盖输出#

¥Coverage output

覆盖率作为顶层键 result 上的 ScriptCoverage 对象数组输出:

¥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 - 实验性的

¥Stability: 1 - Experimental

如果找到,则源映射数据将附加到 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 中)、解析的 Source Map v3 信息(在键 data 中)和行长度源文件(在键 lineLengths 中)。

¥source-map-cache is an object with keys representing the files source maps were extracted from, and values which include the raw source-map URL (in the key url), the parsed Source Map v3 information (in the key data), and the line lengths of the source file (in the key 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
      ]
    }
  }
} 

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,则将覆盖并设置包含受信任证书的 OpenSSL 目录。

¥If --use-openssl-ca is enabled, this overrides and sets OpenSSL's directory containing trusted certificates.

注意,除非显式设置子环境,否则任何子进程都会继承此环境变量,如果它们使用 OpenSSL,可能会导致它们信任与节点相同的 CA。

¥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,则将覆盖并设置包含受信任证书的 OpenSSL 文件。

¥If --use-openssl-ca is enabled, this overrides and sets OpenSSL's file containing trusted certificates.

注意,除非显式设置子环境,否则任何子进程都会继承此环境变量,如果它们使用 OpenSSL,可能会导致它们信任与节点相同的 CA。

¥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,但在它们不存在的情况下,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:

  • 所有 fs API,除了文件监视器 API 和那些显式同步的

    ¥all fs APIs, other than the file watcher APIs and those that are explicitly synchronous

  • 异步加密 API,例如 crypto.pbkdf2()crypto.scrypt()crypto.randomBytes()crypto.randomFill()crypto.generateKeyPair()

    ¥asynchronous crypto APIs such as crypto.pbkdf2(), crypto.scrypt(), crypto.randomBytes(), crypto.randomFill(), crypto.generateKeyPair()

  • dns.lookup()

  • 所有 zlib API,除了那些显式同步的

    ¥all zlib APIs, other than those that are explicitly synchronous

因为 libuv 的线程池有固定的大小,这意味着如果这些 API 中的任何一个由于某种原因需要很长时间,则在 libuv 的线程池中运行的其他(看似无关的)API 的性能将会下降。为了缓解此问题,潜在的解决方案是通过将 'UV_THREADPOOL_SIZE' 环境变量设置为大于 4(其当前默认值)的值来增加 libuv 线程池的大小。有关详细信息,请参阅 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). For more information, see the libuv threadpool documentation.

UV_USE_IO_URING=value#

在支持的平台上启用或禁用 libuv 对 io_uring 的使用。

¥Enable or disable libuv's use of io_uring on supported platforms.

在支持的平台上,io_uring 可以显着提高各种异步 I/O 操作的性能。

¥On supported platforms, io_uring can significantly improve the performance of various asynchronous I/O operations.

出于安全考虑,io_uring 默认处于禁用状态。当启用 io_uring 时,应用不得在运行时更改进程的用户身份。在这种情况下,诸如 process.setuid() 之类的 JavaScript 函数将不可用,并且原生插件不得调用诸如 setuid(2) 之类的系统函数。

¥io_uring is disabled by default due to security concerns. When io_uring is enabled, applications must not change the user identity of the process at runtime. In this case, JavaScript functions such as process.setuid() are unavailable, and native addons must not invoke system functions such as setuid(2).

该环境变量由 Node.js 的依赖实现,可能会在 Node.js 的未来版本中删除。不为此环境变量的行为提供稳定性保证。

¥This environment variable is implemented by a dependency of Node.js and may be removed in future versions of Node.js. No stability guarantees are provided for the behavior of this environment variable.

有用的 V8 选项#

¥Useful V8 options

V8 有自己的一组命令行选项。任何提供给 node 的 V8 命令行选项都将传给 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:

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

¥--max-old-space-size=SIZE (in megabytes)

设置 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 megabytes)

以 MiB(兆字节)为单位设置 V8 的 清除垃圾收集器 的最大 semi-space 大小。增加半空间的最大尺寸可能会提高 Node.js 的吞吐量,但会消耗更多内存。

¥Sets the maximum semi-space size for V8's scavenge garbage collector in MiB (megabytes). 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).

64 位系统的默认值为 16 MiB,32 位系统的默认值为 8 MiB。要为你的应用获得最佳配置,你应该在为你的应用运行基准测试时尝试不同的 max-semi-space-size 值。

¥The default value is 16 MiB for 64-bit systems and 8 MiB for 32-bit systems. 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