- 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 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
Node.js v18.20.8 文档
- Node.js v18.20.8
- 目录
-
导航
- 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 包模块
- net 网络
- os 操作系统
- path 路径
- perf_hooks 性能钩子
- permission 权限
- process 进程
- punycode 域名代码
- querystring 查询字符串
- readline 逐行读取
- repl 交互式解释器
- report 诊断报告
- sea 单个可执行应用程序
- stream 流
- stream/web 网络流
- string_decoder 字符串解码器
- test 测试
- timers 定时器
- tls 安全传输层
- trace_events 跟踪事件
- tty 终端
- url 网址
- util 实用工具
- v8 引擎
- vm 虚拟机
- wasi 网络汇编系统接口
- worker_threads 工作线程
- zlib 压缩
- 其他版本
权限#>
【Permissions】
权限可以用来控制 Node.js 进程可以访问哪些系统资源,或者进程可以对这些资源执行哪些操作。权限还可以控制其他模块可以访问哪些模块。
【Permissions can be used to control what system resources the Node.js process has access to or what actions the process can take with those resources. Permissions can also control what modules can be accessed by other modules.】
- 基于模块的权限 控制在应用执行期间其他模块可以访问哪些文件或 URL。这可以用于控制第三方依赖可以访问哪些模块,例如。
如果你发现潜在的安全漏洞,请参考我们的 安全策略。
【If you find a potential security vulnerability, please refer to our Security Policy.】
基于模块的权限#>
【Module-based permissions】
政策#>
【Policies】
Node.js 包含了对创建加载代码的策略的实验性支持。
【Node.js contains experimental support for creating policies on loading code.】
策略是一种安全功能,旨在允许对 Node.js 能够加载的代码提供保证。使用策略假定对策略文件采用安全做法,例如通过使用文件权限确保 Node.js 应用无法覆盖策略文件。
【Policies are a security feature intended to allow guarantees about what code Node.js is able to load. The use of policies assumes safe practices for the policy files such as ensuring that policy files cannot be overwritten by the Node.js application by using file permissions.】
最佳做法是确保策略清单对正在运行的 Node.js 应用是只读的,并且运行中的 Node.js 应用无法以任何方式更改该文件。典型的设置是以不同于运行 Node.js 的用户 ID 创建策略文件,并授予运行 Node.js 的用户 ID 读取权限。
【A best practice would be to ensure that the policy manifest is read-only for the running Node.js application and that the file cannot be changed by the running Node.js application in any way. A typical setup would be to create the policy file as a different user id than the one running Node.js and granting read permissions to the user id running Node.js.】
启用#>
【Enabling】
--experimental-policy 标志可以在加载模块时启用策略的功能。
【The --experimental-policy flag can be used to enable features for policies
when loading modules.】
一旦设置完成,所有模块必须遵守传递给标志的策略清单文件:
【Once this has been set, all modules must conform to a policy manifest file passed to the flag:】
node --experimental-policy=policy.json app.js
策略清单将用于对 Node.js 加载的代码施加约束。
【The policy manifest will be used to enforce constraints on code loaded by Node.js.】
为了减少对磁盘上策略文件的篡改,可以通过 --policy-integrity 提供策略文件本身的完整性。这允许在文件被修改的情况下仍然运行 node 并验证策略文件的内容。
【To mitigate tampering with policy files on disk, an integrity for
the policy file itself may be provided via --policy-integrity.
This allows running node and asserting the policy file contents
even if the file is changed on disk.】
node --experimental-policy=policy.json --policy-integrity="sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0" app.js
特性#>
【Features】
错误行为#>
【Error behavior】
当策略检查失败时,Node.js 默认会抛出错误。可以通过在策略清单中定义 "onerror" 字段,将错误行为更改为几种可能的选项之一。可以使用以下值来更改行为:
【When a policy check fails, Node.js by default will throw an error. It is possible to change the error behavior to one of a few possibilities by defining an "onerror" field in a policy manifest. The following values are available to change the behavior:】
"exit":将立即退出进程。任何清理代码都不会被执行。"log":将在出错地点记录错误。"throw":将在失败发生的地方抛出一个 JS 错误。这是默认设置。
{
"onerror": "log",
"resources": {
"./app/checked.js": {
"integrity": "sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"
}
}
}
完整性检查#>
【Integrity checks】
策略文件必须使用与浏览器兼容的子资源完整性字符串进行完整性检查,这些字符串与关联绝对 URL 的 integrity 属性 相对应。
【Policy files must use integrity checks with Subresource Integrity strings compatible with the browser integrity attribute associated with absolute URLs.】
使用 require() 或 import 时,如果指定了策略清单,加载所涉及的所有资源都会进行完整性检查。如果资源与清单中列出的完整性不匹配,将会抛出错误。
【When using require() or import all resources involved in loading are checked
for integrity if a policy manifest has been specified. If a resource does not
match the integrity listed in the manifest, an error will be thrown.】
一个示例策略文件,它允许加载文件 checked.js:
【An example policy file that would allow loading a file checked.js:】
{
"resources": {
"./app/checked.js": {
"integrity": "sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"
}
}
}
策略清单中列出的每个资源可以采用以下格式之一来确定其位置:
【Each resource listed in the policy manifest can be of one the following formats to determine its location:】
- 从清单中的资源引用 相对 URL 字符串,例如
./resource.js、../resource.js或/resource.js。 - 指向资源的完整 URL 字符串,例如
file:///resource.js。
在加载资源时,整个 URL 必须完全匹配,包括查询参数和哈希片段。尝试加载 ./a.js 时不会使用 ./a.js?b,反之亦然。
【When loading resources the entire URL must match including search parameters
and hash fragment. ./a.js?b will not be used when attempting to load
./a.js and vice versa.】
要生成完整性字符串,可以使用如下脚本:
node -e 'process.stdout.write("sha256-");process.stdin.pipe(crypto.createHash("sha256").setEncoding("base64")).pipe(process.stdout)' < FILE
【To generate integrity strings, a script such as
node -e 'process.stdout.write("sha256-");process.stdin.pipe(crypto.createHash("sha256").setEncoding("base64")).pipe(process.stdout)' < FILE
can be used.】
完整性可以指定为布尔值 true,以接受资源的任何内容,这在本地开发中可能很有用。但在生产环境中不推荐使用,因为这会允许对资源的意外更改被视为有效。
【Integrity can be specified as the boolean value true to accept any
body for the resource which can be useful for local development. It is not
recommended in production since it would allow unexpected alteration of
resources to be considered valid.】
依赖重定向#>
【Dependency redirection】
应用可能需要发布已修补的模块版本,或防止模块允许所有模块访问所有其他模块。可以通过拦截尝试加载希望被替换的模块的操作来使用重定向。
【An application may need to ship patched versions of modules or to prevent modules from allowing all modules access to all other modules. Redirection can be used by intercepting attempts to load the modules wishing to be replaced.】
{
"resources": {
"./app/checked.js": {
"dependencies": {
"fs": true,
"os": "./app/node_modules/alt-os",
"http": { "import": true }
}
}
}
}
依赖以请求的指定符字符串为键,其值可以是 true、null、指向要解析模块的字符串,或者是条件对象。
【The dependencies are keyed by the requested specifier string and have values
of either true, null, a string pointing to a module to be resolved,
or a conditions object.】
说明符字符串不会执行任何搜索,并且必须与提供给 require() 或 import 的内容完全匹配,除了一个规范化步骤。因此,如果策略使用多个不同的字符串指向同一个模块(例如省略扩展名),可能需要多个说明符。
【The specifier string does not perform any searching and must match exactly what
is provided to the require() or import except for a canonicalization step.
Therefore, multiple specifiers may be needed in the policy if it uses multiple
different strings to point to the same module (such as excluding the extension).】
指定符字符串会被规范化,但在用于匹配之前不会被解析,以便与导入映射保持一定的兼容性,例如如果一个资源 file:///C:/app/server.js 被位于 file:///C:/app/policy.json 的策略进行了以下重定向时:
【Specifier strings are canonicalized but not resolved prior to be used for
matching in order to have some compatibility with import maps, for example if a
resource file:///C:/app/server.js was given the following redirection from a
policy located at file:///C:/app/policy.json:】
{
"resources": {
"file:///C:/app/utils.js": {
"dependencies": {
"./utils.js": "./utils-v2.js"
}
}
}
}
任何用于加载 file:///C:/app/utils.js 的指定符都会被拦截,并被重定向到 file:///C:/app/utils-v2.js,无论使用的是绝对路径还是相对路径指定符。然而,如果使用的指定符不是绝对或相对 URL 字符串,则不会被拦截。因此,如果使用类似 import('#utils') 的导入,它将不会被拦截。
【Any specifier used to load file:///C:/app/utils.js would then be intercepted
and redirected to file:///C:/app/utils-v2.js instead regardless of using an
absolute or relative specifier. However, if a specifier that is not an absolute
or relative URL string is used, it would not be intercepted. So, if an import
such as import('#utils') was used, it would not be intercepted.】
如果重定向的值为 true,策略文件顶部的“dependencies”字段将被使用。如果策略文件顶部的该字段为 true,则使用默认的节点搜索算法来查找模块。
【If the value of the redirection is true, a "dependencies" field at the top of
the policy file will be used. If that field at the top of the policy file is
true the default node searching algorithms are used to find the module.】
如果重定向的值是字符串,它将相对于清单进行解析,然后立即使用,而不进行搜索。
【If the value of the redirection is a string, it is resolved relative to the manifest and then immediately used without searching.】
根据该策略,任何尝试解析但未列在依赖中的指定符字符串都会导致错误。
【Any specifier string for which resolution is attempted and that is not listed in the dependencies results in an error according to the policy.】
重定向并不能阻止通过诸如直接访问 require.cache 或通过 module.constructor 等方式访问 API,这些方式可以访问正在加载的模块。策略重定向仅影响 require() 和 import 的说明符。其他手段,例如通过变量防止对 API 的非预期访问,对于封锁该模块加载路径是必要的。
【Redirection does not prevent access to APIs through means such as direct access
to require.cache or through module.constructor which allow access to
loading modules. Policy redirection only affects specifiers to require() and
import. Other means, such as to prevent undesired access to APIs through
variables, are necessary to lock down that path of loading modules.】
依赖映射的布尔值 true 可以用来允许模块加载任何指定的标识符而无需跳转。这在本地开发中可能很有用,并且在生产环境中也可能有某些有效用例,但在审核模块以确保其行为有效之后应谨慎使用。
【A boolean value of true for the dependencies map can be specified to allow a
module to load any specifier without redirection. This can be useful for local
development and may have some valid usage in production, but should be used
only with care after auditing a module to ensure its behavior is valid.】
类似于 package.json 中的 exports,依赖也可以被指定为包含条件的对象,这些条件决定了依赖的加载方式。在前面的示例中,当加载时包含 "import" 条件时,"http" 是允许的。
【Similar to "exports" in package.json, dependencies can also be specified to
be objects containing conditions which branch how dependencies are loaded. In
the preceding example, "http" is allowed when the "import" condition is
part of loading it.】
将解析值设为 null 会导致解析失败。这可以用于确保某些类型的动态访问被明确阻止。
【A value of null for the resolved value causes the resolution to fail. This
can be used to ensure some kinds of dynamic access are explicitly prevented.】
解析模块位置时的未知值会导致失败,但不保证向前兼容。
【Unknown values for the resolved module location cause failures but are not guaranteed to be forward compatible.】
示例:已修补的依赖#>
【Example: Patched dependency】
重定向的依赖可以根据应用的需要提供减弱或修改后的功能。例如,通过封装原始函数来记录函数持续时间的日志数据:
【Redirected dependencies can provide attenuated or modified functionality as fits the application. For example, log data about timing of function durations by wrapping the original:】
const original = require('fn');
module.exports = function fn(...args) {
console.time();
try {
return new.target ?
Reflect.construct(original, args) :
Reflect.apply(original, this, args);
} finally {
console.timeEnd();
}
};
作用域#>
【Scopes】
使用清单的 "scopes" 字段可以一次为多个资源设置配置。"scopes" 字段通过按段匹配资源来工作。如果某个作用域或资源包含 "cascade": true,未知的说明符将会在其包含的作用域中进行搜索。用于级联的包含作用域是通过递归地减少资源 URL 来找到的,方法是删除段(例如 特别计划),保留尾部的 "/" 后缀,并删除查询参数和哈希片段。这样最终会将 URL 缩减到其源。如果 URL 是非特殊的,作用域将通过 URL 的源来定位。如果找不到源的作用域,或者对于不透明源的情况,可以使用协议字符串作为作用域。如果找不到 URL 协议的作用域,则最终会使用空字符串 "" 作为作用域。
【Use the "scopes" field of a manifest to set configuration for many resources
at once. The "scopes" field works by matching resources by their segments.
If a scope or resource includes "cascade": true, unknown specifiers will
be searched for in their containing scope. The containing scope for cascading
is found by recursively reducing the resource URL by removing segments for
special schemes, keeping trailing "/" suffixes, and removing the query and
hash fragment. This leads to the eventual reduction of the URL to its origin.
If the URL is non-special the scope will be located by the URL's origin. If no
scope is found for the origin or in the case of opaque origins, a protocol
string can be used as a scope. If no scope is found for the URL's protocol, a
final empty string "" scope will be used.】
注意,blob: URL 的来源取自其包含的路径,因此作用域
"blob:https://nodejs.cn" 将没有效果,因为没有 URL 可以具有 blob:https://nodejs.cn 的来源;以 blob:https://nodejs.cn/ 开头的 URL 将使用 https://nodejs.cn 作为其来源,因此 https: 作为其协议作用域。对于不透明来源的 blob: URL,它们将使用 blob: 作为其协议作用域,因为它们不会采用来源。
【Note, blob: URLs adopt their origin from the path they contain, and so a scope
of "blob:https://nodejs.cn" will have no effect since no URL can have an
origin of blob:https://nodejs.cn; URLs starting with
blob:https://nodejs.cn/ will use https://nodejs.cn for its origin and
thus https: for its protocol scope. For opaque origin blob: URLs they will
have blob: for their protocol scope since they do not adopt origins.】
示例#>
【Example】
{
"scopes": {
"file:///C:/app/": {},
"file:": {},
"": {}
}
}
给定一个位于 file:///C:/app/bin/main.js 的文件,将按以下顺序检查作用域:
【Given a file located at file:///C:/app/bin/main.js, the following scopes would
be checked in order:】
"file:///C:/app/bin/"
这决定了所有基于文件的资源的策略 “file:///C:/app/bin/”。这不属于保单的“范围”范畴,且 会跳过。将此范围加入政策会导致其被使用。 在“file:///C:/app/”范围之前。
【This determines the policy for all file based resources within
"file:///C:/app/bin/". This is not in the "scopes" field of the policy and
would be skipped. Adding this scope to the policy would cause it to be used
prior to the "file:///C:/app/" scope.】
"file:///C:/app/"
这决定了所有基于文件的资源的策略 “file:///C:/app/”。这属于保单的“范围”部分,应该是 确定资源在“file:///C:/app/bin/main.js”的策略。如果 范围的“级联”:true,任何未满足的资源查询 将“file:///C:/app/bin/main.js”授权给下一个相关范围,即“文件:”。
【This determines the policy for all file based resources within
"file:///C:/app/". This is in the "scopes" field of the policy and it would
determine the policy for the resource at file:///C:/app/bin/main.js. If the
scope has "cascade": true, any unsatisfied queries about the resource would
delegate to the next relevant scope for file:///C:/app/bin/main.js, "file:".】
"file:///C:/"
这确定了所有位于 "file:///C:/" 的基于文件的资源的策略。这不在策略的 "scopes" 字段中,因此会被忽略。除非将 "file:///" 设置为级联,或者它不在策略的 "scopes" 中,否则它不会用于 file:///C:/app/bin/main.js。
【This determines the policy for all file based resources within "file:///C:/".
This is not in the "scopes" field of the policy and would be skipped. It would
not be used for file:///C:/app/bin/main.js unless "file:///" is set to
cascade or is not in the "scopes" of the policy.】
"file:///"
这决定了 localhost 上所有基于文件的资源的策略。这不在策略的 "scopes" 字段中,因此会被跳过。除非将 "file:///" 设置为级联或它不在策略的 "scopes" 中,否则不会用于 file:///C:/app/bin/main.js。
【This determines the policy for all file based resources on the localhost. This
is not in the "scopes" field of the policy and would be skipped. It would not
be used for file:///C:/app/bin/main.js unless "file:///" is set to cascade
or is not in the "scopes" of the policy.】
"file:"
这决定了所有基于文件的资源的策略。除非将 "file:///" 设置为级联或未包含在策略的 "scopes" 中,否则不会用于 file:///C:/app/bin/main.js。
【This determines the policy for all file based resources. It would not be used
for file:///C:/app/bin/main.js unless "file:///" is set to cascade or is not
in the "scopes" of the policy.】
""
这决定了所有资源的策略。除非设置了 "file:" 来级联,否则不会用于 file:///C:/app/bin/main.js。
【This determines the policy for all resources. It would not be used for
file:///C:/app/bin/main.js unless "file:" is set to cascade.】
使用范围的完整性#>
【Integrity using scopes】
在作用域上将完整性设置为 true,将把清单中未找到的任何资源的完整性设置为 true。
【Setting an integrity to true on a scope will set the integrity for any
resource not found in the manifest to true.】
在作用域上将完整性设置为 null,将导致清单中未找到的任何资源匹配失败。
【Setting an integrity to null on a scope will set the integrity for any
resource not found in the manifest to fail matching.】
不包括完整性与将完整性设置为 null 是一样的。
【Not including an integrity is the same as setting the integrity to null.】
如果明确设置了"integrity",则用于完整性检查的"cascade"将被忽略。
以下示例允许加载任何文件:
【The following example allows loading any file:】
{
"scopes": {
"file:": {
"integrity": true
}
}
}
使用范围的依赖重定向#>
【Dependency redirection using scopes】
以下示例将允许访问 ./app/ 中的所有资源的 fs:
【The following example, would allow access to fs for all resources within
./app/:】
{
"resources": {
"./app/checked.js": {
"cascade": true,
"integrity": true
}
},
"scopes": {
"./app/": {
"dependencies": {
"fs": true
}
}
}
}
下面的示例将允许所有 data: 资源访问 fs:
【The following example, would allow access to fs for all data: resources:】
{
"resources": {
"data:text/javascript,import('node:fs');": {
"cascade": true,
"integrity": true
}
},
"scopes": {
"data:": {
"dependencies": {
"fs": true
}
}
}
}
示例:导入映射模拟#>
【Example: import maps emulation】
给定导入映射:
【Given an import map:】
{
"imports": {
"react": "./app/node_modules/react/index.js"
},
"scopes": {
"./ssr/": {
"react": "./app/node_modules/server-side-react/index.js"
}
}
}
{
"dependencies": true,
"scopes": {
"": {
"cascade": true,
"dependencies": {
"react": "./app/node_modules/react/index.js"
}
},
"./ssr/": {
"cascade": true,
"dependencies": {
"react": "./app/node_modules/server-side-react/index.js"
}
}
}
}
导入映射 假设你可以默认获取任何资源。这意味着策略顶层的 "dependencies" 应设置为 true。策略要求这是可选的,因为它会启用应用的所有资源的跨链接,这在许多场景下没有意义。它们还假设任何给定范围都可以访问其允许依赖之上的任何范围;所有模拟导入映射的范围必须设置 "cascade": true。
导入映射只有一个顶层作用域用于它们的“imports”。所以要模拟“imports”,请使用“”作用域。要模拟“scopes”,可以以类似于导入映射中“scopes”的方式使用“scopes”。
【Import maps only have a single top level scope for their "imports". So for
emulating "imports" use the "" scope. For emulating "scopes" use the
"scopes" in a similar manner to how "scopes" works in import maps.】
注意事项:策略不会对范围的各种查找使用字符串匹配。它们会进行 URL 遍历。这意味着像 blob: 和 data: 这样的 URL 在两个系统之间可能无法完全互操作。例如,导入映射可以通过在 / 字符处分割 URL 来部分匹配 data: 或 blob: URL,而策略则故意不能这样做。对于 blob: URL,导入映射范围不会采用 blob: URL 的源。
【Caveats: Policies do not use string matching for various finding of scope. They
do URL traversals. This means things like blob: and data: URLs might not be
entirely interoperable between the two systems. For example import maps can
partially match a data: or blob: URL by partitioning the URL on a /
character, policies intentionally cannot. For blob: URLs import map scopes do
not adopt the origin of the blob: URL.】
此外,导入地图只在“导入”状态下工作,因此可能需要添加一个 所有依赖映射的“导入”条件。
【Additionally, import maps only work on import so it may be desirable to add a
"import" condition to all dependency mappings.】