summaryrefslogtreecommitdiff
path: root/doc
diff options
context:
space:
mode:
authorbtea <2356281422@qq.com>2023-04-26 14:18:42 +0800
committerGitHub <noreply@github.com>2023-04-26 06:18:42 +0000
commit2fa721f08819ee9f5fc7e7a97e4e7454b9406d4a (patch)
tree72c4055dba6db674d4a2a99dd05f22a1330034cc /doc
parent2e44a14cfb84a0665fb4bac06b2fca76e8da06a7 (diff)
downloadnode-new-2fa721f08819ee9f5fc7e7a97e4e7454b9406d4a.tar.gz
doc: async_hooks asynchronous content example add mjs code
PR-URL: https://github.com/nodejs/node/pull/47401 Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Diffstat (limited to 'doc')
-rw-r--r--doc/api/async_hooks.md43
1 files changed, 42 insertions, 1 deletions
diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md
index 59b2284f29..1b408ba97b 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');