- 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 v20.18.0 文档
- Node.js v20.18.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 域
- 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 压缩
- 其他版本
异步钩子#
¥Async hooks
createHook
、AsyncHook
和 executionAsyncResource
API,因为它们存在可用性问题、安全风险和性能影响。稳定的 AsyncLocalStorage
API 可以更好地服务于异步上下文跟踪用例。如果你有 createHook
、AsyncHook
或 executionAsyncResource
的用例,超出 AsyncLocalStorage
解决的上下文跟踪需求或 诊断通道 当前提供的诊断数据,请在 https://github.com/nodejs/node/issues 上打开一个问题来描述你的用例,以便我们可以创建一个更专注于目的的 API .¥Stability: 1 - Experimental. Please migrate away from this API, if you can.
We do not recommend using the createHook
, AsyncHook
, and
executionAsyncResource
APIs as they have usability issues, safety risks,
and performance implications. Async context tracking use cases are better
served by the stable AsyncLocalStorage
API. If you have a use case for
createHook
, AsyncHook
, or executionAsyncResource
beyond the context
tracking need solved by AsyncLocalStorage
or diagnostics data currently
provided by Diagnostics Channel, please open an issue at
https://github.com/nodejs/node/issues describing your use case so we can
create a more purpose-focused 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
跟踪异步上下文¥
AsyncLocalStorage
tracks async context -
process.getActiveResourcesInfo()
跟踪活动资源¥
process.getActiveResourcesInfo()
tracks active resources
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
接口,每个线程都会使用一组新的 async ID。
¥If Worker
s 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> The Hook Callbacks to register-
init
<Function>init
回调。¥
init
<Function> Theinit
callback. -
before
<Function>before
回调。¥
before
<Function> Thebefore
callback. -
after
<Function>after
回调。¥
after
<Function> Theafter
callback. -
destroy
<Function>destroy
回调。¥
destroy
<Function> Thedestroy
callback. -
promiseResolve
<Function>promiseResolve
回调。¥
promiseResolve
<Function> ThepromiseResolve
callback.
-
-
返回:<AsyncHook> 用于禁用和启用钩子的实例
¥Returns: <AsyncHook> Instance used for disabling and enabling hooks
为每个异步操作的不同生命周期事件注册要调用的函数。
¥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());
因为 promises 是异步资源,其生命周期通过异步钩子机制进行跟踪,所以 init()
、before()
、after()
和 destroy()
回调不能是返回 promises 的异步函数。
¥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
的引用。¥Returns: <AsyncHook> A reference to
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
的引用。¥Returns: <AsyncHook> A reference to
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。¥
asyncId
<number> A unique ID for the async resource. -
type
<string> 异步资源的类型。¥
type
<string> The type of the async resource. -
triggerAsyncId
<number> 在其执行上下文中创建此异步资源的异步资源的唯一 ID。¥
triggerAsyncId
<number> The unique ID of the async resource in whose execution context this async resource was created. -
resource
<Object> 对表示异步操作的资源的引用,需要在销毁期间释放。¥
resource
<Object> Reference to the resource representing the async operation, needs to be released during 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
是导致(或 "triggered")新资源初始化并导致 init
调用的资源的 asyncId
。这不同于 async_hooks.executionAsyncId()
只显示资源创建时间,而 triggerAsyncId
显示资源创建原因。
¥triggerAsyncId
is the asyncId
of the resource that caused (or "triggered")
the new resource to initialize and that caused init
to call. This is different
from async_hooks.executionAsyncId()
that only shows when a resource was
created, while triggerAsyncId
shows why a resource was created.
下面是 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。
¥resource
is an object that represents the actual async resource that has
been initialized. The API to access the object may be specified by the
creator of the resource. Resources created by Node.js itself are internal
and may change at any time. Therefore no API is specified for these.
在某些情况下,出于性能原因,资源对象会被重用,因此将其用作 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()
回调的 'parent' 的原因。
¥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.
使用销毁钩子会导致额外的开销,因为它可以通过垃圾收集器跟踪 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()
不做任何可观察到的同步工作。
¥resolve()
does not do any observable synchronous work.
如果 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> 代表当前执行的资源。用于在资源中存储数据。
¥Returns: <Object> The resource representing the current execution. Useful to store data within the resource.
executionAsyncResource()
返回的资源对象通常是带有未记录 API 的内部 Node.js 句柄对象。在对象上使用任何函数或属性都可能使你的应用崩溃,应该避免。
¥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
。当有调用时对跟踪很有用。¥Returns: <number> The
asyncId
of the current execution context. Useful to track when something calls.
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 执行跟踪 部分。
¥Promise contexts may not get precise executionAsyncIds
by default.
See the section on promise execution tracking.
async_hooks.triggerAsyncId()
#
-
返回:<number> 负责调用当前正在执行的回调的资源 ID。
¥Returns: <number> The ID of the resource responsible for calling the callback that is currently being executed.
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 执行跟踪 部分。
¥Promise contexts may not get valid triggerAsyncId
s by default. See
the section on promise execution tracking.
async_hooks.asyncWrapProviders
#
-
返回:提供商类型到相应数字 ID 的映射。此映射包含
async_hooks.init()
事件可能触发的所有事件类型。¥Returns: A map of provider types to the corresponding numeric id. This map contains all the event types that might be emitted by the
async_hooks.init()
event.
此特性禁止使用 process.binding('async_wrap').Providers
。看:DEP0111
¥This feature suppresses the deprecated usage of process.binding('async_wrap').Providers
.
See: DEP0111
Promise 执行跟踪#
¥Promise execution tracking
默认情况下,由于 V8 提供的 promise 自省 API 相对昂贵,因此不会为 promise 执行分配 asyncId
。这意味着默认情况下,使用 promise 或 async
/await
的程序将无法正确执行并触发 promise 回调上下文的 id。
¥By default, promise executions are not assigned asyncId
s 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 0
const { 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 6
const { 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 PromiseHooks 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
.