- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
Node.js v22.11.0 文档
- Node.js v22.11.0
-
目录
- 命令行 API
- 概要
- 程序入口点
- 选项
-
--
--abort-on-uncaught-exception
--allow-addons
--allow-child-process
--allow-fs-read
--allow-fs-write
--allow-wasi
--allow-worker
--build-snapshot
--build-snapshot-config
-c
,--check
--completion-bash
-C condition
,--conditions=condition
--cpu-prof
--cpu-prof-dir
--cpu-prof-interval
--cpu-prof-name
--diagnostic-dir=directory
--disable-warning=code-or-type
--disable-wasm-trap-handler
--disable-proto=mode
--disallow-code-generation-from-strings
--expose-gc
--dns-result-order=order
--enable-fips
--enable-network-family-autoselection
--enable-source-maps
--entry-url
--env-file=config
--env-file-if-exists=config
-e
,--eval "script"
--experimental-async-context-frame
--experimental-default-type=type
--experimental-transform-types
--experimental-eventsource
--experimental-import-meta-resolve
--experimental-loader=module
--experimental-network-inspection
--experimental-permission
--experimental-require-module
--experimental-sea-config
--experimental-shadow-realm
--experimental-sqlite
--experimental-strip-types
--experimental-test-coverage
--experimental-test-isolation=mode
--experimental-test-module-mocks
--experimental-test-snapshots
--experimental-vm-modules
--experimental-wasi-unstable-preview1
--experimental-wasm-modules
--experimental-webstorage
--force-context-aware
--force-fips
--force-node-api-uncaught-exceptions-policy
--frozen-intrinsics
--heap-prof
--heap-prof-dir
--heap-prof-interval
--heap-prof-name
--heapsnapshot-near-heap-limit=max_count
--heapsnapshot-signal=signal
-h
,--help
--icu-data-dir=file
--import=module
--input-type=type
--insecure-http-parser
--inspect[=[host:]port]
--inspect-brk[=[host:]port]
--inspect-port=[host:]port
--inspect-publish-uid=stderr,http
--inspect-wait[=[host:]port]
-i
,--interactive
--jitless
--localstorage-file=file
--max-http-header-size=size
--napi-modules
--network-family-autoselection-attempt-timeout
--no-addons
--no-deprecation
--no-experimental-fetch
--no-experimental-detect-module
--no-experimental-global-customevent
--no-experimental-global-navigator
--no-experimental-global-webcrypto
--no-experimental-repl-await
--no-experimental-websocket
--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=file
--openssl-legacy-provider
--openssl-shared-config
--pending-deprecation
--preserve-symlinks
--preserve-symlinks-main
-p
,--print "script"
--experimental-print-required-tla
--prof
--prof-process
--redirect-warnings=file
--report-compact
--report-dir=directory
,report-directory=directory
--report-filename=filename
--report-on-fatalerror
--report-on-signal
--report-signal=signal
--report-uncaught-exception
--report-exclude-network
-r
,--require module
--run
--secure-heap=n
--secure-heap-min=n
--snapshot-blob=path
--test
--test-concurrency
--test-coverage-branches=threshold
--test-coverage-exclude
--test-coverage-functions=threshold
--test-coverage-include
--test-coverage-lines=threshold
--test-force-exit
--test-name-pattern
--test-only
--test-reporter
--test-reporter-destination
--test-shard
--test-skip-pattern
--test-timeout
--test-update-snapshots
--throw-deprecation
--title=title
--tls-cipher-list=list
--tls-keylog=file
--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=mode
--use-bundled-ca
,--use-openssl-ca
--use-largepages=mode
--v8-options
--v8-pool-size=num
-v
,--version
--watch
--watch-path
--watch-preserve-output
--zero-fill-buffers
- 环境变量
FORCE_COLOR=[1, 2, 3]
NO_COLOR=<any>
NODE_COMPILE_CACHE=dir
NODE_DEBUG=module[,…]
NODE_DEBUG_NATIVE=module[,…]
NODE_DISABLE_COLORS=1
NODE_DISABLE_COMPILE_CACHE=1
NODE_EXTRA_CA_CERTS=file
NODE_ICU_DATA=file
NODE_NO_WARNINGS=1
NODE_OPTIONS=options...
NODE_PATH=path[:…]
NODE_PENDING_DEPRECATION=1
NODE_PENDING_PIPE_INSTANCES=instances
NODE_PRESERVE_SYMLINKS=1
NODE_REDIRECT_WARNINGS=file
NODE_REPL_EXTERNAL_MODULE=file
NODE_REPL_HISTORY=file
NODE_SKIP_PLATFORM_CHECK=value
NODE_TEST_CONTEXT=value
NODE_TLS_REJECT_UNAUTHORIZED=value
NODE_V8_COVERAGE=dir
OPENSSL_CONF=file
SSL_CERT_DIR=dir
SSL_CERT_FILE=file
TZ
UV_THREADPOOL_SIZE=size
UV_USE_IO_URING=value
- 有用的 V8 选项
--abort-on-uncaught-exception
--disallow-code-generation-from-strings
--enable-etw-stack-walking
--expose-gc
--harmony-shadow-realm
--huge-max-old-generation-size
--jitless
--interpreted-frames-native-stack
--prof
--perf-basic-prof
--perf-basic-prof-only-functions
--perf-prof
--perf-prof-unwinding-info
--max-old-space-size=SIZE
(以 MiB 为单位)--max-semi-space-size=SIZE
(以 MiB 为单位)--security-revert
--stack-trace-limit=limit
- 命令行 API
-
导航
- assert 断言
- async_hooks 异步钩子
- async_hooks/context 异步上下文
- buffer 缓冲区
- C++插件
- C/C++插件(使用 Node-API)
- C++嵌入器
- child_process 子进程
- cluster 集群
- CLI 命令行
- console 控制台
- Corepack 核心包
- crypto 加密
- crypto/webcrypto 网络加密
- debugger 调试器
- deprecation 弃用
- dgram 数据报
- diagnostics_channel 诊断通道
- dns 域名服务器
- domain 域
- Error 错误
- events 事件触发器
- fs 文件系统
- global 全局变量
- http 超文本传输协议
- http2 超文本传输协议 2.0
- https 安全超文本传输协议
- inspector 检查器
- Intl 国际化
- module 模块
- module/cjs CommonJS 模块
- module/esm ECMAScript 模块
- module/package 包模块
- module/typescript TS 模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- 其他版本
命令行 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 parentpackage.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
#
中止而不是退出会导致使用调试器(例如 lldb
、gdb
和 mdb
)生成用于事后分析的核心文件。
¥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
#
¥Stability: 1.1 - Active development
当使用 权限模型 时,该进程默认将无法使用原生插件。尝试这样做将抛出 ERR_DLOPEN_DISABLED
,除非用户在启动 Node.js 时明确传递 --allow-addons
标志。
¥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 --experimental-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
#
¥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
#
¥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 allFileSystemRead
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(receiver, 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
#
¥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 allFileSystemWrite
operations. -
使用多个
--allow-fs-write
标志可以允许多个路径。示例--allow-fs-write=/folder1/ --allow-fs-write=/folder1/
¥Multiple paths can be allowed using multiple
--allow-fs-write
flags. Example--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.
CLI 标志不支持相对路径。
¥Relative paths are NOT supported through the CLI flag.
--allow-wasi
#
¥Stability: 1.1 - Active development
使用 权限模型 时,默认情况下,进程将无法创建任何 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 --experimental-permission --allow-fs-read=* index.js
node:wasi:99
const wrap = new _WASI(args, env, preopens, stdio);
^
Error: Access to this API has been restricted
at new WASI (node:wasi:99:18)
at Object.<anonymous> (/home/index.js:3:1)
at Module._compile (node:internal/modules/cjs/loader:1476:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1555:10)
at Module.load (node:internal/modules/cjs/loader:1288:32)
at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:191:14)
at node:internal/main/run_main_module:30:49 {
code: 'ERR_ACCESS_DENIED',
permission: 'WASI',
}
--allow-worker
#
¥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
#
¥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:
-
快照尚不支持用户级模块,因此只能对一个文件进行快照。但是,用户可以在构建快照之前使用他们选择的打包器将他们的应用打包到一个脚本中。
¥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.
-
只有一部分内置模块在快照中工作,尽管 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.
--build-snapshot-config
#
¥Stability: 1 - Experimental
指定配置快照创建行为的 JSON 配置文件的路径。
¥Specifies the path to a JSON configuration file which configures snapshot creation behavior.
目前支持以下选项:
¥The following options are currently supported:
-
builder
<string> 必需的。为构建快照之前执行的脚本提供名称,就好像--build-snapshot
已通过builder
作为主脚本名称一样。¥
builder
<string> Required. Provides the name to the script that is executed before building the snapshot, as if--build-snapshot
had been passed withbuilder
as the main script name. -
withoutCodeCache
<boolean> 可选的。包含代码缓存可以减少编译快照中包含的函数所花费的时间,但代价是快照大小更大,并可能破坏快照的可移植性。¥
withoutCodeCache
<boolean> Optional. Including the code cache reduces the time spent on compiling functions included in the snapshot at the expense of a bigger snapshot size and potentially breaking portability of the snapshot.
使用此标志时,命令行上提供的其他脚本文件将不会被执行,而是被解释为常规命令行参数。
¥When using this flag, additional script files provided on the command line will not be executed and instead be interpreted as regular command line arguments.
-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
#
¥Stability: 2 - Stable
提供自定义 条件导出 解析条件。
¥Provide 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
#
¥Stability: 2 - Stable
启动时开始 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
#
¥Stability: 2 - Stable
指定放置 --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
#
¥Stability: 2 - Stable
为 --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
#
¥Stability: 2 - Stable
指定 --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
#
¥Stability: 1.1 - Active development
按 code
或 type
禁用特定进程警告。
¥Disable specific process warnings by code
or type
.
从 process.emitWarning()
触发的警告可能包含 code
和 type
。此选项不会触发具有匹配 code
或 type
的警告。
¥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 核心警告类型有:DeprecationWarning
和 ExperimentalWarning
¥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
禁用此优化,以便当 Node.js 进程可用的虚拟内存地址空间低于 V8 WebAssembly 内存笼所需的空间时,用户至少可以运行 WebAssembly(性能不太理想)。
¥--disable-wasm-trap-handler
disables this optimization so that
users can at least run WebAssembly (with less optimal performance)
when the virtual memory address space available to their Node.js
process is lower than what the V8 WebAssembly memory cage needs.
--disable-proto=mode
#
禁用 Object.prototype.__proto__
属性。如果 mode
是 delete
,则该属性将被完全删除。如果 mode
是 throw
,则访问该属性会使用代码 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
#
使从字符串生成代码的 eval
和 new 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.
--expose-gc
#
¥Stability: 1 - Experimental. This flag is inherited from V8 and is subject to change upstream.
此标志将公开 V8 的 gc 扩展。
¥This flag will expose the gc extension from V8.
if (globalThis.gc) {
globalThis.gc();
}
--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
。¥
ipv4first
: sets defaultorder
toipv4first
. -
ipv6first
:将默认order
设置为ipv6first
。¥
ipv6first
: sets defaultorder
toipv6first
. -
verbatim
:将默认order
设置为verbatim
。¥
verbatim
: sets defaultorder
toverbatim
.
默认为 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
#
为堆栈跟踪启用 源映射 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
修改堆栈跟踪。在重写函数中调用并返回原始 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
#
¥Stability: 1 - Experimental
如果存在,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 --experimental-strip-types 'file.ts?query#hash'
node --entry-url 'data:text/javascript,console.log("Hello")'
--env-file=config
#
¥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.
如果文件不存在,则会引发错误。
¥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.
--env-file-if-exists=config
#
行为与 --env-file
相同,但如果文件不存在,则不会引发错误。
¥Behavior is the same as --env-file
, but an error is not thrown if the file
does not exist.
-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-strip-types
来运行包含内联类型的代码。
¥It is possible to run code containing inline types by passing
--experimental-strip-types
.
--experimental-async-context-frame
#
¥Stability: 1 - Experimental
启用由 AsyncContextFrame
支持的 AsyncLocalStorage
,而不是依赖于 async_hooks 的默认实现。这个新模型的实现方式非常不同,因此上下文数据在应用内的流动方式可能会有所不同。因此,目前建议在生产中使用它之前确保你的应用行为不受此更改的影响。
¥Enables the use of AsyncLocalStorage
backed by AsyncContextFrame
rather
than the default implementation which relies on async_hooks. This new model is
implemented very differently and so could have differences in how context data
flows within the application. As such, it is presently recommended to be sure
your application behaviour is unaffected by this change before using it in
production.
--experimental-default-type=type
#
¥Stability: 1.0 - Early development
定义用于以下目的的模块系统 module
或 commonjs
:
¥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 nopackage.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 parentpackage.json
field lacks a"type"
field; unless thepackage.json
folder or any parent folder is inside anode_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-transform-types
#
¥Stability: 1.0 - Early development
启用将仅 TypeScript 语法转换为 JavaScript 代码。暗示 --experimental-strip-types
和 --enable-source-maps
。
¥Enables the transformation of TypeScript-only syntax into JavaScript code.
Implies --experimental-strip-types
and --enable-source-maps
.
--experimental-eventsource
#
在全局作用域内启用 EventSource Web 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-loader=module
#
不鼓励使用此标志,并且可能会在 Node.js 的未来版本中将其删除。请改用
--import
与register()
。¥This flag is discouraged and may be removed in a future version of Node.js. Please use
--import
withregister()
instead.
指定包含导出的 模块定制钩子 的 module
。module
可以是接受为 import
说明符 的任何字符串。
¥Specify the module
containing exported module customization hooks.
module
may be any string accepted as an import
specifier.
--experimental-network-inspection
#
¥Stability: 1 - Experimental
使用 Chrome DevTools 启用对网络检查的实验性支持。
¥Enable experimental support for the network inspection with Chrome DevTools.
--experimental-permission
#
¥Stability: 1.1 - Active development
为当前进程启用权限模型。启用后,以下权限将受到限制:
¥Enable the Permission Model for current process. When enabled, the following permissions are restricted:
-
文件系统 - 可通过
--allow-fs-read
、--allow-fs-write
标志进行管理¥File System - manageable through
--allow-fs-read
,--allow-fs-write
flags -
子进程 - 可通过
--allow-child-process
标志进行管理¥Child Process - manageable through
--allow-child-process
flag -
工作线程 - 可通过
--allow-worker
标志进行管理¥Worker Threads - manageable through
--allow-worker
flag -
WASI - 可通过
--allow-wasi
标志进行管理¥WASI - manageable through
--allow-wasi
flag -
插件 - 可通过
--allow-addons
标志进行管理¥Addons - manageable through
--allow-addons
flag
--experimental-require-module
#
¥Stability: 1.1 - Active Development
支持在 require()
中加载同步 ES 模块图。
¥Supports loading a synchronous ES module graph in require()
.
参见 使用 require()
加载 ECMAScript 模块。
¥See Loading ECMAScript modules using require()
.
--experimental-sea-config
#
¥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-sqlite
#
启用实验性的 node:sqlite
模块。
¥Enable the experimental node:sqlite
module.
--experimental-strip-types
#
¥Stability: 1.0 - Early development
为 TypeScript 文件启用实验性类型剥离。有关更多信息,请参阅 TypeScript 类型剥离 文档。
¥Enable experimental type-stripping for TypeScript files. For more information, see the TypeScript type-stripping documentation.
--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-isolation=mode
#
¥Stability: 1.0 - Early development
配置测试运行器中使用的测试隔离类型。当 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.
--experimental-test-module-mocks
#
¥Stability: 1.0 - Early development
在测试运行器中启用模块模拟。
¥Enable module mocking in the test runner.
--experimental-test-snapshots
#
¥Stability: 1.0 - Early development
在测试运行器中启用 快照测试。
¥Enable snapshot testing in the test runner.
--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-webstorage
#
启用实验性 Web Storage
支持。
¥Enable experimental Web Storage
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
#
¥Stability: 1 - Experimental
启用像 Array
和 Object
这样的实验性冻结内在函数。
¥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
#
¥Stability: 2 - Stable
在启动时开始 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
#
¥Stability: 2 - Stable
指定 --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
#
¥Stability: 2 - Stable
指定 --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
#
¥Stability: 2 - Stable
指定 --heap-prof
生成的堆分析文件的文件名。
¥Specify the file name of the heap profile generated by --heap-prof
.
--heapsnapshot-near-heap-limit=max_count
#
¥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
#
¥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
.
模块预加载到主线程以及任何工作线程、分叉进程或集群进程中。
¥Modules are preloaded into the main thread as well as any worker threads, forked processes, or clustered processes.
--input-type=type
#
这将 Node.js 配置为将 --eval
或 STDIN
输入解释为 CommonJS 或 ES 模块。有效值为 "commonjs"
或 "module"
。除非使用 --experimental-default-type=module
,否则默认值为 "commonjs"
。
¥This configures Node.js to interpret --eval
or STDIN
input as CommonJS or
as an ES module. Valid values are "commonjs"
or "module"
. The default is
"commonjs"
unless --experimental-default-type=module
is used.
REPL 不支持此选项。将 --input-type=module
与 --print
一起使用会引发错误,因为 --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 标头值无效。
¥Invalid HTTP headers values.
-
无效的 HTTP 版本。
¥Invalid HTTP versions.
-
允许包含
Transfer-Encoding
和Content-Length
标头的消息。¥Allow message containing both
Transfer-Encoding
andContent-Length
headers. -
当
Connection: close
存在时,允许在消息后添加额外数据。¥Allow extra data after message when
Connection: close
is present. -
提供
chunked
后允许额外的传输编码。¥Allow extra transfer encodings after
chunked
has been provided. -
允许使用
\n
而不是\r\n
作为标记分隔符。¥Allow
\n
to be used as token separator instead of\r\n
. -
允许在块之后不提供
\r\n
。¥Allow
\r\n
not to be provided after a chunk. -
允许在块大小之后和
\r\n
之前存在空格。¥Allow spaces to be present after a chunk size and before
\r\n
.
上述所有内容都会使你的应用暴露于请求走私或投毒攻击。避免使用此选项。
¥All the above will expose your application to request smuggling or poisoning attack. Avoid using this option.
--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 开发者工具和 IDE 等工具调试和分析 Node.js 实例。这些工具通过 tcp 端口连接到 Node.js 实例,并使用 Chrome DevTools 协议 进行通信。有关 Node.js 调试器的进一步说明,请参阅 Node.js 的 V8 Inspector 集成。
¥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.
警告:将检查器绑定到公共 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:port
为 127.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 Inspector 集成。
¥See V8 Inspector integration for Node.js for further explanation on Node.js debugger.
--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
。如果指定了端口 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.
默认情况下,检查器网络套接字网址在标准错误和 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:port
为 127.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 Inspector 集成。
¥See V8 Inspector integration for Node.js for further explanation on Node.js debugger.
-i
, --interactive
#
即使标准输入似乎不是终端,也会打开交互式解释器。
¥Opens the REPL even if stdin does not appear to be a terminal.
--jitless
#
¥Stability: 1 - Experimental. This flag is inherited from V8 and is subject to change upstream.
禁用 可执行内存的运行时分配。出于安全原因,某些平台可能需要这样做。在其他平台上也可以减少攻击面,但性能影响可能比较严重。
¥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 使用 --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 unless
Node.js is started with the --experimental-webstorage
flag.
--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.
--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-deprecation
#
静默弃用警告。
¥Silence deprecation warnings.
--no-experimental-fetch
#
在全局作用域内禁用 Fetch API 的说明。
¥Disable exposition of Fetch API on the global scope.
--no-experimental-detect-module
#
禁用使用 语法检测 来确定模块类型。
¥Disable using syntax detection to determine module type.
--no-experimental-global-customevent
#
在全局作用域内禁用 CustomEvent Web API 的说明。
¥Disable exposition of CustomEvent Web API on the global scope.
--no-experimental-global-navigator
#
¥Stability: 1 - Experimental
在全局作用域内禁用 导航器 API 的说明。
¥Disable exposition of Navigator 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-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).
--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.
--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.
--experimental-print-required-tla
#
该标志仅在 --experimental-require-module
启用时有用。
¥This flag is only useful when --experimental-require-module
is enabled.
如果 require()
的 ES 模块包含顶层等待,则此标志允许 Node.js 评估该模块,尝试定位顶层等待,并打印其位置以帮助用户找到它们。
¥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.
--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.
--report-exclude-network
#
从诊断报告中排除 header.networkInterfaces
。默认情况下,未设置此项,并且包括网络接口。
¥Exclude header.networkInterfaces
from the diagnostic report. By default
this is not set and the network interfaces are included.
-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
.
模块预加载到主线程以及任何工作线程、分叉进程或集群进程中。
¥Modules are preloaded into the main thread as well as any worker threads, forked processes, or clustered processes.
--run
#
¥Stability: 2 - Stable
这将从 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
will traverse up to the root directory and finds a package.json
file to run the command from.
如果 ancestor-folder/node_modules/.bin
是目录,--run
将当前目录的每个祖级的 ./node_modules/.bin
添加到 PATH
之前,以便从存在多个 node_modules
目录的不同文件夹执行二进制文件。
¥--run
prepends ./node_modules/.bin
for each ancestor of
the current directory, to the PATH
in order to execute the binaries from
different folders where multiple node_modules
directories are present, if
ancestor-folder/node_modules/.bin
is a directory.
--run
在包含相关 package.json
的目录中执行命令。
¥--run
executes the command in the directory containing the related package.json
.
例如,以下命令将运行当前文件夹中 package.json
的 test
脚本:
¥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
实现的一些功能包括:
¥node --run
is not meant to match the behaviors of npm run
or of the run
commands of other package managers. The Node.js implementation is intentionally
more limited, in order to focus on top performance for the most common use
cases.
Some features of other run
implementations that are intentionally excluded
are:
-
除了指定的脚本之外,还运行
pre
或post
脚本。¥Running
pre
orpost
scripts in addition to the specified script. -
定义特定于包管理器的环境变量。
¥Defining package manager-specific environment variables.
环境变量#
¥Environment variables
使用 --run
运行脚本时设置以下环境变量:
¥The following environment variables are set when running a script with --run
:
-
NODE_RUN_SCRIPT_NAME
:正在运行的脚本的名称。例如,如果使用--run
运行test
,则此变量的值将为test
。¥
NODE_RUN_SCRIPT_NAME
: The name of the script being run. For example, if--run
is used to runtest
, the value of this variable will betest
. -
NODE_RUN_PACKAGE_JSON_PATH
:正在处理的package.json
的路径。¥
NODE_RUN_PACKAGE_JSON_PATH
: The path to thepackage.json
that is being processed.
--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-heap
或 2147483647
中的较小者。给定的值必须是 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
#
¥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:
-
正在运行的 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.
-
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 将同时执行的测试文件的最大数量。如果 --experimental-test-isolation
设置为 'none'
,则忽略此标志,并发性为 1。否则,并发默认为 os.availableParallelism() - 1
。
¥The maximum number of test files that the test runner CLI will execute
concurrently. If --experimental-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
#
¥Stability: 1 - Experimental
要求覆盖分支的最小百分比。如果代码覆盖率未达到指定的阈值,则该过程将以代码 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
#
¥Stability: 1 - Experimental
使用 glob 模式从代码覆盖范围中排除特定文件,该模式可以匹配绝对和相对文件路径。
¥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.
--test-coverage-functions=threshold
#
¥Stability: 1 - Experimental
要求覆盖函数的最小百分比。如果代码覆盖率未达到指定的阈值,则该过程将以代码 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
#
¥Stability: 1 - Experimental
使用 glob 模式在代码覆盖范围内包含特定文件,该模式可以匹配绝对和相对文件路径。
¥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
#
¥Stability: 1 - Experimental
要求覆盖行的最小百分比。如果代码覆盖率未达到指定的阈值,则该过程将以代码 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-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-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-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
#
¥Stability: 1.0 - Early development
重新生成测试运行器为 快照测试 使用的快照文件。必须使用 --experimental-test-snapshots
标志启动 Node.js 才能使用此功能。
¥Regenerates the snapshot files used by the test runner for snapshot testing.
Node.js must be started with the --experimental-test-snapshots
flag in order
to use this functionality.
--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
#
¥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(<address> + 0, 1, inf) started
(node:15701) [Thread 0] Atomics.wait(<address> + 0, 1, inf) did not wait because the values mismatched
(node:15701) [Thread 0] Atomics.wait(<address> + 0, 0, 10) started
(node:15701) [Thread 0] Atomics.wait(<address> + 0, 0, 10) timed out
(node:15701) [Thread 0] Atomics.wait(<address> + 4, 0, inf) started
(node:15701) [Thread 1] Atomics.wait(<address> + 4, -1, inf) started
(node:15701) [Thread 0] Atomics.wait(<address> + 4, 0, inf) was woken up by another thread
(node:15701) [Thread 1] Atomics.wait(<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 toAtomics.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
: EmitunhandledRejection
. 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 theunhandledRejection
hook is set or not but do not print the deprecation warning. -
warn-with-error-code
:触发unhandledRejection
。如果未设置此钩子,则触发警告,并将进程退出码设置为 1。¥
warn-with-error-code
: EmitunhandledRejection
. 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_DIR
和 SSL_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
#
¥Stability: 2 - Stable
以监视模式启动 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
#
¥Stability: 2 - Stable
以监视模式启动 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
#
自动零填充所有新分配的 Buffer
和 SlowBuffer
实例。
¥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:
-
1
、true
、或空字符串''
表示支持 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_COLOR
和 NODE_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_COLOR
是 NODE_DISABLE_COLORS
的别名。环境变量的值是任意的。
¥NO_COLOR
is an alias for NODE_DISABLE_COLORS
. The value of the
environment variable is arbitrary.
NODE_COMPILE_CACHE=dir
#
¥Stability: 1.1 - Active Development
为 Node.js 实例启用 模块编译缓存。有关详细信息,请参阅 模块编译缓存 的文档。
¥Enable the module compile cache for the Node.js instance. See the documentation of module compile cache for details.
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_DISABLE_COMPILE_CACHE=1
#
¥Stability: 1.1 - Active Development
为 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
#
设置后,众所周知的 "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 选项位于以下列表中。如果一个选项同时支持 --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-wasi
-
--allow-worker
-
--conditions
,-C
-
--diagnostic-dir
-
--disable-proto
-
--disable-warning
-
--disable-wasm-trap-handler
-
--dns-result-order
-
--enable-fips
-
--enable-network-family-autoselection
-
--enable-source-maps
-
--entry-url
-
--experimental-abortcontroller
-
--experimental-async-context-frame
-
--experimental-default-type
-
--experimental-detect-module
-
--experimental-eventsource
-
--experimental-import-meta-resolve
-
--experimental-json-modules
-
--experimental-loader
-
--experimental-modules
-
--experimental-permission
-
--experimental-print-required-tla
-
--experimental-require-module
-
--experimental-shadow-realm
-
--experimental-specifier-resolution
-
--experimental-sqlite
-
--experimental-strip-types
-
--experimental-top-level-await
-
--experimental-transform-types
-
--experimental-vm-modules
-
--experimental-wasi-unstable-preview1
-
--experimental-wasm-modules
-
--experimental-webstorage
-
--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-wait
-
--inspect
-
--localstorage-file
-
--max-http-header-size
-
--napi-modules
-
--network-family-autoselection-attempt-timeout
-
--no-addons
-
--no-deprecation
-
--no-experimental-fetch
-
--no-experimental-global-customevent
-
--no-experimental-global-navigator
-
--no-experimental-global-webcrypto
-
--no-experimental-repl-await
-
--no-experimental-websocket
-
--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
-
--preserve-symlinks-main
-
--preserve-symlinks
-
--prof-process
-
--redirect-warnings
-
--report-compact
-
--report-dir
,--report-directory
-
--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-name-pattern
-
--test-only
-
--test-reporter-destination
-
--test-reporter
-
--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-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
-
--expose-gc
-
--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
¥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:
--abort-on-uncaught-exception
#
--disallow-code-generation-from-strings
#
--enable-etw-stack-walking
#
--expose-gc
#
--harmony-shadow-realm
#
--huge-max-old-generation-size
#
--jitless
#
--interpreted-frames-native-stack
#
--prof
#
--perf-basic-prof
#
--perf-basic-prof-only-functions
#
--perf-prof
#
--perf-prof-unwinding-info
#
--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
(以 MiB 为单位)#
¥--max-semi-space-size=SIZE
(in MiB)
以 MiB(兆字节)为单位设置 V8 的 清除垃圾收集器 的最大 semi-space 大小。增加半空间的最大尺寸可能会提高 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).
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
--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