Node.js v18.16.0 文档


目录

异步钩子#

稳定性: 1 - 实验。 如果可以,请远离此 API。 我们不建议使用 createHookAsyncHookexecutionAsyncResource API,因为它们存在可用性问题、安全风险和性能影响。 稳定的 AsyncLocalStorage API 可以更好地服务于异步上下文跟踪用例。 如果您有 createHookAsyncHookexecutionAsyncResource 的用例,超出 AsyncLocalStorage 解决的上下文跟踪需求或 诊断通道 当前提供的诊断数据,请在 https://github.com/nodejs/node/issues 上打开一个问题来描述您的用例,以便我们可以创建一个更专注于目的的 API .

源代码: lib/async_hooks.js

我们强烈反对使用 async_hooks API。 其他可以涵盖其大部分用例的 API 包括:

node:async_hooks模块提供了 API 来跟踪异步的资源。 可以使用以下方式访问它:

import async_hooks from 'node:async_hooks';const async_hooks = require('node:async_hooks');

术语#

异步的资源表示具有关联回调的对象。 此回调可能会被多次调用,比如 net.createServer() 中的 'connection' 事件、或者像 fs.open() 一样只调用一次。 资源也可以在调用回调之前关闭。 AsyncHook 没有明确区分这些不同的情况,而是将它们表示为抽象的概念,即资源。

如果使用Worker,每个线程都有一个独立的async_hooks接口,每个线程都会使用一组新的async ID。

概述#

以下是公共 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)#

为每个异步操作的不同生命周期事件注册要调用的函数。

回调 init()/before()/after()/destroy() 在资源的生命周期内为相应的异步事件调用。

所有回调都是可选的。 比如,如果只需要跟踪资源清理,则只需要传入 destroy 回调。 可以传递给 callbacks 的所有函数的细节在 钩子回调 部分。

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) { },
});

回调将通过原型链继承:

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 的异步函数。

错误处理#

如果任何 AsyncHook 回调抛出,则应用程序将打印堆栈跟踪并退出。 退出路径确实遵循未捕获异常的路径,但所有 'uncaughtException' 监听器都被删除,从而强制进程退出。 除非应用程序使用 --abort-on-uncaught-exception 运行,否则仍将调用 'exit' 回调,在这种情况下,将打印堆栈跟踪并且应用程序退出,留下核心文件。

这种错误处理行为的原因是这些回调在对象生命周期中的潜在不稳定点运行,例如在类构造和销毁期间。 因此,认为有必要迅速关闭进程,以防止将来意外中止。 如果进行综合分析以确保异常可以遵循正常的控制流程而不会产生意外的副作用,这可能会在未来发生变化。

AsyncHook 回调中打印#

因为打印到控制台是异步的操作,所以 console.log() 会导致 AsyncHook 回调被调用。 在 AsyncHook 回调函数中使用 console.log() 或类似的异步操作将导致无限递归。 当调试时,一个简单的解决方案是使用同步的日志记录操作,例如 fs.writeFileSync(file, msg, flag)。 这将打印到文件并且不会递归地调用 AsyncHook,因为它是同步的。

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 回调时,应跳过日志记录。 通过这样做,否则无限递归被打破。

类:AsyncHook#

AsyncHook 类公开了一个用于跟踪异步操作的生命周期事件的接口。

asyncHook.enable()#

启用给定 AsyncHook 实例的回调。 如果没有提供回调,则启用是无操作的。

默认禁用 AsyncHook 实例。 如果 AsyncHook 实例应该在创建后立即启用,则可以使用以下模式。

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 实例的回调。 一旦一个钩子被禁用,则它在启用之前不会被再次调用。

为了 API 一致性,disable() 也返回 AsyncHook 实例。

钩子回调#

异步事件生命周期中的关键事件分为四个方面: 实例化,调用回调之前/之后,以及实例被销毁的时间。

