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