From 2fa721f08819ee9f5fc7e7a97e4e7454b9406d4a Mon Sep 17 00:00:00 2001 From: btea <2356281422@qq.com> Date: Wed, 26 Apr 2023 14:18:42 +0800 Subject: [PATCH] doc: async_hooks asynchronous content example add mjs code PR-URL: https://github.com/nodejs/node/pull/47401 Reviewed-By: Luigi Pinca --- doc/api/async_hooks.md | 43 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md index 59b2284f295ee6..1b408ba97b717c 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -445,7 +445,48 @@ The following is an example with additional information about the calls to callback to `listen()` will look like. The output formatting is slightly more elaborate to make calling context easier to see. -```js +```mjs +import async_hooks from 'node:async_hooks'; +import fs from 'node:fs'; +import net from 'node:net'; +import { stdout } from 'node:process'; +const { fd } = stdout; + +let indent = 0; +async_hooks.createHook({ + init(asyncId, type, triggerAsyncId) { + const eid = async_hooks.executionAsyncId(); + const indentStr = ' '.repeat(indent); + fs.writeSync( + fd, + `${indentStr}${type}(${asyncId}):` + + ` trigger: ${triggerAsyncId} execution: ${eid}\n`); + }, + before(asyncId) { + const indentStr = ' '.repeat(indent); + fs.writeSync(fd, `${indentStr}before: ${asyncId}\n`); + indent += 2; + }, + after(asyncId) { + indent -= 2; + const indentStr = ' '.repeat(indent); + fs.writeSync(fd, `${indentStr}after: ${asyncId}\n`); + }, + destroy(asyncId) { + const indentStr = ' '.repeat(indent); + fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\n`); + }, +}).enable(); + +net.createServer(() => {}).listen(8080, () => { + // Let's wait 10ms before logging the server started. + setTimeout(() => { + console.log('>>>', async_hooks.executionAsyncId()); + }, 10); +}); +``` + +```cjs const async_hooks = require('node:async_hooks'); const fs = require('node:fs'); const net = require('node:net');