init(asyncId, type, triggerAsyncId, resource)#
  • asyncId <number> 异步资源的唯一 ID。
  • type <string> 异步资源的类型。
  • triggerAsyncId <number> 在其执行上下文中创建此异步资源的异步资源的唯一 ID。
  • resource <Object> 对表示异步操作的资源的引用,需要在销毁期间释放。

在构造有可能触发异步事件的类时调用。 这并不意味着实例必须在调用 destroy 之前调用 before/after,只是存在这种可能性。

此行为可以通过打开资源然后在资源可以使用之前关闭它来观察。 以下代码片段演示了这一点。

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。

type#

type 是字符串,标识导致调用 init 的资源类型。 一般会对应资源的构造函数名。

由 Node.js 本身创建的 type 资源可以在任何 Node.js 版本中更改。 有效值包括 TLSWRAPTCPWRAPTCPSERVERWRAPGETADDRINFOREQWRAPFSREQCALLBACKMicrotaskTimeout。 检查用于获取完整列表的 Node.js 版本的源代码。

AsyncResource 的进一步用户创建独立于 Node.js 本身的异步资源。

还有 PROMISE 资源类型,用于跟踪 Promise 实例以及它们调度的异步工作。

用户可以在使用公共嵌入器 API 时定义自己的 type

可能存在类型名称冲突。 鼓励嵌入器使用唯一的前缀,例如 npm 包名,以防止在监听钩子时发生冲突。

triggerAsyncId#

triggerAsyncId 是导致(或 "triggered")新资源初始化并导致 init 调用的资源的 asyncId。 这不同于 async_hooks.executionAsyncId() 只显示资源创建时间,而 triggerAsyncId 显示资源创建原因。

下面是 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 访问服务器时的输出:

TCPSERVERWRAP(5): trigger: 1 execution: 1
TCPWRAP(7): trigger: 5 execution: 0 

TCPSERVERWRAP 是接收连接的服务器。

TCPWRAP 是来自客户端的新连接。 当建立新连接时,则立即构造 TCPWrap 实例。 这发生在任何 JavaScript 堆栈之外。 (0executionAsyncId() 表示其是从 C++ 执行的,上面没有 JavaScript 堆栈。)只有这些信息,就不可能将资源链接在一起,因为它们是什么导致它们被创建,所以 triggerAsyncId 被赋予传播什么资源对新资源的存在负责的任务。

resource#

resource 是一个对象,表示已初始化的实际异步资源。 访问对象的 API 可能由资源的创建者指定。 Node.js 本身创建的资源是内部的,可能随时更改。 因此没有为这些指定 API。

在某些情况下,出于性能原因,资源对象会被重用,因此将其用作 WeakMap 中的键或向其添加属性是不安全的。

异步上下文示例#

上下文跟踪用例包含在稳定的 API AsyncLocalStorage 中。 此示例仅说明异步钩子操作,但 AsyncLocalStorage 更适合此用例。

以下是一个示例,其中包含有关 beforeafter 调用之间对 init 的调用的附加信息,特别是对 listen() 的回调将是什么样子。 输出格式稍微复杂一点,使调用上下文更容易看到。

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);
}); 

仅启动服务器的输出:

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 各自指定当前执行上下文的值; 这是通过调用 beforeafter 来描述的。

仅使用 execution 绘制资源分配图结果如下:

  root(1)
     ^
     |
TickObject(6)
     ^
     |
 Timeout(7) 

TCPSERVERWRAP 不是这个图表的一部分,尽管它是调用 console.log() 的原因。 这是因为绑定到一个没有主机名的端口是一个同步操作,但是为了保持一个完全异步的 API,用户的回调被放在一个 process.nextTick() 中。 这就是 TickObject 出现在输出中并且是 .listen() 回调的 'parent' 的原因。

该图仅显示创建资源的时间,而不显示创建原因,因此要跟踪原因,请使用 triggerAsyncId。 可以用下图表示:

 bootstrap(1)
     |
     ˅
