• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1<!DOCTYPE html>
2<html lang="en">
3<head>
4  <meta charset="utf-8">
5  <meta name="viewport" content="width=device-width">
6  <meta name="nodejs.org:node-version" content="v14.20.1">
7  <title>Async hooks | Node.js v14.20.1 Documentation</title>
8  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
9  <link rel="stylesheet" href="assets/style.css">
10  <link rel="stylesheet" href="assets/hljs.css">
11  <link rel="canonical" href="https://nodejs.org/api/async_hooks.html">
12</head>
13<body class="alt apidoc" id="api-section-async_hooks">
14  <div id="content" class="clearfix">
15    <div id="column2" class="interior">
16      <div id="intro" class="interior">
17        <a href="/" title="Go back to the home page">
18          Node.js
19        </a>
20      </div>
21      <ul>
22<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li>
23<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
24</ul>
25<hr class="line">
26<ul>
27<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
28<li><a href="async_hooks.html" class="nav-async_hooks active">Async hooks</a></li>
29<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
30<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
31<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li>
32<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li>
33<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
34<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
35<li><a href="cli.html" class="nav-cli">Command-line options</a></li>
36<li><a href="console.html" class="nav-console">Console</a></li>
37<li><a href="corepack.html" class="nav-corepack">Corepack</a></li>
38<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
39<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
40<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
41<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li>
42<li><a href="dns.html" class="nav-dns">DNS</a></li>
43<li><a href="domain.html" class="nav-domain">Domain</a></li>
44<li><a href="errors.html" class="nav-errors">Errors</a></li>
45<li><a href="events.html" class="nav-events">Events</a></li>
46<li><a href="fs.html" class="nav-fs">File system</a></li>
47<li><a href="globals.html" class="nav-globals">Globals</a></li>
48<li><a href="http.html" class="nav-http">HTTP</a></li>
49<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
50<li><a href="https.html" class="nav-https">HTTPS</a></li>
51<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
52<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
53<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li>
54<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
55<li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li>
56<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li>
57<li><a href="net.html" class="nav-net">Net</a></li>
58<li><a href="os.html" class="nav-os">OS</a></li>
59<li><a href="path.html" class="nav-path">Path</a></li>
60<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
61<li><a href="policy.html" class="nav-policy">Policies</a></li>
62<li><a href="process.html" class="nav-process">Process</a></li>
63<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
64<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
65<li><a href="readline.html" class="nav-readline">Readline</a></li>
66<li><a href="repl.html" class="nav-repl">REPL</a></li>
67<li><a href="report.html" class="nav-report">Report</a></li>
68<li><a href="stream.html" class="nav-stream">Stream</a></li>
69<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
70<li><a href="timers.html" class="nav-timers">Timers</a></li>
71<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
72<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
73<li><a href="tty.html" class="nav-tty">TTY</a></li>
74<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
75<li><a href="url.html" class="nav-url">URL</a></li>
76<li><a href="util.html" class="nav-util">Utilities</a></li>
77<li><a href="v8.html" class="nav-v8">V8</a></li>
78<li><a href="vm.html" class="nav-vm">VM</a></li>
79<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
80<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
81<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
82</ul>
83<hr class="line">
84<ul>
85<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
86</ul>
87    </div>
88
89    <div id="column1" data-id="async_hooks" class="interior">
90      <header>
91        <div class="header-container">
92          <h1>Node.js v14.20.1 documentation</h1>
93          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
94            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
95              <path fill="none" d="M0 0h24v24H0z" />
96              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
97              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
98            </svg>
99            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
100              <path d="M0 0h24v24H0z" fill="none" />
101              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
102            </svg>
103          </button>
104        </div>
105        <div id="gtoc">
106          <ul>
107            <li>
108              <a href="index.html">Index</a>
109            </li>
110            <li>
111              <a href="all.html">View on single page</a>
112            </li>
113            <li>
114              <a href="async_hooks.json">View as JSON</a>
115            </li>
116
117    <li class="version-picker">
118      <a href="#">View another version <span>&#x25bc;</span></a>
119      <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v18.x/api/async_hooks.html">18.x</a></li>
120<li><a href="https://nodejs.org/docs/latest-v17.x/api/async_hooks.html">17.x</a></li>
121<li><a href="https://nodejs.org/docs/latest-v16.x/api/async_hooks.html">16.x <b>LTS</b></a></li>
122<li><a href="https://nodejs.org/docs/latest-v15.x/api/async_hooks.html">15.x</a></li>
123<li><a href="https://nodejs.org/docs/latest-v14.x/api/async_hooks.html">14.x <b>LTS</b></a></li>
124<li><a href="https://nodejs.org/docs/latest-v13.x/api/async_hooks.html">13.x</a></li>
125<li><a href="https://nodejs.org/docs/latest-v12.x/api/async_hooks.html">12.x <b>LTS</b></a></li>
126<li><a href="https://nodejs.org/docs/latest-v11.x/api/async_hooks.html">11.x</a></li>
127<li><a href="https://nodejs.org/docs/latest-v10.x/api/async_hooks.html">10.x</a></li>
128<li><a href="https://nodejs.org/docs/latest-v9.x/api/async_hooks.html">9.x</a></li>
129<li><a href="https://nodejs.org/docs/latest-v8.x/api/async_hooks.html">8.x</a></li></ol>
130    </li>
131
132            <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/async_hooks.md">Edit on GitHub</a></li>
133          </ul>
134        </div>
135        <hr>
136      </header>
137
138      <details id="toc" open><summary>Table of contents</summary><ul>
139<li><span class="stability_1"><a href="#async_hooks_async_hooks">Async hooks</a></span>
140<ul>
141<li><a href="#async_hooks_terminology">Terminology</a></li>
142<li><a href="#async_hooks_overview">Overview</a></li>
143<li><a href="#async_hooks_async_hooks_createhook_callbacks"><code>async_hooks.createHook(callbacks)</code></a>
144<ul>
145<li><a href="#async_hooks_error_handling">Error handling</a></li>
146<li><a href="#async_hooks_printing_in_asynchooks_callbacks">Printing in AsyncHooks callbacks</a></li>
147</ul>
148</li>
149<li><a href="#async_hooks_class_asynchook">Class: <code>AsyncHook</code></a>
150<ul>
151<li><a href="#async_hooks_asynchook_enable"><code>asyncHook.enable()</code></a></li>
152<li><a href="#async_hooks_asynchook_disable"><code>asyncHook.disable()</code></a></li>
153<li><a href="#async_hooks_hook_callbacks">Hook callbacks</a>
154<ul>
155<li><a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init(asyncId, type, triggerAsyncId, resource)</code></a>
156<ul>
157<li><a href="#async_hooks_type"><code>type</code></a></li>
158<li><a href="#async_hooks_triggerasyncid"><code>triggerAsyncId</code></a></li>
159<li><a href="#async_hooks_resource"><code>resource</code></a></li>
160<li><a href="#async_hooks_asynchronous_context_example">Asynchronous context example</a></li>
161</ul>
162</li>
163<li><a href="#async_hooks_before_asyncid"><code>before(asyncId)</code></a></li>
164<li><a href="#async_hooks_after_asyncid"><code>after(asyncId)</code></a></li>
165<li><a href="#async_hooks_destroy_asyncid"><code>destroy(asyncId)</code></a></li>
166<li><a href="#async_hooks_promiseresolve_asyncid"><code>promiseResolve(asyncId)</code></a></li>
167</ul>
168</li>
169<li><a href="#async_hooks_async_hooks_executionasyncresource"><code>async_hooks.executionAsyncResource()</code></a></li>
170<li><a href="#async_hooks_async_hooks_executionasyncid"><code>async_hooks.executionAsyncId()</code></a></li>
171<li><a href="#async_hooks_async_hooks_triggerasyncid"><code>async_hooks.triggerAsyncId()</code></a></li>
172</ul>
173</li>
174<li><a href="#async_hooks_promise_execution_tracking">Promise execution tracking</a></li>
175<li><a href="#async_hooks_javascript_embedder_api">JavaScript embedder API</a>
176<ul>
177<li><a href="#async_hooks_class_asyncresource">Class: <code>AsyncResource</code></a>
178<ul>
179<li><a href="#async_hooks_new_asyncresource_type_options"><code>new AsyncResource(type[, options])</code></a></li>
180<li><a href="#async_hooks_static_method_asyncresource_bind_fn_type">Static method: <code>AsyncResource.bind(fn[, type])</code></a></li>
181<li><a href="#async_hooks_asyncresource_bind_fn"><code>asyncResource.bind(fn)</code></a></li>
182<li><a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code></a></li>
183<li><a href="#async_hooks_asyncresource_emitdestroy"><code>asyncResource.emitDestroy()</code></a></li>
184<li><a href="#async_hooks_asyncresource_asyncid"><code>asyncResource.asyncId()</code></a></li>
185<li><a href="#async_hooks_asyncresource_triggerasyncid"><code>asyncResource.triggerAsyncId()</code></a></li>
186</ul>
187</li>
188<li><a href="#async_hooks_using_asyncresource_for_a_worker_thread_pool">Using <code>AsyncResource</code> for a <code>Worker</code> thread pool</a></li>
189<li><a href="#async_hooks_integrating_asyncresource_with_eventemitter">Integrating <code>AsyncResource</code> with <code>EventEmitter</code></a></li>
190</ul>
191</li>
192<li><a href="#async_hooks_class_asynclocalstorage">Class: <code>AsyncLocalStorage</code></a>
193<ul>
194<li><a href="#async_hooks_new_asynclocalstorage"><code>new AsyncLocalStorage()</code></a></li>
195<li><a href="#async_hooks_asynclocalstorage_disable"><code>asyncLocalStorage.disable()</code></a></li>
196<li><a href="#async_hooks_asynclocalstorage_getstore"><code>asyncLocalStorage.getStore()</code></a></li>
197<li><a href="#async_hooks_asynclocalstorage_enterwith_store"><code>asyncLocalStorage.enterWith(store)</code></a></li>
198<li><a href="#async_hooks_asynclocalstorage_run_store_callback_args"><code>asyncLocalStorage.run(store, callback[, ...args])</code></a></li>
199<li><a href="#async_hooks_asynclocalstorage_exit_callback_args"><code>asyncLocalStorage.exit(callback[, ...args])</code></a></li>
200<li><a href="#async_hooks_usage_with_async_await">Usage with <code>async/await</code></a></li>
201<li><a href="#async_hooks_troubleshooting">Troubleshooting</a></li>
202</ul>
203</li>
204</ul>
205</li>
206</ul></details>
207
208      <div id="apicontent">
209        <h2>Async hooks<span><a class="mark" href="#async_hooks_async_hooks" id="async_hooks_async_hooks">#</a></span></h2>
210
211<p></p><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
212<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v14.20.1/lib/async_hooks.js">lib/async_hooks.js</a></p>
213<p>The <code>async_hooks</code> module provides an API to track asynchronous resources. It
214can be accessed using:</p>
215<pre><code class="language-js"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);</code></pre>
216<section><h3>Terminology<span><a class="mark" href="#async_hooks_terminology" id="async_hooks_terminology">#</a></span></h3>
217<p>An asynchronous resource represents an object with an associated callback.
218This callback may be called multiple times, for example, the <code>'connection'</code>
219event in <code>net.createServer()</code>, or just a single time like in <code>fs.open()</code>.
220A resource can also be closed before the callback is called. <code>AsyncHook</code> does
221not explicitly distinguish between these different cases but will represent them
222as the abstract concept that is a resource.</p>
223<p>If <a href="worker_threads.html#worker_threads_class_worker"><code>Worker</code></a>s are used, each thread has an independent <code>async_hooks</code>
224interface, and each thread will use a new set of async IDs.</p>
225</section><section><h3>Overview<span><a class="mark" href="#async_hooks_overview" id="async_hooks_overview">#</a></span></h3>
226<p>Following is a simple overview of the public API.</p>
227<pre><code class="language-js"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
228
229<span class="hljs-comment">// Return the ID of the current execution context.</span>
230<span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
231
232<span class="hljs-comment">// Return the ID of the handle responsible for triggering the callback of the</span>
233<span class="hljs-comment">// current execution scope to call.</span>
234<span class="hljs-keyword">const</span> tid = async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
235
236<span class="hljs-comment">// Create a new AsyncHook instance. All of these callbacks are optional.</span>
237<span class="hljs-keyword">const</span> asyncHook =
238    async_hooks.<span class="hljs-title function_">createHook</span>({ init, before, after, destroy, promiseResolve });
239
240<span class="hljs-comment">// Allow callbacks of this AsyncHook instance to call. This is not an implicit</span>
241<span class="hljs-comment">// action after running the constructor, and must be explicitly run to begin</span>
242<span class="hljs-comment">// executing callbacks.</span>
243asyncHook.<span class="hljs-title function_">enable</span>();
244
245<span class="hljs-comment">// Disable listening for new asynchronous events.</span>
246asyncHook.<span class="hljs-title function_">disable</span>();
247
248<span class="hljs-comment">//</span>
249<span class="hljs-comment">// The following are the callbacks that can be passed to createHook().</span>
250<span class="hljs-comment">//</span>
251
252<span class="hljs-comment">// init is called during object construction. The resource may not have</span>
253<span class="hljs-comment">// completed construction when this callback runs, therefore all fields of the</span>
254<span class="hljs-comment">// resource referenced by "asyncId" may not have been populated.</span>
255<span class="hljs-keyword">function</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { }
256
257<span class="hljs-comment">// Before is called just before the resource's callback is called. It can be</span>
258<span class="hljs-comment">// called 0-N times for handles (such as TCPWrap), and will be called exactly 1</span>
259<span class="hljs-comment">// time for requests (such as FSReqCallback).</span>
260<span class="hljs-keyword">function</span> <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }
261
262<span class="hljs-comment">// After is called just after the resource's callback has finished.</span>
263<span class="hljs-keyword">function</span> <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }
264
265<span class="hljs-comment">// Destroy is called when the resource is destroyed.</span>
266<span class="hljs-keyword">function</span> <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { }
267
268<span class="hljs-comment">// promiseResolve is called only for promise resources, when the</span>
269<span class="hljs-comment">// `resolve` function passed to the `Promise` constructor is invoked</span>
270<span class="hljs-comment">// (either directly or through other means of resolving a promise).</span>
271<span class="hljs-keyword">function</span> <span class="hljs-title function_">promiseResolve</span>(<span class="hljs-params">asyncId</span>) { }</code></pre>
272</section><section><h3><code>async_hooks.createHook(callbacks)</code><span><a class="mark" href="#async_hooks_async_hooks_createhook_callbacks" id="async_hooks_async_hooks_createhook_callbacks">#</a></span></h3>
273<div class="api_metadata">
274<span>Added in: v8.1.0</span>
275</div>
276<ul>
277<li><code>callbacks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#async_hooks_hook_callbacks">Hook Callbacks</a> to register
278<ul>
279<li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> callback</a>.</li>
280<li><code>before</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#async_hooks_before_asyncid"><code>before</code> callback</a>.</li>
281<li><code>after</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#async_hooks_after_asyncid"><code>after</code> callback</a>.</li>
282<li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#async_hooks_destroy_asyncid"><code>destroy</code> callback</a>.</li>
283<li><code>promiseResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#async_hooks_promiseresolve_asyncid"><code>promiseResolve</code> callback</a>.</li>
284</ul>
285</li>
286<li>Returns: <a href="async_hooks.html#async_hooks_async_hooks_createhook_callbacks" class="type">&#x3C;AsyncHook></a> Instance used for disabling and enabling hooks</li>
287</ul>
288<p>Registers functions to be called for different lifetime events of each async
289operation.</p>
290<p>The callbacks <code>init()</code>/<code>before()</code>/<code>after()</code>/<code>destroy()</code> are called for the
291respective asynchronous event during a resource's lifetime.</p>
292<p>All callbacks are optional. For example, if only resource cleanup needs to
293be tracked, then only the <code>destroy</code> callback needs to be passed. The
294specifics of all functions that can be passed to <code>callbacks</code> is in the
295<a href="#async_hooks_hook_callbacks">Hook Callbacks</a> section.</p>
296<pre><code class="language-js"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
297
298<span class="hljs-keyword">const</span> asyncHook = async_hooks.<span class="hljs-title function_">createHook</span>({
299  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { },
300  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { }
301});</code></pre>
302<p>The callbacks will be inherited via the prototype chain:</p>
303<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MyAsyncCallbacks</span> {
304  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { }
305  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) {}
306}
307
308<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyAddedCallbacks</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">MyAsyncCallbacks</span> {
309  <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }
310  <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }
311}
312
313<span class="hljs-keyword">const</span> asyncHook = async_hooks.<span class="hljs-title function_">createHook</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">MyAddedCallbacks</span>());</code></pre>
314<p>Because promises are asynchronous resources whose lifecycle is tracked
315via the async hooks mechanism, the <code>init()</code>, <code>before()</code>, <code>after()</code>, and
316<code>destroy()</code> callbacks <em>must not</em> be async functions that return promises.</p>
317<h4>Error handling<span><a class="mark" href="#async_hooks_error_handling" id="async_hooks_error_handling">#</a></span></h4>
318<p>If any <code>AsyncHook</code> callbacks throw, the application will print the stack trace
319and exit. The exit path does follow that of an uncaught exception, but
320all <code>'uncaughtException'</code> listeners are removed, thus forcing the process to
321exit. The <code>'exit'</code> callbacks will still be called unless the application is run
322with <code>--abort-on-uncaught-exception</code>, in which case a stack trace will be
323printed and the application exits, leaving a core file.</p>
324<p>The reason for this error handling behavior is that these callbacks are running
325at potentially volatile points in an object's lifetime, for example during
326class construction and destruction. Because of this, it is deemed necessary to
327bring down the process quickly in order to prevent an unintentional abort in the
328future. This is subject to change in the future if a comprehensive analysis is
329performed to ensure an exception can follow the normal control flow without
330unintentional side effects.</p>
331<h4>Printing in AsyncHooks callbacks<span><a class="mark" href="#async_hooks_printing_in_asynchooks_callbacks" id="async_hooks_printing_in_asynchooks_callbacks">#</a></span></h4>
332<p>Because printing to the console is an asynchronous operation, <code>console.log()</code>
333will cause the AsyncHooks callbacks to be called. Using <code>console.log()</code> or
334similar asynchronous operations inside an AsyncHooks callback function will thus
335cause an infinite recursion. An easy solution to this when debugging is to use a
336synchronous logging operation such as <code>fs.writeFileSync(file, msg, flag)</code>.
337This will print to the file and will not invoke AsyncHooks recursively because
338it is synchronous.</p>
339<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
340<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'util'</span>);
341
342<span class="hljs-keyword">function</span> <span class="hljs-title function_">debug</span>(<span class="hljs-params">...args</span>) {
343  <span class="hljs-comment">// Use a function like this one when debugging inside an AsyncHooks callback</span>
344  fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'log.out'</span>, <span class="hljs-string">`<span class="hljs-subst">${util.format(...args)}</span>\n`</span>, { <span class="hljs-attr">flag</span>: <span class="hljs-string">'a'</span> });
345}</code></pre>
346<p>If an asynchronous operation is needed for logging, it is possible to keep
347track of what caused the asynchronous operation using the information
348provided by AsyncHooks itself. The logging should then be skipped when
349it was the logging itself that caused AsyncHooks callback to call. By
350doing this the otherwise infinite recursion is broken.</p>
351</section><section><h3>Class: <code>AsyncHook</code><span><a class="mark" href="#async_hooks_class_asynchook" id="async_hooks_class_asynchook">#</a></span></h3>
352<p>The class <code>AsyncHook</code> exposes an interface for tracking lifetime events
353of asynchronous operations.</p>
354<h4><code>asyncHook.enable()</code><span><a class="mark" href="#async_hooks_asynchook_enable" id="async_hooks_asynchook_enable">#</a></span></h4>
355<ul>
356<li>Returns: <a href="async_hooks.html#async_hooks_async_hooks_createhook_callbacks" class="type">&#x3C;AsyncHook></a> A reference to <code>asyncHook</code>.</li>
357</ul>
358<p>Enable the callbacks for a given <code>AsyncHook</code> instance. If no callbacks are
359provided, enabling is a no-op.</p>
360<p>The <code>AsyncHook</code> instance is disabled by default. If the <code>AsyncHook</code> instance
361should be enabled immediately after creation, the following pattern can be used.</p>
362<pre><code class="language-js"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
363
364<span class="hljs-keyword">const</span> hook = async_hooks.<span class="hljs-title function_">createHook</span>(callbacks).<span class="hljs-title function_">enable</span>();</code></pre>
365<h4><code>asyncHook.disable()</code><span><a class="mark" href="#async_hooks_asynchook_disable" id="async_hooks_asynchook_disable">#</a></span></h4>
366<ul>
367<li>Returns: <a href="async_hooks.html#async_hooks_async_hooks_createhook_callbacks" class="type">&#x3C;AsyncHook></a> A reference to <code>asyncHook</code>.</li>
368</ul>
369<p>Disable the callbacks for a given <code>AsyncHook</code> instance from the global pool of
370<code>AsyncHook</code> callbacks to be executed. Once a hook has been disabled it will not
371be called again until enabled.</p>
372<p>For API consistency <code>disable()</code> also returns the <code>AsyncHook</code> instance.</p>
373<h4>Hook callbacks<span><a class="mark" href="#async_hooks_hook_callbacks" id="async_hooks_hook_callbacks">#</a></span></h4>
374<p>Key events in the lifetime of asynchronous events have been categorized into
375four areas: instantiation, before/after the callback is called, and when the
376instance is destroyed.</p>
377<h5><code>init(asyncId, type, triggerAsyncId, resource)</code><span><a class="mark" href="#async_hooks_init_asyncid_type_triggerasyncid_resource" id="async_hooks_init_asyncid_type_triggerasyncid_resource">#</a></span></h5>
378<ul>
379<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> A unique ID for the async resource.</li>
380<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The type of the async resource.</li>
381<li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The unique ID of the async resource in whose
382execution context this async resource was created.</li>
383<li><code>resource</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Reference to the resource representing the async
384operation, needs to be released during <em>destroy</em>.</li>
385</ul>
386<p>Called when a class is constructed that has the <em>possibility</em> to emit an
387asynchronous event. This <em>does not</em> mean the instance must call
388<code>before</code>/<code>after</code> before <code>destroy</code> is called, only that the possibility
389exists.</p>
390<p>This behavior can be observed by doing something like opening a resource then
391closing it before the resource can be used. The following snippet demonstrates
392this.</p>
393<pre><code class="language-js"><span class="hljs-built_in">require</span>(<span class="hljs-string">'net'</span>).<span class="hljs-title function_">createServer</span>().<span class="hljs-title function_">listen</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">close</span>(); });
394<span class="hljs-comment">// OR</span>
395<span class="hljs-built_in">clearTimeout</span>(<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">10</span>));</code></pre>
396<p>Every new resource is assigned an ID that is unique within the scope of the
397current Node.js instance.</p>
398<h6><code>type</code><span><a class="mark" href="#async_hooks_type" id="async_hooks_type">#</a></span></h6>
399<p>The <code>type</code> is a string identifying the type of resource that caused
400<code>init</code> to be called. Generally, it will correspond to the name of the
401resource's constructor.</p>
402<pre><code class="language-text">FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,
403HTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,
404SHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,
405TTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,
406RANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject</code></pre>
407<p>There is also the <code>PROMISE</code> resource type, which is used to track <code>Promise</code>
408instances and asynchronous work scheduled by them.</p>
409<p>Users are able to define their own <code>type</code> when using the public embedder API.</p>
410<p>It is possible to have type name collisions. Embedders are encouraged to use
411unique prefixes, such as the npm package name, to prevent collisions when
412listening to the hooks.</p>
413<h6><code>triggerAsyncId</code><span><a class="mark" href="#async_hooks_triggerasyncid" id="async_hooks_triggerasyncid">#</a></span></h6>
414<p><code>triggerAsyncId</code> is the <code>asyncId</code> of the resource that caused (or "triggered")
415the new resource to initialize and that caused <code>init</code> to call. This is different
416from <code>async_hooks.executionAsyncId()</code> that only shows <em>when</em> a resource was
417created, while <code>triggerAsyncId</code> shows <em>why</em> a resource was created.</p>
418<p>The following is a simple demonstration of <code>triggerAsyncId</code>:</p>
419<pre><code class="language-js"><span class="hljs-keyword">const</span> { fd } = process.<span class="hljs-property">stdout</span>;
420
421async_hooks.<span class="hljs-title function_">createHook</span>({
422  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
423    <span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
424    fs.<span class="hljs-title function_">writeSync</span>(
425      fd,
426      <span class="hljs-string">`<span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>): trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
427  }
428}).<span class="hljs-title function_">enable</span>();
429
430net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);</code></pre>
431<p>Output when hitting the server with <code>nc localhost 8080</code>:</p>
432<pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1
433TCPWRAP(7): trigger: 5 execution: 0</code></pre>
434<p>The <code>TCPSERVERWRAP</code> is the server which receives the connections.</p>
435<p>The <code>TCPWRAP</code> is the new connection from the client. When a new
436connection is made, the <code>TCPWrap</code> instance is immediately constructed. This
437happens outside of any JavaScript stack. (An <code>executionAsyncId()</code> of <code>0</code> means
438that it is being executed from C++ with no JavaScript stack above it.) With only
439that information, it would be impossible to link resources together in
440terms of what caused them to be created, so <code>triggerAsyncId</code> is given the task
441of propagating what resource is responsible for the new resource's existence.</p>
442<h6><code>resource</code><span><a class="mark" href="#async_hooks_resource" id="async_hooks_resource">#</a></span></h6>
443<p><code>resource</code> is an object that represents the actual async resource that has
444been initialized. This can contain useful information that can vary based on
445the value of <code>type</code>. For instance, for the <code>GETADDRINFOREQWRAP</code> resource type,
446<code>resource</code> provides the host name used when looking up the IP address for the
447host in <code>net.Server.listen()</code>. The API for accessing this information is
448not supported, but using the Embedder API, users can provide
449and document their own resource objects. For example, such a resource object
450could contain the SQL query being executed.</p>
451<p>In some cases the resource object is reused for performance reasons, it is
452thus not safe to use it as a key in a <code>WeakMap</code> or add properties to it.</p>
453<h6>Asynchronous context example<span><a class="mark" href="#async_hooks_asynchronous_context_example" id="async_hooks_asynchronous_context_example">#</a></span></h6>
454<p>The following is an example with additional information about the calls to
455<code>init</code> between the <code>before</code> and <code>after</code> calls, specifically what the
456callback to <code>listen()</code> will look like. The output formatting is slightly more
457elaborate to make calling context easier to see.</p>
458<pre><code class="language-js"><span class="hljs-keyword">const</span> { fd } = process.<span class="hljs-property">stdout</span>;
459
460<span class="hljs-keyword">let</span> indent = <span class="hljs-number">0</span>;
461async_hooks.<span class="hljs-title function_">createHook</span>({
462  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
463    <span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
464    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
465    fs.<span class="hljs-title function_">writeSync</span>(
466      fd,
467      <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span><span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>):`</span> +
468      <span class="hljs-string">` trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
469  },
470  <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) {
471    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
472    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>before:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
473    indent += <span class="hljs-number">2</span>;
474  },
475  <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) {
476    indent -= <span class="hljs-number">2</span>;
477    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
478    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>after:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
479  },
480  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) {
481    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
482    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>destroy:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
483  },
484}).<span class="hljs-title function_">enable</span>();
485
486net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">() =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>, <span class="hljs-function">() =></span> {
487  <span class="hljs-comment">// Let's wait 10ms before logging the server started.</span>
488  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
489    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'>>>'</span>, async_hooks.<span class="hljs-title function_">executionAsyncId</span>());
490  }, <span class="hljs-number">10</span>);
491});</code></pre>
492<p>Output from only starting the server:</p>
493<pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1
494TickObject(6): trigger: 5 execution: 1
495before:  6
496  Timeout(7): trigger: 6 execution: 6
497after:   6
498destroy: 6
499before:  7
500<span class="hljs-meta">></span><span class="language-bash">>> 7</span>
501  TickObject(8): trigger: 7 execution: 7
502after:   7
503before:  8
504after:   8</code></pre>
505<p>As illustrated in the example, <code>executionAsyncId()</code> and <code>execution</code> each specify
506the value of the current execution context; which is delineated by calls to
507<code>before</code> and <code>after</code>.</p>
508<p>Only using <code>execution</code> to graph resource allocation results in the following:</p>
509<pre><code class="language-console">  root(1)
510     ^
511     |
512TickObject(6)
513     ^
514     |
515 Timeout(7)</code></pre>
516<p>The <code>TCPSERVERWRAP</code> is not part of this graph, even though it was the reason for
517<code>console.log()</code> being called. This is because binding to a port without a host
518name is a <em>synchronous</em> operation, but to maintain a completely asynchronous
519API the user's callback is placed in a <code>process.nextTick()</code>. Which is why
520<code>TickObject</code> is present in the output and is a 'parent' for <code>.listen()</code>
521callback.</p>
522<p>The graph only shows <em>when</em> a resource was created, not <em>why</em>, so to track
523the <em>why</em> use <code>triggerAsyncId</code>. Which can be represented with the following
524graph:</p>
525<pre><code class="language-console"> bootstrap(1)
526     |
527     ˅
528TCPSERVERWRAP(5)
529     |
530     ˅
531 TickObject(6)
532     |
533     ˅
534  Timeout(7)</code></pre>
535<h5><code>before(asyncId)</code><span><a class="mark" href="#async_hooks_before_asyncid" id="async_hooks_before_asyncid">#</a></span></h5>
536<ul>
537<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
538</ul>
539<p>When an asynchronous operation is initiated (such as a TCP server receiving a
540new connection) or completes (such as writing data to disk) a callback is
541called to notify the user. The <code>before</code> callback is called just before said
542callback is executed. <code>asyncId</code> is the unique identifier assigned to the
543resource about to execute the callback.</p>
544<p>The <code>before</code> callback will be called 0 to N times. The <code>before</code> callback
545will typically be called 0 times if the asynchronous operation was cancelled
546or, for example, if no connections are received by a TCP server. Persistent
547asynchronous resources like a TCP server will typically call the <code>before</code>
548callback multiple times, while other operations like <code>fs.open()</code> will call
549it only once.</p>
550<h5><code>after(asyncId)</code><span><a class="mark" href="#async_hooks_after_asyncid" id="async_hooks_after_asyncid">#</a></span></h5>
551<ul>
552<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
553</ul>
554<p>Called immediately after the callback specified in <code>before</code> is completed.</p>
555<p>If an uncaught exception occurs during execution of the callback, then <code>after</code>
556will run <em>after</em> the <code>'uncaughtException'</code> event is emitted or a <code>domain</code>'s
557handler runs.</p>
558<h5><code>destroy(asyncId)</code><span><a class="mark" href="#async_hooks_destroy_asyncid" id="async_hooks_destroy_asyncid">#</a></span></h5>
559<ul>
560<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
561</ul>
562<p>Called after the resource corresponding to <code>asyncId</code> is destroyed. It is also
563called asynchronously from the embedder API <code>emitDestroy()</code>.</p>
564<p>Some resources depend on garbage collection for cleanup, so if a reference is
565made to the <code>resource</code> object passed to <code>init</code> it is possible that <code>destroy</code>
566will never be called, causing a memory leak in the application. If the resource
567does not depend on garbage collection, then this will not be an issue.</p>
568<h5><code>promiseResolve(asyncId)</code><span><a class="mark" href="#async_hooks_promiseresolve_asyncid" id="async_hooks_promiseresolve_asyncid">#</a></span></h5>
569<div class="api_metadata">
570<span>Added in: v8.6.0</span>
571</div>
572<ul>
573<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
574</ul>
575<p>Called when the <code>resolve</code> function passed to the <code>Promise</code> constructor is
576invoked (either directly or through other means of resolving a promise).</p>
577<p><code>resolve()</code> does not do any observable synchronous work.</p>
578<p>The <code>Promise</code> is not necessarily fulfilled or rejected at this point if the
579<code>Promise</code> was resolved by assuming the state of another <code>Promise</code>.</p>
580<pre><code class="language-js"><span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =></span> <span class="hljs-title function_">resolve</span>(<span class="hljs-literal">true</span>)).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> {});</code></pre>
581<p>calls the following callbacks:</p>
582<pre><code class="language-text">init for PROMISE with id 5, trigger id: 1
583  promise resolve 5      # corresponds to resolve(true)
584init for PROMISE with id 6, trigger id: 5  # the Promise returned by then()
585  before 6               # the then() callback is entered
586  promise resolve 6      # the then() callback resolves the promise by returning
587  after 6</code></pre>
588<h4><code>async_hooks.executionAsyncResource()</code><span><a class="mark" href="#async_hooks_async_hooks_executionasyncresource" id="async_hooks_async_hooks_executionasyncresource">#</a></span></h4>
589<div class="api_metadata">
590<span>Added in: v13.9.0</span>
591</div>
592<ul>
593<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The resource representing the current execution.
594Useful to store data within the resource.</li>
595</ul>
596<p>Resource objects returned by <code>executionAsyncResource()</code> are most often internal
597Node.js handle objects with undocumented APIs. Using any functions or properties
598on the object is likely to crash your application and should be avoided.</p>
599<p>Using <code>executionAsyncResource()</code> in the top-level execution context will
600return an empty object as there is no handle or request object to use,
601but having an object representing the top-level can be helpful.</p>
602<pre><code class="language-js"><span class="hljs-keyword">const</span> { open } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
603<span class="hljs-keyword">const</span> { executionAsyncId, executionAsyncResource } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
604
605<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>());  <span class="hljs-comment">// 1 {}</span>
606<span class="hljs-title function_">open</span>(__filename, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
607  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>());  <span class="hljs-comment">// 7 FSReqWrap</span>
608});</code></pre>
609<p>This can be used to implement continuation local storage without the
610use of a tracking <code>Map</code> to store the metadata:</p>
611<pre><code class="language-js"><span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
612<span class="hljs-keyword">const</span> {
613  executionAsyncId,
614  executionAsyncResource,
615  createHook
616} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
617<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'state'</span>); <span class="hljs-comment">// Private symbol to avoid pollution</span>
618
619<span class="hljs-title function_">createHook</span>({
620  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) {
621    <span class="hljs-keyword">const</span> cr = <span class="hljs-title function_">executionAsyncResource</span>();
622    <span class="hljs-keyword">if</span> (cr) {
623      resource[sym] = cr[sym];
624    }
625  }
626}).<span class="hljs-title function_">enable</span>();
627
628<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
629  <span class="hljs-title function_">executionAsyncResource</span>()[sym] = { <span class="hljs-attr">state</span>: req.<span class="hljs-property">url</span> };
630  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
631    res.<span class="hljs-title function_">end</span>(<span class="hljs-variable constant_">JSON</span>.<span class="hljs-title function_">stringify</span>(<span class="hljs-title function_">executionAsyncResource</span>()[sym]));
632  }, <span class="hljs-number">100</span>);
633}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code></pre>
634<h4><code>async_hooks.executionAsyncId()</code><span><a class="mark" href="#async_hooks_async_hooks_executionasyncid" id="async_hooks_async_hooks_executionasyncid">#</a></span></h4>
635<div class="api_metadata">
636<details class="changelog"><summary>History</summary>
637<table>
638<tbody><tr><th>Version</th><th>Changes</th></tr>
639<tr><td>v8.2.0</td>
640<td><p>Renamed from <code>currentId</code>.</p></td></tr>
641<tr><td>v8.1.0</td>
642<td><p><span>Added in: v8.1.0</span></p></td></tr>
643</tbody></table>
644</details>
645</div>
646<ul>
647<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The <code>asyncId</code> of the current execution context. Useful to
648track when something calls.</li>
649</ul>
650<pre><code class="language-js"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
651
652<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(async_hooks.<span class="hljs-title function_">executionAsyncId</span>());  <span class="hljs-comment">// 1 - bootstrap</span>
653fs.<span class="hljs-title function_">open</span>(path, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
654  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(async_hooks.<span class="hljs-title function_">executionAsyncId</span>());  <span class="hljs-comment">// 6 - open()</span>
655});</code></pre>
656<p>The ID returned from <code>executionAsyncId()</code> is related to execution timing, not
657causality (which is covered by <code>triggerAsyncId()</code>):</p>
658<pre><code class="language-js"><span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {
659  <span class="hljs-comment">// Returns the ID of the server, not of the new connection, because the</span>
660  <span class="hljs-comment">// callback runs in the execution scope of the server's MakeCallback().</span>
661  async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
662
663}).<span class="hljs-title function_">listen</span>(port, <span class="hljs-function">() =></span> {
664  <span class="hljs-comment">// Returns the ID of a TickObject (process.nextTick()) because all</span>
665  <span class="hljs-comment">// callbacks passed to .listen() are wrapped in a nextTick().</span>
666  async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
667});</code></pre>
668<p>Promise contexts may not get precise <code>executionAsyncIds</code> by default.
669See the section on <a href="#async_hooks_promise_execution_tracking">promise execution tracking</a>.</p>
670<h4><code>async_hooks.triggerAsyncId()</code><span><a class="mark" href="#async_hooks_async_hooks_triggerasyncid" id="async_hooks_async_hooks_triggerasyncid">#</a></span></h4>
671<ul>
672<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The ID of the resource responsible for calling the callback
673that is currently being executed.</li>
674</ul>
675<pre><code class="language-js"><span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {
676  <span class="hljs-comment">// The resource that caused (or triggered) this callback to be called</span>
677  <span class="hljs-comment">// was that of the new connection. Thus the return value of triggerAsyncId()</span>
678  <span class="hljs-comment">// is the asyncId of "conn".</span>
679  async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
680
681}).<span class="hljs-title function_">listen</span>(port, <span class="hljs-function">() =></span> {
682  <span class="hljs-comment">// Even though all callbacks passed to .listen() are wrapped in a nextTick()</span>
683  <span class="hljs-comment">// the callback itself exists because the call to the server's .listen()</span>
684  <span class="hljs-comment">// was made. So the return value would be the ID of the server.</span>
685  async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
686});</code></pre>
687<p>Promise contexts may not get valid <code>triggerAsyncId</code>s by default. See
688the section on <a href="#async_hooks_promise_execution_tracking">promise execution tracking</a>.</p>
689</section><section><h3>Promise execution tracking<span><a class="mark" href="#async_hooks_promise_execution_tracking" id="async_hooks_promise_execution_tracking">#</a></span></h3>
690<p>By default, promise executions are not assigned <code>asyncId</code>s due to the relatively
691expensive nature of the <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">promise introspection API</a> provided by
692V8. This means that programs using promises or <code>async</code>/<code>await</code> will not get
693correct execution and trigger ids for promise callback contexts by default.</p>
694<pre><code class="language-js"><span class="hljs-keyword">const</span> ah = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
695<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
696  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${ah.executionAsyncId()}</span> tid <span class="hljs-subst">${ah.triggerAsyncId()}</span>`</span>);
697});
698<span class="hljs-comment">// produces:</span>
699<span class="hljs-comment">// eid 1 tid 0</span></code></pre>
700<p>Observe that the <code>then()</code> callback claims to have executed in the context of the
701outer scope even though there was an asynchronous hop involved. Also,
702the <code>triggerAsyncId</code> value is <code>0</code>, which means that we are missing context about
703the resource that caused (triggered) the <code>then()</code> callback to be executed.</p>
704<p>Installing async hooks via <code>async_hooks.createHook</code> enables promise execution
705tracking:</p>
706<pre><code class="language-js"><span class="hljs-keyword">const</span> ah = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
707ah.<span class="hljs-title function_">createHook</span>({ <span class="hljs-title function_">init</span>(<span class="hljs-params"></span>) {} }).<span class="hljs-title function_">enable</span>(); <span class="hljs-comment">// forces PromiseHooks to be enabled.</span>
708<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
709  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${ah.executionAsyncId()}</span> tid <span class="hljs-subst">${ah.triggerAsyncId()}</span>`</span>);
710});
711<span class="hljs-comment">// produces:</span>
712<span class="hljs-comment">// eid 7 tid 6</span></code></pre>
713<p>In this example, adding any actual hook function enabled the tracking of
714promises. There are two promises in the example above; the promise created by
715<code>Promise.resolve()</code> and the promise returned by the call to <code>then()</code>. In the
716example above, the first promise got the <code>asyncId</code> <code>6</code> and the latter got
717<code>asyncId</code> <code>7</code>. During the execution of the <code>then()</code> callback, we are executing
718in the context of promise with <code>asyncId</code> <code>7</code>. This promise was triggered by
719async resource <code>6</code>.</p>
720<p>Another subtlety with promises is that <code>before</code> and <code>after</code> callbacks are run
721only on chained promises. That means promises not created by <code>then()</code>/<code>catch()</code>
722will not have the <code>before</code> and <code>after</code> callbacks fired on them. For more details
723see the details of the V8 <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">PromiseHooks</a> API.</p>
724</section><section><h3>JavaScript embedder API<span><a class="mark" href="#async_hooks_javascript_embedder_api" id="async_hooks_javascript_embedder_api">#</a></span></h3>
725<p>Library developers that handle their own asynchronous resources performing tasks
726like I/O, connection pooling, or managing callback queues may use the
727<code>AsyncResource</code> JavaScript API so that all the appropriate callbacks are called.</p>
728<h4>Class: <code>AsyncResource</code><span><a class="mark" href="#async_hooks_class_asyncresource" id="async_hooks_class_asyncresource">#</a></span></h4>
729<p>The class <code>AsyncResource</code> is designed to be extended by the embedder's async
730resources. Using this, users can easily trigger the lifetime events of their
731own resources.</p>
732<p>The <code>init</code> hook will trigger when an <code>AsyncResource</code> is instantiated.</p>
733<p>The following is an overview of the <code>AsyncResource</code> API.</p>
734<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
735
736<span class="hljs-comment">// AsyncResource() is meant to be extended. Instantiating a</span>
737<span class="hljs-comment">// new AsyncResource() also triggers init. If triggerAsyncId is omitted then</span>
738<span class="hljs-comment">// async_hook.executionAsyncId() is used.</span>
739<span class="hljs-keyword">const</span> asyncResource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncResource</span>(
740  type, { <span class="hljs-attr">triggerAsyncId</span>: <span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-attr">requireManualDestroy</span>: <span class="hljs-literal">false</span> }
741);
742
743<span class="hljs-comment">// Run a function in the execution context of the resource. This will</span>
744<span class="hljs-comment">// * establish the context of the resource</span>
745<span class="hljs-comment">// * trigger the AsyncHooks before callbacks</span>
746<span class="hljs-comment">// * call the provided function `fn` with the supplied arguments</span>
747<span class="hljs-comment">// * trigger the AsyncHooks after callbacks</span>
748<span class="hljs-comment">// * restore the original execution context</span>
749asyncResource.<span class="hljs-title function_">runInAsyncScope</span>(fn, thisArg, ...args);
750
751<span class="hljs-comment">// Call AsyncHooks destroy callbacks.</span>
752asyncResource.<span class="hljs-title function_">emitDestroy</span>();
753
754<span class="hljs-comment">// Return the unique ID assigned to the AsyncResource instance.</span>
755asyncResource.<span class="hljs-title function_">asyncId</span>();
756
757<span class="hljs-comment">// Return the trigger ID for the AsyncResource instance.</span>
758asyncResource.<span class="hljs-title function_">triggerAsyncId</span>();</code></pre>
759<h5><code>new AsyncResource(type[, options])</code><span><a class="mark" href="#async_hooks_new_asyncresource_type_options" id="async_hooks_new_asyncresource_type_options">#</a></span></h5>
760<ul>
761<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The type of async event.</li>
762<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
763<ul>
764<li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The ID of the execution context that created this
765async event. <strong>Default:</strong> <code>executionAsyncId()</code>.</li>
766<li><code>requireManualDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to <code>true</code>, disables <code>emitDestroy</code>
767when the object is garbage collected. This usually does not need to be set
768(even if <code>emitDestroy</code> is called manually), unless the resource's <code>asyncId</code>
769is retrieved and the sensitive API's <code>emitDestroy</code> is called with it.
770When set to <code>false</code>, the <code>emitDestroy</code> call on garbage collection
771will only take place if there is at least one active <code>destroy</code> hook.
772<strong>Default:</strong> <code>false</code>.</li>
773</ul>
774</li>
775</ul>
776<p>Example usage:</p>
777<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">DBQuery</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
778  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">db</span>) {
779    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'DBQuery'</span>);
780    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span> = db;
781  }
782
783  <span class="hljs-title function_">getInfo</span>(<span class="hljs-params">query, callback</span>) {
784    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span>.<span class="hljs-title function_">get</span>(query, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
785      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(callback, <span class="hljs-literal">null</span>, err, data);
786    });
787  }
788
789  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
790    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span> = <span class="hljs-literal">null</span>;
791    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>();
792  }
793}</code></pre>
794<h5>Static method: <code>AsyncResource.bind(fn[, type])</code><span><a class="mark" href="#async_hooks_static_method_asyncresource_bind_fn_type" id="async_hooks_static_method_asyncresource_bind_fn_type">#</a></span></h5>
795<div class="api_metadata">
796<span>Added in: v14.8.0</span>
797</div>
798<ul>
799<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to bind to the current execution context.</li>
800<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> An optional name to associate with the underlying
801<code>AsyncResource</code>.</li>
802</ul>
803<p>Binds the given function to the current execution context.</p>
804<p>The returned function will have an <code>asyncResource</code> property referencing
805the <code>AsyncResource</code> to which the function is bound.</p>
806<h5><code>asyncResource.bind(fn)</code><span><a class="mark" href="#async_hooks_asyncresource_bind_fn" id="async_hooks_asyncresource_bind_fn">#</a></span></h5>
807<div class="api_metadata">
808<span>Added in: v14.8.0</span>
809</div>
810<ul>
811<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to bind to the current <code>AsyncResource</code>.</li>
812</ul>
813<p>Binds the given function to execute to this <code>AsyncResource</code>'s scope.</p>
814<p>The returned function will have an <code>asyncResource</code> property referencing
815the <code>AsyncResource</code> to which the function is bound.</p>
816<h5><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code><span><a class="mark" href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args" id="async_hooks_asyncresource_runinasyncscope_fn_thisarg_args">#</a></span></h5>
817<div class="api_metadata">
818<span>Added in: v9.6.0</span>
819</div>
820<ul>
821<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to call in the execution context of this async
822resource.</li>
823<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The receiver to be used for the function call.</li>
824<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Optional arguments to pass to the function.</li>
825</ul>
826<p>Call the provided function with the provided arguments in the execution context
827of the async resource. This will establish the context, trigger the AsyncHooks
828before callbacks, call the function, trigger the AsyncHooks after callbacks, and
829then restore the original execution context.</p>
830<h5><code>asyncResource.emitDestroy()</code><span><a class="mark" href="#async_hooks_asyncresource_emitdestroy" id="async_hooks_asyncresource_emitdestroy">#</a></span></h5>
831<ul>
832<li>Returns: <a href="async_hooks.html#async_hooks_class_asyncresource" class="type">&#x3C;AsyncResource></a> A reference to <code>asyncResource</code>.</li>
833</ul>
834<p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will
835be thrown if it is called more than once. This <strong>must</strong> be manually called. If
836the resource is left to be collected by the GC then the <code>destroy</code> hooks will
837never be called.</p>
838<h5><code>asyncResource.asyncId()</code><span><a class="mark" href="#async_hooks_asyncresource_asyncid" id="async_hooks_asyncresource_asyncid">#</a></span></h5>
839<ul>
840<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The unique <code>asyncId</code> assigned to the resource.</li>
841</ul>
842<h5><code>asyncResource.triggerAsyncId()</code><span><a class="mark" href="#async_hooks_asyncresource_triggerasyncid" id="async_hooks_asyncresource_triggerasyncid">#</a></span></h5>
843<ul>
844<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The same <code>triggerAsyncId</code> that is passed to the
845<code>AsyncResource</code> constructor.</li>
846</ul>
847<p><a id="async-resource-worker-pool"></a></p>
848<h4>Using <code>AsyncResource</code> for a <code>Worker</code> thread pool<span><a class="mark" href="#async_hooks_using_asyncresource_for_a_worker_thread_pool" id="async_hooks_using_asyncresource_for_a_worker_thread_pool">#</a></span></h4>
849<p>The following example shows how to use the <code>AsyncResource</code> class to properly
850provide async tracking for a <a href="worker_threads.html#worker_threads_class_worker"><code>Worker</code></a> pool. Other resource pools, such as
851database connection pools, can follow a similar model.</p>
852<p>Assuming that the task is adding two numbers, using a file named
853<code>task_processor.js</code> with the following content:</p>
854<pre><code class="language-js"><span class="hljs-keyword">const</span> { parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
855parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">task</span>) =></span> {
856  parentPort.<span class="hljs-title function_">postMessage</span>(task.<span class="hljs-property">a</span> + task.<span class="hljs-property">b</span>);
857});</code></pre>
858<p>a Worker pool around it could use the following structure:</p>
859<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
860<span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
861<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);
862<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'worker_threads'</span>);
863
864<span class="hljs-keyword">const</span> kTaskInfo = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kTaskInfo'</span>);
865<span class="hljs-keyword">const</span> kWorkerFreedEvent = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kWorkerFreedEvent'</span>);
866
867<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
868  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">callback</span>) {
869    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'WorkerPoolTaskInfo'</span>);
870    <span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span> = callback;
871  }
872
873  <span class="hljs-title function_">done</span>(<span class="hljs-params">err, result</span>) {
874    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span>, <span class="hljs-literal">null</span>, err, result);
875    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>();  <span class="hljs-comment">// `TaskInfo`s are used only once.</span>
876  }
877}
878
879<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPool</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
880  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">numThreads</span>) {
881    <span class="hljs-variable language_">super</span>();
882    <span class="hljs-variable language_">this</span>.<span class="hljs-property">numThreads</span> = numThreads;
883    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span> = [];
884    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span> = [];
885    <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span> = [];
886
887    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numThreads; i++)
888      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
889
890    <span class="hljs-comment">// Any time the kWorkerFreedEvent is emitted, dispatch</span>
891    <span class="hljs-comment">// the next task pending in the queue, if any.</span>
892    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">on</span>(kWorkerFreedEvent, <span class="hljs-function">() =></span> {
893      <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-property">length</span> > <span class="hljs-number">0</span>) {
894        <span class="hljs-keyword">const</span> { task, callback } = <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">shift</span>();
895        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runTask</span>(task, callback);
896      }
897    });
898  }
899
900  <span class="hljs-title function_">addNewWorker</span>(<span class="hljs-params"></span>) {
901    <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(path.<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'task_processor.js'</span>));
902    worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
903      <span class="hljs-comment">// In case of success: Call the callback that was passed to `runTask`,</span>
904      <span class="hljs-comment">// remove the `TaskInfo` associated with the Worker, and mark it as free</span>
905      <span class="hljs-comment">// again.</span>
906      worker[kTaskInfo].<span class="hljs-title function_">done</span>(<span class="hljs-literal">null</span>, result);
907      worker[kTaskInfo] = <span class="hljs-literal">null</span>;
908      <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
909      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
910    });
911    worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
912      <span class="hljs-comment">// In case of an uncaught exception: Call the callback that was passed to</span>
913      <span class="hljs-comment">// `runTask` with the error.</span>
914      <span class="hljs-keyword">if</span> (worker[kTaskInfo])
915        worker[kTaskInfo].<span class="hljs-title function_">done</span>(err, <span class="hljs-literal">null</span>);
916      <span class="hljs-keyword">else</span>
917        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
918      <span class="hljs-comment">// Remove the worker from the list and start a new Worker to replace the</span>
919      <span class="hljs-comment">// current one.</span>
920      <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">splice</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">indexOf</span>(worker), <span class="hljs-number">1</span>);
921      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
922    });
923    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">push</span>(worker);
924    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
925    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
926  }
927
928  <span class="hljs-title function_">runTask</span>(<span class="hljs-params">task, callback</span>) {
929    <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-property">length</span> === <span class="hljs-number">0</span>) {
930      <span class="hljs-comment">// No free threads, wait until a worker thread becomes free.</span>
931      <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">push</span>({ task, callback });
932      <span class="hljs-keyword">return</span>;
933    }
934
935    <span class="hljs-keyword">const</span> worker = <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">pop</span>();
936    worker[kTaskInfo] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span>(callback);
937    worker.<span class="hljs-title function_">postMessage</span>(task);
938  }
939
940  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
941    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>) worker.<span class="hljs-title function_">terminate</span>();
942  }
943}
944
945<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-title class_">WorkerPool</span>;</code></pre>
946<p>Without the explicit tracking added by the <code>WorkerPoolTaskInfo</code> objects,
947it would appear that the callbacks are associated with the individual <code>Worker</code>
948objects. However, the creation of the <code>Worker</code>s is not associated with the
949creation of the tasks and does not provide information about when tasks
950were scheduled.</p>
951<p>This pool could be used as follows:</p>
952<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">WorkerPool</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./worker_pool.js'</span>);
953<span class="hljs-keyword">const</span> os = <span class="hljs-built_in">require</span>(<span class="hljs-string">'os'</span>);
954
955<span class="hljs-keyword">const</span> pool = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPool</span>(os.<span class="hljs-title function_">cpus</span>().<span class="hljs-property">length</span>);
956
957<span class="hljs-keyword">let</span> finished = <span class="hljs-number">0</span>;
958<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; i++) {
959  pool.<span class="hljs-title function_">runTask</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">42</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">100</span> }, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =></span> {
960    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i, err, result);
961    <span class="hljs-keyword">if</span> (++finished === <span class="hljs-number">10</span>)
962      pool.<span class="hljs-title function_">close</span>();
963  });
964}</code></pre>
965<h4>Integrating <code>AsyncResource</code> with <code>EventEmitter</code><span><a class="mark" href="#async_hooks_integrating_asyncresource_with_eventemitter" id="async_hooks_integrating_asyncresource_with_eventemitter">#</a></span></h4>
966<p>Event listeners triggered by an <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> may be run in a different
967execution context than the one that was active when <code>eventEmitter.on()</code> was
968called.</p>
969<p>The following example shows how to use the <code>AsyncResource</code> class to properly
970associate an event listener with the correct execution context. The same
971approach can be applied to a <a href="stream.html#stream_stream"><code>Stream</code></a> or a similar event-driven class.</p>
972<pre><code class="language-js"><span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
973<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
974
975<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
976  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-title class_">AsyncResource</span>.<span class="hljs-title function_">bind</span>(<span class="hljs-function">() =></span> {
977    <span class="hljs-comment">// Execution context is bound to the current outer scope.</span>
978  }));
979  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
980    <span class="hljs-comment">// Execution context is bound to the scope that caused 'close' to emit.</span>
981  });
982  res.<span class="hljs-title function_">end</span>();
983}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code></pre>
984</section><section><h3>Class: <code>AsyncLocalStorage</code><span><a class="mark" href="#async_hooks_class_asynclocalstorage" id="async_hooks_class_asynclocalstorage">#</a></span></h3>
985<div class="api_metadata">
986<span>Added in: v13.10.0</span>
987</div>
988<p>This class is used to create asynchronous state within callbacks and promise
989chains. It allows storing data throughout the lifetime of a web request
990or any other asynchronous duration. It is similar to thread-local storage
991in other languages.</p>
992<p>While you can create your own implementation on top of the <code>async_hooks</code> module,
993<code>AsyncLocalStorage</code> should be preferred as it is a performant and memory safe
994implementation that involves significant optimizations that are non-obvious to
995implement.</p>
996<p>The following example uses <code>AsyncLocalStorage</code> to build a simple logger
997that assigns IDs to incoming HTTP requests and includes them in messages
998logged within each request.</p>
999<pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
1000<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'async_hooks'</span>);
1001
1002<span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
1003
1004<span class="hljs-keyword">function</span> <span class="hljs-title function_">logWithId</span>(<span class="hljs-params">msg</span>) {
1005  <span class="hljs-keyword">const</span> id = asyncLocalStorage.<span class="hljs-title function_">getStore</span>();
1006  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${id !== <span class="hljs-literal">undefined</span> ? id : <span class="hljs-string">'-'</span>}</span>:`</span>, msg);
1007}
1008
1009<span class="hljs-keyword">let</span> idSeq = <span class="hljs-number">0</span>;
1010http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
1011  asyncLocalStorage.<span class="hljs-title function_">run</span>(idSeq++, <span class="hljs-function">() =></span> {
1012    <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'start'</span>);
1013    <span class="hljs-comment">// Imagine any chain of async operations here</span>
1014    <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
1015      <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'finish'</span>);
1016      res.<span class="hljs-title function_">end</span>();
1017    });
1018  });
1019}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);
1020
1021http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
1022http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
1023<span class="hljs-comment">// Prints:</span>
1024<span class="hljs-comment">//   0: start</span>
1025<span class="hljs-comment">//   1: start</span>
1026<span class="hljs-comment">//   0: finish</span>
1027<span class="hljs-comment">//   1: finish</span></code></pre>
1028<p>When having multiple instances of <code>AsyncLocalStorage</code>, they are independent
1029from each other. It is safe to instantiate this class multiple times.</p>
1030<h4><code>new AsyncLocalStorage()</code><span><a class="mark" href="#async_hooks_new_asynclocalstorage" id="async_hooks_new_asynclocalstorage">#</a></span></h4>
1031<div class="api_metadata">
1032<span>Added in: v13.10.0</span>
1033</div>
1034<p>Creates a new instance of <code>AsyncLocalStorage</code>. Store is only provided within a
1035<code>run()</code> call or after an <code>enterWith()</code> call.</p>
1036<h4><code>asyncLocalStorage.disable()</code><span><a class="mark" href="#async_hooks_asynclocalstorage_disable" id="async_hooks_asynclocalstorage_disable">#</a></span></h4>
1037<div class="api_metadata">
1038<span>Added in: v13.10.0</span>
1039</div>
1040<p>Disables the instance of <code>AsyncLocalStorage</code>. All subsequent calls
1041to <code>asyncLocalStorage.getStore()</code> will return <code>undefined</code> until
1042<code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code> is called again.</p>
1043<p>When calling <code>asyncLocalStorage.disable()</code>, all current contexts linked to the
1044instance will be exited.</p>
1045<p>Calling <code>asyncLocalStorage.disable()</code> is required before the
1046<code>asyncLocalStorage</code> can be garbage collected. This does not apply to stores
1047provided by the <code>asyncLocalStorage</code>, as those objects are garbage collected
1048along with the corresponding async resources.</p>
1049<p>Use this method when the <code>asyncLocalStorage</code> is not in use anymore
1050in the current process.</p>
1051<h4><code>asyncLocalStorage.getStore()</code><span><a class="mark" href="#async_hooks_asynclocalstorage_getstore" id="async_hooks_asynclocalstorage_getstore">#</a></span></h4>
1052<div class="api_metadata">
1053<span>Added in: v13.10.0</span>
1054</div>
1055<ul>
1056<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
1057</ul>
1058<p>Returns the current store.
1059If called outside of an asynchronous context initialized by
1060calling <code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code>, it
1061returns <code>undefined</code>.</p>
1062<h4><code>asyncLocalStorage.enterWith(store)</code><span><a class="mark" href="#async_hooks_asynclocalstorage_enterwith_store" id="async_hooks_asynclocalstorage_enterwith_store">#</a></span></h4>
1063<div class="api_metadata">
1064<span>Added in: v13.11.0</span>
1065</div>
1066<ul>
1067<li><code>store</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
1068</ul>
1069<p>Transitions into the context for the remainder of the current
1070synchronous execution and then persists the store through any following
1071asynchronous calls.</p>
1072<p>Example:</p>
1073<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
1074<span class="hljs-comment">// Replaces previous store with the given store object</span>
1075asyncLocalStorage.<span class="hljs-title function_">enterWith</span>(store);
1076asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
1077<span class="hljs-title function_">someAsyncOperation</span>(<span class="hljs-function">() =></span> {
1078  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span>
1079});</code></pre>
1080<p>This transition will continue for the <em>entire</em> synchronous execution.
1081This means that if, for example, the context is entered within an event
1082handler subsequent event handlers will also run within that context unless
1083specifically bound to another context with an <code>AsyncResource</code>. That is why
1084<code>run()</code> should be preferred over <code>enterWith()</code> unless there are strong reasons
1085to use the latter method.</p>
1086<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
1087
1088emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'my-event'</span>, <span class="hljs-function">() =></span> {
1089  asyncLocalStorage.<span class="hljs-title function_">enterWith</span>(store);
1090});
1091emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'my-event'</span>, <span class="hljs-function">() =></span> {
1092  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span>
1093});
1094
1095asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
1096emitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'my-event'</span>);
1097asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span></code></pre>
1098<h4><code>asyncLocalStorage.run(store, callback[, ...args])</code><span><a class="mark" href="#async_hooks_asynclocalstorage_run_store_callback_args" id="async_hooks_asynclocalstorage_run_store_callback_args">#</a></span></h4>
1099<div class="api_metadata">
1100<span>Added in: v13.10.0</span>
1101</div>
1102<ul>
1103<li><code>store</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
1104<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
1105<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
1106</ul>
1107<p>Runs a function synchronously within a context and returns its
1108return value. The store is not accessible outside of the callback function.
1109The store is accessible to any asynchronous operations created within the
1110callback.</p>
1111<p>The optional <code>args</code> are passed to the callback function.</p>
1112<p>If the callback function throws an error, the error is thrown by <code>run()</code> too.
1113The stacktrace is not impacted by this call and the context is exited.</p>
1114<p>Example:</p>
1115<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span> };
1116<span class="hljs-keyword">try</span> {
1117  asyncLocalStorage.<span class="hljs-title function_">run</span>(store, <span class="hljs-function">() =></span> {
1118    asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
1119    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
1120      asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
1121    }, <span class="hljs-number">200</span>);
1122    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
1123  });
1124} <span class="hljs-keyword">catch</span> (e) {
1125  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
1126  <span class="hljs-comment">// The error will be caught here</span>
1127}</code></pre>
1128<h4><code>asyncLocalStorage.exit(callback[, ...args])</code><span><a class="mark" href="#async_hooks_asynclocalstorage_exit_callback_args" id="async_hooks_asynclocalstorage_exit_callback_args">#</a></span></h4>
1129<div class="api_metadata">
1130<span>Added in: v13.10.0</span>
1131</div>
1132<ul>
1133<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
1134<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
1135</ul>
1136<p>Runs a function synchronously outside of a context and returns its
1137return value. The store is not accessible within the callback function or
1138the asynchronous operations created within the callback. Any <code>getStore()</code>
1139call done within the callback function will always return <code>undefined</code>.</p>
1140<p>The optional <code>args</code> are passed to the callback function.</p>
1141<p>If the callback function throws an error, the error is thrown by <code>exit()</code> too.
1142The stacktrace is not impacted by this call and the context is re-entered.</p>
1143<p>Example:</p>
1144<pre><code class="language-js"><span class="hljs-comment">// Within a call to run</span>
1145<span class="hljs-keyword">try</span> {
1146  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object or value</span>
1147  asyncLocalStorage.<span class="hljs-title function_">exit</span>(<span class="hljs-function">() =></span> {
1148    asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
1149    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
1150  });
1151} <span class="hljs-keyword">catch</span> (e) {
1152  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object or value</span>
1153  <span class="hljs-comment">// The error will be caught here</span>
1154}</code></pre>
1155<h4>Usage with <code>async/await</code><span><a class="mark" href="#async_hooks_usage_with_async_await" id="async_hooks_usage_with_async_await">#</a></span></h4>
1156<p>If, within an async function, only one <code>await</code> call is to run within a context,
1157the following pattern should be used:</p>
1158<pre><code class="language-js"><span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params"></span>) {
1159  <span class="hljs-keyword">await</span> asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>(), <span class="hljs-function">() =></span> {
1160    asyncLocalStorage.<span class="hljs-title function_">getStore</span>().<span class="hljs-title function_">set</span>(<span class="hljs-string">'key'</span>, value);
1161    <span class="hljs-keyword">return</span> <span class="hljs-title function_">foo</span>(); <span class="hljs-comment">// The return value of foo will be awaited</span>
1162  });
1163}</code></pre>
1164<p>In this example, the store is only available in the callback function and the
1165functions called by <code>foo</code>. Outside of <code>run</code>, calling <code>getStore</code> will return
1166<code>undefined</code>.</p>
1167<h4>Troubleshooting<span><a class="mark" href="#async_hooks_troubleshooting" id="async_hooks_troubleshooting">#</a></span></h4>
1168<p>In most cases your application or library code should have no issues with
1169<code>AsyncLocalStorage</code>. But in rare cases you may face situations when the
1170current store is lost in one of asynchronous operations. In those cases,
1171consider the following options.</p>
1172<p>If your code is callback-based, it is enough to promisify it with
1173<a href="util.html#util_util_promisify_original"><code>util.promisify()</code></a>, so it starts working with native promises.</p>
1174<p>If you need to keep using callback-based API, or your code assumes
1175a custom thenable implementation, use the <a href="#async_hooks_class_asyncresource"><code>AsyncResource</code></a> class
1176to associate the asynchronous operation with the correct execution context.</p></section>
1177        <!-- API END -->
1178      </div>
1179    </div>
1180  </div>
1181  <script>
1182    'use strict';
1183    {
1184      const kCustomPreference = 'customDarkTheme';
1185      const userSettings = sessionStorage.getItem(kCustomPreference);
1186      const themeToggleButton = document.getElementById('theme-toggle-btn');
1187      if (userSettings === null && window.matchMedia) {
1188        const mq = window.matchMedia('(prefers-color-scheme: dark)');
1189        if ('onchange' in mq) {
1190          function mqChangeListener(e) {
1191            document.body.classList.toggle('dark-mode', e.matches);
1192          }
1193          mq.addEventListener('change', mqChangeListener);
1194          if (themeToggleButton) {
1195            themeToggleButton.addEventListener('click', function() {
1196              mq.removeEventListener('change', mqChangeListener);
1197            }, { once: true });
1198          }
1199        }
1200        if (mq.matches) {
1201          document.body.classList.add('dark-mode');
1202        }
1203      } else if (userSettings === 'true') {
1204        document.body.classList.add('dark-mode');
1205      }
1206      if (themeToggleButton) {
1207        themeToggleButton.hidden = false;
1208        themeToggleButton.addEventListener('click', function() {
1209          sessionStorage.setItem(
1210            kCustomPreference,
1211            document.body.classList.toggle('dark-mode')
1212          );
1213        });
1214      }
1215    }
1216  </script>
1217</body>
1218</html>
1219