{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.0.json","id":"async_hooks","path":"/async_hooks","type":"module","module":"async_hooks","title":"Async hooks","introducedIn":"v8.1.0","sourceLink":{"path":"lib/async_hooks.js","url":"https://github.com/nodejs/node/blob/HEAD/lib/async_hooks.js"},"stability":{"index":"1","description":"Experimental. Please migrate away from this API, if you can.\nWe do not recommend using the [`createHook`](#async_hookscreatehookoptions), [`AsyncHook`](#class-asynchook), and\n[`executionAsyncResource`](#async_hooksexecutionasyncresource) APIs as they have usability issues, safety risks,\nand performance implications. Async context tracking use cases are better\nserved by the stable [`AsyncLocalStorage`](async_context.html#class-asynclocalstorage) API. If you have a use case for\n`createHook`, `AsyncHook`, or `executionAsyncResource` beyond the context\ntracking need solved by [`AsyncLocalStorage`](async_context.html#class-asynclocalstorage) or diagnostics data currently\nprovided by [Diagnostics Channel](diagnostics_channel.html), please open an issue at\n<https://github.com/nodejs/node/issues> describing your use case so we can\ncreate a more purpose-focused API."},"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"We strongly discourage the use of the `async_hooks` API.\nOther APIs that can cover most of its use cases include:\n\n* [`AsyncLocalStorage`](async_context.html#class-asynclocalstorage) tracks async context\n* [`process.getActiveResourcesInfo()`](process.html#processgetactiveresourcesinfo) tracks active resources\n\nThe `node:async_hooks` module provides an API to track asynchronous resources.\nIt can be accessed using:\n\n```mjs\nimport async_hooks from 'node:async_hooks';\n```\n\n```cjs\nconst async_hooks = require('node:async_hooks');\n```","summary":"We strongly discourage the use of the `async_hooks` API. Other APIs that can cover most of its use cases include:","examples":[{"language":"mjs","displayName":null,"code":"import async_hooks from 'node:async_hooks';"},{"language":"cjs","displayName":null,"code":"const async_hooks = require('node:async_hooks');"}],"children":[{"kind":"section","id":"terminology","name":"Terminology","title":"Terminology","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"An asynchronous resource represents an object with an associated callback.\nThis callback may be called multiple times, such as the `'connection'`\nevent in `net.createServer()`, or just a single time like in `fs.open()`.\nA resource can also be closed before the callback is called. `AsyncHook` does\nnot explicitly distinguish between these different cases but will represent them\nas the abstract concept that is a resource.\n\nIf [`Worker`](worker_threads.html#class-worker)s are used, each thread has an independent `async_hooks`\ninterface, and each thread will use a new set of async IDs.","summary":"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.","examples":[],"children":[]},{"kind":"section","id":"overview","name":"Overview","title":"Overview","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Following is a simple overview of the public API.\n\n```mjs\nimport async_hooks from 'node:async_hooks';\n\n// Return the ID of the current execution context.\nconst eid = async_hooks.executionAsyncId();\n\n// Return the ID of the handle responsible for triggering the callback of the\n// current execution scope to call.\nconst tid = async_hooks.triggerAsyncId();\n\n// Create a new AsyncHook instance. All of these callbacks are optional.\nconst asyncHook =\n    async_hooks.createHook({ init, before, after, destroy, promiseResolve });\n\n// Allow callbacks of this AsyncHook instance to call. This is not an implicit\n// action after running the constructor, and must be explicitly run to begin\n// executing callbacks.\nasyncHook.enable();\n\n// Disable listening for new asynchronous events.\nasyncHook.disable();\n\n//\n// The following are the callbacks that can be passed to createHook().\n//\n\n// init() is called during object construction. The resource may not have\n// completed construction when this callback runs. Therefore, all fields of the\n// resource referenced by \"asyncId\" may not have been populated.\nfunction init(asyncId, type, triggerAsyncId, resource) { }\n\n// before() is called just before the resource's callback is called. It can be\n// called 0-N times for handles (such as TCPWrap), and will be called exactly 1\n// time for requests (such as FSReqCallback).\nfunction before(asyncId) { }\n\n// after() is called just after the resource's callback has finished.\nfunction after(asyncId) { }\n\n// destroy() is called when the resource is destroyed.\nfunction destroy(asyncId) { }\n\n// promiseResolve() is called only for promise resources, when the\n// resolve() function passed to the Promise constructor is invoked\n// (either directly or through other means of resolving a promise).\nfunction promiseResolve(asyncId) { }\n```\n\n```cjs\nconst async_hooks = require('node:async_hooks');\n\n// Return the ID of the current execution context.\nconst eid = async_hooks.executionAsyncId();\n\n// Return the ID of the handle responsible for triggering the callback of the\n// current execution scope to call.\nconst tid = async_hooks.triggerAsyncId();\n\n// Create a new AsyncHook instance. All of these callbacks are optional.\nconst asyncHook =\n    async_hooks.createHook({ init, before, after, destroy, promiseResolve });\n\n// Allow callbacks of this AsyncHook instance to call. This is not an implicit\n// action after running the constructor, and must be explicitly run to begin\n// executing callbacks.\nasyncHook.enable();\n\n// Disable listening for new asynchronous events.\nasyncHook.disable();\n\n//\n// The following are the callbacks that can be passed to createHook().\n//\n\n// init() is called during object construction. The resource may not have\n// completed construction when this callback runs. Therefore, all fields of the\n// resource referenced by \"asyncId\" may not have been populated.\nfunction init(asyncId, type, triggerAsyncId, resource) { }\n\n// before() is called just before the resource's callback is called. It can be\n// called 0-N times for handles (such as TCPWrap), and will be called exactly 1\n// time for requests (such as FSReqCallback).\nfunction before(asyncId) { }\n\n// after() is called just after the resource's callback has finished.\nfunction after(asyncId) { }\n\n// destroy() is called when the resource is destroyed.\nfunction destroy(asyncId) { }\n\n// promiseResolve() is called only for promise resources, when the\n// resolve() function passed to the Promise constructor is invoked\n// (either directly or through other means of resolving a promise).\nfunction promiseResolve(asyncId) { }\n```","summary":"Following is a simple overview of the public API.","examples":[{"language":"mjs","displayName":null,"code":"import async_hooks from 'node:async_hooks';\n\n// Return the ID of the current execution context.\nconst eid = async_hooks.executionAsyncId();\n\n// Return the ID of the handle responsible for triggering the callback of the\n// current execution scope to call.\nconst tid = async_hooks.triggerAsyncId();\n\n// Create a new AsyncHook instance. All of these callbacks are optional.\nconst asyncHook =\n    async_hooks.createHook({ init, before, after, destroy, promiseResolve });\n\n// Allow callbacks of this AsyncHook instance to call. This is not an implicit\n// action after running the constructor, and must be explicitly run to begin\n// executing callbacks.\nasyncHook.enable();\n\n// Disable listening for new asynchronous events.\nasyncHook.disable();\n\n//\n// The following are the callbacks that can be passed to createHook().\n//\n\n// init() is called during object construction. The resource may not have\n// completed construction when this callback runs. Therefore, all fields of the\n// resource referenced by \"asyncId\" may not have been populated.\nfunction init(asyncId, type, triggerAsyncId, resource) { }\n\n// before() is called just before the resource's callback is called. It can be\n// called 0-N times for handles (such as TCPWrap), and will be called exactly 1\n// time for requests (such as FSReqCallback).\nfunction before(asyncId) { }\n\n// after() is called just after the resource's callback has finished.\nfunction after(asyncId) { }\n\n// destroy() is called when the resource is destroyed.\nfunction destroy(asyncId) { }\n\n// promiseResolve() is called only for promise resources, when the\n// resolve() function passed to the Promise constructor is invoked\n// (either directly or through other means of resolving a promise).\nfunction promiseResolve(asyncId) { }"},{"language":"cjs","displayName":null,"code":"const async_hooks = require('node:async_hooks');\n\n// Return the ID of the current execution context.\nconst eid = async_hooks.executionAsyncId();\n\n// Return the ID of the handle responsible for triggering the callback of the\n// current execution scope to call.\nconst tid = async_hooks.triggerAsyncId();\n\n// Create a new AsyncHook instance. All of these callbacks are optional.\nconst asyncHook =\n    async_hooks.createHook({ init, before, after, destroy, promiseResolve });\n\n// Allow callbacks of this AsyncHook instance to call. This is not an implicit\n// action after running the constructor, and must be explicitly run to begin\n// executing callbacks.\nasyncHook.enable();\n\n// Disable listening for new asynchronous events.\nasyncHook.disable();\n\n//\n// The following are the callbacks that can be passed to createHook().\n//\n\n// init() is called during object construction. The resource may not have\n// completed construction when this callback runs. Therefore, all fields of the\n// resource referenced by \"asyncId\" may not have been populated.\nfunction init(asyncId, type, triggerAsyncId, resource) { }\n\n// before() is called just before the resource's callback is called. It can be\n// called 0-N times for handles (such as TCPWrap), and will be called exactly 1\n// time for requests (such as FSReqCallback).\nfunction before(asyncId) { }\n\n// after() is called just after the resource's callback has finished.\nfunction after(asyncId) { }\n\n// destroy() is called when the resource is destroyed.\nfunction destroy(asyncId) { }\n\n// promiseResolve() is called only for promise resources, when the\n// resolve() function passed to the Promise constructor is invoked\n// (either directly or through other means of resolving a promise).\nfunction promiseResolve(asyncId) { }"}],"children":[]},{"kind":"method","id":"async_hookscreatehookoptions","name":"createHook","title":"`async_hooks.createHook(options)`","scope":"module","overloadOf":null,"stability":null,"added":["v8.1.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The [Hook Callbacks](#hook-callbacks) to register","default":null,"optional":false,"rest":false,"properties":[{"name":"init","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The [`init` callback](#initasyncid-type-triggerasyncid-resource).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"before","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The [`before` callback](#beforeasyncid).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"after","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The [`after` callback](#afterasyncid).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"destroy","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The [`destroy` callback](#destroyasyncid).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"promiseResolve","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"The [`promiseResolve` callback](#promiseresolveasyncid).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"trackPromises","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Whether the hook should track `Promise`s. Cannot be `false` if\n`promiseResolve` is set. **Default**: `true`.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"AsyncHook","links":[{"name":"AsyncHook","href":"async_hooks.html#async_hookscreatehookoptions","start":0,"end":9}]},"description":"Instance used for disabling and enabling hooks"}},"description":"Registers functions to be called for different lifetime events of each async\noperation.\n\nThe callbacks `init()`/`before()`/`after()`/`destroy()` are called for the\nrespective asynchronous event during a resource's lifetime.\n\nAll callbacks are optional. For example, if only resource cleanup needs to\nbe tracked, then only the `destroy` callback needs to be passed. The\nspecifics of all functions that can be passed to `callbacks` is in the\n[Hook Callbacks](#hook-callbacks) section.\n\n```mjs\nimport { createHook } from 'node:async_hooks';\n\nconst asyncHook = createHook({\n  init(asyncId, type, triggerAsyncId, resource) { },\n  destroy(asyncId) { },\n});\n```\n\n```cjs\nconst async_hooks = require('node:async_hooks');\n\nconst asyncHook = async_hooks.createHook({\n  init(asyncId, type, triggerAsyncId, resource) { },\n  destroy(asyncId) { },\n});\n```\n\nThe callbacks will be inherited via the prototype chain:\n\n```js\nclass MyAsyncCallbacks {\n  init(asyncId, type, triggerAsyncId, resource) { }\n  destroy(asyncId) {}\n}\n\nclass MyAddedCallbacks extends MyAsyncCallbacks {\n  before(asyncId) { }\n  after(asyncId) { }\n}\n\nconst asyncHook = async_hooks.createHook(new MyAddedCallbacks());\n```\n\nBecause promises are asynchronous resources whose lifecycle is tracked\nvia the async hooks mechanism, the `init()`, `before()`, `after()`, and\n`destroy()` callbacks *must not* be async functions that return promises.","summary":"Registers functions to be called for different lifetime events of each async operation.","examples":[{"language":"mjs","displayName":null,"code":"import { createHook } from 'node:async_hooks';\n\nconst asyncHook = createHook({\n  init(asyncId, type, triggerAsyncId, resource) { },\n  destroy(asyncId) { },\n});"},{"language":"cjs","displayName":null,"code":"const async_hooks = require('node:async_hooks');\n\nconst asyncHook = async_hooks.createHook({\n  init(asyncId, type, triggerAsyncId, resource) { },\n  destroy(asyncId) { },\n});"},{"language":"js","displayName":null,"code":"class MyAsyncCallbacks {\n  init(asyncId, type, triggerAsyncId, resource) { }\n  destroy(asyncId) {}\n}\n\nclass MyAddedCallbacks extends MyAsyncCallbacks {\n  before(asyncId) { }\n  after(asyncId) { }\n}\n\nconst asyncHook = async_hooks.createHook(new MyAddedCallbacks());"}],"children":[{"kind":"section","id":"error-handling","name":"Error handling","title":"Error handling","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"If any `AsyncHook` callbacks throw, the application will print the stack trace\nand exit. The exit path does follow that of an uncaught exception, but\nall `'uncaughtException'` listeners are removed, thus forcing the process to\nexit. The `'exit'` callbacks will still be called unless the application is run\nwith `--abort-on-uncaught-exception`, in which case a stack trace will be\nprinted and the application exits, leaving a core file.\n\nThe reason for this error handling behavior is that these callbacks are running\nat potentially volatile points in an object's lifetime, for example during\nclass construction and destruction. Because of this, it is deemed necessary to\nbring down the process quickly in order to prevent an unintentional abort in the\nfuture. This is subject to change in the future if a comprehensive analysis is\nperformed to ensure an exception can follow the normal control flow without\nunintentional side effects.","summary":"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.","examples":[],"children":[]},{"kind":"section","id":"printing-in-asynchook-callbacks","name":"Printing in AsyncHook callbacks","title":"Printing in `AsyncHook` callbacks","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Because printing to the console is an asynchronous operation, `console.log()`\nwill cause `AsyncHook` callbacks to be called. Using `console.log()` or\nsimilar asynchronous operations inside an `AsyncHook` callback function will\ncause an infinite recursion. An easy solution to this when debugging is to use a\nsynchronous logging operation such as `fs.writeFileSync(file, msg, flag)`.\nThis will print to the file and will not invoke `AsyncHook` recursively because\nit is synchronous.\n\n```mjs\nimport { writeFileSync } from 'node:fs';\nimport { format } from 'node:util';\n\nfunction debug(...args) {\n  // Use a function like this one when debugging inside an AsyncHook callback\n  writeFileSync('log.out', `${format(...args)}\\n`, { flag: 'a' });\n}\n```\n\n```cjs\nconst fs = require('node:fs');\nconst util = require('node:util');\n\nfunction debug(...args) {\n  // Use a function like this one when debugging inside an AsyncHook callback\n  fs.writeFileSync('log.out', `${util.format(...args)}\\n`, { flag: 'a' });\n}\n```\n\nIf an asynchronous operation is needed for logging, it is possible to keep\ntrack of what caused the asynchronous operation using the information\nprovided by `AsyncHook` itself. The logging should then be skipped when\nit was the logging itself that caused the `AsyncHook` callback to be called. By\ndoing this, the otherwise infinite recursion is broken.","summary":"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.","examples":[{"language":"mjs","displayName":null,"code":"import { writeFileSync } from 'node:fs';\nimport { format } from 'node:util';\n\nfunction debug(...args) {\n  // Use a function like this one when debugging inside an AsyncHook callback\n  writeFileSync('log.out', `${format(...args)}\\n`, { flag: 'a' });\n}"},{"language":"cjs","displayName":null,"code":"const fs = require('node:fs');\nconst util = require('node:util');\n\nfunction debug(...args) {\n  // Use a function like this one when debugging inside an AsyncHook callback\n  fs.writeFileSync('log.out', `${util.format(...args)}\\n`, { flag: 'a' });\n}"}],"children":[]}]},{"kind":"class","id":"class-asynchook","name":"AsyncHook","title":"Class: `AsyncHook`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"The class `AsyncHook` exposes an interface for tracking lifetime events\nof asynchronous operations.","summary":"The class `AsyncHook` exposes an interface for tracking lifetime events of asynchronous operations.","examples":[],"children":[{"kind":"method","id":"asynchookenable","name":"enable","title":"`asyncHook.enable()`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"AsyncHook","links":[{"name":"AsyncHook","href":"async_hooks.html#async_hookscreatehookoptions","start":0,"end":9}]},"description":"A reference to `asyncHook`."}},"description":"Enable the callbacks for a given `AsyncHook` instance. If no callbacks are\nprovided, enabling is a no-op.\n\nThe `AsyncHook` instance is disabled by default. If the `AsyncHook` instance\nshould be enabled immediately after creation, the following pattern can be used.\n\n```mjs\nimport { createHook } from 'node:async_hooks';\n\nconst hook = createHook(callbacks).enable();\n```\n\n```cjs\nconst async_hooks = require('node:async_hooks');\n\nconst hook = async_hooks.createHook(callbacks).enable();\n```","summary":"Enable the callbacks for a given `AsyncHook` instance. If no callbacks are provided, enabling is a no-op.","examples":[{"language":"mjs","displayName":null,"code":"import { createHook } from 'node:async_hooks';\n\nconst hook = createHook(callbacks).enable();"},{"language":"cjs","displayName":null,"code":"const async_hooks = require('node:async_hooks');\n\nconst hook = async_hooks.createHook(callbacks).enable();"}],"children":[]},{"kind":"method","id":"asynchookdisable","name":"disable","title":"`asyncHook.disable()`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"AsyncHook","links":[{"name":"AsyncHook","href":"async_hooks.html#async_hookscreatehookoptions","start":0,"end":9}]},"description":"A reference to `asyncHook`."}},"description":"Disable the callbacks for a given `AsyncHook` instance from the global pool of\n`AsyncHook` callbacks to be executed. Once a hook has been disabled it will not\nbe called again until enabled.\n\nFor API consistency `disable()` also returns the `AsyncHook` instance.","summary":"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.","examples":[],"children":[]},{"kind":"section","id":"hook-callbacks","name":"Hook callbacks","title":"Hook callbacks","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Key events in the lifetime of asynchronous events have been categorized into\nfour areas: instantiation, before/after the callback is called, and when the\ninstance is destroyed.","summary":"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.","examples":[],"children":[{"kind":"method","id":"initasyncid-type-triggerasyncid-resource","name":"init","title":"`init(asyncId, type, triggerAsyncId, resource)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"asyncId","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"A unique ID for the async resource.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"type","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The type of the async resource.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"triggerAsyncId","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The unique ID of the async resource in whose\nexecution context this async resource was created.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"resource","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"Reference to the resource representing the async\noperation, needs to be released during *destroy*.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"Called when a class is constructed that has the *possibility* to emit an\nasynchronous event. This *does not* mean the instance must call\n`before`/`after` before `destroy` is called, only that the possibility\nexists.\n\nThis behavior can be observed by doing something like opening a resource then\nclosing it before the resource can be used. The following snippet demonstrates\nthis.\n\n```mjs\nimport { createServer } from 'node:net';\n\ncreateServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));\n```\n\n```cjs\nrequire('node:net').createServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));\n```\n\nEvery new resource is assigned an ID that is unique within the scope of the\ncurrent Node.js instance.","summary":"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.","examples":[{"language":"mjs","displayName":null,"code":"import { createServer } from 'node:net';\n\ncreateServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));"},{"language":"cjs","displayName":null,"code":"require('node:net').createServer().listen(function() { this.close(); });\n// OR\nclearTimeout(setTimeout(() => {}, 10));"}],"children":[{"kind":"section","id":"type","name":"type","title":"`type`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `type` is a string identifying the type of resource that caused\n`init` to be called. Generally, it will correspond to the name of the\nresource's constructor.\n\nThe `type` of resources created by Node.js itself can change in any Node.js\nrelease. Valid values include `TLSWRAP`,\n`TCPWRAP`, `TCPSERVERWRAP`, `GETADDRINFOREQWRAP`, `FSREQCALLBACK`,\n`Microtask`, and `Timeout`. Inspect the source code of the Node.js version used\nto get the full list.\n\nFurthermore users of [`AsyncResource`](async_context.html#class-asyncresource) create async resources independent\nof Node.js itself.\n\nThere is also the `PROMISE` resource type, which is used to track `Promise`\ninstances and asynchronous work scheduled by them. The `Promise`s are only\ntracked when `trackPromises` option is set to `true`.\n\nUsers are able to define their own `type` when using the public embedder API.\n\nIt is possible to have type name collisions. Embedders are encouraged to use\nunique prefixes, such as the npm package name, to prevent collisions when\nlistening to the hooks.","summary":"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.","examples":[],"children":[]},{"kind":"section","id":"triggerasyncid","name":"triggerAsyncId","title":"`triggerAsyncId`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"`triggerAsyncId` is the `asyncId` of the resource that caused (or \"triggered\")\nthe new resource to initialize and that caused `init` to call. This is different\nfrom `async_hooks.executionAsyncId()` that only shows *when* a resource was\ncreated, while `triggerAsyncId` shows *why* a resource was created.\n\nThe following is a simple demonstration of `triggerAsyncId`:\n\n```mjs\nimport { createHook, executionAsyncId } from 'node:async_hooks';\nimport { stdout } from 'node:process';\nimport net from 'node:net';\nimport fs from 'node:fs';\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = executionAsyncId();\n    fs.writeSync(\n      stdout.fd,\n      `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n}).enable();\n\nnet.createServer((conn) => {}).listen(8080);\n```\n\n```cjs\nconst { createHook, executionAsyncId } = require('node:async_hooks');\nconst { stdout } = require('node:process');\nconst net = require('node:net');\nconst fs = require('node:fs');\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = executionAsyncId();\n    fs.writeSync(\n      stdout.fd,\n      `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n}).enable();\n\nnet.createServer((conn) => {}).listen(8080);\n```\n\nOutput when hitting the server with `nc localhost 8080`:\n\n```console\nTCPSERVERWRAP(5): trigger: 1 execution: 1\nTCPWRAP(7): trigger: 5 execution: 0\n```\n\nThe `TCPSERVERWRAP` is the server which receives the connections.\n\nThe `TCPWRAP` is the new connection from the client. When a new\nconnection is made, the `TCPWrap` instance is immediately constructed. This\nhappens outside of any JavaScript stack. (An `executionAsyncId()` of `0` means\nthat it is being executed from C++ with no JavaScript stack above it.) With only\nthat information, it would be impossible to link resources together in\nterms of what caused them to be created, so `triggerAsyncId` is given the task\nof propagating what resource is responsible for the new resource's existence.","summary":"`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.","examples":[{"language":"mjs","displayName":null,"code":"import { createHook, executionAsyncId } from 'node:async_hooks';\nimport { stdout } from 'node:process';\nimport net from 'node:net';\nimport fs from 'node:fs';\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = executionAsyncId();\n    fs.writeSync(\n      stdout.fd,\n      `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n}).enable();\n\nnet.createServer((conn) => {}).listen(8080);"},{"language":"cjs","displayName":null,"code":"const { createHook, executionAsyncId } = require('node:async_hooks');\nconst { stdout } = require('node:process');\nconst net = require('node:net');\nconst fs = require('node:fs');\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = executionAsyncId();\n    fs.writeSync(\n      stdout.fd,\n      `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n}).enable();\n\nnet.createServer((conn) => {}).listen(8080);"},{"language":"console","displayName":null,"code":"TCPSERVERWRAP(5): trigger: 1 execution: 1\nTCPWRAP(7): trigger: 5 execution: 0"}],"children":[]},{"kind":"section","id":"resource","name":"resource","title":"`resource`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"`resource` is an object that represents the actual async resource that has\nbeen initialized. The API to access the object may be specified by the\ncreator of the resource. Resources created by Node.js itself are internal\nand may change at any time. Therefore no API is specified for these.\n\nIn some cases the resource object is reused for performance reasons, it is\nthus not safe to use it as a key in a `WeakMap` or add properties to it.","summary":"`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.","examples":[],"children":[]},{"kind":"section","id":"asynchronous-context-example","name":"Asynchronous context example","title":"Asynchronous context example","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The context tracking use case is covered by the stable API [`AsyncLocalStorage`](async_context.html#class-asynclocalstorage).\nThis example only illustrates async hooks operation but [`AsyncLocalStorage`](async_context.html#class-asynclocalstorage)\nfits better to this use case.\n\nThe following is an example with additional information about the calls to\n`init` between the `before` and `after` calls, specifically what the\ncallback to `listen()` will look like. The output formatting is slightly more\nelaborate to make calling context easier to see.\n\n```mjs\nimport async_hooks from 'node:async_hooks';\nimport fs from 'node:fs';\nimport net from 'node:net';\nimport { stdout } from 'node:process';\nconst { fd } = stdout;\n\nlet indent = 0;\nasync_hooks.createHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = async_hooks.executionAsyncId();\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(\n      fd,\n      `${indentStr}${type}(${asyncId}):` +\n      ` trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n  before(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}before:  ${asyncId}\\n`);\n    indent += 2;\n  },\n  after(asyncId) {\n    indent -= 2;\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}after:  ${asyncId}\\n`);\n  },\n  destroy(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}destroy:  ${asyncId}\\n`);\n  },\n}).enable();\n\nnet.createServer(() => {}).listen(8080, () => {\n  // Let's wait 10ms before logging the server started.\n  setTimeout(() => {\n    console.log('>>>', async_hooks.executionAsyncId());\n  }, 10);\n});\n```\n\n```cjs\nconst async_hooks = require('node:async_hooks');\nconst fs = require('node:fs');\nconst net = require('node:net');\nconst { fd } = process.stdout;\n\nlet indent = 0;\nasync_hooks.createHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = async_hooks.executionAsyncId();\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(\n      fd,\n      `${indentStr}${type}(${asyncId}):` +\n      ` trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n  before(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}before:  ${asyncId}\\n`);\n    indent += 2;\n  },\n  after(asyncId) {\n    indent -= 2;\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}after:  ${asyncId}\\n`);\n  },\n  destroy(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}destroy:  ${asyncId}\\n`);\n  },\n}).enable();\n\nnet.createServer(() => {}).listen(8080, () => {\n  // Let's wait 10ms before logging the server started.\n  setTimeout(() => {\n    console.log('>>>', async_hooks.executionAsyncId());\n  }, 10);\n});\n```\n\nOutput from only starting the server:\n\n```console\nTCPSERVERWRAP(5): trigger: 1 execution: 1\nTickObject(6): trigger: 5 execution: 1\nbefore:  6\n  Timeout(7): trigger: 6 execution: 6\nafter:   6\ndestroy: 6\nbefore:  7\n>>> 7\n  TickObject(8): trigger: 7 execution: 7\nafter:   7\nbefore:  8\nafter:   8\n```\n\nAs illustrated in the example, `executionAsyncId()` and `execution` each specify\nthe value of the current execution context; which is delineated by calls to\n`before` and `after`.\n\nOnly using `execution` to graph resource allocation results in the following:\n\n```console\n  root(1)\n     ^\n     |\nTickObject(6)\n     ^\n     |\n Timeout(7)\n```\n\nThe `TCPSERVERWRAP` is not part of this graph, even though it was the reason for\n`console.log()` being called. This is because binding to a port without a host\nname is a *synchronous* operation, but to maintain a completely asynchronous\nAPI the user's callback is placed in a `process.nextTick()`. Which is why\n`TickObject` is present in the output and is a 'parent' for `.listen()`\ncallback.\n\nThe graph only shows *when* a resource was created, not *why*, so to track\nthe *why* use `triggerAsyncId`. Which can be represented with the following\ngraph:\n\n```console\n bootstrap(1)\n     |\n     ˅\nTCPSERVERWRAP(5)\n     |\n     ˅\n TickObject(6)\n     |\n     ˅\n  Timeout(7)\n```","summary":"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.","examples":[{"language":"mjs","displayName":null,"code":"import async_hooks from 'node:async_hooks';\nimport fs from 'node:fs';\nimport net from 'node:net';\nimport { stdout } from 'node:process';\nconst { fd } = stdout;\n\nlet indent = 0;\nasync_hooks.createHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = async_hooks.executionAsyncId();\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(\n      fd,\n      `${indentStr}${type}(${asyncId}):` +\n      ` trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n  before(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}before:  ${asyncId}\\n`);\n    indent += 2;\n  },\n  after(asyncId) {\n    indent -= 2;\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}after:  ${asyncId}\\n`);\n  },\n  destroy(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}destroy:  ${asyncId}\\n`);\n  },\n}).enable();\n\nnet.createServer(() => {}).listen(8080, () => {\n  // Let's wait 10ms before logging the server started.\n  setTimeout(() => {\n    console.log('>>>', async_hooks.executionAsyncId());\n  }, 10);\n});"},{"language":"cjs","displayName":null,"code":"const async_hooks = require('node:async_hooks');\nconst fs = require('node:fs');\nconst net = require('node:net');\nconst { fd } = process.stdout;\n\nlet indent = 0;\nasync_hooks.createHook({\n  init(asyncId, type, triggerAsyncId) {\n    const eid = async_hooks.executionAsyncId();\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(\n      fd,\n      `${indentStr}${type}(${asyncId}):` +\n      ` trigger: ${triggerAsyncId} execution: ${eid}\\n`);\n  },\n  before(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}before:  ${asyncId}\\n`);\n    indent += 2;\n  },\n  after(asyncId) {\n    indent -= 2;\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}after:  ${asyncId}\\n`);\n  },\n  destroy(asyncId) {\n    const indentStr = ' '.repeat(indent);\n    fs.writeSync(fd, `${indentStr}destroy:  ${asyncId}\\n`);\n  },\n}).enable();\n\nnet.createServer(() => {}).listen(8080, () => {\n  // Let's wait 10ms before logging the server started.\n  setTimeout(() => {\n    console.log('>>>', async_hooks.executionAsyncId());\n  }, 10);\n});"},{"language":"console","displayName":null,"code":"TCPSERVERWRAP(5): trigger: 1 execution: 1\nTickObject(6): trigger: 5 execution: 1\nbefore:  6\n  Timeout(7): trigger: 6 execution: 6\nafter:   6\ndestroy: 6\nbefore:  7\n>>> 7\n  TickObject(8): trigger: 7 execution: 7\nafter:   7\nbefore:  8\nafter:   8"},{"language":"console","displayName":null,"code":"  root(1)\n     ^\n     |\nTickObject(6)\n     ^\n     |\n Timeout(7)"},{"language":"console","displayName":null,"code":" bootstrap(1)\n     |\n     ˅\nTCPSERVERWRAP(5)\n     |\n     ˅\n TickObject(6)\n     |\n     ˅\n  Timeout(7)"}],"children":[]}]},{"kind":"method","id":"beforeasyncid","name":"before","title":"`before(asyncId)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"asyncId","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"When an asynchronous operation is initiated (such as a TCP server receiving a\nnew connection) or completes (such as writing data to disk) a callback is\ncalled to notify the user. The `before` callback is called just before said\ncallback is executed. `asyncId` is the unique identifier assigned to the\nresource about to execute the callback.\n\nThe `before` callback will be called 0 to N times. The `before` callback\nwill typically be called 0 times if the asynchronous operation was cancelled\nor, for example, if no connections are received by a TCP server. Persistent\nasynchronous resources like a TCP server will typically call the `before`\ncallback multiple times, while other operations like `fs.open()` will call\nit only once.","summary":"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.","examples":[],"children":[]},{"kind":"method","id":"afterasyncid","name":"after","title":"`after(asyncId)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"asyncId","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"Called immediately after the callback specified in `before` is completed.\n\nIf an uncaught exception occurs during execution of the callback, then `after`\nwill run *after* the `'uncaughtException'` event is emitted or a `domain`'s\nhandler runs.","summary":"Called immediately after the callback specified in `before` is completed.","examples":[],"children":[]},{"kind":"method","id":"destroyasyncid","name":"destroy","title":"`destroy(asyncId)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"asyncId","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"Called after the resource corresponding to `asyncId` is destroyed. It is also\ncalled asynchronously from the embedder API `emitDestroy()`.\n\nSome resources depend on garbage collection for cleanup, so if a reference is\nmade to the `resource` object passed to `init` it is possible that `destroy`\nwill never be called, causing a memory leak in the application. If the resource\ndoes not depend on garbage collection, then this will not be an issue.\n\nUsing the destroy hook results in additional overhead because it enables\ntracking of `Promise` instances via the garbage collector.","summary":"Called after the resource corresponding to `asyncId` is destroyed. It is also called asynchronously from the embedder API `emitDestroy()`.","examples":[],"children":[]},{"kind":"method","id":"promiseresolveasyncid","name":"promiseResolve","title":"`promiseResolve(asyncId)`","scope":"module","overloadOf":null,"stability":null,"added":["v8.6.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"asyncId","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"Called when the `resolve` function passed to the `Promise` constructor is\ninvoked (either directly or through other means of resolving a promise).\n\n`resolve()` does not do any observable synchronous work.\n\nThe `Promise` is not necessarily fulfilled or rejected at this point if the\n`Promise` was resolved by assuming the state of another `Promise`.\n\n```js\nnew Promise((resolve) => resolve(true)).then((a) => {});\n```\n\ncalls the following callbacks:\n\n```text\ninit for PROMISE with id 5, trigger id: 1\n  promise resolve 5      # corresponds to resolve(true)\ninit for PROMISE with id 6, trigger id: 5  # the Promise returned by then()\n  before 6               # the then() callback is entered\n  promise resolve 6      # the then() callback resolves the promise by returning\n  after 6\n```","summary":"Called when the `resolve` function passed to the `Promise` constructor is invoked (either directly or through other means of resolving a promise).","examples":[{"language":"js","displayName":null,"code":"new Promise((resolve) => resolve(true)).then((a) => {});"},{"language":"text","displayName":null,"code":"init for PROMISE with id 5, trigger id: 1\n  promise resolve 5      # corresponds to resolve(true)\ninit for PROMISE with id 6, trigger id: 5  # the Promise returned by then()\n  before 6               # the then() callback is entered\n  promise resolve 6      # the then() callback resolves the promise by returning\n  after 6"}],"children":[]}]},{"kind":"method","id":"async_hooksexecutionasyncresource","name":"executionAsyncResource","title":"`async_hooks.executionAsyncResource()`","scope":"module","overloadOf":null,"stability":null,"added":["v13.9.0","v12.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The resource representing the current execution.\nUseful to store data within the resource."}},"description":"Resource objects returned by `executionAsyncResource()` are most often internal\nNode.js handle objects with undocumented APIs. Using any functions or properties\non the object is likely to crash your application and should be avoided.\n\nUsing `executionAsyncResource()` in the top-level execution context will\nreturn an empty object as there is no handle or request object to use,\nbut having an object representing the top-level can be helpful.\n\n```mjs\nimport { open } from 'node:fs';\nimport { executionAsyncId, executionAsyncResource } from 'node:async_hooks';\n\nconsole.log(executionAsyncId(), executionAsyncResource());  // 1 {}\nopen(new URL(import.meta.url), 'r', (err, fd) => {\n  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap\n});\n```\n\n```cjs\nconst { open } = require('node:fs');\nconst { executionAsyncId, executionAsyncResource } = require('node:async_hooks');\n\nconsole.log(executionAsyncId(), executionAsyncResource());  // 1 {}\nopen(__filename, 'r', (err, fd) => {\n  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap\n});\n```\n\nThis can be used to implement continuation local storage without the\nuse of a tracking `Map` to store the metadata:\n\n```mjs\nimport { createServer } from 'node:http';\nimport {\n  executionAsyncId,\n  executionAsyncResource,\n  createHook,\n} from 'node:async_hooks';\nconst sym = Symbol('state'); // Private symbol to avoid pollution\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId, resource) {\n    const cr = executionAsyncResource();\n    if (cr) {\n      resource[sym] = cr[sym];\n    }\n  },\n}).enable();\n\nconst server = createServer((req, res) => {\n  executionAsyncResource()[sym] = { state: req.url };\n  setTimeout(function() {\n    res.end(JSON.stringify(executionAsyncResource()[sym]));\n  }, 100);\n}).listen(3000);\n```\n\n```cjs\nconst { createServer } = require('node:http');\nconst {\n  executionAsyncId,\n  executionAsyncResource,\n  createHook,\n} = require('node:async_hooks');\nconst sym = Symbol('state'); // Private symbol to avoid pollution\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId, resource) {\n    const cr = executionAsyncResource();\n    if (cr) {\n      resource[sym] = cr[sym];\n    }\n  },\n}).enable();\n\nconst server = createServer((req, res) => {\n  executionAsyncResource()[sym] = { state: req.url };\n  setTimeout(function() {\n    res.end(JSON.stringify(executionAsyncResource()[sym]));\n  }, 100);\n}).listen(3000);\n```","summary":"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.","examples":[{"language":"mjs","displayName":null,"code":"import { open } from 'node:fs';\nimport { executionAsyncId, executionAsyncResource } from 'node:async_hooks';\n\nconsole.log(executionAsyncId(), executionAsyncResource());  // 1 {}\nopen(new URL(import.meta.url), 'r', (err, fd) => {\n  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap\n});"},{"language":"cjs","displayName":null,"code":"const { open } = require('node:fs');\nconst { executionAsyncId, executionAsyncResource } = require('node:async_hooks');\n\nconsole.log(executionAsyncId(), executionAsyncResource());  // 1 {}\nopen(__filename, 'r', (err, fd) => {\n  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap\n});"},{"language":"mjs","displayName":null,"code":"import { createServer } from 'node:http';\nimport {\n  executionAsyncId,\n  executionAsyncResource,\n  createHook,\n} from 'node:async_hooks';\nconst sym = Symbol('state'); // Private symbol to avoid pollution\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId, resource) {\n    const cr = executionAsyncResource();\n    if (cr) {\n      resource[sym] = cr[sym];\n    }\n  },\n}).enable();\n\nconst server = createServer((req, res) => {\n  executionAsyncResource()[sym] = { state: req.url };\n  setTimeout(function() {\n    res.end(JSON.stringify(executionAsyncResource()[sym]));\n  }, 100);\n}).listen(3000);"},{"language":"cjs","displayName":null,"code":"const { createServer } = require('node:http');\nconst {\n  executionAsyncId,\n  executionAsyncResource,\n  createHook,\n} = require('node:async_hooks');\nconst sym = Symbol('state'); // Private symbol to avoid pollution\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId, resource) {\n    const cr = executionAsyncResource();\n    if (cr) {\n      resource[sym] = cr[sym];\n    }\n  },\n}).enable();\n\nconst server = createServer((req, res) => {\n  executionAsyncResource()[sym] = { state: req.url };\n  setTimeout(function() {\n    res.end(JSON.stringify(executionAsyncResource()[sym]));\n  }, 100);\n}).listen(3000);"}],"children":[]},{"kind":"method","id":"async_hooksexecutionasyncid","name":"executionAsyncId","title":"`async_hooks.executionAsyncId()`","scope":"module","overloadOf":null,"stability":null,"added":["v8.1.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v8.2.0"],"prUrl":"https://github.com/nodejs/node/pull/13490","commit":null,"description":"Renamed from `currentId`."}],"signature":{"parameters":[],"returns":{"type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The `asyncId` of the current execution context. Useful to\ntrack when something calls."}},"description":"```mjs\nimport { executionAsyncId } from 'node:async_hooks';\nimport fs from 'node:fs';\n\nconsole.log(executionAsyncId());  // 1 - bootstrap\nconst path = '.';\nfs.open(path, 'r', (err, fd) => {\n  console.log(executionAsyncId());  // 6 - open()\n});\n```\n\n```cjs\nconst async_hooks = require('node:async_hooks');\nconst fs = require('node:fs');\n\nconsole.log(async_hooks.executionAsyncId());  // 1 - bootstrap\nconst path = '.';\nfs.open(path, 'r', (err, fd) => {\n  console.log(async_hooks.executionAsyncId());  // 6 - open()\n});\n```\n\nThe ID returned from `executionAsyncId()` is related to execution timing, not\ncausality (which is covered by `triggerAsyncId()`):\n\n```js\nconst server = net.createServer((conn) => {\n  // Returns the ID of the server, not of the new connection, because the\n  // callback runs in the execution scope of the server's MakeCallback().\n  async_hooks.executionAsyncId();\n\n}).listen(port, () => {\n  // Returns the ID of a TickObject (process.nextTick()) because all\n  // callbacks passed to .listen() are wrapped in a nextTick().\n  async_hooks.executionAsyncId();\n});\n```\n\nPromise contexts may not get precise `executionAsyncIds` by default.\nSee the section on [promise execution tracking](#promise-execution-tracking).","summary":"The ID returned from `executionAsyncId()` is related to execution timing, not causality (which is covered by `triggerAsyncId()`):","examples":[{"language":"mjs","displayName":null,"code":"import { executionAsyncId } from 'node:async_hooks';\nimport fs from 'node:fs';\n\nconsole.log(executionAsyncId());  // 1 - bootstrap\nconst path = '.';\nfs.open(path, 'r', (err, fd) => {\n  console.log(executionAsyncId());  // 6 - open()\n});"},{"language":"cjs","displayName":null,"code":"const async_hooks = require('node:async_hooks');\nconst fs = require('node:fs');\n\nconsole.log(async_hooks.executionAsyncId());  // 1 - bootstrap\nconst path = '.';\nfs.open(path, 'r', (err, fd) => {\n  console.log(async_hooks.executionAsyncId());  // 6 - open()\n});"},{"language":"js","displayName":null,"code":"const server = net.createServer((conn) => {\n  // Returns the ID of the server, not of the new connection, because the\n  // callback runs in the execution scope of the server's MakeCallback().\n  async_hooks.executionAsyncId();\n\n}).listen(port, () => {\n  // Returns the ID of a TickObject (process.nextTick()) because all\n  // callbacks passed to .listen() are wrapped in a nextTick().\n  async_hooks.executionAsyncId();\n});"}],"children":[]},{"kind":"method","id":"async_hookstriggerasyncid","name":"triggerAsyncId","title":"`async_hooks.triggerAsyncId()`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The ID of the resource responsible for calling the callback\nthat is currently being executed."}},"description":"```js\nconst server = net.createServer((conn) => {\n  // The resource that caused (or triggered) this callback to be called\n  // was that of the new connection. Thus the return value of triggerAsyncId()\n  // is the asyncId of \"conn\".\n  async_hooks.triggerAsyncId();\n\n}).listen(port, () => {\n  // Even though all callbacks passed to .listen() are wrapped in a nextTick()\n  // the callback itself exists because the call to the server's .listen()\n  // was made. So the return value would be the ID of the server.\n  async_hooks.triggerAsyncId();\n});\n```\n\nPromise contexts may not get valid `triggerAsyncId`s by default. See\nthe section on [promise execution tracking](#promise-execution-tracking).","summary":"Promise contexts may not get valid `triggerAsyncId`s by default. See the section on promise execution tracking.","examples":[{"language":"js","displayName":null,"code":"const server = net.createServer((conn) => {\n  // The resource that caused (or triggered) this callback to be called\n  // was that of the new connection. Thus the return value of triggerAsyncId()\n  // is the asyncId of \"conn\".\n  async_hooks.triggerAsyncId();\n\n}).listen(port, () => {\n  // Even though all callbacks passed to .listen() are wrapped in a nextTick()\n  // the callback itself exists because the call to the server's .listen()\n  // was made. So the return value would be the ID of the server.\n  async_hooks.triggerAsyncId();\n});"}],"children":[]},{"kind":"property","id":"async_hooksasyncwrapproviders","name":"asyncWrapProviders","title":"`async_hooks.asyncWrapProviders`","scope":"module","overloadOf":null,"stability":null,"added":["v17.2.0","v16.14.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":null,"default":null,"description":"A map of provider types to the corresponding numeric id.\nThis map contains all the event types that might be emitted by the `async_hooks.init()` event.\n\nThis feature suppresses the deprecated usage of `process.binding('async_wrap').Providers`.\nSee: [DEP0111](deprecations.html#dep0111-processbinding)","summary":"This feature suppresses the deprecated usage of `process.binding('async_wrap').Providers`. See: DEP0111","examples":[],"children":[]}]},{"kind":"section","id":"promise-execution-tracking","name":"Promise execution tracking","title":"Promise execution tracking","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"By default, promise executions are not assigned `asyncId`s due to the relatively\nexpensive nature of the [promise introspection API](https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit) provided by\nV8. This means that programs using promises or `async`/`await` will not get\ncorrect execution and trigger ids for promise callback contexts by default.\n\n```mjs\nimport { executionAsyncId, triggerAsyncId } from 'node:async_hooks';\n\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0\n```\n\n```cjs\nconst { executionAsyncId, triggerAsyncId } = require('node:async_hooks');\n\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0\n```\n\nObserve that the `then()` callback claims to have executed in the context of the\nouter scope even though there was an asynchronous hop involved. Also,\nthe `triggerAsyncId` value is `0`, which means that we are missing context about\nthe resource that caused (triggered) the `then()` callback to be executed.\n\nInstalling async hooks via `async_hooks.createHook` enables promise execution\ntracking:\n\n```mjs\nimport { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';\ncreateHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 7 tid 6\n```\n\n```cjs\nconst { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');\n\ncreateHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 7 tid 6\n```\n\nIn this example, adding any actual hook function enabled the tracking of\npromises. There are two promises in the example above; the promise created by\n`Promise.resolve()` and the promise returned by the call to `then()`. In the\nexample above, the first promise got the `asyncId` `6` and the latter got\n`asyncId` `7`. During the execution of the `then()` callback, we are executing\nin the context of promise with `asyncId` `7`. This promise was triggered by\nasync resource `6`.\n\nAnother subtlety with promises is that `before` and `after` callbacks are run\nonly on chained promises. That means promises not created by `then()`/`catch()`\nwill not have the `before` and `after` callbacks fired on them. For more details\nsee the details of the V8 [PromiseHooks](https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit) API.","summary":"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.","examples":[{"language":"mjs","displayName":null,"code":"import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';\n\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0"},{"language":"cjs","displayName":null,"code":"const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');\n\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 1 tid 0"},{"language":"mjs","displayName":null,"code":"import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';\ncreateHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 7 tid 6"},{"language":"cjs","displayName":null,"code":"const { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');\n\ncreateHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.\nPromise.resolve(1729).then(() => {\n  console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);\n});\n// produces:\n// eid 7 tid 6"}],"children":[{"kind":"section","id":"disabling-promise-execution-tracking","name":"Disabling promise execution tracking","title":"Disabling promise execution tracking","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Tracking promise execution can cause a significant performance overhead.\nTo opt out of promise tracking, set `trackPromises` to `false`:\n\n```cjs\nconst { createHook } = require('node:async_hooks');\nconst { writeSync } = require('node:fs');\ncreateHook({\n  init(asyncId, type, triggerAsyncId, resource) {\n    // This init hook does not get called when trackPromises is set to false.\n    writeSync(1, `init hook triggered for ${type}\\n`);\n  },\n  trackPromises: false,  // Do not track promises.\n}).enable();\nPromise.resolve(1729);\n```\n\n```mjs\nimport { createHook } from 'node:async_hooks';\nimport { writeSync } from 'node:fs';\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId, resource) {\n    // This init hook does not get called when trackPromises is set to false.\n    writeSync(1, `init hook triggered for ${type}\\n`);\n  },\n  trackPromises: false,  // Do not track promises.\n}).enable();\nPromise.resolve(1729);\n```","summary":"Tracking promise execution can cause a significant performance overhead. To opt out of promise tracking, set `trackPromises` to `false`:","examples":[{"language":"cjs","displayName":null,"code":"const { createHook } = require('node:async_hooks');\nconst { writeSync } = require('node:fs');\ncreateHook({\n  init(asyncId, type, triggerAsyncId, resource) {\n    // This init hook does not get called when trackPromises is set to false.\n    writeSync(1, `init hook triggered for ${type}\\n`);\n  },\n  trackPromises: false,  // Do not track promises.\n}).enable();\nPromise.resolve(1729);"},{"language":"mjs","displayName":null,"code":"import { createHook } from 'node:async_hooks';\nimport { writeSync } from 'node:fs';\n\ncreateHook({\n  init(asyncId, type, triggerAsyncId, resource) {\n    // This init hook does not get called when trackPromises is set to false.\n    writeSync(1, `init hook triggered for ${type}\\n`);\n  },\n  trackPromises: false,  // Do not track promises.\n}).enable();\nPromise.resolve(1729);"}],"children":[]}]},{"kind":"section","id":"javascript-embedder-api","name":"JavaScript embedder API","title":"JavaScript embedder API","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Library developers that handle their own asynchronous resources performing tasks\nlike I/O, connection pooling, or managing callback queues may use the\n`AsyncResource` JavaScript API so that all the appropriate callbacks are called.","summary":"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.","examples":[],"children":[{"kind":"class","id":"class-asyncresource","name":"AsyncResource","title":"Class: `AsyncResource`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"The documentation for this class has moved [`AsyncResource`](async_context.html#class-asyncresource).","summary":"The documentation for this class has moved `AsyncResource`.","examples":[],"children":[]}]},{"kind":"class","id":"class-asynclocalstorage","name":"AsyncLocalStorage","title":"Class: `AsyncLocalStorage`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"The documentation for this class has moved [`AsyncLocalStorage`](async_context.html#class-asynclocalstorage).","summary":"The documentation for this class has moved `AsyncLocalStorage`.","examples":[],"children":[]}]}