TCPSERVERWRAP(5)
     |
     ˅
 TickObject(6)
     |
     ˅
  Timeout(7) 

before(asyncId)#

当异步操作启动(如 TCP 服务器接收新连接)或完成(如将数据写入磁盘)时,会调用回调通知用户。 before 回调在所述回调执行之前被调用。 asyncId 是分配给即将执行回调的资源的唯一标识符。

before 回调将被调用 0 到 N 次。 如果异步操作被取消,或者例如,如果 TCP 服务器没有接收到连接,则 before 回调通常会被调用 0 次。 像 TCP 服务器这样的持久异步资源通常会多次调用 before 回调,而像 fs.open() 等其他操作只会调用一次。

after(asyncId)#

before 中指定的回调完成后立即调用。

如果在执行回调期间发生未捕获的异常,则 after 将在 'uncaughtException' 事件触发或 domain 的处理程序运行后运行。

destroy(asyncId)#

asyncId 对应的资源销毁后调用。 它也从嵌入器 API emitDestroy() 异步调用。

有些资源依赖垃圾回收来清理,所以如果引用传给 initresource 对象,可能永远不会调用 destroy,从而导致应用程序内存泄漏。 如果资源不依赖垃圾回收,则这不是问题。

使用销毁钩子会导致额外的开销,因为它可以通过垃圾收集器跟踪 Promise 实例。

promiseResolve(asyncId)#

当调用传给 Promise 构造函数的 resolve 函数时调用(直接或通过其他解决 promise 的方法)。

resolve() 不做任何可观察到的同步工作。

如果 Promise 是通过假设另一个 Promise 的状态来解决的,则此时 Promise 不一定满足或拒绝。

new Promise((resolve) => resolve(true)).then((a) => {}); 

调用以下回调:

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() 返回的资源对象通常是带有未记录 API 的内部 Node.js 句柄对象。 在对象上使用任何函数或属性都可能使您的应用程序崩溃,应该避免。

在顶层执行上下文中使用 executionAsyncResource() 将返回空的对象,因为没有要使用的句柄或请求对象,但是有一个代表顶层的对象可能会有所帮助。

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 来存储元数据:

import { createServer } from 'node:http';
import {
  executionAsyncId,
  executionAsyncResource,
  createHook,
} from '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
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
fs.open(path, 'r', (err, fd) => {
  console.log(async_hooks.executionAsyncId());  // 6 - open()
});

executionAsyncId() 返回的 ID 与执行时机有关,与因果无关(被 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 执行跟踪 部分。

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 执行跟踪 部分。

async_hooks.asyncWrapProviders#

  • 返回: 提供商类型到相应数字 ID 的映射。 此映射包含 async_hooks.init() 事件可能触发的所有事件类型。

此特性禁止使用 process.binding('async_wrap').Providers。 看: DEP0111

Promise 执行跟踪#

默认情况下,由于 V8 提供的 promise 自省 API 相对昂贵,因此不会为 promise 执行分配 asyncId。 这意味着默认情况下,使用 promise 或 async/await 的程序将无法正确执行并触发 promise 回调上下文的 id。

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() 回调被执行的资源的上下文。

通过 async_hooks.createHook 安装异步钩子启用 promise 执行跟踪:

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 触发。

promise 的另一个微妙之处是 beforeafter 回调仅在链式 promise 上运行。 这意味着不是由 then()/catch() 创建的 promise 不会触发 beforeafter 回调。 有关更多详细信息,请参阅 V8 PromiseHooks API 的详细信息。

JavaScript 嵌入器 API#

处理自己的异步资源执行 I/O、连接池或管理回调队列等任务的库开发者可以使用 AsyncResource JavaScript API 以便调用所有适当的回调。

类:AsyncResource#

该类的文档已移至 AsyncResource

类:AsyncLocalStorage#

该类的文档已移至 AsyncLocalStorage