- 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 域
- env 环境变量
- 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.22.0 文档
- Node.js v22.22.0
- 目录
-
导航
- 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 域
- env 环境变量
- 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 单个可执行应用程序
- 其他版本
异步钩子#>
【Async hooks】
createHook、AsyncHook 和
executionAsyncResource API,因为它们存在可用性问题、安全风险和性能影响。异步上下文跟踪的使用场景更适合使用稳定的 AsyncLocalStorage API。如果你有使用 createHook、AsyncHook 或 executionAsyncResource 的需求,且超出了 AsyncLocalStorage 解决的上下文跟踪需求或 诊断通道 当前提供的诊断数据,请在 https://github.com/nodejs/node/issues 提交问题,描述你的使用场景,以便我们开发更有针对性的 API。源代码: lib/async_hooks.js
我们强烈不建议使用 async_hooks API。其他可以涵盖其大多数用例的 API 包括:
【We strongly discourage the use of the async_hooks API.
Other APIs that can cover most of its use cases include:】
AsyncLocalStorage跟踪异步上下文process.getActiveResourcesInfo()跟踪活动资源
node:async_hooks 模块提供了一个用于跟踪异步资源的 API。可以通过以下方式访问:
【The node:async_hooks module provides an API to track asynchronous resources.
It can be accessed using:】
import async_hooks from 'node:async_hooks';const async_hooks = require('node:async_hooks');
术语#>
【Terminology】
异步资源表示一个与回调关联的对象。这个回调可能会被多次调用,例如 net.createServer() 中的 'connection' 事件,或者只调用一次,例如 fs.open()。资源也可能在回调被调用之前就被关闭。AsyncHook 并不会明确区分这些不同的情况,而是将它们表示为资源这一抽象概念。
【An asynchronous resource represents an object with an associated callback.
This callback may be called multiple times, such as the 'connection'
event in net.createServer(), or just a single time like in fs.open().
A resource can also be closed before the callback is called. AsyncHook does
not explicitly distinguish between these different cases but will represent them
as the abstract concept that is a resource.】
如果使用 Worker,每个线程都有独立的 async_hooks 接口,并且每个线程将使用一组新的异步 ID。
【If Workers are used, each thread has an independent async_hooks
interface, and each thread will use a new set of async IDs.】
概述#>
【Overview】
以下是公共 API 的简单概述。
【Following is a simple overview of the public API.】
import async_hooks from 'node:async_hooks';
// Return the ID of the current execution context.
const eid = async_hooks.executionAsyncId();
// Return the ID of the handle responsible for triggering the callback of the
// current execution scope to call.
const tid = async_hooks.triggerAsyncId();
// Create a new AsyncHook instance. All of these callbacks are optional.
const asyncHook =
async_hooks.createHook({ init, before, after, destroy, promiseResolve });
// Allow callbacks of this AsyncHook instance to call. This is not an implicit
// action after running the constructor, and must be explicitly run to begin
// executing callbacks.
asyncHook.enable();
// Disable listening for new asynchronous events.
asyncHook.disable();
//
// The following are the callbacks that can be passed to createHook().
//
// init() is called during object construction. The resource may not have
// completed construction when this callback runs. Therefore, all fields of the
// resource referenced by "asyncId" may not have been populated.
function init(asyncId, type, triggerAsyncId, resource) { }
// before() is called just before the resource's callback is called. It can be
// called 0-N times for handles (such as TCPWrap), and will be called exactly 1
// time for requests (such as FSReqCallback).
function before(asyncId) { }
// after() is called just after the resource's callback has finished.
function after(asyncId) { }
// destroy() is called when the resource is destroyed.
function destroy(asyncId) { }
// promiseResolve() is called only for promise resources, when the
// resolve() function passed to the Promise constructor is invoked
// (either directly or through other means of resolving a promise).
function promiseResolve(asyncId) { }const async_hooks = require('node:async_hooks');
// Return the ID of the current execution context.
const eid = async_hooks.executionAsyncId();
// Return the ID of the handle responsible for triggering the callback of the
// current execution scope to call.
const tid = async_hooks.triggerAsyncId();
// Create a new AsyncHook instance. All of these callbacks are optional.
const asyncHook =
async_hooks.createHook({ init, before, after, destroy, promiseResolve });
// Allow callbacks of this AsyncHook instance to call. This is not an implicit
// action after running the constructor, and must be explicitly run to begin
// executing callbacks.
asyncHook.enable();
// Disable listening for new asynchronous events.
asyncHook.disable();
//
// The following are the callbacks that can be passed to createHook().
//
// init() is called during object construction. The resource may not have
// completed construction when this callback runs. Therefore, all fields of the
// resource referenced by "asyncId" may not have been populated.
function init(asyncId, type, triggerAsyncId, resource) { }
// before() is called just before the resource's callback is called. It can be
// called 0-N times for handles (such as TCPWrap), and will be called exactly 1
// time for requests (such as FSReqCallback).
function before(asyncId) { }
// after() is called just after the resource's callback has finished.
function after(asyncId) { }
// destroy() is called when the resource is destroyed.
function destroy(asyncId) { }
// promiseResolve() is called only for promise resources, when the
// resolve() function passed to the Promise constructor is invoked
// (either directly or through other means of resolving a promise).
function promiseResolve(asyncId) { }
async_hooks.createHook(callbacks)#>
callbacks<Object> 用于注册 钩子回调init<Function> 这个init回调。before<Function> 这个before回调。after<Function> 这个after回调。destroy<Function> 摧毁destroy回调。promiseResolve<Function> 这个promiseResolve回调。
- 返回:用于禁用和启用钩子的 <AsyncHook> 实例
注册函数,以在每个异步操作的不同生命周期事件中调用。
【Registers functions to be called for different lifetime events of each async operation.】
在资源的生命周期内,针对相应的异步事件会调用回调函数 init()/before()/after()/destroy()。
【The callbacks init()/before()/after()/destroy() are called for the
respective asynchronous event during a resource's lifetime.】
所有回调都是可选的。例如,如果只需要跟踪资源清理,那么只需要传入 destroy 回调即可。可以传递给 callbacks 的所有函数的具体信息在 钩子回调 部分。
【All callbacks are optional. For example, if only resource cleanup needs to
be tracked, then only the destroy callback needs to be passed. The
specifics of all functions that can be passed to callbacks is in the
Hook Callbacks section.】
import { createHook } from 'node:async_hooks';
const asyncHook = createHook({
init(asyncId, type, triggerAsyncId, resource) { },
destroy(asyncId) { },
});const async_hooks = require('node:async_hooks');
const asyncHook = async_hooks.createHook({
init(asyncId, type, triggerAsyncId, resource) { },
destroy(asyncId) { },
});
回调将通过原型链继承:
【The callbacks will be inherited via the prototype chain:】
class MyAsyncCallbacks {
init(asyncId, type, triggerAsyncId, resource) { }
destroy(asyncId) {}
}
class MyAddedCallbacks extends MyAsyncCallbacks {
before(asyncId) { }
after(asyncId) { }
}
const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
因为 Promise 是异步资源,其生命周期是通过 async hooks 机制跟踪的,所以 init()、before()、after() 和 destroy() 回调 不能 是返回 Promise 的异步函数。
【Because promises are asynchronous resources whose lifecycle is tracked
via the async hooks mechanism, the init(), before(), after(), and
destroy() callbacks must not be async functions that return promises.】
错误处理#>
【Error handling】
如果任何 AsyncHook 回调抛出异常,应用将打印堆栈跟踪并退出。退出路径确实与未捕获异常的路径相同,但所有 'uncaughtException' 监听器都已被移除,因此强制进程退出。除非应用使用 --abort-on-uncaught-exception 运行,否则 'exit' 回调仍会被调用,在这种情况下,会打印堆栈跟踪并应用退出,同时生成核心文件。
【If any AsyncHook callbacks throw, the application will print the stack trace
and exit. The exit path does follow that of an uncaught exception, but
all 'uncaughtException' listeners are removed, thus forcing the process to
exit. The 'exit' callbacks will still be called unless the application is run
with --abort-on-uncaught-exception, in which case a stack trace will be
printed and the application exits, leaving a core file.】
这种错误处理行为的原因是,这些回调可能在对象生命周期中不稳定的时刻运行,例如在类的构造和析构过程中。因此,被认为有必要迅速终止进程,以防止将来发生意外中止。如果将来进行全面分析以确保异常可以在不产生意外副作用的情况下遵循正常的控制流程,这种行为可能会发生变化。
【The reason for this error handling behavior is that these callbacks are running at potentially volatile points in an object's lifetime, for example during class construction and destruction. Because of this, it is deemed necessary to bring down the process quickly in order to prevent an unintentional abort in the future. This is subject to change in the future if a comprehensive analysis is performed to ensure an exception can follow the normal control flow without unintentional side effects.】
AsyncHook 回调中的打印#>
【Printing in AsyncHook callbacks】
因为向控制台打印是一个异步操作,console.log() 会导致 AsyncHook 回调被调用。在 AsyncHook 回调函数中使用 console.log() 或类似的异步操作会导致无限递归。在调试时,一个简单的解决方法是使用同步的日志操作,例如 fs.writeFileSync(file, msg, flag)。这将把内容打印到文件中,并且不会递归调用 AsyncHook,因为它是同步的。
【Because printing to the console is an asynchronous operation, console.log()
will cause AsyncHook callbacks to be called. Using console.log() or
similar asynchronous operations inside an AsyncHook callback function will
cause an infinite recursion. An easy solution to this when debugging is to use a
synchronous logging operation such as fs.writeFileSync(file, msg, flag).
This will print to the file and will not invoke AsyncHook recursively because
it is synchronous.】
import { writeFileSync } from 'node:fs';
import { format } from 'node:util';
function debug(...args) {
// Use a function like this one when debugging inside an AsyncHook callback
writeFileSync('log.out', `${format(...args)}\n`, { flag: 'a' });
}const fs = require('node:fs');
const util = require('node:util');
function debug(...args) {
// Use a function like this one when debugging inside an AsyncHook callback
fs.writeFileSync('log.out', `${util.format(...args)}\n`, { flag: 'a' });
}
如果日志记录需要异步操作,可以使用 AsyncHook 本身提供的信息来跟踪导致异步操作的原因。当触发 AsyncHook 回调的是日志操作本身时,应跳过日志记录。通过这样做,可以打破原本无限的递归。
【If an asynchronous operation is needed for logging, it is possible to keep
track of what caused the asynchronous operation using the information
provided by AsyncHook itself. The logging should then be skipped when
it was the logging itself that caused the AsyncHook callback to be called. By
doing this, the otherwise infinite recursion is broken.】
类:AsyncHook#>
【Class: AsyncHook】
类 AsyncHook 提供了一个用于跟踪异步操作生命周期事件的接口。
【The class AsyncHook exposes an interface for tracking lifetime events
of asynchronous operations.】
asyncHook.enable()#>
- 返回:<AsyncHook> 对
asyncHook的引用。
为给定的 AsyncHook 实例启用回调。如果未提供回调,则启用操作不会产生任何效果。
【Enable the callbacks for a given AsyncHook instance. If no callbacks are
provided, enabling is a no-op.】
AsyncHook 实例默认是禁用的。如果希望在创建后立即启用 AsyncHook 实例,可以使用以下模式。
【The AsyncHook instance is disabled by default. If the AsyncHook instance
should be enabled immediately after creation, the following pattern can be used.】
import { createHook } from 'node:async_hooks';
const hook = createHook(callbacks).enable();const async_hooks = require('node:async_hooks');
const hook = async_hooks.createHook(callbacks).enable();
asyncHook.disable()#>
- 返回:<AsyncHook> 对
asyncHook的引用。
禁用给定 AsyncHook 实例的回调,使其不会从全局 AsyncHook 回调池中执行。一旦钩子被禁用,它将不会再次被调用,直到重新启用。
【Disable the callbacks for a given AsyncHook instance from the global pool of
AsyncHook callbacks to be executed. Once a hook has been disabled it will not
be called again until enabled.】
为了 API 一致性,disable() 也会返回 AsyncHook 实例。
【For API consistency disable() also returns the AsyncHook instance.】
钩子回调#>
【Hook callbacks】
异步事件生命周期中的关键事件已被归类为四个方面:实例化、回调调用前/后以及实例被销毁时。
【Key events in the lifetime of asynchronous events have been categorized into four areas: instantiation, before/after the callback is called, and when the instance is destroyed.】
init(asyncId, type, triggerAsyncId, resource)#>
asyncId<number> 异步资源的唯一 ID。type<string> 异步资源的类型。triggerAsyncId<number> 该异步资源所在的执行上下文中创建的异步资源的唯一ID。resource<Object> 指向表示异步操作的资源的引用,需要在 destroy 期间释放。
当构造一个有可能触发异步事件的类时调用。这并不意味着实例必须在调用 destroy 之前调用 before/after,只是表示存在这种可能性。
【Called when a class is constructed that has the possibility to emit an
asynchronous event. This does not mean the instance must call
before/after before destroy is called, only that the possibility
exists.】
这种行为可以通过执行类似打开一个资源然后在使用该资源之前关闭它的操作来观察。以下代码片段演示了这一点。
【This behavior can be observed by doing something like opening a resource then closing it before the resource can be used. The following snippet demonstrates this.】
import { createServer } from 'node:net';
createServer().listen(function() { this.close(); });
// OR
clearTimeout(setTimeout(() => {}, 10));require('node:net').createServer().listen(function() { this.close(); });
// OR
clearTimeout(setTimeout(() => {}, 10));
每个新资源都会被分配一个在当前 Node.js 实例范围内唯一的 ID。
【Every new resource is assigned an ID that is unique within the scope of the current Node.js instance.】
type#>
type 是一个字符串,用于标识导致调用 init 的资源类型。通常,它会对应于该资源构造函数的名称。
【The type is a string identifying the type of resource that caused
init to be called. Generally, it will correspond to the name of the
resource's constructor.】
Node.js 本身创建的资源的 type 可以在任何 Node.js 版本中发生变化。有效值包括 TLSWRAP、TCPWRAP、TCPSERVERWRAP、GETADDRINFOREQWRAP、FSREQCALLBACK、Microtask 和 Timeout。请检查所使用 Node.js 版本的源代码以获取完整列表。
【The type of resources created by Node.js itself can change in any Node.js
release. Valid values include TLSWRAP,
TCPWRAP, TCPSERVERWRAP, GETADDRINFOREQWRAP, FSREQCALLBACK,
Microtask, and Timeout. Inspect the source code of the Node.js version used
to get the full list.】
此外,AsyncResource 的用户可以创建独立于 Node.js 本身的异步资源。
【Furthermore users of AsyncResource create async resources independent
of Node.js itself.】
还有一种 PROMISE 资源类型,用于跟踪 Promise 实例及其安排的异步工作。
【There is also the PROMISE resource type, which is used to track Promise
instances and asynchronous work scheduled by them.】
用户在使用公共嵌入器 API 时能够定义自己的 type。
【Users are able to define their own type when using the public embedder API.】
类型名称可能会发生冲突。建议使用者使用唯一前缀,例如 npm 包名,以防在监听钩子时发生冲突。
【It is possible to have type name collisions. Embedders are encouraged to use unique prefixes, such as the npm package name, to prevent collisions when listening to the hooks.】
triggerAsyncId#>
triggerAsyncId 是导致(或“触发”)新资源初始化并调用 init 的资源的 asyncId。这不同于 async_hooks.executionAsyncId(),后者只显示资源 何时 被创建,而 triggerAsyncId 显示的是资源被创建的 原因。
下面是一个关于 triggerAsyncId 的简单演示:
【The following is a simple demonstration of triggerAsyncId:】
import { createHook, executionAsyncId } from 'node:async_hooks';
import { stdout } from 'node:process';
import net from 'node:net';
import fs from 'node:fs';
createHook({
init(asyncId, type, triggerAsyncId) {
const eid = executionAsyncId();
fs.writeSync(
stdout.fd,
`${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
},
}).enable();
net.createServer((conn) => {}).listen(8080);const { createHook, executionAsyncId } = require('node:async_hooks');
const { stdout } = require('node:process');
const net = require('node:net');
const fs = require('node:fs');
createHook({
init(asyncId, type, triggerAsyncId) {
const eid = executionAsyncId();
fs.writeSync(
stdout.fd,
`${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
},
}).enable();
net.createServer((conn) => {}).listen(8080);
使用 nc localhost 8080 连接服务器时的输出:
【Output when hitting the server with nc localhost 8080:】
TCPSERVERWRAP(5): trigger: 1 execution: 1
TCPWRAP(7): trigger: 5 execution: 0
TCPSERVERWRAP 是接收连接的服务器。
【The TCPSERVERWRAP is the server which receives the connections.】
TCPWRAP 是来自客户端的新连接。当建立新连接时,TCPWrap 实例会立即被构建。这发生在任何 JavaScript 调用栈之外。(executionAsyncId() 为 0 表示它是在 C++ 中执行的,且上面没有 JavaScript 调用栈。)仅凭这些信息,是不可能将资源与其创建的原因关联起来的,因此 triggerAsyncId 被赋予了传播哪个资源负责新资源存在的任务。
【The TCPWRAP is the new connection from the client. When a new
connection is made, the TCPWrap instance is immediately constructed. This
happens outside of any JavaScript stack. (An executionAsyncId() of 0 means
that it is being executed from C++ with no JavaScript stack above it.) With only
that information, it would be impossible to link resources together in
terms of what caused them to be created, so triggerAsyncId is given the task
of propagating what resource is responsible for the new resource's existence.】
resource#>
resource 是一个表示已初始化的实际异步资源的对象。访问该对象的 API 可能由资源的创建者指定。由 Node.js 本身创建的资源是内部资源,可能随时发生变化。因此,这些资源没有指定的 API。
在某些情况下,出于性能原因会重用资源对象,因此将其用作 WeakMap 的键或向其添加属性是不安全的。
【In some cases the resource object is reused for performance reasons, it is
thus not safe to use it as a key in a WeakMap or add properties to it.】
异步上下文示例#>
【Asynchronous context example】
上下文跟踪用例由稳定的 API AsyncLocalStorage 覆盖。这个例子仅说明异步钩子的操作,但 AsyncLocalStorage 更适合这个用例。
【The context tracking use case is covered by the stable API AsyncLocalStorage.
This example only illustrates async hooks operation but AsyncLocalStorage
fits better to this use case.】
以下是一个示例,提供了有关在 before 和 after 调用之间对 init 的调用的附加信息,特别是 listen() 的回调将是什么样子。输出格式稍微复杂一些,以便更容易看到调用上下文。
【The following is an example with additional information about the calls to
init between the before and after calls, specifically what the
callback to listen() will look like. The output formatting is slightly more
elaborate to make calling context easier to see.】
import async_hooks from 'node:async_hooks';
import fs from 'node:fs';
import net from 'node:net';
import { stdout } from 'node:process';
const { fd } = stdout;
let indent = 0;
async_hooks.createHook({
init(asyncId, type, triggerAsyncId) {
const eid = async_hooks.executionAsyncId();
const indentStr = ' '.repeat(indent);
fs.writeSync(
fd,
`${indentStr}${type}(${asyncId}):` +
` trigger: ${triggerAsyncId} execution: ${eid}\n`);
},
before(asyncId) {
const indentStr = ' '.repeat(indent);
fs.writeSync(fd, `${indentStr}before: ${asyncId}\n`);
indent += 2;
},
after(asyncId) {
indent -= 2;
const indentStr = ' '.repeat(indent);
fs.writeSync(fd, `${indentStr}after: ${asyncId}\n`);
},
destroy(asyncId) {
const indentStr = ' '.repeat(indent);
fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\n`);
},
}).enable();
net.createServer(() => {}).listen(8080, () => {
// Let's wait 10ms before logging the server started.
setTimeout(() => {
console.log('>>>', async_hooks.executionAsyncId());
}, 10);
});const async_hooks = require('node:async_hooks');
const fs = require('node:fs');
const net = require('node:net');
const { fd } = process.stdout;
let indent = 0;
async_hooks.createHook({
init(asyncId, type, triggerAsyncId) {
const eid = async_hooks.executionAsyncId();
const indentStr = ' '.repeat(indent);
fs.writeSync(
fd,
`${indentStr}${type}(${asyncId}):` +
` trigger: ${triggerAsyncId} execution: ${eid}\n`);
},
before(asyncId) {
const indentStr = ' '.repeat(indent);
fs.writeSync(fd, `${indentStr}before: ${asyncId}\n`);
indent += 2;
},
after(asyncId) {
indent -= 2;
const indentStr = ' '.repeat(indent);
fs.writeSync(fd, `${indentStr}after: ${asyncId}\n`);
},
destroy(asyncId) {
const indentStr = ' '.repeat(indent);
fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\n`);
},
}).enable();
net.createServer(() => {}).listen(8080, () => {
// Let's wait 10ms before logging the server started.
setTimeout(() => {
console.log('>>>', async_hooks.executionAsyncId());
}, 10);
});
仅启动服务器的输出:
【Output from only starting the server:】
TCPSERVERWRAP(5): trigger: 1 execution: 1
TickObject(6): trigger: 5 execution: 1
before: 6
Timeout(7): trigger: 6 execution: 6
after: 6
destroy: 6
before: 7
>>> 7
TickObject(8): trigger: 7 execution: 7
after: 7
before: 8
after: 8
如示例所示,executionAsyncId() 和 execution 各自指定当前执行上下文的值;该上下文由对 before 和 after 的调用来划定。
【As illustrated in the example, executionAsyncId() and execution each specify
the value of the current execution context; which is delineated by calls to
before and after.】
仅使用 execution 来绘制资源分配会产生以下结果:
【Only using execution to graph resource allocation results in the following:】
root(1)
^
|
TickObject(6)
^
|
Timeout(7)
TCPSERVERWRAP 并不是这个图的一部分,尽管它是 console.log() 被调用的原因。这是因为绑定到一个没有主机名的端口是一个同步操作,但为了保持完全异步的 API,用户的回调被放在 process.nextTick() 中。这就是为什么输出中会出现 TickObject,并且它是 .listen() 回调的“父级”。
【The TCPSERVERWRAP is not part of this graph, even though it was the reason for
console.log() being called. This is because binding to a port without a host
name is a synchronous operation, but to maintain a completely asynchronous
API the user's callback is placed in a process.nextTick(). Which is why
TickObject is present in the output and is a 'parent' for .listen()
callback.】
该图仅显示资源的创建时间,而不显示原因,因此要追踪原因,请使用 triggerAsyncId。其可以用以下图表示:
【The graph only shows when a resource was created, not why, so to track
the why use triggerAsyncId. Which can be represented with the following
graph:】
bootstrap(1)
|
˅
TCPSERVERWRAP(5)
|
˅
TickObject(6)
|
˅
Timeout(7)
before(asyncId)#>
asyncId<number>
当启动异步操作(例如 TCP 服务器接收新连接)或异步操作完成(例如将数据写入磁盘)时,会调用回调函数来通知用户。before 回调会在该回调执行之前调用。asyncId 是分配给即将执行回调的资源的唯一标识符。
【When an asynchronous operation is initiated (such as a TCP server receiving a
new connection) or completes (such as writing data to disk) a callback is
called to notify the user. The before callback is called just before said
callback is executed. asyncId is the unique identifier assigned to the
resource about to execute the callback.】
before 回调会被调用 0 到 N 次。如果异步操作被取消,或者例如 TCP 服务器没有收到任何连接,before 回调通常会被调用 0 次。持久的异步资源(如 TCP 服务器)通常会多次调用 before 回调,而其他操作(如 fs.open())只会调用一次。
【The before callback will be called 0 to N times. The before callback
will typically be called 0 times if the asynchronous operation was cancelled
or, for example, if no connections are received by a TCP server. Persistent
asynchronous resources like a TCP server will typically call the before
callback multiple times, while other operations like fs.open() will call
it only once.】
after(asyncId)#>
asyncId<number>
在 before 中指定的回调完成后立即调用。
【Called immediately after the callback specified in before is completed.】
如果在回调执行期间发生未捕获的异常,那么 after 会在 'uncaughtException' 事件被触发或者 domain 的处理程序运行之后执行。
【If an uncaught exception occurs during execution of the callback, then after
will run after the 'uncaughtException' event is emitted or a domain's
handler runs.】
destroy(asyncId)#>
asyncId<number>
在与 asyncId 对应的资源被销毁后调用。它也会异步地从嵌入器 API emitDestroy() 调用。
【Called after the resource corresponding to asyncId is destroyed. It is also
called asynchronously from the embedder API emitDestroy().】
有些资源依赖垃圾回收来进行清理,因此如果对传递给 init 的 resource 对象进行了引用,destroy 可能永远不会被调用,从而导致应用的内存泄漏。如果该资源不依赖垃圾回收,那么这就不会成为问题。
【Some resources depend on garbage collection for cleanup, so if a reference is
made to the resource object passed to init it is possible that destroy
will never be called, causing a memory leak in the application. If the resource
does not depend on garbage collection, then this will not be an issue.】
使用 destroy 钩子会导致额外的开销,因为它使垃圾回收器能够追踪 Promise 实例。
【Using the destroy hook results in additional overhead because it enables
tracking of Promise instances via the garbage collector.】
promiseResolve(asyncId)#>
asyncId<number>
当传递给 Promise 构造函数的 resolve 函数被调用时(无论是直接调用还是通过其他方式解决 promise)会被调用。
【Called when the resolve function passed to the Promise constructor is
invoked (either directly or through other means of resolving a promise).】
resolve() 不会执行任何可观察的同步工作。
如果 Promise 是通过采用另一个 Promise 的状态来解析的,那么此时该 Promise 不一定会被兑现或拒绝。
【The Promise is not necessarily fulfilled or rejected at this point if the
Promise was resolved by assuming the state of another Promise.】
new Promise((resolve) => resolve(true)).then((a) => {});
调用以下回调:
【calls the following callbacks:】
init for PROMISE with id 5, trigger id: 1
promise resolve 5 # corresponds to resolve(true)
init for PROMISE with id 6, trigger id: 5 # the Promise returned by then()
before 6 # the then() callback is entered
promise resolve 6 # the then() callback resolves the promise by returning
after 6
async_hooks.executionAsyncResource()#>
- 返回:<Object> 表示当前执行的资源。可用于在资源中存储数据。
executionAsyncResource() 返回的资源对象大多是内部的 Node.js 句柄对象,具有未记录的 API。在这些对象上使用任何函数或属性很可能会导致应用崩溃,应避免这样做。
【Resource objects returned by executionAsyncResource() are most often internal
Node.js handle objects with undocumented APIs. Using any functions or properties
on the object is likely to crash your application and should be avoided.】
在顶层执行上下文中使用 executionAsyncResource() 将返回一个空对象,因为没有可用的句柄或请求对象,但拥有一个表示顶层的对象可能是有用的。
【Using executionAsyncResource() in the top-level execution context will
return an empty object as there is no handle or request object to use,
but having an object representing the top-level can be helpful.】
import { open } from 'node:fs';
import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
open(new URL(import.meta.url), 'r', (err, fd) => {
console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
});const { open } = require('node:fs');
const { executionAsyncId, executionAsyncResource } = require('node:async_hooks');
console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
open(__filename, 'r', (err, fd) => {
console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
});
这可以用来实现连续本地存储,而无需使用跟踪 Map 来存储元数据:
【This can be used to implement continuation local storage without the
use of a tracking Map to store the metadata:】
import { createServer } from 'node:http';
import {
executionAsyncId,
executionAsyncResource,
createHook,
} from 'node:async_hooks';
const sym = Symbol('state'); // Private symbol to avoid pollution
createHook({
init(asyncId, type, triggerAsyncId, resource) {
const cr = executionAsyncResource();
if (cr) {
resource[sym] = cr[sym];
}
},
}).enable();
const server = createServer((req, res) => {
executionAsyncResource()[sym] = { state: req.url };
setTimeout(function() {
res.end(JSON.stringify(executionAsyncResource()[sym]));
}, 100);
}).listen(3000);const { createServer } = require('node:http');
const {
executionAsyncId,
executionAsyncResource,
createHook,
} = require('node:async_hooks');
const sym = Symbol('state'); // Private symbol to avoid pollution
createHook({
init(asyncId, type, triggerAsyncId, resource) {
const cr = executionAsyncResource();
if (cr) {
resource[sym] = cr[sym];
}
},
}).enable();
const server = createServer((req, res) => {
executionAsyncResource()[sym] = { state: req.url };
setTimeout(function() {
res.end(JSON.stringify(executionAsyncResource()[sym]));
}, 100);
}).listen(3000);
async_hooks.executionAsyncId()#>
- 返回值:<number> 当前执行上下文的
asyncId。用于追踪某个调用发生的时间。
import { executionAsyncId } from 'node:async_hooks';
import fs from 'node:fs';
console.log(executionAsyncId()); // 1 - bootstrap
const path = '.';
fs.open(path, 'r', (err, fd) => {
console.log(executionAsyncId()); // 6 - open()
});const async_hooks = require('node:async_hooks');
const fs = require('node:fs');
console.log(async_hooks.executionAsyncId()); // 1 - bootstrap
const path = '.';
fs.open(path, 'r', (err, fd) => {
console.log(async_hooks.executionAsyncId()); // 6 - open()
});
executionAsyncId() 返回的 ID 与执行时机相关,而不是因果关系(因果关系由 triggerAsyncId() 覆盖):
【The ID returned from executionAsyncId() is related to execution timing, not
causality (which is covered by triggerAsyncId()):】
const server = net.createServer((conn) => {
// Returns the ID of the server, not of the new connection, because the
// callback runs in the execution scope of the server's MakeCallback().
async_hooks.executionAsyncId();
}).listen(port, () => {
// Returns the ID of a TickObject (process.nextTick()) because all
// callbacks passed to .listen() are wrapped in a nextTick().
async_hooks.executionAsyncId();
});
默认情况下,Promise 上下文可能无法获得精确的 executionAsyncIds。请参阅 承诺执行跟踪 部分。
【Promise contexts may not get precise executionAsyncIds by default.
See the section on promise execution tracking.】
async_hooks.triggerAsyncId()#>
- 返回值:<number> 当前正在执行的回调函数所对应的资源 ID。
const server = net.createServer((conn) => {
// The resource that caused (or triggered) this callback to be called
// was that of the new connection. Thus the return value of triggerAsyncId()
// is the asyncId of "conn".
async_hooks.triggerAsyncId();
}).listen(port, () => {
// Even though all callbacks passed to .listen() are wrapped in a nextTick()
// the callback itself exists because the call to the server's .listen()
// was made. So the return value would be the ID of the server.
async_hooks.triggerAsyncId();
});
Promise 上下文默认可能无法获得有效的 triggerAsyncId。请参阅 承诺执行跟踪 部分。
【Promise contexts may not get valid triggerAsyncIds by default. See
the section on promise execution tracking.】
async_hooks.asyncWrapProviders#>
- 返回值:一个将提供者类型映射到对应数字 ID 的映射。该映射包含可能由
async_hooks.init()事件发出的所有事件类型。
此功能会抑制 process.binding('async_wrap').Providers 的弃用用法。
参见:DEP0111
【This feature suppresses the deprecated usage of process.binding('async_wrap').Providers.
See: DEP0111】
Promise 执行跟踪#>
【Promise execution tracking】
默认情况下,promise 执行不会被分配 asyncId,因为 V8 提供的 承诺内省 API 相对开销较大。这意味着使用 promise 或 async/await 的程序默认情况下不会获得正确的执行和触发 id 对于 promise 回调上下文。
【By default, promise executions are not assigned asyncIds due to the relatively
expensive nature of the promise introspection API provided by
V8. This means that programs using promises or async/await will not get
correct execution and trigger ids for promise callback contexts by default.】
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
Promise.resolve(1729).then(() => {
console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
});
// produces:
// eid 1 tid 0const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');
Promise.resolve(1729).then(() => {
console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
});
// produces:
// eid 1 tid 0
请注意,then() 回调声称是在外部作用域的上下文中执行的,即使其中涉及异步跳转。此外,triggerAsyncId 的值为 0,这意味着我们缺少关于导致(触发)then() 回调执行的资源的上下文信息。
【Observe that the then() callback claims to have executed in the context of the
outer scope even though there was an asynchronous hop involved. Also,
the triggerAsyncId value is 0, which means that we are missing context about
the resource that caused (triggered) the then() callback to be executed.】
通过 async_hooks.createHook 安装异步钩子可以启用对 Promise 执行的跟踪:
【Installing async hooks via async_hooks.createHook enables promise execution
tracking:】
import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
Promise.resolve(1729).then(() => {
console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
});
// produces:
// eid 7 tid 6const { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
Promise.resolve(1729).then(() => {
console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
});
// produces:
// eid 7 tid 6
在这个例子中,添加任何实际的钩子函数都可以启用对 Promise 的跟踪。上面的例子中有两个 Promise:一个是由 Promise.resolve() 创建的 Promise,另一个是 then() 调用返回的 Promise。在上面的例子中,第一个 Promise 得到了 asyncId 6,后一个得到了 asyncId 7。在执行 then() 回调期间,我们是在 asyncId 为 7 的 Promise 上下文中执行的。这个 Promise 是由异步资源 6 触发的。
【In this example, adding any actual hook function enabled the tracking of
promises. There are two promises in the example above; the promise created by
Promise.resolve() and the promise returned by the call to then(). In the
example above, the first promise got the asyncId 6 and the latter got
asyncId 7. During the execution of the then() callback, we are executing
in the context of promise with asyncId 7. This promise was triggered by
async resource 6.】
关于 Promise 的另一个微妙之处是,before 和 after 回调只会在链式 Promise 上运行。这意味着不是通过 then()/catch() 创建的 Promise 不会触发其 before 和 after 回调。更多详细信息请参阅 V8 Promise钩子 API 的相关说明。
【Another subtlety with promises is that before and after callbacks are run
only on chained promises. That means promises not created by then()/catch()
will not have the before and after callbacks fired on them. For more details
see the details of the V8 PromiseHooks API.】
JavaScript 嵌入器 API#>
【JavaScript embedder API】
处理自身异步资源(如执行 I/O、连接池管理或管理回调队列)的库开发者可以使用 AsyncResource JavaScript API,以确保所有适当的回调都被调用。
【Library developers that handle their own asynchronous resources performing tasks
like I/O, connection pooling, or managing callback queues may use the
AsyncResource JavaScript API so that all the appropriate callbacks are called.】
类:AsyncResource#>
【Class: AsyncResource】
此类的文档已移至 AsyncResource。
【The documentation for this class has moved AsyncResource.】
类:AsyncLocalStorage#>
【Class: AsyncLocalStorage】
此类的文档已移至 AsyncLocalStorage。
【The documentation for this class has moved AsyncLocalStorage.】