diff --git a/content/api/v16/assert.en.md b/content/api/v16/assert.en.md
index 6065cf859f..30296972d4 100644
--- a/content/api/v16/assert.en.md
+++ b/content/api/v16/assert.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:assert` module provides a set of assertion functions for verifying
invariants.
diff --git a/content/api/v16/async_context.en.md b/content/api/v16/async_context.en.md
index 012ce21e3e..45990b68f9 100644
--- a/content/api/v16/async_context.en.md
+++ b/content/api/v16/async_context.en.md
@@ -13,7 +13,7 @@ Stable
-
+
### Introduction
diff --git a/content/api/v16/async_hooks.en.md b/content/api/v16/async_hooks.en.md
index 042ccffb65..cc13fc86a0 100644
--- a/content/api/v16/async_hooks.en.md
+++ b/content/api/v16/async_hooks.en.md
@@ -13,7 +13,7 @@ Experimental
-
+
The `node:async_hooks` module provides an API to track asynchronous resources.
It can be accessed using:
diff --git a/content/api/v16/buffer.en.md b/content/api/v16/buffer.en.md
index 60bcc366ab..c00e1ae2f2 100644
--- a/content/api/v16/buffer.en.md
+++ b/content/api/v16/buffer.en.md
@@ -13,7 +13,7 @@ Stable
-
+
`Buffer` objects are used to represent a fixed-length sequence of bytes. Many
Node.js APIs support `Buffer`s.
diff --git a/content/api/v16/child_process.en.md b/content/api/v16/child_process.en.md
index d9be5c4012..07133468c5 100644
--- a/content/api/v16/child_process.en.md
+++ b/content/api/v16/child_process.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:child_process` module provides the ability to spawn subprocesses in
a manner that is similar, but not identical, to popen(3). This capability
diff --git a/content/api/v16/cluster.en.md b/content/api/v16/cluster.en.md
index 7a221dcbd5..c5f23e2c3b 100644
--- a/content/api/v16/cluster.en.md
+++ b/content/api/v16/cluster.en.md
@@ -13,7 +13,7 @@ Stable
-
+
Clusters of Node.js processes can be used to run multiple instances of Node.js
that can distribute workloads among their application threads. When process
diff --git a/content/api/v16/console.en.md b/content/api/v16/console.en.md
index 58df618887..ee394af4d6 100644
--- a/content/api/v16/console.en.md
+++ b/content/api/v16/console.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:console` module provides a simple debugging console that is similar to
the JavaScript console mechanism provided by web browsers.
diff --git a/content/api/v16/crypto.en.md b/content/api/v16/crypto.en.md
index 50b241c79e..3058fa0813 100644
--- a/content/api/v16/crypto.en.md
+++ b/content/api/v16/crypto.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:crypto` module provides cryptographic functionality that includes a
set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
@@ -954,12 +954,17 @@ If `outputEncoding` is given a string is returned; otherwise, a
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value.
* Returns: [`Buffer`](/api/v16/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-Generates private and public Diffie-Hellman key values, and returns
+Generates private and public Diffie-Hellman key values unless they have been
+generated or computed already, and returns
the public key in the specified `encoding`. This key should be
transferred to the other party.
If `encoding` is provided a string is returned; otherwise a
[`Buffer`][] is returned.
+This function is a thin wrapper around [`DH_generate_key()`][]. In particular,
+once a private key has been generated or set, calling this function only updates
+the public key but does not generate a new private key.
+
#### `diffieHellman.getGenerator([encoding])`
@@ -1016,6 +1021,10 @@ Sets the Diffie-Hellman private key. If the `encoding` argument is provided,
to be a string. If no `encoding` is provided, `privateKey` is expected
to be a [`Buffer`][], `TypedArray`, or `DataView`.
+This function does not automatically compute the associated public key. Either
+[`diffieHellman.setPublicKey()`][] or [`diffieHellman.generateKeys()`][] can be
+used to manually provide the public key or to automatically derive it.
+
#### `diffieHellman.setPublicKey(publicKey[, encoding])`
@@ -5094,6 +5103,7 @@ See the [list of SSL OP Flags][] for details.
[Web Crypto API documentation]: /api/v16/webcrypto
[`BN_is_prime_ex`]: https://www.openssl.org/docs/man1.1.1/man3/BN_is_prime_ex.html
[`Buffer`]: /api/v16/buffer
+[`DH_generate_key()`]: https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html
[`DiffieHellmanGroup`]: #class-diffiehellmangroup
[`EVP_BytesToKey`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html
[`KeyObject`]: #class-keyobject
@@ -5128,6 +5138,7 @@ See the [list of SSL OP Flags][] for details.
[`crypto.scrypt()`]: #cryptoscryptpassword-salt-keylen-options-callback
[`decipher.final()`]: #decipherfinaloutputencoding
[`decipher.update()`]: #decipherupdatedata-inputencoding-outputencoding
+[`diffieHellman.generateKeys()`]: #diffiehellmangeneratekeysencoding
[`diffieHellman.setPublicKey()`]: #diffiehellmansetpublickeypublickey-encoding
[`ecdh.generateKeys()`]: #ecdhgeneratekeysencoding-format
[`ecdh.setPrivateKey()`]: #ecdhsetprivatekeyprivatekey-encoding
diff --git a/content/api/v16/dgram.en.md b/content/api/v16/dgram.en.md
index 59338eeb77..de0f224bc7 100644
--- a/content/api/v16/dgram.en.md
+++ b/content/api/v16/dgram.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:dgram` module provides an implementation of UDP datagram sockets.
diff --git a/content/api/v16/diagnostics_channel.en.md b/content/api/v16/diagnostics_channel.en.md
index e992cbd011..0f007e70c8 100644
--- a/content/api/v16/diagnostics_channel.en.md
+++ b/content/api/v16/diagnostics_channel.en.md
@@ -13,7 +13,7 @@ Experimental
-
+
The `node:diagnostics_channel` module provides an API to create named channels
to report arbitrary message data for diagnostics purposes.
diff --git a/content/api/v16/dns.en.md b/content/api/v16/dns.en.md
index dbc91aeaba..165f9c7cd6 100644
--- a/content/api/v16/dns.en.md
+++ b/content/api/v16/dns.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:dns` module enables name resolution. For example, use it to look up IP
addresses of host names.
diff --git a/content/api/v16/domain.en.md b/content/api/v16/domain.en.md
index 941b15bf92..c0ff2ad67e 100644
--- a/content/api/v16/domain.en.md
+++ b/content/api/v16/domain.en.md
@@ -15,7 +15,7 @@ Deprecated
-
+
**This module is pending deprecation.** Once a replacement API has been
finalized, this module will be fully deprecated. Most developers should
diff --git a/content/api/v16/events.en.md b/content/api/v16/events.en.md
index 16d9fcb585..abac6f9475 100644
--- a/content/api/v16/events.en.md
+++ b/content/api/v16/events.en.md
@@ -15,7 +15,7 @@ Stable
-
+
Much of the Node.js core API is built around an idiomatic asynchronous
event-driven architecture in which certain kinds of objects (called "emitters")
diff --git a/content/api/v16/fs.en.md b/content/api/v16/fs.en.md
index ce9584c06d..86fcdf1349 100644
--- a/content/api/v16/fs.en.md
+++ b/content/api/v16/fs.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:fs` module enables interacting with the file system in a
way modeled on standard POSIX functions.
diff --git a/content/api/v16/http.en.md b/content/api/v16/http.en.md
index 2b2811fc64..9e81112bcf 100644
--- a/content/api/v16/http.en.md
+++ b/content/api/v16/http.en.md
@@ -13,7 +13,7 @@ Stable
-
+
To use the HTTP server and client one must `require('node:http')`.
diff --git a/content/api/v16/http2.en.md b/content/api/v16/http2.en.md
index 8532277951..39cfc6dff6 100644
--- a/content/api/v16/http2.en.md
+++ b/content/api/v16/http2.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:http2` module provides an implementation of the [HTTP/2][] protocol.
It can be accessed using:
diff --git a/content/api/v16/https.en.md b/content/api/v16/https.en.md
index 8458b5677c..ad61b9b038 100644
--- a/content/api/v16/https.en.md
+++ b/content/api/v16/https.en.md
@@ -13,7 +13,7 @@ Stable
-
+
HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.
diff --git a/content/api/v16/inspector.en.md b/content/api/v16/inspector.en.md
index 962518913b..fb08ec7b7a 100644
--- a/content/api/v16/inspector.en.md
+++ b/content/api/v16/inspector.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:inspector` module provides an API for interacting with the V8
inspector.
diff --git a/content/api/v16/net.en.md b/content/api/v16/net.en.md
index 8961601604..fee71c3ff7 100644
--- a/content/api/v16/net.en.md
+++ b/content/api/v16/net.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:net` module provides an asynchronous network API for creating stream-based
TCP or [IPC][] servers ([`net.createServer()`][]) and clients
diff --git a/content/api/v16/os.en.md b/content/api/v16/os.en.md
index 373d4ac98b..2fafd3d86e 100644
--- a/content/api/v16/os.en.md
+++ b/content/api/v16/os.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:os` module provides operating system-related utility methods and
properties. It can be accessed using:
diff --git a/content/api/v16/path.en.md b/content/api/v16/path.en.md
index 11a424ca2c..36a4c0bb6e 100644
--- a/content/api/v16/path.en.md
+++ b/content/api/v16/path.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:path` module provides utilities for working with file and directory
paths. It can be accessed using:
diff --git a/content/api/v16/perf_hooks.en.md b/content/api/v16/perf_hooks.en.md
index 52b5ce2652..8efbebc15f 100644
--- a/content/api/v16/perf_hooks.en.md
+++ b/content/api/v16/perf_hooks.en.md
@@ -13,7 +13,7 @@ Stable
-
+
This module provides an implementation of a subset of the W3C
[Web Performance APIs][] as well as additional APIs for
diff --git a/content/api/v16/process.en.md b/content/api/v16/process.en.md
index 8ae1743b93..61b22944a9 100644
--- a/content/api/v16/process.en.md
+++ b/content/api/v16/process.en.md
@@ -9,7 +9,7 @@ version: 'v16'
-
+
The `process` object provides information about, and control over, the current
Node.js process.
diff --git a/content/api/v16/punycode.en.md b/content/api/v16/punycode.en.md
index 9d14574e4c..6123f579e6 100644
--- a/content/api/v16/punycode.en.md
+++ b/content/api/v16/punycode.en.md
@@ -15,7 +15,7 @@ Deprecated
-
+
**The version of the punycode module bundled in Node.js is being deprecated.**
In a future major version of Node.js this module will be removed. Users
diff --git a/content/api/v16/querystring.en.md b/content/api/v16/querystring.en.md
index 2b9f6b6520..619688b2f4 100644
--- a/content/api/v16/querystring.en.md
+++ b/content/api/v16/querystring.en.md
@@ -15,7 +15,7 @@ Legacy
-
+
The `node:querystring` module provides utilities for parsing and formatting URL
query strings. It can be accessed using:
diff --git a/content/api/v16/readline.en.md b/content/api/v16/readline.en.md
index bc16f0f9b9..37ec868884 100644
--- a/content/api/v16/readline.en.md
+++ b/content/api/v16/readline.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:readline` module provides an interface for reading data from a
[Readable][] stream (such as [`process.stdin`][]) one line at a time.
diff --git a/content/api/v16/repl.en.md b/content/api/v16/repl.en.md
index f43fb0ff24..44f3d5be08 100644
--- a/content/api/v16/repl.en.md
+++ b/content/api/v16/repl.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation
that is available both as a standalone program or includible in other
diff --git a/content/api/v16/stream.en.md b/content/api/v16/stream.en.md
index d749f01724..754c8223ed 100644
--- a/content/api/v16/stream.en.md
+++ b/content/api/v16/stream.en.md
@@ -13,7 +13,7 @@ Stable
-
+
A stream is an abstract interface for working with streaming data in Node.js.
The `node:stream` module provides an API for implementing the stream interface.
diff --git a/content/api/v16/string_decoder.en.md b/content/api/v16/string_decoder.en.md
index b3beb37ba1..70af2bf2b1 100644
--- a/content/api/v16/string_decoder.en.md
+++ b/content/api/v16/string_decoder.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:string_decoder` module provides an API for decoding `Buffer` objects
into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
diff --git a/content/api/v16/test.en.md b/content/api/v16/test.en.md
index 24d3780e89..ddff0a6be4 100644
--- a/content/api/v16/test.en.md
+++ b/content/api/v16/test.en.md
@@ -13,7 +13,7 @@ Experimental
-
+
The `node:test` module facilitates the creation of JavaScript tests that
report results in [TAP][] format. To access it:
diff --git a/content/api/v16/timers.en.md b/content/api/v16/timers.en.md
index 054d29ec20..51a3135099 100644
--- a/content/api/v16/timers.en.md
+++ b/content/api/v16/timers.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `timer` module exposes a global API for scheduling functions to
be called at some future period of time. Because the timer functions are
diff --git a/content/api/v16/tls.en.md b/content/api/v16/tls.en.md
index b793d83716..083c0214be 100644
--- a/content/api/v16/tls.en.md
+++ b/content/api/v16/tls.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:tls` module provides an implementation of the Transport Layer Security
(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
diff --git a/content/api/v16/tracing.en.md b/content/api/v16/tracing.en.md
index 7150c40c6b..8a4c33d004 100644
--- a/content/api/v16/tracing.en.md
+++ b/content/api/v16/tracing.en.md
@@ -13,7 +13,7 @@ Experimental
-
+
The `node:trace_events` module provides a mechanism to centralize tracing
information generated by V8, Node.js core, and userspace code.
diff --git a/content/api/v16/tty.en.md b/content/api/v16/tty.en.md
index 86e1124f89..a802c064b8 100644
--- a/content/api/v16/tty.en.md
+++ b/content/api/v16/tty.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`
classes. In most cases, it will not be necessary or possible to use this module
diff --git a/content/api/v16/url.en.md b/content/api/v16/url.en.md
index 6c69378721..5e4975997a 100644
--- a/content/api/v16/url.en.md
+++ b/content/api/v16/url.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:url` module provides utilities for URL resolution and parsing. It can
be accessed using:
diff --git a/content/api/v16/util.en.md b/content/api/v16/util.en.md
index 490f8b0d5e..5b05c2e985 100644
--- a/content/api/v16/util.en.md
+++ b/content/api/v16/util.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:util` module supports the needs of Node.js internal APIs. Many of the
utilities are useful for application and module developers as well. To access
diff --git a/content/api/v16/v8.en.md b/content/api/v16/v8.en.md
index 350c367458..64a8696ad5 100644
--- a/content/api/v16/v8.en.md
+++ b/content/api/v16/v8.en.md
@@ -7,7 +7,7 @@ version: 'v16'
-
+
The `node:v8` module exposes APIs that are specific to the version of [V8][]
built into the Node.js binary. It can be accessed using:
diff --git a/content/api/v16/vm.en.md b/content/api/v16/vm.en.md
index 39094a35cd..e36e969610 100644
--- a/content/api/v16/vm.en.md
+++ b/content/api/v16/vm.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:vm` module enables compiling and running code within V8 Virtual
Machine contexts.
diff --git a/content/api/v16/wasi.en.md b/content/api/v16/wasi.en.md
index 76d391b9e7..c2354579dd 100644
--- a/content/api/v16/wasi.en.md
+++ b/content/api/v16/wasi.en.md
@@ -13,7 +13,7 @@ Experimental
-
+
The WASI API provides an implementation of the [WebAssembly System Interface][]
specification. WASI gives sandboxed WebAssembly applications access to the
diff --git a/content/api/v16/worker_threads.en.md b/content/api/v16/worker_threads.en.md
index c7947f752e..ecbbf744e3 100644
--- a/content/api/v16/worker_threads.en.md
+++ b/content/api/v16/worker_threads.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:worker_threads` module enables the use of threads that execute
JavaScript in parallel. To access it:
diff --git a/content/api/v16/zlib.en.md b/content/api/v16/zlib.en.md
index 48e7543407..d02bc55897 100644
--- a/content/api/v16/zlib.en.md
+++ b/content/api/v16/zlib.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:zlib` module provides compression functionality implemented using
Gzip, Deflate/Inflate, and Brotli.
diff --git a/content/api/v18/assert.en.md b/content/api/v18/assert.en.md
index 4032b41fda..3a0b79c5c7 100644
--- a/content/api/v18/assert.en.md
+++ b/content/api/v18/assert.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:assert` module provides a set of assertion functions for verifying
invariants.
diff --git a/content/api/v18/async_context.en.md b/content/api/v18/async_context.en.md
index 7dfc56f1e9..66389114f9 100644
--- a/content/api/v18/async_context.en.md
+++ b/content/api/v18/async_context.en.md
@@ -13,7 +13,7 @@ Stable
-
+
### Introduction
@@ -113,30 +113,66 @@ Each instance of `AsyncLocalStorage` maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.
-#### `new AsyncLocalStorage([options])`
+#### `new AsyncLocalStorage()`
-
+
+
+Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
+`run()` call or after an `enterWith()` call.
+
+#### Static method: `AsyncLocalStorage.bind(fn)`
+
+
-`options.onPropagate` is experimental.
+Experimental
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `onPropagate` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional callback invoked before a store is
- propagated to a new async resource. Returning `true` allows propagation,
- returning `false` avoids it. Default is to propagate always.
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to bind to the current execution context.
+* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A new function that calls `fn` within the captured
+ execution context.
-Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
-`run()` call or after an `enterWith()` call.
+Binds the given function to the current execution context.
+
+#### Static method: `AsyncLocalStorage.snapshot()`
+
+
+
+
-The `onPropagate` is called during creation of an async resource. Throwing at
-this time will print the stack trace and exit. See
-[`async_hooks` Error handling][] for details.
+Experimental
+
+
+
+* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A new function with the signature
+ `(fn: (...args) : R, ...args) : R`.
-Creating an async resource within the `onPropagate` callback will result in
-a recursive call to `onPropagate`.
+Captures the current execution context and returns a function that accepts a
+function as an argument. Whenever the returned function is called, it
+calls the function passed to it within the captured context.
+
+```js
+const asyncLocalStorage = new AsyncLocalStorage();
+const runInAsyncScope = asyncLocalStorage.run(123, () => asyncLocalStorage.snapshot());
+const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
+console.log(result); // returns 123
+```
+
+AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
+async context tracking purposes, for example:
+
+```js
+class Foo {
+ #runInAsyncScope = AsyncLocalStorage.snapshot();
+
+ get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
+}
+
+const foo = asyncLocalStorage.run(123, () => new Foo());
+console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
+```
#### `asyncLocalStorage.disable()`
@@ -774,5 +810,4 @@ const server = createServer((req, res) => {
[`EventEmitter`]: /api/v18/events#class-eventemitter
[`Stream`]: /api/v18/stream#stream
[`Worker`]: worker_threads.md#class-worker
-[`async_hooks` Error handling]: async_hooks.md#error-handling
[`util.promisify()`]: /api/v18/util#utilpromisifyoriginal
diff --git a/content/api/v18/async_hooks.en.md b/content/api/v18/async_hooks.en.md
index 1937563de9..fe81a3504d 100644
--- a/content/api/v18/async_hooks.en.md
+++ b/content/api/v18/async_hooks.en.md
@@ -13,7 +13,7 @@ Experimental. Please migrate away from this API, if you can. We do not recommend
-
+
We strongly discourage the use of the `async_hooks` API.
Other APIs that can cover most of its use cases include:
@@ -361,6 +361,7 @@ The following is a simple demonstration of `triggerAsyncId`:
import { createHook, executionAsyncId } from 'node:async_hooks';
import { stdout } from 'node:process';
import net from 'node:net';
+import fs from 'node:fs';
createHook({
init(asyncId, type, triggerAsyncId) {
@@ -376,6 +377,7 @@ net.createServer((conn) => {}).listen(8080);
const { createHook, executionAsyncId } = require('node:async_hooks');
const { stdout } = require('node:process');
const net = require('node:net');
+const fs = require('node:fs');
createHook({
init(asyncId, type, triggerAsyncId) {
@@ -690,6 +692,7 @@ const server = createServer((req, res) => {
```mjs|cjs
import { executionAsyncId } from 'node:async_hooks';
+import fs from 'node:fs';
console.log(executionAsyncId()); // 1 - bootstrap
fs.open(path, 'r', (err, fd) => {
@@ -697,6 +700,7 @@ fs.open(path, 'r', (err, fd) => {
});
--------------
const async_hooks = require('node:async_hooks');
+const fs = require('node:fs');
console.log(async_hooks.executionAsyncId()); // 1 - bootstrap
fs.open(path, 'r', (err, fd) => {
diff --git a/content/api/v18/buffer.en.md b/content/api/v18/buffer.en.md
index 3e2fbd4645..c17b131ae9 100644
--- a/content/api/v18/buffer.en.md
+++ b/content/api/v18/buffer.en.md
@@ -13,7 +13,7 @@ Stable
-
+
`Buffer` objects are used to represent a fixed-length sequence of bytes. Many
Node.js APIs support `Buffer`s.
@@ -916,6 +916,26 @@ console.log(bufA.length);
`Buffer.concat()` may also use the internal `Buffer` pool like
[`Buffer.allocUnsafe()`][] does.
+#### Static method: `Buffer.copyBytesFrom(view[, offset[, length]])`
+
+
+
+* `view` [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) The [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) to copy.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The starting offset within `view`. **Default:**: `0`.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of elements from `view` to copy.
+ **Default:** `view.length - offset`.
+
+Copies the underlying memory of `view` into a new `Buffer`.
+
+```js
+const u16 = new Uint16Array([0, 0xffff]);
+const buf = Buffer.copyBytesFrom(u16, 0, 1);
+u16[1] = 0;
+console.log(buf.length); // 2
+console.log(buf[0]); // 255
+console.log(buf[1]); // 255
+```
+
#### Static method: `Buffer.from(array)`
diff --git a/content/api/v18/child_process.en.md b/content/api/v18/child_process.en.md
index 3a34627440..a041774de9 100644
--- a/content/api/v18/child_process.en.md
+++ b/content/api/v18/child_process.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:child_process` module provides the ability to spawn subprocesses in
a manner that is similar, but not identical, to popen(3). This capability
diff --git a/content/api/v18/cli.en.md b/content/api/v18/cli.en.md
index 2fd11ef036..7cc470aa45 100644
--- a/content/api/v18/cli.en.md
+++ b/content/api/v18/cli.en.md
@@ -162,7 +162,7 @@ $ node --completion-bash > node_bash_completion
$ source node_bash_completion
```
-#### `-C=condition`, `--conditions=condition`
+#### `-C condition`, `--conditions=condition`
@@ -183,7 +183,7 @@ The default Node.js conditions of `"node"`, `"default"`, `"import"`, and
For example, to run a module with "development" resolutions:
```console
-$ node -C=development app.js
+$ node -C development app.js
```
#### `--cpu-prof`
diff --git a/content/api/v18/cluster.en.md b/content/api/v18/cluster.en.md
index 70e78f506a..276a98a457 100644
--- a/content/api/v18/cluster.en.md
+++ b/content/api/v18/cluster.en.md
@@ -13,7 +13,7 @@ Stable
-
+
Clusters of Node.js processes can be used to run multiple instances of Node.js
that can distribute workloads among their application threads. When process
diff --git a/content/api/v18/console.en.md b/content/api/v18/console.en.md
index 4bf1723c50..7e22858e13 100644
--- a/content/api/v18/console.en.md
+++ b/content/api/v18/console.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:console` module provides a simple debugging console that is similar to
the JavaScript console mechanism provided by web browsers.
diff --git a/content/api/v18/crypto.en.md b/content/api/v18/crypto.en.md
index 4b045b2b3f..a5ebb570bb 100644
--- a/content/api/v18/crypto.en.md
+++ b/content/api/v18/crypto.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:crypto` module provides cryptographic functionality that includes a
set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
@@ -30,12 +30,12 @@ console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
--------------
-const crypto = require('node:crypto');
+const { createHmac } = require('node:crypto');
const secret = 'abcdefg';
-const hash = crypto.createHmac('sha256', secret)
- .update('I love cupcakes')
- .digest('hex');
+const hash = createHmac('sha256', secret)
+ .update('I love cupcakes')
+ .digest('hex');
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
@@ -153,8 +153,8 @@ const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
--------------
-const { Certificate } = require('node:crypto');
const { Buffer } = require('node:buffer');
+const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
@@ -257,8 +257,8 @@ const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
--------------
-const { Certificate } = require('node:crypto');
const { Buffer } = require('node:buffer');
+const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
@@ -954,12 +954,17 @@ If `outputEncoding` is given a string is returned; otherwise, a
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value.
* Returns: [`Buffer`](/api/v18/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-Generates private and public Diffie-Hellman key values, and returns
+Generates private and public Diffie-Hellman key values unless they have been
+generated or computed already, and returns
the public key in the specified `encoding`. This key should be
transferred to the other party.
If `encoding` is provided a string is returned; otherwise a
[`Buffer`][] is returned.
+This function is a thin wrapper around [`DH_generate_key()`][]. In particular,
+once a private key has been generated or set, calling this function only updates
+the public key but does not generate a new private key.
+
#### `diffieHellman.getGenerator([encoding])`
@@ -1016,6 +1021,10 @@ Sets the Diffie-Hellman private key. If the `encoding` argument is provided,
to be a string. If no `encoding` is provided, `privateKey` is expected
to be a [`Buffer`][], `TypedArray`, or `DataView`.
+This function does not automatically compute the associated public key. Either
+[`diffieHellman.setPublicKey()`][] or [`diffieHellman.generateKeys()`][] can be
+used to manually provide the public key or to automatically derive it.
+
#### `diffieHellman.setPublicKey(publicKey[, encoding])`
@@ -4768,7 +4777,7 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_ALL
Applies multiple bug workarounds within OpenSSL. See
- https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html
+ https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html
for detail.
@@ -4780,13 +4789,13 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
Allows legacy insecure renegotiation between OpenSSL and unpatched
clients or servers. See
- https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html .
+ https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html .
SSL_OP_CIPHER_SERVER_PREFERENCE
Attempts to use the server's preferences instead of the client's when
selecting a cipher. Behavior depends on protocol version. See
- https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html .
+ https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html .
SSL_OP_CISCO_ANYCONNECT
@@ -4806,44 +4815,10 @@ See the [list of SSL OP Flags][] for details.
Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability
workaround added in OpenSSL 0.9.6d.
-
- SSL_OP_EPHEMERAL_RSA
- Instructs OpenSSL to always use the tmp_rsa key when performing RSA
- operations.
-
SSL_OP_LEGACY_SERVER_CONNECT
Allows initial connection to servers that do not support RI.
-
- SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
-
-
-
- SSL_OP_MICROSOFT_SESS_ID_BUG
-
-
-
- SSL_OP_MSIE_SSLV2_RSA_PADDING
- Instructs OpenSSL to disable the workaround for a man-in-the-middle
- protocol-version vulnerability in the SSL 2.0 server implementation.
-
-
- SSL_OP_NETSCAPE_CA_DN_BUG
-
-
-
- SSL_OP_NETSCAPE_CHALLENGE_BUG
-
-
-
- SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
-
-
-
- SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
-
-
SSL_OP_NO_COMPRESSION
Instructs OpenSSL to disable support for SSL/TLS compression.
@@ -4893,14 +4868,6 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_NO_TLSv1_3
Instructs OpenSSL to turn off TLS v1.3
-
- SSL_OP_PKCS1_CHECK_1
-
-
-
- SSL_OP_PKCS1_CHECK_2
-
-
SSL_OP_PRIORITIZE_CHACHA
Instructs OpenSSL server to prioritize ChaCha20-Poly1305
@@ -4909,32 +4876,6 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_CIPHER_SERVER_PREFERENCE
is not enabled.
-
- SSL_OP_SINGLE_DH_USE
- Instructs OpenSSL to always create a new key when using
- temporary/ephemeral DH parameters.
-
-
- SSL_OP_SINGLE_ECDH_USE
- Instructs OpenSSL to always create a new key when using
- temporary/ephemeral ECDH parameters.
-
-
- SSL_OP_SSLEAY_080_CLIENT_DH_BUG
-
-
-
- SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
-
-
-
- SSL_OP_TLS_BLOCK_PADDING_BUG
-
-
-
- SSL_OP_TLS_D5_BUG
-
-
SSL_OP_TLS_ROLLBACK_BUG
Instructs OpenSSL to disable version rollback attack detection.
@@ -5117,6 +5058,7 @@ See the [list of SSL OP Flags][] for details.
[Web Crypto API documentation]: /api/v18/webcrypto
[`BN_is_prime_ex`]: https://www.openssl.org/docs/man1.1.1/man3/BN_is_prime_ex.html
[`Buffer`]: /api/v18/buffer
+[`DH_generate_key()`]: https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html
[`DiffieHellmanGroup`]: #class-diffiehellmangroup
[`EVP_BytesToKey`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html
[`KeyObject`]: #class-keyobject
@@ -5153,6 +5095,7 @@ See the [list of SSL OP Flags][] for details.
[`crypto.webcrypto.subtle`]: /api/v18/webcrypto#class-subtlecrypto
[`decipher.final()`]: #decipherfinaloutputencoding
[`decipher.update()`]: #decipherupdatedata-inputencoding-outputencoding
+[`diffieHellman.generateKeys()`]: #diffiehellmangeneratekeysencoding
[`diffieHellman.setPublicKey()`]: #diffiehellmansetpublickeypublickey-encoding
[`ecdh.generateKeys()`]: #ecdhgeneratekeysencoding-format
[`ecdh.setPrivateKey()`]: #ecdhsetprivatekeyprivatekey-encoding
diff --git a/content/api/v18/debugger.en.md b/content/api/v18/debugger.en.md
index 13b63ea36d..5c0a921404 100644
--- a/content/api/v18/debugger.en.md
+++ b/content/api/v18/debugger.en.md
@@ -206,11 +206,19 @@ debug>
after)
* `watch(expr)`: Add expression to watch list
* `unwatch(expr)`: Remove expression from watch list
+* `unwatch(index)`: Remove expression at specific index from watch list
* `watchers`: List all watchers and their values (automatically listed on each
breakpoint)
* `repl`: Open debugger's repl for evaluation in debugging script's context
* `exec expr`, `p expr`: Execute an expression in debugging script's context and
print its value
+* `profile`: Start CPU profiling session
+* `profileEnd`: Stop current CPU profiling session
+* `profiles`: List all completed CPU profiling sessions
+* `profiles[n].save(filepath = 'node.cpuprofile')`: Save CPU profiling session
+ to disk as JSON
+* `takeHeapSnapshot(filepath = 'node.heapsnapshot')`: Take a heap snapshot
+ and save to disk as JSON
#### Execution control
diff --git a/content/api/v18/deprecations.en.md b/content/api/v18/deprecations.en.md
index 4f2022ebcb..2b677f8310 100644
--- a/content/api/v18/deprecations.en.md
+++ b/content/api/v18/deprecations.en.md
@@ -1864,7 +1864,7 @@ In a future version of Node.js, [`message.headers`][],
[`dnsPromises.lookup()`]: /api/v18/dns#dnspromiseslookuphostname-options
[`domain`]: /api/v18/domain
[`ecdh.setPublicKey()`]: /api/v18/crypto#ecdhsetpublickeypublickey-encoding
-[`emitter.listenerCount(eventName)`]: /api/v18/events#emitterlistenercounteventname
+[`emitter.listenerCount(eventName)`]: /api/v18/events#emitterlistenercounteventname-listener
[`events.listenerCount(emitter, eventName)`]: /api/v18/events#eventslistenercountemitter-eventname
[`fs.FileHandle`]: /api/v18/fs#class-filehandle
[`fs.access()`]: /api/v18/fs#fsaccesspath-mode-callback
diff --git a/content/api/v18/dgram.en.md b/content/api/v18/dgram.en.md
index edc0c86399..ff64e61bd1 100644
--- a/content/api/v18/dgram.en.md
+++ b/content/api/v18/dgram.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:dgram` module provides an implementation of UDP datagram sockets.
diff --git a/content/api/v18/diagnostics_channel.en.md b/content/api/v18/diagnostics_channel.en.md
index 7df9628e85..1267e6f41c 100644
--- a/content/api/v18/diagnostics_channel.en.md
+++ b/content/api/v18/diagnostics_channel.en.md
@@ -5,7 +5,7 @@ category: 'api'
version: 'v18'
---
-
+
@@ -15,7 +15,7 @@ Stable
-
+
The `node:diagnostics_channel` module provides an API to create named channels
to report arbitrary message data for diagnostics purposes.
diff --git a/content/api/v18/dns.en.md b/content/api/v18/dns.en.md
index 0c9a173b59..4f0ab40d10 100644
--- a/content/api/v18/dns.en.md
+++ b/content/api/v18/dns.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:dns` module enables name resolution. For example, use it to look up IP
addresses of host names.
diff --git a/content/api/v18/domain.en.md b/content/api/v18/domain.en.md
index 34a54674ad..622b8036e2 100644
--- a/content/api/v18/domain.en.md
+++ b/content/api/v18/domain.en.md
@@ -15,7 +15,7 @@ Deprecated
-
+
**This module is pending deprecation.** Once a replacement API has been
finalized, this module will be fully deprecated. Most developers should
diff --git a/content/api/v18/esm.en.md b/content/api/v18/esm.en.md
index dfb9a32e34..733d4776d6 100644
--- a/content/api/v18/esm.en.md
+++ b/content/api/v18/esm.en.md
@@ -1015,7 +1015,7 @@ export async function load(url, context, nextLoad) {
// file, search up the file system for the nearest parent package.json file
// and read its "type" field.
const format = await getPackageType(url);
- // When a hook returns a format of 'commonjs', `source` is be ignored.
+ // When a hook returns a format of 'commonjs', `source` is ignored.
// To handle CommonJS files, a handler needs to be registered with
// `require.extensions` in order to process the files with the CommonJS
// loader. Avoiding the need for a separate CommonJS handler is a future
diff --git a/content/api/v18/events.en.md b/content/api/v18/events.en.md
index ea3e56fcf3..4b53b06bd4 100644
--- a/content/api/v18/events.en.md
+++ b/content/api/v18/events.en.md
@@ -15,7 +15,7 @@ Stable
-
+
Much of the Node.js core API is built around an idiomatic asynchronous
event-driven architecture in which certain kinds of objects (called "emitters")
@@ -596,14 +596,17 @@ Returns the current max listener value for the `EventEmitter` which is either
set by [`emitter.setMaxListeners(n)`][] or defaults to
[`events.defaultMaxListeners`][].
-#### `emitter.listenerCount(eventName)`
+#### `emitter.listenerCount(eventName[, listener])`
-
+
* `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The name of the event being listened for
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The event handler function
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-Returns the number of listeners listening to the event named `eventName`.
+Returns the number of listeners listening for the event named `eventName`.
+If `listener` is provided, it will return how many times the listener is found
+in the list of the listeners of the event.
#### `emitter.listeners(eventName)`
@@ -2086,6 +2089,18 @@ equivalent `EventEmitter` API. The only difference between `addListener()` and
`addEventListener()` is that `addListener()` will return a reference to the
`EventTarget`.
+##### `nodeEventTarget.emit(type, arg)`
+
+
+
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `arg` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if event listeners registered for the `type` exist,
+ otherwise `false`.
+
+Node.js-specific extension to the `EventTarget` class that dispatches the
+`arg` to the list of handlers for `type`.
+
##### `nodeEventTarget.eventNames()`
@@ -2137,7 +2152,7 @@ of max event listeners.
* Returns: [`EventTarget`](/api/v18/events#eventtarget) this
-Node.js-specific alias for `eventTarget.removeListener()`.
+Node.js-specific alias for `eventTarget.removeEventListener()`.
##### `nodeEventTarget.on(type, listener)`
@@ -2149,7 +2164,7 @@ Node.js-specific alias for `eventTarget.removeListener()`.
* Returns: [`EventTarget`](/api/v18/events#eventtarget) this
-Node.js-specific alias for `eventTarget.addListener()`.
+Node.js-specific alias for `eventTarget.addEventListener()`.
##### `nodeEventTarget.once(type, listener)`
@@ -2202,7 +2217,7 @@ to the `EventTarget`.
[`EventTarget` error handling]: #eventtarget-error-handling
[`Event` Web API]: https://dom.spec.whatwg.org/#event
[`domain`]: /api/v18/domain
-[`emitter.listenerCount()`]: #emitterlistenercounteventname
+[`emitter.listenerCount()`]: #emitterlistenercounteventname-listener
[`emitter.removeListener()`]: #emitterremovelistenereventname-listener
[`emitter.setMaxListeners(n)`]: #emittersetmaxlistenersn
[`event.defaultPrevented`]: #eventdefaultprevented
diff --git a/content/api/v18/fs.en.md b/content/api/v18/fs.en.md
index 62d78e5d54..ae2aacd81e 100644
--- a/content/api/v18/fs.en.md
+++ b/content/api/v18/fs.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:fs` module enables interacting with the file system in a
way modeled on standard POSIX functions.
@@ -962,7 +962,7 @@ try {
}
--------------
const { mkdir } = require('node:fs/promises');
-const { resolve, join } = require('node:path');
+const { join } = require('node:path');
async function makeDirectory() {
const projectFolder = join(__dirname, 'test', 'project');
@@ -996,9 +996,11 @@ object with an `encoding` property specifying the character encoding to use.
```mjs
import { mkdtemp } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
try {
- await mkdtemp(path.join(os.tmpdir(), 'foo-'));
+ await mkdtemp(join(tmpdir(), 'foo-'));
} catch (err) {
console.error(err);
}
@@ -2469,8 +2471,10 @@ object with an `encoding` property specifying the character encoding to use.
```mjs
import { mkdtemp } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
-mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
+mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
if (err) throw err;
console.log(directory);
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
@@ -5633,6 +5637,8 @@ For example, the following is prone to error because the `fs.stat()`
operation might complete before the `fs.rename()` operation:
```js
+const fs = require('node:fs');
+
fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
console.log('renamed complete');
@@ -5649,12 +5655,12 @@ of one before invoking the other:
```mjs|cjs
import { rename, stat } from 'node:fs/promises';
-const from = '/tmp/hello';
-const to = '/tmp/world';
+const oldPath = '/tmp/hello';
+const newPath = '/tmp/world';
try {
- await rename(from, to);
- const stats = await stat(to);
+ await rename(oldPath, newPath);
+ const stats = await stat(newPath);
console.log(`stats: ${JSON.stringify(stats)}`);
} catch (error) {
console.error('there was an error:', error.message);
@@ -5662,10 +5668,10 @@ try {
--------------
const { rename, stat } = require('node:fs/promises');
-(async function(from, to) {
+(async function(oldPath, newPath) {
try {
- await rename(from, to);
- const stats = await stat(to);
+ await rename(oldPath, newPath);
+ const stats = await stat(newPath);
console.log(`stats: ${JSON.stringify(stats)}`);
} catch (error) {
console.error('there was an error:', error.message);
@@ -5719,7 +5725,7 @@ try {
fd = await open('/open/some/file.txt', 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
@@ -5733,7 +5739,7 @@ try {
fd = await open('file.txt', 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
@@ -5846,7 +5852,7 @@ try {
fd = await open(Buffer.from('/open/some/file.txt'), 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
diff --git a/content/api/v18/http.en.md b/content/api/v18/http.en.md
index 875451f81c..6b1fcbe35f 100644
--- a/content/api/v18/http.en.md
+++ b/content/api/v18/http.en.md
@@ -13,7 +13,7 @@ Stable
-
+
To use the HTTP server and client one must `require('node:http')`.
@@ -363,8 +363,9 @@ the data is read it will consume memory that can eventually lead to a
For backward compatibility, `res` will only emit `'error'` if there is an
`'error'` listener registered.
-Set `Content-Length` header to limit the response body size. Mismatching the
-`Content-Length` header value will result in an \[`Error`]\[] being thrown,
+Set `Content-Length` header to limit the response body size.
+If [`response.strictContentLength`][] is set to `true`, mismatching the
+`Content-Length` header value will result in an `Error` being thrown,
identified by `code:` [`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`][].
`Content-Length` value should be in bytes, not characters. Use
@@ -1118,7 +1119,8 @@ not be emitted.
If a client connection emits an `'error'` event, it will be forwarded here.
Listener of this event is responsible for closing/destroying the underlying
socket. For example, one may wish to more gracefully close the socket with a
-custom HTTP response instead of abruptly severing the connection.
+custom HTTP response instead of abruptly severing the connection. The socket
+**must be closed or destroyed** before the listener ends.
This event is guaranteed to be passed an instance of the [`net.Socket`](/api/v18/net#netsocket) class,
a subclass of [`stream.Duplex`](/api/v18/stream#streamduplex), unless the user specifies a socket
@@ -1761,6 +1763,17 @@ response.statusMessage = 'Not found';
After response header was sent to the client, this property indicates the
status message which was sent out.
+#### `response.strictContentLength`
+
+
+
+* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
+
+If set to `true`, Node.js will check whether the `Content-Length`
+header value and the size of the body, in bytes, are equal.
+Mismatching the `Content-Length` header value will result
+in an `Error` being thrown, identified by `code:` [`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`][].
+
#### `response.uncork()`
@@ -2684,6 +2697,7 @@ Found'`.
* `requestTimeout`: Sets the timeout value in milliseconds for receiving
the entire request from the client.
See [`server.requestTimeout`][] for more information.
+ **Default:** `300000`.
* `joinDuplicateHeaders` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) It joins the field line values of multiple
headers in a request with `, ` instead of discarding the duplicates.
See [`message.headers`][] for more information.
@@ -2691,7 +2705,6 @@ Found'`.
* `ServerResponse` [`http.ServerResponse`](/api/v18/http#httpserverresponse) Specifies the `ServerResponse` class
to be used. Useful for extending the original `ServerResponse`. **Default:**
`ServerResponse`.
- **Default:** `300000`.
* `uniqueHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) A list of response headers that should be sent only
once. If the header's value is an array, the items will be joined
using `; `.
@@ -3233,6 +3246,7 @@ Set the maximum number of idle HTTP parsers.
[`response.getHeader()`]: #responsegetheadername
[`response.setHeader()`]: #responsesetheadername-value
[`response.socket`]: #responsesocket
+[`response.strictContentLength`]: #responsestrictcontentlength
[`response.writableEnded`]: #responsewritableended
[`response.writableFinished`]: #responsewritablefinished
[`response.write()`]: #responsewritechunk-encoding-callback
diff --git a/content/api/v18/http2.en.md b/content/api/v18/http2.en.md
index 26f1e42a19..5b73f08905 100644
--- a/content/api/v18/http2.en.md
+++ b/content/api/v18/http2.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:http2` module provides an implementation of the [HTTP/2][] protocol.
It can be accessed using:
@@ -328,7 +328,7 @@ server.on('stream', (stream, headers) => {
stream.end('Hello World ');
});
-server.listen(80);
+server.listen(8000);
```
Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence,
@@ -2158,7 +2158,7 @@ server.on('stream', (stream, headers) => {
stream.end('Hello World ');
});
-server.listen(80);
+server.listen(8000);
```
#### `http2.createSecureServer(options[, onRequestHandler])`
@@ -2255,7 +2255,7 @@ server.on('stream', (stream, headers) => {
stream.end('Hello World ');
});
-server.listen(80);
+server.listen(8443);
```
#### `http2.connect(authority[, options][, listener])`
@@ -2657,7 +2657,7 @@ const client = http2.connect('http://localhost:8001');
// for CONNECT requests or an error will be thrown.
const req = client.request({
':method': 'CONNECT',
- ':authority': `localhost:${port}`,
+ ':authority': 'localhost:8000',
});
req.on('response', (headers) => {
diff --git a/content/api/v18/https.en.md b/content/api/v18/https.en.md
index 96eac0c15b..f0047688f5 100644
--- a/content/api/v18/https.en.md
+++ b/content/api/v18/https.en.md
@@ -13,7 +13,7 @@ Stable
-
+
HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.
diff --git a/content/api/v18/inspector.en.md b/content/api/v18/inspector.en.md
index bf0d393d06..27f5adae4a 100644
--- a/content/api/v18/inspector.en.md
+++ b/content/api/v18/inspector.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:inspector` module provides an API for interacting with the V8
inspector.
diff --git a/content/api/v18/navigation.json b/content/api/v18/navigation.json
index b13e4736c2..d231687cf6 100644
--- a/content/api/v18/navigation.json
+++ b/content/api/v18/navigation.json
@@ -1099,6 +1099,12 @@
"type": "module",
"name": "report"
},
+ {
+ "slug": "/api/v18/single-executable-applications/",
+ "title": "Single executable applications",
+ "type": "module",
+ "name": "single-executable-applications"
+ },
{
"slug": "/api/v18/stream/",
"title": "Stream",
diff --git a/content/api/v18/net.en.md b/content/api/v18/net.en.md
index a669a1f9cc..e4c94566b9 100644
--- a/content/api/v18/net.en.md
+++ b/content/api/v18/net.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:net` module provides an asynchronous network API for creating stream-based
TCP or [IPC][] servers ([`net.createServer()`][]) and clients
diff --git a/content/api/v18/os.en.md b/content/api/v18/os.en.md
index 65380abbf8..d5c1dcfff8 100644
--- a/content/api/v18/os.en.md
+++ b/content/api/v18/os.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:os` module provides operating system-related utility methods and
properties. It can be accessed using:
diff --git a/content/api/v18/path.en.md b/content/api/v18/path.en.md
index 1a368718c4..3bdb8da1f1 100644
--- a/content/api/v18/path.en.md
+++ b/content/api/v18/path.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:path` module provides utilities for working with file and directory
paths. It can be accessed using:
diff --git a/content/api/v18/perf_hooks.en.md b/content/api/v18/perf_hooks.en.md
index befd311d44..fadebc5fb3 100644
--- a/content/api/v18/perf_hooks.en.md
+++ b/content/api/v18/perf_hooks.en.md
@@ -13,7 +13,7 @@ Stable
-
+
This module provides an implementation of a subset of the W3C
[Web Performance APIs][] as well as additional APIs for
diff --git a/content/api/v18/process.en.md b/content/api/v18/process.en.md
index 2a39a476d2..c30b24bfdb 100644
--- a/content/api/v18/process.en.md
+++ b/content/api/v18/process.en.md
@@ -9,7 +9,7 @@ version: 'v18'
-
+
The `process` object provides information about, and control over, the current
Node.js process.
diff --git a/content/api/v18/punycode.en.md b/content/api/v18/punycode.en.md
index 48f6202adb..24b3dbf4d7 100644
--- a/content/api/v18/punycode.en.md
+++ b/content/api/v18/punycode.en.md
@@ -15,7 +15,7 @@ Deprecated
-
+
**The version of the punycode module bundled in Node.js is being deprecated.**
In a future major version of Node.js this module will be removed. Users
diff --git a/content/api/v18/querystring.en.md b/content/api/v18/querystring.en.md
index 3230f06db3..384eedf006 100644
--- a/content/api/v18/querystring.en.md
+++ b/content/api/v18/querystring.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:querystring` module provides utilities for parsing and formatting URL
query strings. It can be accessed using:
diff --git a/content/api/v18/readline.en.md b/content/api/v18/readline.en.md
index b9b1fd4ae1..c419f72bbd 100644
--- a/content/api/v18/readline.en.md
+++ b/content/api/v18/readline.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:readline` module provides an interface for reading data from a
[Readable][] stream (such as [`process.stdin`][]) one line at a time.
diff --git a/content/api/v18/repl.en.md b/content/api/v18/repl.en.md
index 739dd5d203..8ec70db9d6 100644
--- a/content/api/v18/repl.en.md
+++ b/content/api/v18/repl.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation
that is available both as a standalone program or includible in other
diff --git a/content/api/v18/single-executable-applications.en.md b/content/api/v18/single-executable-applications.en.md
new file mode 100644
index 0000000000..6d2b86767d
--- /dev/null
+++ b/content/api/v18/single-executable-applications.en.md
@@ -0,0 +1,149 @@
+---
+title: 'single-executable-applications'
+displayTitle: 'Single executable applications'
+category: 'api'
+version: 'v18'
+---
+
+
+
+
+
+Experimental: This feature is being designed and will change.
+
+
+
+
+
+This feature allows the distribution of a Node.js application conveniently to a
+system that does not have Node.js installed.
+
+Node.js supports the creation of [single executable applications][] by allowing
+the injection of a JavaScript file into the `node` binary. During start up, the
+program checks if anything has been injected. If the script is found, it
+executes its contents. Otherwise Node.js operates as it normally does.
+
+The single executable application feature only supports running a single
+embedded [CommonJS][] file.
+
+A bundled JavaScript file can be turned into a single executable application
+with any tool which can inject resources into the `node` binary.
+
+Here are the steps for creating a single executable application using one such
+tool, [postject][]:
+
+1. Create a JavaScript file:
+ ```console
+ $ echo 'console.log(`Hello, $process.argv[2]!`);' > hello.js
+ ```
+
+2. Create a copy of the `node` executable and name it according to your needs:
+ ```console
+ $ cp $(command -v node) hello
+ ```
+
+3. Inject the JavaScript file into the copied binary by running `postject` with
+ the following options:
+
+ * `hello` - The name of the copy of the `node` executable created in step 2.
+ * `NODE_JS_CODE` - The name of the resource / note / section in the binary
+ where the contents of the JavaScript file will be stored.
+ * `hello.js` - The name of the JavaScript file created in step 1.
+ * `--sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2` - The
+ [fuse][] used by the Node.js project to detect if a file has been injected.
+ * `--macho-segment-name NODE_JS` (only needed on macOS) - The name of the
+ segment in the binary where the contents of the JavaScript file will be
+ stored.
+
+ To summarize, here is the required command for each platform:
+
+ * On systems other than macOS:
+ ```console
+ $ npx postject hello NODE_JS_CODE hello.js \
+ --sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2
+ ```
+
+ * On macOS:
+ ```console
+ $ npx postject hello NODE_JS_CODE hello.js \
+ --sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \
+ --macho-segment-name NODE_JS
+ ```
+
+4. Run the binary:
+ ```console
+ $ ./hello world
+ Hello, world!
+ ```
+
+### Notes
+
+#### `require(id)` in the injected module is not file based
+
+`require()` in the injected module is not the same as the [`require()`][]
+available to modules that are not injected. It also does not have any of the
+properties that non-injected [`require()`][] has except [`require.main`][]. It
+can only be used to load built-in modules. Attempting to load a module that can
+only be found in the file system will throw an error.
+
+Instead of relying on a file based `require()`, users can bundle their
+application into a standalone JavaScript file to inject into the executable.
+This also ensures a more deterministic dependency graph.
+
+However, if a file based `require()` is still needed, that can also be achieved:
+
+```js
+const { createRequire } = require('node:module');
+require = createRequire(__filename);
+```
+
+#### `__filename` and `module.filename` in the injected module
+
+The values of `__filename` and `module.filename` in the injected module are
+equal to [`process.execPath`][].
+
+#### `__dirname` in the injected module
+
+The value of `__dirname` in the injected module is equal to the directory name
+of [`process.execPath`][].
+
+#### Single executable application creation process
+
+A tool aiming to create a single executable Node.js application must
+inject the contents of a JavaScript file into:
+
+* a resource named `NODE_JS_CODE` if the `node` binary is a [PE][] file
+* a section named `NODE_JS_CODE` in the `NODE_JS` segment if the `node` binary
+ is a [Mach-O][] file
+* a note named `NODE_JS_CODE` if the `node` binary is an [ELF][] file
+
+Search the binary for the
+`NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2:0` [fuse][] string and flip the
+last character to `1` to indicate that a resource has been injected.
+
+#### Platform support
+
+Single-executable support is tested regularly on CI only on the following
+platforms:
+
+* Windows
+* macOS
+* Linux (AMD64 only)
+
+This is due to a lack of better tools to generate single-executables that can be
+used to test this feature on other platforms.
+
+Suggestions for other resource injection tools/workflows are welcomed. Please
+start a discussion at [https://github.com/nodejs/single-executable/discussions](https://github.com/nodejs/single-executable/discussions)
+to help us document them.
+
+[CommonJS]: /api/v18/modules#modules-commonjs-modules
+[ELF]: https://en.wikipedia.org/wiki/Executable_and_Linkable_Format
+[Mach-O]: https://en.wikipedia.org/wiki/Mach-O
+[PE]: https://en.wikipedia.org/wiki/Portable_Executable
+[`process.execPath`]: /api/v18/process#processexecpath
+[`require()`]: /api/v18/modules#requireid
+[`require.main`]: /api/v18/modules#accessing-the-main-module
+[fuse]: https://www.electronjs.org/docs/latest/tutorial/fuses
+[postject]: https://github.com/nodejs/postject
+[single executable applications]: https://github.com/nodejs/single-executable
diff --git a/content/api/v18/stream.en.md b/content/api/v18/stream.en.md
index eee8a0d18e..ded99be493 100644
--- a/content/api/v18/stream.en.md
+++ b/content/api/v18/stream.en.md
@@ -13,7 +13,7 @@ Stable
-
+
A stream is an abstract interface for working with streaming data in Node.js.
The `node:stream` module provides an API for implementing the stream interface.
@@ -2058,7 +2058,7 @@ const anyBigFile = await Readable.from([
'file3',
]).some(async (fileName) => {
const stats = await stat(fileName);
- return stat.size > 1024 * 1024;
+ return stats.size > 1024 * 1024;
}, { concurrency: 2 });
console.log(anyBigFile); // `true` if any file in the list is bigger than 1MB
console.log('done'); // Stream has finished
@@ -2110,7 +2110,7 @@ const foundBigFile = await Readable.from([
'file3',
]).find(async (fileName) => {
const stats = await stat(fileName);
- return stat.size > 1024 * 1024;
+ return stats.size > 1024 * 1024;
}, { concurrency: 2 });
console.log(foundBigFile); // File name of large file, if any file in the list is bigger than 1MB
console.log('done'); // Stream has finished
@@ -2160,7 +2160,7 @@ const allBigFiles = await Readable.from([
'file3',
]).every(async (fileName) => {
const stats = await stat(fileName);
- return stat.size > 1024 * 1024;
+ return stats.size > 1024 * 1024;
}, { concurrency: 2 });
// `true` if all files in the list are bigger than 1MiB
console.log(allBigFiles);
@@ -2472,15 +2472,16 @@ const cleanup = finished(rs, (err) => {
#### `stream.pipeline(streams, callback)`
-
+
-* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]
-* `source` [`Stream`](/api/v18/stream#stream) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]|
+ ReadableStream\[]|WritableStream\[]|TransformStream\[]
+* `source` [`Stream`](/api/v18/stream#stream) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`ReadableStream`](/api/v18/webstreams#readablestream)
* Returns: [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
-* `...transforms` [`Stream`](/api/v18/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `...transforms` [`Stream`](/api/v18/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`TransformStream`](/api/v18/webstreams#transformstream)
* `source` [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
* Returns: [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
-* `destination` [`Stream`](/api/v18/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `destination` [`Stream`](/api/v18/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`WritableStream`](/api/v18/webstreams#writablestream)
* `source` [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
* Returns: [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called when the pipeline is fully done.
@@ -2552,7 +2553,7 @@ const server = http.createServer((req, res) => {
#### `stream.compose(...streams)`
-
+
@@ -2560,7 +2561,8 @@ const server = http.createServer((req, res) => {
-* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]
+* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]|
+ ReadableStream\[]|WritableStream\[]|TransformStream\[]
* Returns: [`stream.Duplex`](/api/v18/stream#streamduplex)
Combines two or more streams into a `Duplex` stream that writes to the
@@ -2765,8 +2767,14 @@ Experimental
* `streamReadable` [`stream.Readable`](/api/v18/stream#streamreadable)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `strategy` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `size` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+ * `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The maximum internal queue size (of the created
+ `ReadableStream`) before backpressure is applied in reading from the given
+ `stream.Readable`. If no value is provided, it will be taken from the
+ given `stream.Readable`.
+ * `size` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A function that size of the given chunk of data.
+ If no value is provided, the size will be `1` for all the chunks.
+ * `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+ * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`ReadableStream`](/api/v18/webstreams#readablestream)
#### `stream.Writable.fromWeb(writableStream[, options])`
@@ -2979,17 +2987,19 @@ readable.getReader().read().then((result) => {
#### `stream.addAbortSignal(signal, stream)`
-
+
* `signal` [`AbortSignal`](/api/v18/globals#abortsignal) A signal representing possible cancellation
-* `stream` [`Stream`](/api/v18/stream#stream) a stream to attach a signal to
+* `stream` [`Stream`](/api/v18/stream#stream) | [`ReadableStream`](/api/v18/webstreams#readablestream) | [`WritableStream`](/api/v18/webstreams#writablestream)
+
+A stream to attach a signal to.
Attaches an AbortSignal to a readable or writeable stream. This lets code
control stream destruction using an `AbortController`.
Calling `abort` on the `AbortController` corresponding to the passed
`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`
-on the stream.
+on the stream, and `controller.error(new AbortError())` for webstreams.
```js
const fs = require('node:fs');
@@ -3027,6 +3037,37 @@ const stream = addAbortSignal(
})();
```
+Or using an `AbortSignal` with a ReadableStream:
+
+```js
+const controller = new AbortController();
+const rs = new ReadableStream({
+ start(controller) {
+ controller.enqueue('hello');
+ controller.enqueue('world');
+ controller.close();
+ },
+});
+
+addAbortSignal(controller.signal, rs);
+
+finished(rs, (err) => {
+ if (err) {
+ if (err.name === 'AbortError') {
+ // The operation was cancelled
+ }
+ }
+});
+
+const reader = rs.getReader();
+
+reader.read().then(({ value, done }) => {
+ console.log(value); // hello
+ console.log(done); // false
+ controller.abort();
+});
+```
+
### API for stream implementers
diff --git a/content/api/v18/string_decoder.en.md b/content/api/v18/string_decoder.en.md
index 84a889b7ab..c87baec081 100644
--- a/content/api/v18/string_decoder.en.md
+++ b/content/api/v18/string_decoder.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:string_decoder` module provides an API for decoding `Buffer` objects
into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
diff --git a/content/api/v18/test.en.md b/content/api/v18/test.en.md
index 4a6037b0ec..728780a3db 100644
--- a/content/api/v18/test.en.md
+++ b/content/api/v18/test.en.md
@@ -7,13 +7,15 @@ version: 'v18'
+
+
Experimental
-
+
The `node:test` module facilitates the creation of JavaScript tests.
To access it:
@@ -155,8 +157,7 @@ test('skip() method with message', (t) => {
Running tests can also be done using `describe` to declare a suite
and `it` to declare a test.
A suite is used to organize and group related tests together.
-`it` is an alias for `test`, except there is no test context passed,
-since nesting is done using suites.
+`it` is a shorthand for [`test()`][].
```js
describe('A thing', () => {
@@ -514,8 +515,7 @@ flags for the test runner to use a specific reporter.
The following built-reporters are supported:
* `tap`
- The `tap` reporter is the default reporter used by the test runner. It outputs
- the test results in the [TAP][] format.
+ The `tap` reporter outputs the test results in the [TAP][] format.
* `spec`
The `spec` reporter outputs the test results in a human-readable format.
@@ -525,10 +525,13 @@ The following built-reporters are supported:
where each passing test is represented by a `.`,
and each failing test is represented by a `X`.
+When `stdout` is a [TTY][], the `spec` reporter is used by default.
+Otherwise, the `tap` reporter is used by default.
+
#### Custom reporters
[`--test-reporter`][] can be used to specify a path to custom reporter.
-a custom reporter is a module that exports a value
+A custom reporter is a module that exports a value
accepted by [stream.compose][].
Reporters should transform events emitted by a TestsStream
@@ -556,6 +559,11 @@ const customReporter = new Transform({
case 'test:diagnostic':
callback(null, event.data.message);
break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ callback(null, `total line count: ${totalLineCount}\n`);
+ break;
+ }
}
},
});
@@ -583,6 +591,11 @@ const customReporter = new Transform({
case 'test:diagnostic':
callback(null, event.data.message);
break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ callback(null, `total line count: ${totalLineCount}\n`);
+ break;
+ }
}
},
});
@@ -611,6 +624,11 @@ export default async function * customReporter(source) {
case 'test:diagnostic':
yield `${event.data.message}\n`;
break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ yield `total line count: ${totalLineCount}\n`;
+ break;
+ }
}
}
}
@@ -633,6 +651,11 @@ module.exports = async function * customReporter(source) {
case 'test:diagnostic':
yield `${event.data.message}\n`;
break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ yield `total line count: ${totalLineCount}\n`;
+ break;
+ }
}
}
};
@@ -669,11 +692,10 @@ unless a destination is explicitly provided.
properties are supported:
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If a number is provided,
then that many files would run in parallel.
- If truthy, it would run (number of cpu cores - 1)
- files in parallel.
- If falsy, it would only run one file at a time.
- If unspecified, subtests inherit this value from their parent.
- **Default:** `true`.
+ If `true`, it would run `os.availableParallelism() - 1` test files in
+ parallel.
+ If `false`, it would only run one test file at a time.
+ **Default:** `false`.
* `files`: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the list of files to run.
**Default** matching files from [test runner execution model][].
* `setup` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A function that accepts the `TestsStream` instance
@@ -707,10 +729,9 @@ run({ files: [path.resolve('./tests/test.js')] })
properties are supported:
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If a number is provided,
then that many tests would run in parallel.
- If truthy, it would run (number of cpu cores - 1)
- tests in parallel.
+ If `true`, it would run `os.availableParallelism() - 1` tests in parallel.
For subtests, it will be `Infinity` tests in parallel.
- If falsy, it would only run one test at a time.
+ If `false`, it would only run one test at a time.
If unspecified, subtests inherit this value from their parent.
**Default:** `false`.
* `only` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If truthy, and the test context is configured to run
@@ -730,7 +751,8 @@ run({ files: [path.resolve('./tests/test.js')] })
to this function is a [`TestContext`][] object. If the test uses callbacks,
the callback function is passed as the second argument. **Default:** A no-op
function.
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Resolved with `undefined` once the test completes.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Resolved with `undefined` once
+ the test completes, or immediately if the test runs within [`describe()`][].
The `test()` function is the value imported from the `test` module. Each
invocation of this function results in reporting the test to the TestsStream.
@@ -739,10 +761,12 @@ The `TestContext` object passed to the `fn` argument can be used to perform
actions related to the current test. Examples include skipping the test, adding
additional diagnostic information, or creating subtests.
-`test()` returns a `Promise` that resolves once the test completes. The return
-value can usually be discarded for top level tests. However, the return value
-from subtests should be used to prevent the parent test from finishing first
-and cancelling the subtest as shown in the following example.
+`test()` returns a `Promise` that resolves once the test completes.
+if `test()` is called within a `describe()` block, it resolve immediately.
+The return value can usually be discarded for top level tests.
+However, the return value from subtests should be used to prevent the parent
+test from finishing first and cancelling the subtest
+as shown in the following example.
```js
test('top level test', async (t) => {
@@ -798,17 +822,11 @@ Shorthand for marking a suite as `only`, same as
### `it([name][, options][, fn])`
-* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the test, which is displayed when reporting test
- results. **Default:** The `name` property of `fn`, or `''` if `fn`
- does not have a name.
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the suite.
- supports the same options as `test([name][, options][, fn])`.
-* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) The function under test.
- If the test uses callbacks, the callback function is passed as an argument.
- **Default:** A no-op function.
-* Returns: `undefined`.
+
-The `it()` function is the value imported from the `node:test` module.
+Shorthand for [`test()`][].
+
+The `it()` function is imported from the `node:test` module.
### `it.skip([name][, options][, fn])`
@@ -899,7 +917,7 @@ before each subtest of the current suite.
```js
describe('tests', async () => {
- beforeEach(() => t.diagnostic('about to run a test'));
+ beforeEach(() => console.log('about to run a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
@@ -926,7 +944,7 @@ after each subtest of the current test.
```js
describe('tests', async () => {
- afterEach(() => t.diagnostic('about to run a test'));
+ afterEach(() => console.log('finished running a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
@@ -1507,9 +1525,12 @@ test('top level test', (t) => {
`fn` does not have a name.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the subtest. The following
properties are supported:
- * `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of tests that can be run at the same time.
+ * `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) If a number is provided,
+ then that many tests would run in parallel.
+ If `true`, it would run all subtests in parallel.
+ If `false`, it would only run one test at a time.
If unspecified, subtests inherit this value from their parent.
- **Default:** `1`.
+ **Default:** `null`.
* `only` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If truthy, and the test context is configured to run
`only` tests, then this test will be run. Otherwise, the test is skipped.
**Default:** `false`.
@@ -1566,6 +1587,7 @@ The name of the suite.
aborted.
[TAP]: https://testanything.org/
+[TTY]: /api/v18/tty
[`--experimental-test-coverage`]: /api/v18/cli#--experimental-test-coverage
[`--test-name-pattern`]: /api/v18/cli#--test-name-pattern
[`--test-only`]: /api/v18/cli#--test-only
@@ -1581,6 +1603,7 @@ The name of the suite.
[`context.diagnostic`]: #contextdiagnosticmessage
[`context.skip`]: #contextskipmessage
[`context.todo`]: #contexttodomessage
+[`describe()`]: #describename-options-fn
[`run()`]: #runoptions
[`test()`]: #testname-options-fn
[describe options]: #describename-options-fn
diff --git a/content/api/v18/timers.en.md b/content/api/v18/timers.en.md
index 28f7f3ed4f..e96b7246e9 100644
--- a/content/api/v18/timers.en.md
+++ b/content/api/v18/timers.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `timer` module exposes a global API for scheduling functions to
be called at some future period of time. Because the timer functions are
diff --git a/content/api/v18/tls.en.md b/content/api/v18/tls.en.md
index 32e4cb2534..aa2027b0be 100644
--- a/content/api/v18/tls.en.md
+++ b/content/api/v18/tls.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:tls` module provides an implementation of the Transport Layer Security
(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
@@ -130,23 +130,17 @@ all sessions). Methods implementing this technique are called "ephemeral".
Currently two methods are commonly used to achieve perfect forward secrecy (note
the character "E" appended to the traditional abbreviations):
-* [DHE][]: An ephemeral version of the Diffie-Hellman key-agreement protocol.
* [ECDHE][]: An ephemeral version of the Elliptic Curve Diffie-Hellman
key-agreement protocol.
+* [DHE][]: An ephemeral version of the Diffie-Hellman key-agreement protocol.
-To use perfect forward secrecy using `DHE` with the `node:tls` module, it is
-required to generate Diffie-Hellman parameters and specify them with the
-`dhparam` option to [`tls.createSecureContext()`][]. The following illustrates
-the use of the OpenSSL command-line interface to generate such parameters:
-
-```bash
-openssl dhparam -outform PEM -out dhparam.pem 2048
-```
+Perfect forward secrecy using ECDHE is enabled by default. The `ecdhCurve`
+option can be used when creating a TLS server to customize the list of supported
+ECDH curves to use. See [`tls.createServer()`][] for more info.
-If using perfect forward secrecy using `ECDHE`, Diffie-Hellman parameters are
-not required and a default ECDHE curve will be used. The `ecdhCurve` property
-can be used when creating a TLS Server to specify the list of names of supported
-curves to use, see [`tls.createServer()`][] for more info.
+DHE is disabled by default but can be enabled alongside ECDHE by setting the
+`dhparam` option to `'auto'`. Custom DHE parameters are also supported but
+discouraged in favor of automatically selected, well-known parameters.
Perfect forward secrecy was optional up to TLSv1.2. As of TLSv1.3, (EC)DHE is
always used (with the exception of PSK-only connections).
@@ -363,6 +357,30 @@ export NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'
node server.js
```
+To verify, use the following command to show the set cipher list, note the
+difference between `defaultCoreCipherList` and `defaultCipherList`:
+
+```bash
+node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' -p crypto.constants.defaultCipherList | tr ':' '\n'
+ECDHE-RSA-AES128-GCM-SHA256
+!RC4
+```
+
+i.e. the `defaultCoreCipherList` list is set at compilation time and the
+`defaultCipherList` is set at runtime.
+
+To modify the default cipher suites from within the runtime, modify the
+`tls.DEFAULT_CIPHERS` variable, this must be performed before listening on any
+sockets, it will not affect sockets already opened. For example:
+
+```js
+// Remove Obsolete CBC Ciphers and RSA Key Exchange based Ciphers as they don't provide Forward Secrecy
+tls.DEFAULT_CIPHERS +=
+ ':!ECDHE-RSA-AES128-SHA:!ECDHE-RSA-AES128-SHA256:!ECDHE-RSA-AES256-SHA:!ECDHE-RSA-AES256-SHA384' +
+ ':!ECDHE-ECDSA-AES128-SHA:!ECDHE-ECDSA-AES128-SHA256:!ECDHE-ECDSA-AES256-SHA:!ECDHE-ECDSA-AES256-SHA384' +
+ ':!kRSA';
+```
+
The default can also be replaced on a per client or server basis using the
`ciphers` option from [`tls.createSecureContext()`][], which is also available
in [`tls.createServer()`][], [`tls.connect()`][], and when creating new
@@ -1555,7 +1573,7 @@ argument.
### `tls.createSecureContext([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `ca` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) Optionally override the trusted CA
@@ -1599,12 +1617,10 @@ argument.
client certificate.
* `crl` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) PEM formatted CRLs (Certificate
Revocation Lists).
- * `dhparam` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) Diffie-Hellman parameters, required for
- [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters.
- The key length must be greater than or equal to 1024 bits or else an error
- will be thrown. Although 1024 bits is permissible, use 2048 bits or larger
- for stronger security. If omitted or invalid, the parameters are silently
- discarded and DHE ciphers will not be available.
+ * `dhparam` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) `'auto'` or custom Diffie-Hellman parameters,
+ required for non-ECDHE [perfect forward secrecy][]. If omitted or invalid,
+ the parameters are silently discarded and DHE ciphers will not be available.
+ [ECDHE][]-based [perfect forward secrecy][] will still be available.
* `ecdhCurve` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string describing a named curve or a colon separated
list of curve NIDs or names, for example `P-521:P-384:P-256`, to use for
ECDH key agreement. Set to `auto` to select the
@@ -1691,6 +1707,13 @@ A key is _required_ for ciphers that use certificates. Either `key` or
If the `ca` option is not given, then Node.js will default to using
[Mozilla's publicly trusted list of CAs][].
+Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`
+option. When set to `'auto'`, well-known DHE parameters of sufficient strength
+will be selected automatically. Otherwise, if necessary, `openssl dhparam` can
+be used to create custom parameters. The key length must be greater than or
+equal to 1024 bits or else an error will be thrown. Although 1024 bits is
+permissible, use 2048 bits or larger for stronger security.
+
### `tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])`
@@ -1927,6 +1950,16 @@ information.
`'TLSv1.3'`. If multiple of the options are provided, the lowest minimum is
used.
+### `tls.DEFAULT_CIPHERS`
+
+
+
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The default value of the `ciphers` option of
+ [`tls.createSecureContext()`][]. It can be assigned any of the supported
+ OpenSSL ciphers. Defaults to the content of
+ `crypto.constants.defaultCoreCipherList`, unless changed using CLI options
+ using `--tls-default-ciphers`.
+
[CVE-2021-44531]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531
[Chrome's 'modern cryptography' setting]: https://www.chromium.org/Home/chromium-security/education/tls#TOC-Cipher-Suites
[DHE]: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
diff --git a/content/api/v18/tracing.en.md b/content/api/v18/tracing.en.md
index d61d41bfb2..4eab9a5ba0 100644
--- a/content/api/v18/tracing.en.md
+++ b/content/api/v18/tracing.en.md
@@ -13,7 +13,7 @@ Experimental
-
+
The `node:trace_events` module provides a mechanism to centralize tracing
information generated by V8, Node.js core, and userspace code.
diff --git a/content/api/v18/tty.en.md b/content/api/v18/tty.en.md
index b2b0bfdc55..3133bda05c 100644
--- a/content/api/v18/tty.en.md
+++ b/content/api/v18/tty.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`
classes. In most cases, it will not be necessary or possible to use this module
diff --git a/content/api/v18/url.en.md b/content/api/v18/url.en.md
index 239e11de5a..b409d66480 100644
--- a/content/api/v18/url.en.md
+++ b/content/api/v18/url.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:url` module provides utilities for URL resolution and parsing. It can
be accessed using:
@@ -529,14 +529,14 @@ instance, the `URL` object will not percent encode the ASCII tilde (`~`)
character, while `URLSearchParams` will always encode it:
```js
-const myUrl = new URL('https://example.org/abc?foo=~bar');
+const myURL = new URL('https://example.org/abc?foo=~bar');
-console.log(myUrl.search); // prints ?foo=~bar
+console.log(myURL.search); // prints ?foo=~bar
// Modify the URL via searchParams...
-myUrl.searchParams.sort();
+myURL.searchParams.sort();
-console.log(myUrl.search); // prints ?foo=%7Ebar
+console.log(myURL.search); // prints ?foo=%7Ebar
```
##### `url.username`
@@ -896,6 +896,12 @@ console.log(params.toString());
// Prints foo=def&abc=def&xyz=opq
```
+##### `urlSearchParams.size`
+
+
+
+The total number of parameter entries.
+
##### `urlSearchParams.sort()`
@@ -1185,7 +1191,7 @@ console.log(urlToHttpOptions(myURL));
const { urlToHttpOptions } = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');
-console.log(urlToHttpOptions(myUrl));
+console.log(urlToHttpOptions(myURL));
/*
{
protocol: 'https:',
diff --git a/content/api/v18/util.en.md b/content/api/v18/util.en.md
index ca24e9fff1..c6cbfd1634 100644
--- a/content/api/v18/util.en.md
+++ b/content/api/v18/util.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:util` module supports the needs of Node.js internal APIs. Many of the
utilities are useful for application and module developers as well. To access
@@ -1769,6 +1769,51 @@ const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);
```
+### `util.aborted(signal, resource)`
+
+
+
+
+
+Experimental
+
+
+
+* `signal` [`AbortSignal`](/api/v18/globals#abortsignal)
+* `resource` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Any non-null entity, reference to which is held weakly.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+
+Listens to abort event on the provided `signal` and
+returns a promise that is fulfilled when the `signal` is
+aborted. If the passed `resource` is garbage collected before the `signal` is
+aborted, the returned promise shall remain pending indefinitely.
+
+```cjs|mjs
+const { aborted } = require('node:util');
+
+const dependent = obtainSomethingAbortable();
+
+aborted(dependent.signal, dependent).then(() => {
+ // Do something when dependent is aborted.
+});
+
+dependent.on('event', () => {
+ dependent.abort();
+});
+--------------
+import { aborted } from 'node:util';
+
+const dependent = obtainSomethingAbortable();
+
+aborted(dependent.signal, dependent).then(() => {
+ // Do something when dependent is aborted.
+});
+
+dependent.on('event', () => {
+ dependent.abort();
+});
+```
+
### `util.types`
diff --git a/content/api/v18/v8.en.md b/content/api/v18/v8.en.md
index 8d0ad4dd35..65a2ad69e1 100644
--- a/content/api/v18/v8.en.md
+++ b/content/api/v18/v8.en.md
@@ -7,7 +7,7 @@ version: 'v18'
-
+
The `node:v8` module exposes APIs that are specific to the version of [V8][]
built into the Node.js binary. It can be accessed using:
diff --git a/content/api/v18/vm.en.md b/content/api/v18/vm.en.md
index 4deb79f972..8b1dec6aea 100644
--- a/content/api/v18/vm.en.md
+++ b/content/api/v18/vm.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:vm` module enables compiling and running code within V8 Virtual
Machine contexts.
diff --git a/content/api/v18/wasi.en.md b/content/api/v18/wasi.en.md
index 21bc461be9..60dbeb81a2 100644
--- a/content/api/v18/wasi.en.md
+++ b/content/api/v18/wasi.en.md
@@ -13,7 +13,7 @@ Experimental
-
+
The WASI API provides an implementation of the [WebAssembly System Interface][]
specification. WASI gives sandboxed WebAssembly applications access to the
diff --git a/content/api/v18/webstreams.en.md b/content/api/v18/webstreams.en.md
index ae196c441a..74bcb14da8 100644
--- a/content/api/v18/webstreams.en.md
+++ b/content/api/v18/webstreams.en.md
@@ -1334,7 +1334,7 @@ json(readable).then((data) => {
UTF-8 encoded string.
```mjs|cjs
-import { json, text, blob, buffer } from 'node:stream/consumers';
+import { text } from 'node:stream/consumers';
import { Readable } from 'node:stream';
const readable = Readable.from('Hello world from consumers!');
diff --git a/content/api/v18/worker_threads.en.md b/content/api/v18/worker_threads.en.md
index 0181170f2b..797df05bb2 100644
--- a/content/api/v18/worker_threads.en.md
+++ b/content/api/v18/worker_threads.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:worker_threads` module enables the use of threads that execute
JavaScript in parallel. To access it:
@@ -789,7 +789,7 @@ if (isMainThread) {
#### `new Worker(filename[, options])`
-
+
* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api) The path to the Worker's main script or module. Must
be either an absolute path or a relative path (i.e. relative to the
@@ -854,6 +854,9 @@ if (isMainThread) {
used for generated code.
* `stackSizeMb` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The default maximum stack size for the thread.
Small values may lead to unusable Worker instances. **Default:** `4`.
+ * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) An optional `name` to be appended to the worker title
+ for debuggin/identification purposes, making the final title as
+ `[worker $id] $name`. **Default:** `''`.
#### `'error'`
diff --git a/content/api/v18/zlib.en.md b/content/api/v18/zlib.en.md
index 0879116e99..30ca5ff110 100644
--- a/content/api/v18/zlib.en.md
+++ b/content/api/v18/zlib.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:zlib` module provides compression functionality implemented using
Gzip, Deflate/Inflate, and Brotli.
diff --git a/content/api/v20/addons.en.md b/content/api/v20/addons.en.md
new file mode 100644
index 0000000000..5f39e813b0
--- /dev/null
+++ b/content/api/v20/addons.en.md
@@ -0,0 +1,1388 @@
+---
+title: 'addons'
+displayTitle: 'C++ addons'
+category: 'api'
+version: 'v20'
+---
+
+
+
+
+
+_Addons_ are dynamically-linked shared objects written in C++. The
+[`require()`][require] function can load addons as ordinary Node.js modules.
+Addons provide an interface between JavaScript and C/C++ libraries.
+
+There are three options for implementing addons: Node-API, nan, or direct
+use of internal V8, libuv, and Node.js libraries. Unless there is a need for
+direct access to functionality which is not exposed by Node-API, use Node-API.
+Refer to [C/C++ addons with Node-API](n-api.md) for more information on
+Node-API.
+
+When not using Node-API, implementing addons is complicated,
+involving knowledge of several components and APIs:
+
+* [V8][]: the C++ library Node.js uses to provide the
+ JavaScript implementation. V8 provides the mechanisms for creating objects,
+ calling functions, etc. V8's API is documented mostly in the
+ `v8.h` header file (`deps/v8/include/v8.h` in the Node.js source
+ tree), which is also available [online][v8-docs].
+
+* [libuv][]: The C library that implements the Node.js event loop, its worker
+ threads and all of the asynchronous behaviors of the platform. It also
+ serves as a cross-platform abstraction library, giving easy, POSIX-like
+ access across all major operating systems to many common system tasks, such
+ as interacting with the file system, sockets, timers, and system events. libuv
+ also provides a threading abstraction similar to POSIX threads for
+ more sophisticated asynchronous addons that need to move beyond the
+ standard event loop. Addon authors should
+ avoid blocking the event loop with I/O or other time-intensive tasks by
+ offloading work via libuv to non-blocking system operations, worker threads,
+ or a custom use of libuv threads.
+
+* Internal Node.js libraries. Node.js itself exports C++ APIs that addons can
+ use, the most important of which is the `node::ObjectWrap` class.
+
+* Node.js includes other statically linked libraries including OpenSSL. These
+ other libraries are located in the `deps/` directory in the Node.js source
+ tree. Only the libuv, OpenSSL, V8, and zlib symbols are purposefully
+ re-exported by Node.js and may be used to various extents by addons. See
+ [Linking to libraries included with Node.js][] for additional information.
+
+All of the following examples are available for [download][] and may
+be used as the starting-point for an addon.
+
+### Hello world
+
+This "Hello world" example is a simple addon, written in C++, that is the
+equivalent of the following JavaScript code:
+
+```js
+module.exports.hello = () => 'world';
+```
+
+First, create the file `hello.cc`:
+
+```cpp
+// hello.cc
+#include
+
+namespace demo {
+
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void Method(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ args.GetReturnValue().Set(String::NewFromUtf8(
+ isolate, "world").ToLocalChecked());
+}
+
+void Initialize(Local exports) {
+ NODE_SET_METHOD(exports, "hello", Method);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
+
+} // namespace demo
+```
+
+All Node.js addons must export an initialization function following
+the pattern:
+
+```cpp
+void Initialize(Local exports);
+NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
+```
+
+There is no semi-colon after `NODE_MODULE` as it's not a function (see
+`node.h`).
+
+The `module_name` must match the filename of the final binary (excluding
+the `.node` suffix).
+
+In the `hello.cc` example, then, the initialization function is `Initialize`
+and the addon module name is `addon`.
+
+When building addons with `node-gyp`, using the macro `NODE_GYP_MODULE_NAME` as
+the first parameter of `NODE_MODULE()` will ensure that the name of the final
+binary will be passed to `NODE_MODULE()`.
+
+Addons defined with `NODE_MODULE()` can not be loaded in multiple contexts or
+multiple threads at the same time.
+
+#### Context-aware addons
+
+There are environments in which Node.js addons may need to be loaded multiple
+times in multiple contexts. For example, the [Electron][] runtime runs multiple
+instances of Node.js in a single process. Each instance will have its own
+`require()` cache, and thus each instance will need a native addon to behave
+correctly when loaded via `require()`. This means that the addon
+must support multiple initializations.
+
+A context-aware addon can be constructed by using the macro
+`NODE_MODULE_INITIALIZER`, which expands to the name of a function which Node.js
+will expect to find when it loads an addon. An addon can thus be initialized as
+in the following example:
+
+```cpp
+using namespace v8;
+
+extern "C" NODE_MODULE_EXPORT void
+NODE_MODULE_INITIALIZER(Local exports,
+ Local module,
+ Local context) {
+ /* Perform addon initialization steps here. */
+}
+```
+
+Another option is to use the macro `NODE_MODULE_INIT()`, which will also
+construct a context-aware addon. Unlike `NODE_MODULE()`, which is used to
+construct an addon around a given addon initializer function,
+`NODE_MODULE_INIT()` serves as the declaration of such an initializer to be
+followed by a function body.
+
+The following three variables may be used inside the function body following an
+invocation of `NODE_MODULE_INIT()`:
+
+* `Local exports`,
+* `Local module`, and
+* `Local context`
+
+The choice to build a context-aware addon carries with it the responsibility of
+carefully managing global static data. Since the addon may be loaded multiple
+times, potentially even from different threads, any global static data stored
+in the addon must be properly protected, and must not contain any persistent
+references to JavaScript objects. The reason for this is that JavaScript
+objects are only valid in one context, and will likely cause a crash when
+accessed from the wrong context or from a different thread than the one on which
+they were created.
+
+The context-aware addon can be structured to avoid global static data by
+performing the following steps:
+
+* Define a class which will hold per-addon-instance data and which has a static
+ member of the form
+ ```cpp
+ static void DeleteInstance(void* data) {
+ // Cast `data` to an instance of the class and delete it.
+ }
+ ```
+* Heap-allocate an instance of this class in the addon initializer. This can be
+ accomplished using the `new` keyword.
+* Call `node::AddEnvironmentCleanupHook()`, passing it the above-created
+ instance and a pointer to `DeleteInstance()`. This will ensure the instance is
+ deleted when the environment is torn down.
+* Store the instance of the class in a `v8::External`, and
+* Pass the `v8::External` to all methods exposed to JavaScript by passing it
+ to `v8::FunctionTemplate::New()` or `v8::Function::New()` which creates the
+ native-backed JavaScript functions. The third parameter of
+ `v8::FunctionTemplate::New()` or `v8::Function::New()` accepts the
+ `v8::External` and makes it available in the native callback using the
+ `v8::FunctionCallbackInfo::Data()` method.
+
+This will ensure that the per-addon-instance data reaches each binding that can
+be called from JavaScript. The per-addon-instance data must also be passed into
+any asynchronous callbacks the addon may create.
+
+The following example illustrates the implementation of a context-aware addon:
+
+```cpp
+#include
+
+using namespace v8;
+
+class AddonData {
+ public:
+ explicit AddonData(Isolate* isolate):
+ call_count(0) {
+ // Ensure this per-addon-instance data is deleted at environment cleanup.
+ node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);
+ }
+
+ // Per-addon data.
+ int call_count;
+
+ static void DeleteInstance(void* data) {
+ delete static_cast(data);
+ }
+};
+
+static void Method(const v8::FunctionCallbackInfo& info) {
+ // Retrieve the per-addon-instance data.
+ AddonData* data =
+ reinterpret_cast(info.Data().As()->Value());
+ data->call_count++;
+ info.GetReturnValue().Set((double)data->call_count);
+}
+
+// Initialize this addon to be context-aware.
+NODE_MODULE_INIT(/* exports, module, context */) {
+ Isolate* isolate = context->GetIsolate();
+
+ // Create a new instance of `AddonData` for this instance of the addon and
+ // tie its life cycle to that of the Node.js environment.
+ AddonData* data = new AddonData(isolate);
+
+ // Wrap the data in a `v8::External` so we can pass it to the method we
+ // expose.
+ Local external = External::New(isolate, data);
+
+ // Expose the method `Method` to JavaScript, and make sure it receives the
+ // per-addon-instance data we created above by passing `external` as the
+ // third parameter to the `FunctionTemplate` constructor.
+ exports->Set(context,
+ String::NewFromUtf8(isolate, "method").ToLocalChecked(),
+ FunctionTemplate::New(isolate, Method, external)
+ ->GetFunction(context).ToLocalChecked()).FromJust();
+}
+```
+
+##### Worker support
+
+
+
+In order to be loaded from multiple Node.js environments,
+such as a main thread and a Worker thread, an add-on needs to either:
+
+* Be an Node-API addon, or
+* Be declared as context-aware using `NODE_MODULE_INIT()` as described above
+
+In order to support [`Worker`][] threads, addons need to clean up any resources
+they may have allocated when such a thread exists. This can be achieved through
+the usage of the `AddEnvironmentCleanupHook()` function:
+
+```cpp
+void AddEnvironmentCleanupHook(v8::Isolate* isolate,
+ void (*fun)(void* arg),
+ void* arg);
+```
+
+This function adds a hook that will run before a given Node.js instance shuts
+down. If necessary, such hooks can be removed before they are run using
+`RemoveEnvironmentCleanupHook()`, which has the same signature. Callbacks are
+run in last-in first-out order.
+
+If necessary, there is an additional pair of `AddEnvironmentCleanupHook()`
+and `RemoveEnvironmentCleanupHook()` overloads, where the cleanup hook takes a
+callback function. This can be used for shutting down asynchronous resources,
+such as any libuv handles registered by the addon.
+
+The following `addon.cc` uses `AddEnvironmentCleanupHook`:
+
+```cpp
+// addon.cc
+#include
+#include
+#include
+
+using node::AddEnvironmentCleanupHook;
+using v8::HandleScope;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+
+// Note: In a real-world application, do not rely on static/global data.
+static char cookie[] = "yum yum";
+static int cleanup_cb1_called = 0;
+static int cleanup_cb2_called = 0;
+
+static void cleanup_cb1(void* arg) {
+ Isolate* isolate = static_cast(arg);
+ HandleScope scope(isolate);
+ Local obj = Object::New(isolate);
+ assert(!obj.IsEmpty()); // assert VM is still alive
+ assert(obj->IsObject());
+ cleanup_cb1_called++;
+}
+
+static void cleanup_cb2(void* arg) {
+ assert(arg == static_cast(cookie));
+ cleanup_cb2_called++;
+}
+
+static void sanity_check(void*) {
+ assert(cleanup_cb1_called == 1);
+ assert(cleanup_cb2_called == 1);
+}
+
+// Initialize this addon to be context-aware.
+NODE_MODULE_INIT(/* exports, module, context */) {
+ Isolate* isolate = context->GetIsolate();
+
+ AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);
+ AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);
+ AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);
+}
+```
+
+Test in JavaScript by running:
+
+```js
+// test.js
+require('./build/Release/addon');
+```
+
+#### Building
+
+Once the source code has been written, it must be compiled into the binary
+`addon.node` file. To do so, create a file called `binding.gyp` in the
+top-level of the project describing the build configuration of the module
+using a JSON-like format. This file is used by [node-gyp][], a tool written
+specifically to compile Node.js addons.
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [ "hello.cc" ]
+ }
+ ]
+}
+```
+
+A version of the `node-gyp` utility is bundled and distributed with
+Node.js as part of `npm`. This version is not made directly available for
+developers to use and is intended only to support the ability to use the
+`npm install` command to compile and install addons. Developers who wish to
+use `node-gyp` directly can install it using the command
+`npm install -g node-gyp`. See the `node-gyp` [installation instructions][] for
+more information, including platform-specific requirements.
+
+Once the `binding.gyp` file has been created, use `node-gyp configure` to
+generate the appropriate project build files for the current platform. This
+will generate either a `Makefile` (on Unix platforms) or a `vcxproj` file
+(on Windows) in the `build/` directory.
+
+Next, invoke the `node-gyp build` command to generate the compiled `addon.node`
+file. This will be put into the `build/Release/` directory.
+
+When using `npm install` to install a Node.js addon, npm uses its own bundled
+version of `node-gyp` to perform this same set of actions, generating a
+compiled version of the addon for the user's platform on demand.
+
+Once built, the binary addon can be used from within Node.js by pointing
+[`require()`][require] to the built `addon.node` module:
+
+```js
+// hello.js
+const addon = require('./build/Release/addon');
+
+console.log(addon.hello());
+// Prints: 'world'
+```
+
+Because the exact path to the compiled addon binary can vary depending on how
+it is compiled (i.e. sometimes it may be in `./build/Debug/`), addons can use
+the [bindings][] package to load the compiled module.
+
+While the `bindings` package implementation is more sophisticated in how it
+locates addon modules, it is essentially using a `try…catch` pattern similar to:
+
+```js
+try {
+ return require('./build/Release/addon.node');
+} catch (err) {
+ return require('./build/Debug/addon.node');
+}
+```
+
+#### Linking to libraries included with Node.js
+
+Node.js uses statically linked libraries such as V8, libuv, and OpenSSL. All
+addons are required to link to V8 and may link to any of the other dependencies
+as well. Typically, this is as simple as including the appropriate
+`#include <...>` statements (e.g. `#include `) and `node-gyp` will locate
+the appropriate headers automatically. However, there are a few caveats to be
+aware of:
+
+* When `node-gyp` runs, it will detect the specific release version of Node.js
+ and download either the full source tarball or just the headers. If the full
+ source is downloaded, addons will have complete access to the full set of
+ Node.js dependencies. However, if only the Node.js headers are downloaded,
+ then only the symbols exported by Node.js will be available.
+
+* `node-gyp` can be run using the `--nodedir` flag pointing at a local Node.js
+ source image. Using this option, the addon will have access to the full set of
+ dependencies.
+
+#### Loading addons using `require()`
+
+The filename extension of the compiled addon binary is `.node` (as opposed
+to `.dll` or `.so`). The [`require()`][require] function is written to look for
+files with the `.node` file extension and initialize those as dynamically-linked
+libraries.
+
+When calling [`require()`][require], the `.node` extension can usually be
+omitted and Node.js will still find and initialize the addon. One caveat,
+however, is that Node.js will first attempt to locate and load modules or
+JavaScript files that happen to share the same base name. For instance, if
+there is a file `addon.js` in the same directory as the binary `addon.node`,
+then [`require('addon')`][require] will give precedence to the `addon.js` file
+and load it instead.
+
+### Native abstractions for Node.js
+
+Each of the examples illustrated in this document directly use the
+Node.js and V8 APIs for implementing addons. The V8 API can, and has, changed
+dramatically from one V8 release to the next (and one major Node.js release to
+the next). With each change, addons may need to be updated and recompiled in
+order to continue functioning. The Node.js release schedule is designed to
+minimize the frequency and impact of such changes but there is little that
+Node.js can do to ensure stability of the V8 APIs.
+
+The [Native Abstractions for Node.js][] (or `nan`) provide a set of tools that
+addon developers are recommended to use to keep compatibility between past and
+future releases of V8 and Node.js. See the `nan` [examples][] for an
+illustration of how it can be used.
+
+### Node-API
+
+
+
+Stable
+
+
+
+Node-API is an API for building native addons. It is independent from
+the underlying JavaScript runtime (e.g. V8) and is maintained as part of
+Node.js itself. This API will be Application Binary Interface (ABI) stable
+across versions of Node.js. It is intended to insulate addons from
+changes in the underlying JavaScript engine and allow modules
+compiled for one version to run on later versions of Node.js without
+recompilation. Addons are built/packaged with the same approach/tools
+outlined in this document (node-gyp, etc.). The only difference is the
+set of APIs that are used by the native code. Instead of using the V8
+or [Native Abstractions for Node.js][] APIs, the functions available
+in the Node-API are used.
+
+Creating and maintaining an addon that benefits from the ABI stability
+provided by Node-API carries with it certain
+[implementation considerations][].
+
+To use Node-API in the above "Hello world" example, replace the content of
+`hello.cc` with the following. All other instructions remain the same.
+
+```cpp
+// hello.cc using Node-API
+#include
+
+namespace demo {
+
+napi_value Method(napi_env env, napi_callback_info args) {
+ napi_value greeting;
+ napi_status status;
+
+ status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
+ if (status != napi_ok) return nullptr;
+ return greeting;
+}
+
+napi_value init(napi_env env, napi_value exports) {
+ napi_status status;
+ napi_value fn;
+
+ status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
+ if (status != napi_ok) return nullptr;
+
+ status = napi_set_named_property(env, exports, "hello", fn);
+ if (status != napi_ok) return nullptr;
+ return exports;
+}
+
+NAPI_MODULE(NODE_GYP_MODULE_NAME, init)
+
+} // namespace demo
+```
+
+The functions available and how to use them are documented in
+[C/C++ addons with Node-API](n-api.md).
+
+### Addon examples
+
+Following are some example addons intended to help developers get started. The
+examples use the V8 APIs. Refer to the online [V8 reference][v8-docs]
+for help with the various V8 calls, and V8's [Embedder's Guide][] for an
+explanation of several concepts used such as handles, scopes, function
+templates, etc.
+
+Each of these examples using the following `binding.gyp` file:
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [ "addon.cc" ]
+ }
+ ]
+}
+```
+
+In cases where there is more than one `.cc` file, simply add the additional
+filename to the `sources` array:
+
+```json
+"sources": ["addon.cc", "myexample.cc"]
+```
+
+Once the `binding.gyp` file is ready, the example addons can be configured and
+built using `node-gyp`:
+
+```bash
+node-gyp configure build
+```
+
+#### Function arguments
+
+Addons will typically expose objects and functions that can be accessed from
+JavaScript running within Node.js. When functions are invoked from JavaScript,
+the input arguments and return value must be mapped to and from the C/C++
+code.
+
+The following example illustrates how to read function arguments passed from
+JavaScript and how to return a result:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Exception;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+// This is the implementation of the "add" method
+// Input arguments are passed using the
+// const FunctionCallbackInfo& args struct
+void Add(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ // Check the number of arguments passed.
+ if (args.Length() < 2) {
+ // Throw an Error that is passed back to JavaScript
+ isolate->ThrowException(Exception::TypeError(
+ String::NewFromUtf8(isolate,
+ "Wrong number of arguments").ToLocalChecked()));
+ return;
+ }
+
+ // Check the argument types
+ if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
+ isolate->ThrowException(Exception::TypeError(
+ String::NewFromUtf8(isolate,
+ "Wrong arguments").ToLocalChecked()));
+ return;
+ }
+
+ // Perform the operation
+ double value =
+ args[0].As()->Value() + args[1].As()->Value();
+ Local num = Number::New(isolate, value);
+
+ // Set the return value (using the passed in
+ // FunctionCallbackInfo&)
+ args.GetReturnValue().Set(num);
+}
+
+void Init(Local exports) {
+ NODE_SET_METHOD(exports, "add", Add);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+Once compiled, the example addon can be required and used from within Node.js:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+console.log('This should be eight:', addon.add(3, 5));
+```
+
+#### Callbacks
+
+It is common practice within addons to pass JavaScript functions to a C++
+function and execute them from there. The following example illustrates how
+to invoke such callbacks:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Null;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void RunCallback(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+ Local cb = Local::Cast(args[0]);
+ const unsigned argc = 1;
+ Local argv[argc] = {
+ String::NewFromUtf8(isolate,
+ "hello world").ToLocalChecked() };
+ cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();
+}
+
+void Init(Local exports, Local module) {
+ NODE_SET_METHOD(module, "exports", RunCallback);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+This example uses a two-argument form of `Init()` that receives the full
+`module` object as the second argument. This allows the addon to completely
+overwrite `exports` with a single function instead of adding the function as a
+property of `exports`.
+
+To test it, run the following JavaScript:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+addon((msg) => {
+ console.log(msg);
+// Prints: 'hello world'
+});
+```
+
+In this example, the callback function is invoked synchronously.
+
+#### Object factory
+
+Addons can create and return new objects from within a C++ function as
+illustrated in the following example. An object is created and returned with a
+property `msg` that echoes the string passed to `createObject()`:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Context;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void CreateObject(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ Local obj = Object::New(isolate);
+ obj->Set(context,
+ String::NewFromUtf8(isolate,
+ "msg").ToLocalChecked(),
+ args[0]->ToString(context).ToLocalChecked())
+ .FromJust();
+
+ args.GetReturnValue().Set(obj);
+}
+
+void Init(Local exports, Local module) {
+ NODE_SET_METHOD(module, "exports", CreateObject);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+To test it in JavaScript:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const obj1 = addon('hello');
+const obj2 = addon('world');
+console.log(obj1.msg, obj2.msg);
+// Prints: 'hello world'
+```
+
+#### Function factory
+
+Another common scenario is creating JavaScript functions that wrap C++
+functions and returning those back to JavaScript:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void MyFunction(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ args.GetReturnValue().Set(String::NewFromUtf8(
+ isolate, "hello world").ToLocalChecked());
+}
+
+void CreateFunction(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ Local context = isolate->GetCurrentContext();
+ Local tpl = FunctionTemplate::New(isolate, MyFunction);
+ Local fn = tpl->GetFunction(context).ToLocalChecked();
+
+ // omit this to make it anonymous
+ fn->SetName(String::NewFromUtf8(
+ isolate, "theFunction").ToLocalChecked());
+
+ args.GetReturnValue().Set(fn);
+}
+
+void Init(Local exports, Local module) {
+ NODE_SET_METHOD(module, "exports", CreateFunction);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+To test:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const fn = addon();
+console.log(fn());
+// Prints: 'hello world'
+```
+
+#### Wrapping C++ objects
+
+It is also possible to wrap C++ objects/classes in a way that allows new
+instances to be created using the JavaScript `new` operator:
+
+```cpp
+// addon.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using v8::Local;
+using v8::Object;
+
+void InitAll(Local exports) {
+ MyObject::Init(exports);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
+
+} // namespace demo
+```
+
+Then, in `myobject.h`, the wrapper class inherits from `node::ObjectWrap`:
+
+```cpp
+// myobject.h
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include
+#include
+
+namespace demo {
+
+class MyObject : public node::ObjectWrap {
+ public:
+ static void Init(v8::Local exports);
+
+ private:
+ explicit MyObject(double value = 0);
+ ~MyObject();
+
+ static void New(const v8::FunctionCallbackInfo& args);
+ static void PlusOne(const v8::FunctionCallbackInfo& args);
+
+ double value_;
+};
+
+} // namespace demo
+
+#endif
+```
+
+In `myobject.cc`, implement the various methods that are to be exposed.
+Below, the method `plusOne()` is exposed by adding it to the constructor's
+prototype:
+
+```cpp
+// myobject.cc
+#include "myobject.h"
+
+namespace demo {
+
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::ObjectTemplate;
+using v8::String;
+using v8::Value;
+
+MyObject::MyObject(double value) : value_(value) {
+}
+
+MyObject::~MyObject() {
+}
+
+void MyObject::Init(Local exports) {
+ Isolate* isolate = exports->GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ Local addon_data_tpl = ObjectTemplate::New(isolate);
+ addon_data_tpl->SetInternalFieldCount(1); // 1 field for the MyObject::New()
+ Local addon_data =
+ addon_data_tpl->NewInstance(context).ToLocalChecked();
+
+ // Prepare constructor template
+ Local tpl = FunctionTemplate::New(isolate, New, addon_data);
+ tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
+ tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+ // Prototype
+ NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
+
+ Local constructor = tpl->GetFunction(context).ToLocalChecked();
+ addon_data->SetInternalField(0, constructor);
+ exports->Set(context, String::NewFromUtf8(
+ isolate, "MyObject").ToLocalChecked(),
+ constructor).FromJust();
+}
+
+void MyObject::New(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ if (args.IsConstructCall()) {
+ // Invoked as constructor: `new MyObject(...)`
+ double value = args[0]->IsUndefined() ?
+ 0 : args[0]->NumberValue(context).FromMaybe(0);
+ MyObject* obj = new MyObject(value);
+ obj->Wrap(args.This());
+ args.GetReturnValue().Set(args.This());
+ } else {
+ // Invoked as plain function `MyObject(...)`, turn into construct call.
+ const int argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons =
+ args.Data().As()->GetInternalField(0).As();
+ Local result =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+ args.GetReturnValue().Set(result);
+ }
+}
+
+void MyObject::PlusOne(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ MyObject* obj = ObjectWrap::Unwrap(args.Holder());
+ obj->value_ += 1;
+
+ args.GetReturnValue().Set(Number::New(isolate, obj->value_));
+}
+
+} // namespace demo
+```
+
+To build this example, the `myobject.cc` file must be added to the
+`binding.gyp`:
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [
+ "addon.cc",
+ "myobject.cc"
+ ]
+ }
+ ]
+}
+```
+
+Test it with:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const obj = new addon.MyObject(10);
+console.log(obj.plusOne());
+// Prints: 11
+console.log(obj.plusOne());
+// Prints: 12
+console.log(obj.plusOne());
+// Prints: 13
+```
+
+The destructor for a wrapper object will run when the object is
+garbage-collected. For destructor testing, there are command-line flags that
+can be used to make it possible to force garbage collection. These flags are
+provided by the underlying V8 JavaScript engine. They are subject to change
+or removal at any time. They are not documented by Node.js or V8, and they
+should never be used outside of testing.
+
+During shutdown of the process or worker threads destructors are not called
+by the JS engine. Therefore it's the responsibility of the user to track
+these objects and ensure proper destruction to avoid resource leaks.
+
+#### Factory of wrapped objects
+
+Alternatively, it is possible to use a factory pattern to avoid explicitly
+creating object instances using the JavaScript `new` operator:
+
+```js
+const obj = addon.createObject();
+// instead of:
+// const obj = new addon.Object();
+```
+
+First, the `createObject()` method is implemented in `addon.cc`:
+
+```cpp
+// addon.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void CreateObject(const FunctionCallbackInfo& args) {
+ MyObject::NewInstance(args);
+}
+
+void InitAll(Local exports, Local module) {
+ MyObject::Init(exports->GetIsolate());
+
+ NODE_SET_METHOD(module, "exports", CreateObject);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
+
+} // namespace demo
+```
+
+In `myobject.h`, the static method `NewInstance()` is added to handle
+instantiating the object. This method takes the place of using `new` in
+JavaScript:
+
+```cpp
+// myobject.h
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include
+#include
+
+namespace demo {
+
+class MyObject : public node::ObjectWrap {
+ public:
+ static void Init(v8::Isolate* isolate);
+ static void NewInstance(const v8::FunctionCallbackInfo& args);
+
+ private:
+ explicit MyObject(double value = 0);
+ ~MyObject();
+
+ static void New(const v8::FunctionCallbackInfo& args);
+ static void PlusOne(const v8::FunctionCallbackInfo& args);
+ static v8::Global constructor;
+ double value_;
+};
+
+} // namespace demo
+
+#endif
+```
+
+The implementation in `myobject.cc` is similar to the previous example:
+
+```cpp
+// myobject.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using node::AddEnvironmentCleanupHook;
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Global;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+// Warning! This is not thread-safe, this addon cannot be used for worker
+// threads.
+Global MyObject::constructor;
+
+MyObject::MyObject(double value) : value_(value) {
+}
+
+MyObject::~MyObject() {
+}
+
+void MyObject::Init(Isolate* isolate) {
+ // Prepare constructor template
+ Local tpl = FunctionTemplate::New(isolate, New);
+ tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
+ tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+ // Prototype
+ NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
+
+ Local context = isolate->GetCurrentContext();
+ constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());
+
+ AddEnvironmentCleanupHook(isolate, [](void*) {
+ constructor.Reset();
+ }, nullptr);
+}
+
+void MyObject::New(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ if (args.IsConstructCall()) {
+ // Invoked as constructor: `new MyObject(...)`
+ double value = args[0]->IsUndefined() ?
+ 0 : args[0]->NumberValue(context).FromMaybe(0);
+ MyObject* obj = new MyObject(value);
+ obj->Wrap(args.This());
+ args.GetReturnValue().Set(args.This());
+ } else {
+ // Invoked as plain function `MyObject(...)`, turn into construct call.
+ const int argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons = Local::New(isolate, constructor);
+ Local instance =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+ args.GetReturnValue().Set(instance);
+ }
+}
+
+void MyObject::NewInstance(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ const unsigned argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons = Local::New(isolate, constructor);
+ Local context = isolate->GetCurrentContext();
+ Local instance =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+
+ args.GetReturnValue().Set(instance);
+}
+
+void MyObject::PlusOne(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ MyObject* obj = ObjectWrap::Unwrap(args.Holder());
+ obj->value_ += 1;
+
+ args.GetReturnValue().Set(Number::New(isolate, obj->value_));
+}
+
+} // namespace demo
+```
+
+Once again, to build this example, the `myobject.cc` file must be added to the
+`binding.gyp`:
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [
+ "addon.cc",
+ "myobject.cc"
+ ]
+ }
+ ]
+}
+```
+
+Test it with:
+
+```js
+// test.js
+const createObject = require('./build/Release/addon');
+
+const obj = createObject(10);
+console.log(obj.plusOne());
+// Prints: 11
+console.log(obj.plusOne());
+// Prints: 12
+console.log(obj.plusOne());
+// Prints: 13
+
+const obj2 = createObject(20);
+console.log(obj2.plusOne());
+// Prints: 21
+console.log(obj2.plusOne());
+// Prints: 22
+console.log(obj2.plusOne());
+// Prints: 23
+```
+
+#### Passing wrapped objects around
+
+In addition to wrapping and returning C++ objects, it is possible to pass
+wrapped objects around by unwrapping them with the Node.js helper function
+`node::ObjectWrap::Unwrap`. The following examples shows a function `add()`
+that can take two `MyObject` objects as input arguments:
+
+```cpp
+// addon.cc
+#include
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using v8::Context;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void CreateObject(const FunctionCallbackInfo& args) {
+ MyObject::NewInstance(args);
+}
+
+void Add(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ MyObject* obj1 = node::ObjectWrap::Unwrap(
+ args[0]->ToObject(context).ToLocalChecked());
+ MyObject* obj2 = node::ObjectWrap::Unwrap(
+ args[1]->ToObject(context).ToLocalChecked());
+
+ double sum = obj1->value() + obj2->value();
+ args.GetReturnValue().Set(Number::New(isolate, sum));
+}
+
+void InitAll(Local exports) {
+ MyObject::Init(exports->GetIsolate());
+
+ NODE_SET_METHOD(exports, "createObject", CreateObject);
+ NODE_SET_METHOD(exports, "add", Add);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
+
+} // namespace demo
+```
+
+In `myobject.h`, a new public method is added to allow access to private values
+after unwrapping the object.
+
+```cpp
+// myobject.h
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include
+#include
+
+namespace demo {
+
+class MyObject : public node::ObjectWrap {
+ public:
+ static void Init(v8::Isolate* isolate);
+ static void NewInstance(const v8::FunctionCallbackInfo& args);
+ inline double value() const { return value_; }
+
+ private:
+ explicit MyObject(double value = 0);
+ ~MyObject();
+
+ static void New(const v8::FunctionCallbackInfo& args);
+ static v8::Global constructor;
+ double value_;
+};
+
+} // namespace demo
+
+#endif
+```
+
+The implementation of `myobject.cc` is similar to before:
+
+```cpp
+// myobject.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using node::AddEnvironmentCleanupHook;
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Global;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+// Warning! This is not thread-safe, this addon cannot be used for worker
+// threads.
+Global MyObject::constructor;
+
+MyObject::MyObject(double value) : value_(value) {
+}
+
+MyObject::~MyObject() {
+}
+
+void MyObject::Init(Isolate* isolate) {
+ // Prepare constructor template
+ Local tpl = FunctionTemplate::New(isolate, New);
+ tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
+ tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+ Local context = isolate->GetCurrentContext();
+ constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());
+
+ AddEnvironmentCleanupHook(isolate, [](void*) {
+ constructor.Reset();
+ }, nullptr);
+}
+
+void MyObject::New(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ if (args.IsConstructCall()) {
+ // Invoked as constructor: `new MyObject(...)`
+ double value = args[0]->IsUndefined() ?
+ 0 : args[0]->NumberValue(context).FromMaybe(0);
+ MyObject* obj = new MyObject(value);
+ obj->Wrap(args.This());
+ args.GetReturnValue().Set(args.This());
+ } else {
+ // Invoked as plain function `MyObject(...)`, turn into construct call.
+ const int argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons = Local::New(isolate, constructor);
+ Local instance =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+ args.GetReturnValue().Set(instance);
+ }
+}
+
+void MyObject::NewInstance(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ const unsigned argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons = Local::New(isolate, constructor);
+ Local context = isolate->GetCurrentContext();
+ Local instance =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+
+ args.GetReturnValue().Set(instance);
+}
+
+} // namespace demo
+```
+
+Test it with:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const obj1 = addon.createObject(10);
+const obj2 = addon.createObject(20);
+const result = addon.add(obj1, obj2);
+
+console.log(result);
+// Prints: 30
+```
+
+[Electron]: https://electronjs.org/
+[Embedder's Guide]: https://v8.dev/docs/embed
+[Linking to libraries included with Node.js]: #linking-to-libraries-included-with-nodejs
+[Native Abstractions for Node.js]: https://github.com/nodejs/nan
+[V8]: https://v8.dev/
+[`Worker`]: worker_threads.md#class-worker
+[bindings]: https://github.com/TooTallNate/node-bindings
+[download]: https://github.com/nodejs/node-addon-examples
+[examples]: https://github.com/nodejs/nan/tree/HEAD/examples/
+[implementation considerations]: n-api.md#implications-of-abi-stability
+[installation instructions]: https://github.com/nodejs/node-gyp#installation
+[libuv]: https://github.com/libuv/libuv
+[node-gyp]: https://github.com/nodejs/node-gyp
+[require]: /api/v20/modules#requireid
+[v8-docs]: https://v8docs.nodesource.com/
diff --git a/content/api/v20/assert.en.md b/content/api/v20/assert.en.md
new file mode 100644
index 0000000000..8fd87ed2ad
--- /dev/null
+++ b/content/api/v20/assert.en.md
@@ -0,0 +1,2221 @@
+---
+title: 'assert'
+displayTitle: 'Assert'
+category: 'api'
+version: 'v20'
+---
+
+
+
+
+
+Stable
+
+
+
+
+
+The `node:assert` module provides a set of assertion functions for verifying
+invariants.
+
+### Strict assertion mode
+
+
+
+In strict assertion mode, non-strict methods behave like their corresponding
+strict methods. For example, [`assert.deepEqual()`][] will behave like
+[`assert.deepStrictEqual()`][].
+
+In strict assertion mode, error messages for objects display a diff. In legacy
+assertion mode, error messages for objects display the objects, often truncated.
+
+To use strict assertion mode:
+
+```mjs|cjs
+import { strict as assert } from 'node:assert';
+--------------
+const assert = require('node:assert').strict;
+```
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+--------------
+const assert = require('node:assert/strict');
+```
+
+Example error diff:
+
+```mjs|cjs
+import { strict as assert } from 'node:assert';
+
+assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected ... Lines skipped
+//
+// [
+// [
+// ...
+// 2,
+// + 3
+// - '3'
+// ],
+// ...
+// 5
+// ]
+--------------
+const assert = require('node:assert/strict');
+
+assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected ... Lines skipped
+//
+// [
+// [
+// ...
+// 2,
+// + 3
+// - '3'
+// ],
+// ...
+// 5
+// ]
+```
+
+To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS`
+environment variables. This will also deactivate the colors in the REPL. For
+more on color support in terminal environments, read the tty
+[`getColorDepth()`][] documentation.
+
+### Legacy assertion mode
+
+Legacy assertion mode uses the [`==` operator][] in:
+
+* [`assert.deepEqual()`][]
+* [`assert.equal()`][]
+* [`assert.notDeepEqual()`][]
+* [`assert.notEqual()`][]
+
+To use legacy assertion mode:
+
+```mjs|cjs
+import assert from 'node:assert';
+--------------
+const assert = require('node:assert');
+```
+
+Legacy assertion mode may have surprising results, especially when using
+[`assert.deepEqual()`][]:
+
+```cjs
+// WARNING: This does not throw an AssertionError in legacy assertion mode!
+assert.deepEqual(/a/gi, new Date());
+```
+
+### assert.AssertionError
+
+* Extends: [`errors.Error`](/api/v20/errors#error)
+
+Indicates the failure of an assertion. All errors thrown by the `node:assert`
+module will be instances of the `AssertionError` class.
+
+#### `new assert.AssertionError(options)`
+
+
+
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If provided, the error message is set to this value.
+ * `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `actual` property on the error instance.
+ * `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `expected` property on the error instance.
+ * `operator` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The `operator` property on the error instance.
+ * `stackStartFn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) If provided, the generated stack trace omits
+ frames before this function.
+
+A subclass of `Error` that indicates the failure of an assertion.
+
+All instances contain the built-in `Error` properties (`message` and `name`)
+and:
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Set to the `actual` argument for methods such as
+ [`assert.strictEqual()`][].
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Set to the `expected` value for methods such as
+ [`assert.strictEqual()`][].
+* `generatedMessage` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates if the message was auto-generated
+ (`true`) or not.
+* `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Value is always `ERR_ASSERTION` to show that the error is an
+ assertion error.
+* `operator` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Set to the passed in operator value.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+// Generate an AssertionError to compare the error message later:
+const { message } = new assert.AssertionError({
+ actual: 1,
+ expected: 2,
+ operator: 'strictEqual',
+});
+
+// Verify error output:
+try {
+ assert.strictEqual(1, 2);
+} catch (err) {
+ assert(err instanceof assert.AssertionError);
+ assert.strictEqual(err.message, message);
+ assert.strictEqual(err.name, 'AssertionError');
+ assert.strictEqual(err.actual, 1);
+ assert.strictEqual(err.expected, 2);
+ assert.strictEqual(err.code, 'ERR_ASSERTION');
+ assert.strictEqual(err.operator, 'strictEqual');
+ assert.strictEqual(err.generatedMessage, true);
+}
+--------------
+const assert = require('node:assert');
+
+// Generate an AssertionError to compare the error message later:
+const { message } = new assert.AssertionError({
+ actual: 1,
+ expected: 2,
+ operator: 'strictEqual',
+});
+
+// Verify error output:
+try {
+ assert.strictEqual(1, 2);
+} catch (err) {
+ assert(err instanceof assert.AssertionError);
+ assert.strictEqual(err.message, message);
+ assert.strictEqual(err.name, 'AssertionError');
+ assert.strictEqual(err.actual, 1);
+ assert.strictEqual(err.expected, 2);
+ assert.strictEqual(err.code, 'ERR_ASSERTION');
+ assert.strictEqual(err.operator, 'strictEqual');
+ assert.strictEqual(err.generatedMessage, true);
+}
+```
+
+### `assert.CallTracker`
+
+
+
+
+
+Deprecated
+
+
+
+This feature is deprecated and will be removed in a future version.
+Please consider using alternatives such as the
+[`mock`][] helper function.
+
+#### `new assert.CallTracker()`
+
+
+
+Creates a new [`CallTracker`][] object which can be used to track if functions
+were called a specific number of times. The `tracker.verify()` must be called
+for the verification to take place. The usual pattern would be to call it in a
+[`process.on('exit')`][] handler.
+
+```mjs|cjs
+import assert from 'node:assert';
+import process from 'node:process';
+
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// callsfunc() must be called exactly 1 time before tracker.verify().
+const callsfunc = tracker.calls(func, 1);
+
+callsfunc();
+
+// Calls tracker.verify() and verifies if all tracker.calls() functions have
+// been called exact times.
+process.on('exit', () => {
+ tracker.verify();
+});
+--------------
+const assert = require('node:assert');
+
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// callsfunc() must be called exactly 1 time before tracker.verify().
+const callsfunc = tracker.calls(func, 1);
+
+callsfunc();
+
+// Calls tracker.verify() and verifies if all tracker.calls() functions have
+// been called exact times.
+process.on('exit', () => {
+ tracker.verify();
+});
+```
+
+#### `tracker.calls([fn][, exact])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) **Default:** A no-op function.
+* `exact` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `1`.
+* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) that wraps `fn`.
+
+The wrapper function is expected to be called exactly `exact` times. If the
+function has not been called exactly `exact` times when
+[`tracker.verify()`][] is called, then [`tracker.verify()`][] will throw an
+error.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func);
+--------------
+const assert = require('node:assert');
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func);
+```
+
+#### `tracker.getCalls(fn)`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function).
+
+* Returns: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) with all the calls to a tracked function.
+
+* Object [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `thisArg` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `arguments` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) the arguments passed to the tracked function
+
+```mjs|cjs
+import assert from 'node:assert';
+
+const tracker = new assert.CallTracker();
+
+function func() {}
+const callsfunc = tracker.calls(func);
+callsfunc(1, 2, 3);
+
+assert.deepStrictEqual(tracker.getCalls(callsfunc),
+ [{ thisArg: undefined, arguments: [1, 2, 3] }]);
+--------------
+const assert = require('node:assert');
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+const callsfunc = tracker.calls(func);
+callsfunc(1, 2, 3);
+
+assert.deepStrictEqual(tracker.getCalls(callsfunc),
+ [{ thisArg: undefined, arguments: [1, 2, 3] }]);
+```
+
+#### `tracker.report()`
+
+
+
+* Returns: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of objects containing information about the wrapper functions
+ returned by [`tracker.calls()`][].
+* Object [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+ * `actual` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The actual number of times the function was called.
+ * `expected` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of times the function was expected to be
+ called.
+ * `operator` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the function that is wrapped.
+ * `stack` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A stack trace of the function.
+
+The arrays contains information about the expected and actual number of calls of
+the functions that have not been called the expected number of times.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func, 2);
+
+// Returns an array containing information on callsfunc()
+console.log(tracker.report());
+// [
+// {
+// message: 'Expected the func function to be executed 2 time(s) but was
+// executed 0 time(s).',
+// actual: 0,
+// expected: 2,
+// operator: 'func',
+// stack: stack trace
+// }
+// ]
+--------------
+const assert = require('node:assert');
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func, 2);
+
+// Returns an array containing information on callsfunc()
+console.log(tracker.report());
+// [
+// {
+// message: 'Expected the func function to be executed 2 time(s) but was
+// executed 0 time(s).',
+// actual: 0,
+// expected: 2,
+// operator: 'func',
+// stack: stack trace
+// }
+// ]
+```
+
+#### `tracker.reset([fn])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) a tracked function to reset.
+
+Reset calls of the call tracker.
+If a tracked function is passed as an argument, the calls will be reset for it.
+If no arguments are passed, all tracked functions will be reset
+
+```mjs|cjs
+import assert from 'node:assert';
+
+const tracker = new assert.CallTracker();
+
+function func() {}
+const callsfunc = tracker.calls(func);
+
+callsfunc();
+// Tracker was called once
+assert.strictEqual(tracker.getCalls(callsfunc).length, 1);
+
+tracker.reset(callsfunc);
+assert.strictEqual(tracker.getCalls(callsfunc).length, 0);
+--------------
+const assert = require('node:assert');
+
+const tracker = new assert.CallTracker();
+
+function func() {}
+const callsfunc = tracker.calls(func);
+
+callsfunc();
+// Tracker was called once
+assert.strictEqual(tracker.getCalls(callsfunc).length, 1);
+
+tracker.reset(callsfunc);
+assert.strictEqual(tracker.getCalls(callsfunc).length, 0);
+```
+
+#### `tracker.verify()`
+
+
+
+Iterates through the list of functions passed to
+[`tracker.calls()`][] and will throw an error for functions that
+have not been called the expected number of times.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func, 2);
+
+callsfunc();
+
+// Will throw an error since callsfunc() was only called once.
+tracker.verify();
+--------------
+const assert = require('node:assert');
+
+// Creates call tracker.
+const tracker = new assert.CallTracker();
+
+function func() {}
+
+// Returns a function that wraps func() that must be called exact times
+// before tracker.verify().
+const callsfunc = tracker.calls(func, 2);
+
+callsfunc();
+
+// Will throw an error since callsfunc() was only called once.
+tracker.verify();
+```
+
+### `assert(value[, message])`
+
+
+
+* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The input that is checked for being truthy.
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+An alias of [`assert.ok()`][].
+
+### `assert.deepEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+**Strict assertion mode**
+
+An alias of [`assert.deepStrictEqual()`][].
+
+**Legacy assertion mode**
+
+
+
+Legacy: Use [`assert.deepStrictEqual()`][] instead.
+
+
+
+Tests for deep equality between the `actual` and `expected` parameters. Consider
+using [`assert.deepStrictEqual()`][] instead. [`assert.deepEqual()`][] can have
+surprising results.
+
+_Deep equality_ means that the enumerable "own" properties of child objects
+are also recursively evaluated by the following rules.
+
+#### Comparison details
+
+* Primitive values are compared with the [`==` operator][],
+ with the exception of `NaN`. It is treated as being identical in case
+ both sides are `NaN`.
+* [Type tags][Object.prototype.toString()] of objects should be the same.
+* Only [enumerable "own" properties][] are considered.
+* [`Error`][] names and messages are always compared, even if these are not
+ enumerable properties.
+* [Object wrappers][] are compared both as objects and unwrapped values.
+* `Object` properties are compared unordered.
+* [`Map`][] keys and [`Set`][] items are compared unordered.
+* Recursion stops when both sides differ or both sides encounter a circular
+ reference.
+* Implementation does not test the [`[[Prototype]]`][prototype-spec] of
+ objects.
+* [`Symbol`][] properties are not compared.
+* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values.
+* [`RegExp`][] lastIndex, flags, and source are always compared, even if these
+ are not enumerable properties.
+
+The following example does not throw an [`AssertionError`][] because the
+primitives are compared using the [`==` operator][].
+
+```mjs|cjs
+import assert from 'node:assert';
+// WARNING: This does not throw an AssertionError!
+
+assert.deepEqual('+00000000', false);
+--------------
+const assert = require('node:assert');
+// WARNING: This does not throw an AssertionError!
+
+assert.deepEqual('+00000000', false);
+```
+
+"Deep" equality means that the enumerable "own" properties of child objects
+are evaluated also:
+
+```mjs|cjs
+import assert from 'node:assert';
+
+const obj1 = {
+ a: {
+ b: 1,
+ },
+};
+const obj2 = {
+ a: {
+ b: 2,
+ },
+};
+const obj3 = {
+ a: {
+ b: 1,
+ },
+};
+const obj4 = { __proto__: obj1 };
+
+assert.deepEqual(obj1, obj1);
+// OK
+
+// Values of b are different:
+assert.deepEqual(obj1, obj2);
+// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
+
+assert.deepEqual(obj1, obj3);
+// OK
+
+// Prototypes are ignored:
+assert.deepEqual(obj1, obj4);
+// AssertionError: { a: { b: 1 } } deepEqual {}
+--------------
+const assert = require('node:assert');
+
+const obj1 = {
+ a: {
+ b: 1,
+ },
+};
+const obj2 = {
+ a: {
+ b: 2,
+ },
+};
+const obj3 = {
+ a: {
+ b: 1,
+ },
+};
+const obj4 = { __proto__: obj1 };
+
+assert.deepEqual(obj1, obj1);
+// OK
+
+// Values of b are different:
+assert.deepEqual(obj1, obj2);
+// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
+
+assert.deepEqual(obj1, obj3);
+// OK
+
+// Prototypes are ignored:
+assert.deepEqual(obj1, obj4);
+// AssertionError: { a: { b: 1 } } deepEqual {}
+```
+
+If the values are not equal, an [`AssertionError`][] is thrown with a `message`
+property set equal to the value of the `message` parameter. If the `message`
+parameter is undefined, a default error message is assigned. If the `message`
+parameter is an instance of an [`Error`][] then it will be thrown instead of the
+[`AssertionError`][].
+
+### `assert.deepStrictEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Tests for deep equality between the `actual` and `expected` parameters.
+"Deep" equality means that the enumerable "own" properties of child objects
+are recursively evaluated also by the following rules.
+
+#### Comparison details
+
+* Primitive values are compared using [`Object.is()`][].
+* [Type tags][Object.prototype.toString()] of objects should be the same.
+* [`[[Prototype]]`][prototype-spec] of objects are compared using
+ the [`===` operator][].
+* Only [enumerable "own" properties][] are considered.
+* [`Error`][] names and messages are always compared, even if these are not
+ enumerable properties.
+* Enumerable own [`Symbol`][] properties are compared as well.
+* [Object wrappers][] are compared both as objects and unwrapped values.
+* `Object` properties are compared unordered.
+* [`Map`][] keys and [`Set`][] items are compared unordered.
+* Recursion stops when both sides differ or both sides encounter a circular
+ reference.
+* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values. See
+ below for further details.
+* [`RegExp`][] lastIndex, flags, and source are always compared, even if these
+ are not enumerable properties.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+// This fails because 1 !== '1'.
+assert.deepStrictEqual({ a: 1 }, { a: '1' });
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// {
+// + a: 1
+// - a: '1'
+// }
+
+// The following objects don't have own properties
+const date = new Date();
+const object = {};
+const fakeDate = {};
+Object.setPrototypeOf(fakeDate, Date.prototype);
+
+// Different [[Prototype]]:
+assert.deepStrictEqual(object, fakeDate);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + {}
+// - Date {}
+
+// Different type tags:
+assert.deepStrictEqual(date, fakeDate);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + 2018-04-26T00:49:08.604Z
+// - Date {}
+
+assert.deepStrictEqual(NaN, NaN);
+// OK because Object.is(NaN, NaN) is true.
+
+// Different unwrapped numbers:
+assert.deepStrictEqual(new Number(1), new Number(2));
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + [Number: 1]
+// - [Number: 2]
+
+assert.deepStrictEqual(new String('foo'), Object('foo'));
+// OK because the object and the string are identical when unwrapped.
+
+assert.deepStrictEqual(-0, -0);
+// OK
+
+// Different zeros:
+assert.deepStrictEqual(0, -0);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + 0
+// - -0
+
+const symbol1 = Symbol();
+const symbol2 = Symbol();
+assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
+// OK, because it is the same symbol on both objects.
+
+assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
+// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
+//
+// {
+// [Symbol()]: 1
+// }
+
+const weakMap1 = new WeakMap();
+const weakMap2 = new WeakMap([[{}, {}]]);
+const weakMap3 = new WeakMap();
+weakMap3.unequal = true;
+
+assert.deepStrictEqual(weakMap1, weakMap2);
+// OK, because it is impossible to compare the entries
+
+// Fails because weakMap3 has a property that weakMap1 does not contain:
+assert.deepStrictEqual(weakMap1, weakMap3);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// WeakMap {
+// + [items unknown]
+// - [items unknown],
+// - unequal: true
+// }
+--------------
+const assert = require('node:assert/strict');
+
+// This fails because 1 !== '1'.
+assert.deepStrictEqual({ a: 1 }, { a: '1' });
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// {
+// + a: 1
+// - a: '1'
+// }
+
+// The following objects don't have own properties
+const date = new Date();
+const object = {};
+const fakeDate = {};
+Object.setPrototypeOf(fakeDate, Date.prototype);
+
+// Different [[Prototype]]:
+assert.deepStrictEqual(object, fakeDate);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + {}
+// - Date {}
+
+// Different type tags:
+assert.deepStrictEqual(date, fakeDate);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + 2018-04-26T00:49:08.604Z
+// - Date {}
+
+assert.deepStrictEqual(NaN, NaN);
+// OK because Object.is(NaN, NaN) is true.
+
+// Different unwrapped numbers:
+assert.deepStrictEqual(new Number(1), new Number(2));
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + [Number: 1]
+// - [Number: 2]
+
+assert.deepStrictEqual(new String('foo'), Object('foo'));
+// OK because the object and the string are identical when unwrapped.
+
+assert.deepStrictEqual(-0, -0);
+// OK
+
+// Different zeros:
+assert.deepStrictEqual(0, -0);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// + 0
+// - -0
+
+const symbol1 = Symbol();
+const symbol2 = Symbol();
+assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
+// OK, because it is the same symbol on both objects.
+
+assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
+// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
+//
+// {
+// [Symbol()]: 1
+// }
+
+const weakMap1 = new WeakMap();
+const weakMap2 = new WeakMap([[{}, {}]]);
+const weakMap3 = new WeakMap();
+weakMap3.unequal = true;
+
+assert.deepStrictEqual(weakMap1, weakMap2);
+// OK, because it is impossible to compare the entries
+
+// Fails because weakMap3 has a property that weakMap1 does not contain:
+assert.deepStrictEqual(weakMap1, weakMap3);
+// AssertionError: Expected inputs to be strictly deep-equal:
+// + actual - expected
+//
+// WeakMap {
+// + [items unknown]
+// - [items unknown],
+// - unequal: true
+// }
+```
+
+If the values are not equal, an [`AssertionError`][] is thrown with a `message`
+property set equal to the value of the `message` parameter. If the `message`
+parameter is undefined, a default error message is assigned. If the `message`
+parameter is an instance of an [`Error`][] then it will be thrown instead of the
+`AssertionError`.
+
+### `assert.doesNotMatch(string, regexp[, message])`
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `regexp` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Expects the `string` input not to match the regular expression.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.doesNotMatch('I will fail', /fail/);
+// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
+
+assert.doesNotMatch(123, /pass/);
+// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
+
+assert.doesNotMatch('I will pass', /different/);
+// OK
+--------------
+const assert = require('node:assert/strict');
+
+assert.doesNotMatch('I will fail', /fail/);
+// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
+
+assert.doesNotMatch(123, /pass/);
+// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
+
+assert.doesNotMatch('I will pass', /different/);
+// OK
+```
+
+If the values do match, or if the `string` argument is of another type than
+`string`, an [`AssertionError`][] is thrown with a `message` property set equal
+to the value of the `message` parameter. If the `message` parameter is
+undefined, a default error message is assigned. If the `message` parameter is an
+instance of an [`Error`][] then it will be thrown instead of the
+[`AssertionError`][].
+
+### `assert.doesNotReject(asyncFn[, error][, message])`
+
+
+
+* `asyncFn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+* `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
+calls the function and awaits the returned promise to complete. It will then
+check that the promise is not rejected.
+
+If `asyncFn` is a function and it throws an error synchronously,
+`assert.doesNotReject()` will return a rejected `Promise` with that error. If
+the function does not return a promise, `assert.doesNotReject()` will return a
+rejected `Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases
+the error handler is skipped.
+
+Using `assert.doesNotReject()` is actually not useful because there is little
+benefit in catching a rejection and then rejecting it again. Instead, consider
+adding a comment next to the specific code path that should not reject and keep
+error messages as expressive as possible.
+
+If specified, `error` can be a [`Class`][], [`RegExp`][], or a validation
+function. See [`assert.throws()`][] for more details.
+
+Besides the async nature to await the completion behaves identically to
+[`assert.doesNotThrow()`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+await assert.doesNotReject(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError,
+);
+--------------
+const assert = require('node:assert/strict');
+
+(async () => {
+ await assert.doesNotReject(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError,
+ );
+})();
+```
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
+ .then(() => {
+ // ...
+ });
+--------------
+const assert = require('node:assert/strict');
+
+assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
+ .then(() => {
+ // ...
+ });
+```
+
+### `assert.doesNotThrow(fn[, error][, message])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Asserts that the function `fn` does not throw an error.
+
+Using `assert.doesNotThrow()` is actually not useful because there
+is no benefit in catching an error and then rethrowing it. Instead, consider
+adding a comment next to the specific code path that should not throw and keep
+error messages as expressive as possible.
+
+When `assert.doesNotThrow()` is called, it will immediately call the `fn`
+function.
+
+If an error is thrown and it is the same type as that specified by the `error`
+parameter, then an [`AssertionError`][] is thrown. If the error is of a
+different type, or if the `error` parameter is undefined, the error is
+propagated back to the caller.
+
+If specified, `error` can be a [`Class`][], [`RegExp`][], or a validation
+function. See [`assert.throws()`][] for more details.
+
+The following, for instance, will throw the [`TypeError`][] because there is no
+matching error type in the assertion:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError,
+);
+--------------
+const assert = require('node:assert/strict');
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError,
+);
+```
+
+However, the following will result in an [`AssertionError`][] with the message
+'Got unwanted exception...':
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ TypeError,
+);
+--------------
+const assert = require('node:assert/strict');
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ TypeError,
+);
+```
+
+If an [`AssertionError`][] is thrown and a value is provided for the `message`
+parameter, the value of `message` will be appended to the [`AssertionError`][]
+message:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ /Wrong value/,
+ 'Whoops',
+);
+// Throws: AssertionError: Got unwanted exception: Whoops
+--------------
+const assert = require('node:assert/strict');
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ /Wrong value/,
+ 'Whoops',
+);
+// Throws: AssertionError: Got unwanted exception: Whoops
+```
+
+### `assert.equal(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+**Strict assertion mode**
+
+An alias of [`assert.strictEqual()`][].
+
+**Legacy assertion mode**
+
+
+
+Legacy: Use [`assert.strictEqual()`][] instead.
+
+
+
+Tests shallow, coercive equality between the `actual` and `expected` parameters
+using the [`==` operator][]. `NaN` is specially handled
+and treated as being identical if both sides are `NaN`.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+assert.equal(1, 1);
+// OK, 1 == 1
+assert.equal(1, '1');
+// OK, 1 == '1'
+assert.equal(NaN, NaN);
+// OK
+
+assert.equal(1, 2);
+// AssertionError: 1 == 2
+assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
+// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
+--------------
+const assert = require('node:assert');
+
+assert.equal(1, 1);
+// OK, 1 == 1
+assert.equal(1, '1');
+// OK, 1 == '1'
+assert.equal(NaN, NaN);
+// OK
+
+assert.equal(1, 2);
+// AssertionError: 1 == 2
+assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
+// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
+```
+
+If the values are not equal, an [`AssertionError`][] is thrown with a `message`
+property set equal to the value of the `message` parameter. If the `message`
+parameter is undefined, a default error message is assigned. If the `message`
+parameter is an instance of an [`Error`][] then it will be thrown instead of the
+`AssertionError`.
+
+### `assert.fail([message])`
+
+
+
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) **Default:** `'Failed'`
+
+Throws an [`AssertionError`][] with the provided error message or a default
+error message. If the `message` parameter is an instance of an [`Error`][] then
+it will be thrown instead of the [`AssertionError`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.fail();
+// AssertionError [ERR_ASSERTION]: Failed
+
+assert.fail('boom');
+// AssertionError [ERR_ASSERTION]: boom
+
+assert.fail(new TypeError('need array'));
+// TypeError: need array
+--------------
+const assert = require('node:assert/strict');
+
+assert.fail();
+// AssertionError [ERR_ASSERTION]: Failed
+
+assert.fail('boom');
+// AssertionError [ERR_ASSERTION]: boom
+
+assert.fail(new TypeError('need array'));
+// TypeError: need array
+```
+
+Using `assert.fail()` with more than two arguments is possible but deprecated.
+See below for further details.
+
+### `assert.fail(actual, expected[, message[, operator[, stackStartFn]]])`
+
+
+
+
+
+Deprecated: Use `assert.fail([message])` or other assert functions instead.
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+* `operator` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'!='`
+* `stackStartFn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) **Default:** `assert.fail`
+
+If `message` is falsy, the error message is set as the values of `actual` and
+`expected` separated by the provided `operator`. If just the two `actual` and
+`expected` arguments are provided, `operator` will default to `'!='`. If
+`message` is provided as third argument it will be used as the error message and
+the other arguments will be stored as properties on the thrown object. If
+`stackStartFn` is provided, all stack frames above that function will be
+removed from stacktrace (see [`Error.captureStackTrace`][]). If no arguments are
+given, the default message `Failed` will be used.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.fail('a', 'b');
+// AssertionError [ERR_ASSERTION]: 'a' != 'b'
+
+assert.fail(1, 2, undefined, '>');
+// AssertionError [ERR_ASSERTION]: 1 > 2
+
+assert.fail(1, 2, 'fail');
+// AssertionError [ERR_ASSERTION]: fail
+
+assert.fail(1, 2, 'whoops', '>');
+// AssertionError [ERR_ASSERTION]: whoops
+
+assert.fail(1, 2, new TypeError('need array'));
+// TypeError: need array
+--------------
+const assert = require('node:assert/strict');
+
+assert.fail('a', 'b');
+// AssertionError [ERR_ASSERTION]: 'a' != 'b'
+
+assert.fail(1, 2, undefined, '>');
+// AssertionError [ERR_ASSERTION]: 1 > 2
+
+assert.fail(1, 2, 'fail');
+// AssertionError [ERR_ASSERTION]: fail
+
+assert.fail(1, 2, 'whoops', '>');
+// AssertionError [ERR_ASSERTION]: whoops
+
+assert.fail(1, 2, new TypeError('need array'));
+// TypeError: need array
+```
+
+In the last three cases `actual`, `expected`, and `operator` have no
+influence on the error message.
+
+Example use of `stackStartFn` for truncating the exception's stacktrace:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+function suppressFrame() {
+ assert.fail('a', 'b', undefined, '!==', suppressFrame);
+}
+suppressFrame();
+// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
+// at repl:1:1
+// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
+// ...
+--------------
+const assert = require('node:assert/strict');
+
+function suppressFrame() {
+ assert.fail('a', 'b', undefined, '!==', suppressFrame);
+}
+suppressFrame();
+// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
+// at repl:1:1
+// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
+// ...
+```
+
+### `assert.ifError(value)`
+
+
+
+* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Throws `value` if `value` is not `undefined` or `null`. This is useful when
+testing the `error` argument in callbacks. The stack trace contains all frames
+from the error passed to `ifError()` including the potential new frames for
+`ifError()` itself.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.ifError(null);
+// OK
+assert.ifError(0);
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
+assert.ifError('error');
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
+assert.ifError(new Error());
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
+
+// Create some random error frames.
+let err;
+(function errorFrame() {
+ err = new Error('test error');
+})();
+
+(function ifErrorFrame() {
+ assert.ifError(err);
+})();
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
+// at ifErrorFrame
+// at errorFrame
+--------------
+const assert = require('node:assert/strict');
+
+assert.ifError(null);
+// OK
+assert.ifError(0);
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
+assert.ifError('error');
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
+assert.ifError(new Error());
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
+
+// Create some random error frames.
+let err;
+(function errorFrame() {
+ err = new Error('test error');
+})();
+
+(function ifErrorFrame() {
+ assert.ifError(err);
+})();
+// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
+// at ifErrorFrame
+// at errorFrame
+```
+
+### `assert.match(string, regexp[, message])`
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `regexp` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Expects the `string` input to match the regular expression.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.match('I will fail', /pass/);
+// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
+
+assert.match(123, /pass/);
+// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
+
+assert.match('I will pass', /pass/);
+// OK
+--------------
+const assert = require('node:assert/strict');
+
+assert.match('I will fail', /pass/);
+// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
+
+assert.match(123, /pass/);
+// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
+
+assert.match('I will pass', /pass/);
+// OK
+```
+
+If the values do not match, or if the `string` argument is of another type than
+`string`, an [`AssertionError`][] is thrown with a `message` property set equal
+to the value of the `message` parameter. If the `message` parameter is
+undefined, a default error message is assigned. If the `message` parameter is an
+instance of an [`Error`][] then it will be thrown instead of the
+[`AssertionError`][].
+
+### `assert.notDeepEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+**Strict assertion mode**
+
+An alias of [`assert.notDeepStrictEqual()`][].
+
+**Legacy assertion mode**
+
+
+
+Legacy: Use [`assert.notDeepStrictEqual()`][] instead.
+
+
+
+Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
+
+```mjs|cjs
+import assert from 'node:assert';
+
+const obj1 = {
+ a: {
+ b: 1,
+ },
+};
+const obj2 = {
+ a: {
+ b: 2,
+ },
+};
+const obj3 = {
+ a: {
+ b: 1,
+ },
+};
+const obj4 = { __proto__: obj1 };
+
+assert.notDeepEqual(obj1, obj1);
+// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
+
+assert.notDeepEqual(obj1, obj2);
+// OK
+
+assert.notDeepEqual(obj1, obj3);
+// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
+
+assert.notDeepEqual(obj1, obj4);
+// OK
+--------------
+const assert = require('node:assert');
+
+const obj1 = {
+ a: {
+ b: 1,
+ },
+};
+const obj2 = {
+ a: {
+ b: 2,
+ },
+};
+const obj3 = {
+ a: {
+ b: 1,
+ },
+};
+const obj4 = { __proto__: obj1 };
+
+assert.notDeepEqual(obj1, obj1);
+// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
+
+assert.notDeepEqual(obj1, obj2);
+// OK
+
+assert.notDeepEqual(obj1, obj3);
+// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
+
+assert.notDeepEqual(obj1, obj4);
+// OK
+```
+
+If the values are deeply equal, an [`AssertionError`][] is thrown with a
+`message` property set equal to the value of the `message` parameter. If the
+`message` parameter is undefined, a default error message is assigned. If the
+`message` parameter is an instance of an [`Error`][] then it will be thrown
+instead of the `AssertionError`.
+
+### `assert.notDeepStrictEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
+// OK
+--------------
+const assert = require('node:assert/strict');
+
+assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
+// OK
+```
+
+If the values are deeply and strictly equal, an [`AssertionError`][] is thrown
+with a `message` property set equal to the value of the `message` parameter. If
+the `message` parameter is undefined, a default error message is assigned. If
+the `message` parameter is an instance of an [`Error`][] then it will be thrown
+instead of the [`AssertionError`][].
+
+### `assert.notEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+**Strict assertion mode**
+
+An alias of [`assert.notStrictEqual()`][].
+
+**Legacy assertion mode**
+
+
+
+Legacy: Use [`assert.notStrictEqual()`][] instead.
+
+
+
+Tests shallow, coercive inequality with the [`!=` operator][]. `NaN` is
+specially handled and treated as being identical if both sides are `NaN`.
+
+```mjs|cjs
+import assert from 'node:assert';
+
+assert.notEqual(1, 2);
+// OK
+
+assert.notEqual(1, 1);
+// AssertionError: 1 != 1
+
+assert.notEqual(1, '1');
+// AssertionError: 1 != '1'
+--------------
+const assert = require('node:assert');
+
+assert.notEqual(1, 2);
+// OK
+
+assert.notEqual(1, 1);
+// AssertionError: 1 != 1
+
+assert.notEqual(1, '1');
+// AssertionError: 1 != '1'
+```
+
+If the values are equal, an [`AssertionError`][] is thrown with a `message`
+property set equal to the value of the `message` parameter. If the `message`
+parameter is undefined, a default error message is assigned. If the `message`
+parameter is an instance of an [`Error`][] then it will be thrown instead of the
+`AssertionError`.
+
+### `assert.notStrictEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Tests strict inequality between the `actual` and `expected` parameters as
+determined by [`Object.is()`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.notStrictEqual(1, 2);
+// OK
+
+assert.notStrictEqual(1, 1);
+// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
+//
+// 1
+
+assert.notStrictEqual(1, '1');
+// OK
+--------------
+const assert = require('node:assert/strict');
+
+assert.notStrictEqual(1, 2);
+// OK
+
+assert.notStrictEqual(1, 1);
+// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
+//
+// 1
+
+assert.notStrictEqual(1, '1');
+// OK
+```
+
+If the values are strictly equal, an [`AssertionError`][] is thrown with a
+`message` property set equal to the value of the `message` parameter. If the
+`message` parameter is undefined, a default error message is assigned. If the
+`message` parameter is an instance of an [`Error`][] then it will be thrown
+instead of the `AssertionError`.
+
+### `assert.ok(value[, message])`
+
+
+
+* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Tests if `value` is truthy. It is equivalent to
+`assert.equal(!!value, true, message)`.
+
+If `value` is not truthy, an [`AssertionError`][] is thrown with a `message`
+property set equal to the value of the `message` parameter. If the `message`
+parameter is `undefined`, a default error message is assigned. If the `message`
+parameter is an instance of an [`Error`][] then it will be thrown instead of the
+`AssertionError`.
+If no arguments are passed in at all `message` will be set to the string:
+``'No value argument passed to `assert.ok()`'``.
+
+Be aware that in the `repl` the error message will be different to the one
+thrown in a file! See below for further details.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.ok(true);
+// OK
+assert.ok(1);
+// OK
+
+assert.ok();
+// AssertionError: No value argument passed to `assert.ok()`
+
+assert.ok(false, 'it\'s false');
+// AssertionError: it's false
+
+// In the repl:
+assert.ok(typeof 123 === 'string');
+// AssertionError: false == true
+
+// In a file (e.g. test.js):
+assert.ok(typeof 123 === 'string');
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(typeof 123 === 'string')
+
+assert.ok(false);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(false)
+
+assert.ok(0);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(0)
+--------------
+const assert = require('node:assert/strict');
+
+assert.ok(true);
+// OK
+assert.ok(1);
+// OK
+
+assert.ok();
+// AssertionError: No value argument passed to `assert.ok()`
+
+assert.ok(false, 'it\'s false');
+// AssertionError: it's false
+
+// In the repl:
+assert.ok(typeof 123 === 'string');
+// AssertionError: false == true
+
+// In a file (e.g. test.js):
+assert.ok(typeof 123 === 'string');
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(typeof 123 === 'string')
+
+assert.ok(false);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(false)
+
+assert.ok(0);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert.ok(0)
+```
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+// Using `assert()` works the same:
+assert(0);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert(0)
+--------------
+const assert = require('node:assert');
+
+// Using `assert()` works the same:
+assert(0);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert(0)
+```
+
+### `assert.rejects(asyncFn[, error][, message])`
+
+
+
+* `asyncFn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+* `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
+calls the function and awaits the returned promise to complete. It will then
+check that the promise is rejected.
+
+If `asyncFn` is a function and it throws an error synchronously,
+`assert.rejects()` will return a rejected `Promise` with that error. If the
+function does not return a promise, `assert.rejects()` will return a rejected
+`Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases the error
+handler is skipped.
+
+Besides the async nature to await the completion behaves identically to
+[`assert.throws()`][].
+
+If specified, `error` can be a [`Class`][], [`RegExp`][], a validation function,
+an object where each property will be tested for, or an instance of error where
+each property will be tested for including the non-enumerable `message` and
+`name` properties.
+
+If specified, `message` will be the message provided by the [`AssertionError`][]
+if the `asyncFn` fails to reject.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+await assert.rejects(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ {
+ name: 'TypeError',
+ message: 'Wrong value',
+ },
+);
+--------------
+const assert = require('node:assert/strict');
+
+(async () => {
+ await assert.rejects(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ {
+ name: 'TypeError',
+ message: 'Wrong value',
+ },
+ );
+})();
+```
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+await assert.rejects(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ (err) => {
+ assert.strictEqual(err.name, 'TypeError');
+ assert.strictEqual(err.message, 'Wrong value');
+ return true;
+ },
+);
+--------------
+const assert = require('node:assert/strict');
+
+(async () => {
+ await assert.rejects(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ (err) => {
+ assert.strictEqual(err.name, 'TypeError');
+ assert.strictEqual(err.message, 'Wrong value');
+ return true;
+ },
+ );
+})();
+```
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.rejects(
+ Promise.reject(new Error('Wrong value')),
+ Error,
+).then(() => {
+ // ...
+});
+--------------
+const assert = require('node:assert/strict');
+
+assert.rejects(
+ Promise.reject(new Error('Wrong value')),
+ Error,
+).then(() => {
+ // ...
+});
+```
+
+`error` cannot be a string. If a string is provided as the second
+argument, then `error` is assumed to be omitted and the string will be used for
+`message` instead. This can lead to easy-to-miss mistakes. Please read the
+example in [`assert.throws()`][] carefully if using a string as the second
+argument gets considered.
+
+### `assert.strictEqual(actual, expected[, message])`
+
+
+
+* `actual` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `expected` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+
+Tests strict equality between the `actual` and `expected` parameters as
+determined by [`Object.is()`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.strictEqual(1, 2);
+// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
+//
+// 1 !== 2
+
+assert.strictEqual(1, 1);
+// OK
+
+assert.strictEqual('Hello foobar', 'Hello World!');
+// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
+// + actual - expected
+//
+// + 'Hello foobar'
+// - 'Hello World!'
+// ^
+
+const apples = 1;
+const oranges = 2;
+assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
+// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
+
+assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
+// TypeError: Inputs are not identical
+--------------
+const assert = require('node:assert/strict');
+
+assert.strictEqual(1, 2);
+// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
+//
+// 1 !== 2
+
+assert.strictEqual(1, 1);
+// OK
+
+assert.strictEqual('Hello foobar', 'Hello World!');
+// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
+// + actual - expected
+//
+// + 'Hello foobar'
+// - 'Hello World!'
+// ^
+
+const apples = 1;
+const oranges = 2;
+assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
+// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
+
+assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
+// TypeError: Inputs are not identical
+```
+
+If the values are not strictly equal, an [`AssertionError`][] is thrown with a
+`message` property set equal to the value of the `message` parameter. If the
+`message` parameter is undefined, a default error message is assigned. If the
+`message` parameter is an instance of an [`Error`][] then it will be thrown
+instead of the [`AssertionError`][].
+
+### `assert.throws(fn[, error][, message])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `error` [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Expects the function `fn` to throw an error.
+
+If specified, `error` can be a [`Class`][], [`RegExp`][], a validation function,
+a validation object where each property will be tested for strict deep equality,
+or an instance of error where each property will be tested for strict deep
+equality including the non-enumerable `message` and `name` properties. When
+using an object, it is also possible to use a regular expression, when
+validating against a string property. See below for examples.
+
+If specified, `message` will be appended to the message provided by the
+`AssertionError` if the `fn` call fails to throw or in case the error validation
+fails.
+
+Custom validation object/error instance:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+const err = new TypeError('Wrong value');
+err.code = 404;
+err.foo = 'bar';
+err.info = {
+ nested: true,
+ baz: 'text',
+};
+err.reg = /abc/i;
+
+assert.throws(
+ () => {
+ throw err;
+ },
+ {
+ name: 'TypeError',
+ message: 'Wrong value',
+ info: {
+ nested: true,
+ baz: 'text',
+ },
+ // Only properties on the validation object will be tested for.
+ // Using nested objects requires all properties to be present. Otherwise
+ // the validation is going to fail.
+ },
+);
+
+// Using regular expressions to validate error properties:
+assert.throws(
+ () => {
+ throw err;
+ },
+ {
+ // The `name` and `message` properties are strings and using regular
+ // expressions on those will match against the string. If they fail, an
+ // error is thrown.
+ name: /^TypeError$/,
+ message: /Wrong/,
+ foo: 'bar',
+ info: {
+ nested: true,
+ // It is not possible to use regular expressions for nested properties!
+ baz: 'text',
+ },
+ // The `reg` property contains a regular expression and only if the
+ // validation object contains an identical regular expression, it is going
+ // to pass.
+ reg: /abc/i,
+ },
+);
+
+// Fails due to the different `message` and `name` properties:
+assert.throws(
+ () => {
+ const otherErr = new Error('Not found');
+ // Copy all enumerable properties from `err` to `otherErr`.
+ for (const [key, value] of Object.entries(err)) {
+ otherErr[key] = value;
+ }
+ throw otherErr;
+ },
+ // The error's `message` and `name` properties will also be checked when using
+ // an error as validation object.
+ err,
+);
+--------------
+const assert = require('node:assert/strict');
+
+const err = new TypeError('Wrong value');
+err.code = 404;
+err.foo = 'bar';
+err.info = {
+ nested: true,
+ baz: 'text',
+};
+err.reg = /abc/i;
+
+assert.throws(
+ () => {
+ throw err;
+ },
+ {
+ name: 'TypeError',
+ message: 'Wrong value',
+ info: {
+ nested: true,
+ baz: 'text',
+ },
+ // Only properties on the validation object will be tested for.
+ // Using nested objects requires all properties to be present. Otherwise
+ // the validation is going to fail.
+ },
+);
+
+// Using regular expressions to validate error properties:
+assert.throws(
+ () => {
+ throw err;
+ },
+ {
+ // The `name` and `message` properties are strings and using regular
+ // expressions on those will match against the string. If they fail, an
+ // error is thrown.
+ name: /^TypeError$/,
+ message: /Wrong/,
+ foo: 'bar',
+ info: {
+ nested: true,
+ // It is not possible to use regular expressions for nested properties!
+ baz: 'text',
+ },
+ // The `reg` property contains a regular expression and only if the
+ // validation object contains an identical regular expression, it is going
+ // to pass.
+ reg: /abc/i,
+ },
+);
+
+// Fails due to the different `message` and `name` properties:
+assert.throws(
+ () => {
+ const otherErr = new Error('Not found');
+ // Copy all enumerable properties from `err` to `otherErr`.
+ for (const [key, value] of Object.entries(err)) {
+ otherErr[key] = value;
+ }
+ throw otherErr;
+ },
+ // The error's `message` and `name` properties will also be checked when using
+ // an error as validation object.
+ err,
+);
+```
+
+Validate instanceof using constructor:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ Error,
+);
+--------------
+const assert = require('node:assert/strict');
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ Error,
+);
+```
+
+Validate error message using [`RegExp`][]:
+
+Using a regular expression runs `.toString` on the error object, and will
+therefore also include the error name.
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ /^Error: Wrong value$/,
+);
+--------------
+const assert = require('node:assert/strict');
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ /^Error: Wrong value$/,
+);
+```
+
+Custom error validation:
+
+The function must return `true` to indicate all internal validations passed.
+It will otherwise fail with an [`AssertionError`][].
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ (err) => {
+ assert(err instanceof Error);
+ assert(/value/.test(err));
+ // Avoid returning anything from validation functions besides `true`.
+ // Otherwise, it's not clear what part of the validation failed. Instead,
+ // throw an error about the specific validation that failed (as done in this
+ // example) and add as much helpful debugging information to that error as
+ // possible.
+ return true;
+ },
+ 'unexpected error',
+);
+--------------
+const assert = require('node:assert/strict');
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ (err) => {
+ assert(err instanceof Error);
+ assert(/value/.test(err));
+ // Avoid returning anything from validation functions besides `true`.
+ // Otherwise, it's not clear what part of the validation failed. Instead,
+ // throw an error about the specific validation that failed (as done in this
+ // example) and add as much helpful debugging information to that error as
+ // possible.
+ return true;
+ },
+ 'unexpected error',
+);
+```
+
+`error` cannot be a string. If a string is provided as the second
+argument, then `error` is assumed to be omitted and the string will be used for
+`message` instead. This can lead to easy-to-miss mistakes. Using the same
+message as the thrown error message is going to result in an
+`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using
+a string as the second argument gets considered:
+
+```mjs|cjs
+import assert from 'node:assert/strict';
+
+function throwingFirst() {
+ throw new Error('First');
+}
+
+function throwingSecond() {
+ throw new Error('Second');
+}
+
+function notThrowing() {}
+
+// The second argument is a string and the input function threw an Error.
+// The first case will not throw as it does not match for the error message
+// thrown by the input function!
+assert.throws(throwingFirst, 'Second');
+// In the next example the message has no benefit over the message from the
+// error and since it is not clear if the user intended to actually match
+// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
+assert.throws(throwingSecond, 'Second');
+// TypeError [ERR_AMBIGUOUS_ARGUMENT]
+
+// The string is only used (as message) in case the function does not throw:
+assert.throws(notThrowing, 'Second');
+// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
+
+// If it was intended to match for the error message do this instead:
+// It does not throw because the error messages match.
+assert.throws(throwingSecond, /Second$/);
+
+// If the error message does not match, an AssertionError is thrown.
+assert.throws(throwingFirst, /Second$/);
+// AssertionError [ERR_ASSERTION]
+--------------
+const assert = require('node:assert/strict');
+
+function throwingFirst() {
+ throw new Error('First');
+}
+
+function throwingSecond() {
+ throw new Error('Second');
+}
+
+function notThrowing() {}
+
+// The second argument is a string and the input function threw an Error.
+// The first case will not throw as it does not match for the error message
+// thrown by the input function!
+assert.throws(throwingFirst, 'Second');
+// In the next example the message has no benefit over the message from the
+// error and since it is not clear if the user intended to actually match
+// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
+assert.throws(throwingSecond, 'Second');
+// TypeError [ERR_AMBIGUOUS_ARGUMENT]
+
+// The string is only used (as message) in case the function does not throw:
+assert.throws(notThrowing, 'Second');
+// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
+
+// If it was intended to match for the error message do this instead:
+// It does not throw because the error messages match.
+assert.throws(throwingSecond, /Second$/);
+
+// If the error message does not match, an AssertionError is thrown.
+assert.throws(throwingFirst, /Second$/);
+// AssertionError [ERR_ASSERTION]
+```
+
+Due to the confusing error-prone notation, avoid a string as the second
+argument.
+
+[Object wrappers]: https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript
+[Object.prototype.toString()]: https://tc39.github.io/ecma262/#sec-object.prototype.tostring
+[`!=` operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality
+[`===` operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality
+[`==` operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality
+[`AssertionError`]: #class-assertassertionerror
+[`CallTracker`]: #class-assertcalltracker
+[`Class`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
+[`ERR_INVALID_RETURN_VALUE`]: /api/v20/errors#err_invalid_return_value
+[`Error.captureStackTrace`]: /api/v20/errors#errorcapturestacktracetargetobject-constructoropt
+[`Error`]: /api/v20/errors#class-error
+[`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
+[`Object.is()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
+[`RegExp`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
+[`Set`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
+[`Symbol`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
+[`TypeError`]: /api/v20/errors#class-typeerror
+[`WeakMap`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
+[`WeakSet`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet
+[`assert.deepEqual()`]: #assertdeepequalactual-expected-message
+[`assert.deepStrictEqual()`]: #assertdeepstrictequalactual-expected-message
+[`assert.doesNotThrow()`]: #assertdoesnotthrowfn-error-message
+[`assert.equal()`]: #assertequalactual-expected-message
+[`assert.notDeepEqual()`]: #assertnotdeepequalactual-expected-message
+[`assert.notDeepStrictEqual()`]: #assertnotdeepstrictequalactual-expected-message
+[`assert.notEqual()`]: #assertnotequalactual-expected-message
+[`assert.notStrictEqual()`]: #assertnotstrictequalactual-expected-message
+[`assert.ok()`]: #assertokvalue-message
+[`assert.strictEqual()`]: #assertstrictequalactual-expected-message
+[`assert.throws()`]: #assertthrowsfn-error-message
+[`getColorDepth()`]: /api/v20/tty#writestreamgetcolordepthenv
+[`mock`]: /api/v20/test#mocking
+[`process.on('exit')`]: /api/v20/process#event-exit
+[`tracker.calls()`]: #trackercallsfn-exact
+[`tracker.verify()`]: #trackerverify
+[enumerable "own" properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
+[prototype-spec]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots
diff --git a/content/api/v20/async_context.en.md b/content/api/v20/async_context.en.md
new file mode 100644
index 0000000000..6bf26c9111
--- /dev/null
+++ b/content/api/v20/async_context.en.md
@@ -0,0 +1,807 @@
+---
+title: 'async_context'
+displayTitle: 'Asynchronous context tracking'
+category: 'api'
+version: 'v20'
+---
+
+
+
+
+
+Stable
+
+
+
+
+
+### Introduction
+
+These classes are used to associate state and propagate it throughout
+callbacks and promise chains.
+They allow storing data throughout the lifetime of a web request
+or any other asynchronous duration. It is similar to thread-local storage
+in other languages.
+
+The `AsyncLocalStorage` and `AsyncResource` classes are part of the
+`node:async_hooks` module:
+
+```mjs|cjs
+import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
+--------------
+const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');
+```
+
+### `AsyncLocalStorage`
+
+
+
+This class creates stores that stay coherent through asynchronous operations.
+
+While you can create your own implementation on top of the `node:async_hooks`
+module, `AsyncLocalStorage` should be preferred as it is a performant and memory
+safe implementation that involves significant optimizations that are non-obvious
+to implement.
+
+The following example uses `AsyncLocalStorage` to build a simple logger
+that assigns IDs to incoming HTTP requests and includes them in messages
+logged within each request.
+
+```mjs|cjs
+import http from 'node:http';
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+const asyncLocalStorage = new AsyncLocalStorage();
+
+function logWithId(msg) {
+ const id = asyncLocalStorage.getStore();
+ console.log(`${id !== undefined ? id : '-'}:`, msg);
+}
+
+let idSeq = 0;
+http.createServer((req, res) => {
+ asyncLocalStorage.run(idSeq++, () => {
+ logWithId('start');
+ // Imagine any chain of async operations here
+ setImmediate(() => {
+ logWithId('finish');
+ res.end();
+ });
+ });
+}).listen(8080);
+
+http.get('http://localhost:8080');
+http.get('http://localhost:8080');
+// Prints:
+// 0: start
+// 1: start
+// 0: finish
+// 1: finish
+--------------
+const http = require('node:http');
+const { AsyncLocalStorage } = require('node:async_hooks');
+
+const asyncLocalStorage = new AsyncLocalStorage();
+
+function logWithId(msg) {
+ const id = asyncLocalStorage.getStore();
+ console.log(`${id !== undefined ? id : '-'}:`, msg);
+}
+
+let idSeq = 0;
+http.createServer((req, res) => {
+ asyncLocalStorage.run(idSeq++, () => {
+ logWithId('start');
+ // Imagine any chain of async operations here
+ setImmediate(() => {
+ logWithId('finish');
+ res.end();
+ });
+ });
+}).listen(8080);
+
+http.get('http://localhost:8080');
+http.get('http://localhost:8080');
+// Prints:
+// 0: start
+// 1: start
+// 0: finish
+// 1: finish
+```
+
+Each instance of `AsyncLocalStorage` maintains an independent storage context.
+Multiple instances can safely exist simultaneously without risk of interfering
+with each other's data.
+
+#### `new AsyncLocalStorage()`
+
+
+
+Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
+`run()` call or after an `enterWith()` call.
+
+#### Static method: `AsyncLocalStorage.bind(fn)`
+
+
+
+
+
+Experimental
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to bind to the current execution context.
+* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A new function that calls `fn` within the captured
+ execution context.
+
+Binds the given function to the current execution context.
+
+#### Static method: `AsyncLocalStorage.snapshot()`
+
+
+
+
+
+Experimental
+
+
+
+* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A new function with the signature
+ `(fn: (...args) : R, ...args) : R`.
+
+Captures the current execution context and returns a function that accepts a
+function as an argument. Whenever the returned function is called, it
+calls the function passed to it within the captured context.
+
+```js
+const asyncLocalStorage = new AsyncLocalStorage();
+const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot());
+const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
+console.log(result); // returns 123
+```
+
+AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
+async context tracking purposes, for example:
+
+```js
+class Foo {
+ #runInAsyncScope = AsyncLocalStorage.snapshot();
+
+ get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
+}
+
+const foo = asyncLocalStorage.run(123, () => new Foo());
+console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
+```
+
+#### `asyncLocalStorage.disable()`
+
+
+
+
+
+Experimental
+
+
+
+Disables the instance of `AsyncLocalStorage`. All subsequent calls
+to `asyncLocalStorage.getStore()` will return `undefined` until
+`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again.
+
+When calling `asyncLocalStorage.disable()`, all current contexts linked to the
+instance will be exited.
+
+Calling `asyncLocalStorage.disable()` is required before the
+`asyncLocalStorage` can be garbage collected. This does not apply to stores
+provided by the `asyncLocalStorage`, as those objects are garbage collected
+along with the corresponding async resources.
+
+Use this method when the `asyncLocalStorage` is not in use anymore
+in the current process.
+
+#### `asyncLocalStorage.getStore()`
+
+
+
+* Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Returns the current store.
+If called outside of an asynchronous context initialized by
+calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it
+returns `undefined`.
+
+#### `asyncLocalStorage.enterWith(store)`
+
+
+
+
+
+Experimental
+
+
+
+* `store` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Transitions into the context for the remainder of the current
+synchronous execution and then persists the store through any following
+asynchronous calls.
+
+Example:
+
+```js
+const store = { id: 1 };
+// Replaces previous store with the given store object
+asyncLocalStorage.enterWith(store);
+asyncLocalStorage.getStore(); // Returns the store object
+someAsyncOperation(() => {
+ asyncLocalStorage.getStore(); // Returns the same object
+});
+```
+
+This transition will continue for the _entire_ synchronous execution.
+This means that if, for example, the context is entered within an event
+handler subsequent event handlers will also run within that context unless
+specifically bound to another context with an `AsyncResource`. That is why
+`run()` should be preferred over `enterWith()` unless there are strong reasons
+to use the latter method.
+
+```js
+const store = { id: 1 };
+
+emitter.on('my-event', () => {
+ asyncLocalStorage.enterWith(store);
+});
+emitter.on('my-event', () => {
+ asyncLocalStorage.getStore(); // Returns the same object
+});
+
+asyncLocalStorage.getStore(); // Returns undefined
+emitter.emit('my-event');
+asyncLocalStorage.getStore(); // Returns the same object
+```
+
+#### `asyncLocalStorage.run(store, callback[, ...args])`
+
+
+
+* `store` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Runs a function synchronously within a context and returns its
+return value. The store is not accessible outside of the callback function.
+The store is accessible to any asynchronous operations created within the
+callback.
+
+The optional `args` are passed to the callback function.
+
+If the callback function throws an error, the error is thrown by `run()` too.
+The stacktrace is not impacted by this call and the context is exited.
+
+Example:
+
+```js
+const store = { id: 2 };
+try {
+ asyncLocalStorage.run(store, () => {
+ asyncLocalStorage.getStore(); // Returns the store object
+ setTimeout(() => {
+ asyncLocalStorage.getStore(); // Returns the store object
+ }, 200);
+ throw new Error();
+ });
+} catch (e) {
+ asyncLocalStorage.getStore(); // Returns undefined
+ // The error will be caught here
+}
+```
+
+#### `asyncLocalStorage.exit(callback[, ...args])`
+
+
+
+
+
+Experimental
+
+
+
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Runs a function synchronously outside of a context and returns its
+return value. The store is not accessible within the callback function or
+the asynchronous operations created within the callback. Any `getStore()`
+call done within the callback function will always return `undefined`.
+
+The optional `args` are passed to the callback function.
+
+If the callback function throws an error, the error is thrown by `exit()` too.
+The stacktrace is not impacted by this call and the context is re-entered.
+
+Example:
+
+```js
+// Within a call to run
+try {
+ asyncLocalStorage.getStore(); // Returns the store object or value
+ asyncLocalStorage.exit(() => {
+ asyncLocalStorage.getStore(); // Returns undefined
+ throw new Error();
+ });
+} catch (e) {
+ asyncLocalStorage.getStore(); // Returns the same object or value
+ // The error will be caught here
+}
+```
+
+#### Usage with `async/await`
+
+If, within an async function, only one `await` call is to run within a context,
+the following pattern should be used:
+
+```js
+async function fn() {
+ await asyncLocalStorage.run(new Map(), () => {
+ asyncLocalStorage.getStore().set('key', value);
+ return foo(); // The return value of foo will be awaited
+ });
+}
+```
+
+In this example, the store is only available in the callback function and the
+functions called by `foo`. Outside of `run`, calling `getStore` will return
+`undefined`.
+
+#### Troubleshooting: Context loss
+
+In most cases, `AsyncLocalStorage` works without issues. In rare situations, the
+current store is lost in one of the asynchronous operations.
+
+If your code is callback-based, it is enough to promisify it with
+[`util.promisify()`][] so it starts working with native promises.
+
+If you need to use a callback-based API or your code assumes
+a custom thenable implementation, use the [`AsyncResource`][] class
+to associate the asynchronous operation with the correct execution context.
+Find the function call responsible for the context loss by logging the content
+of `asyncLocalStorage.getStore()` after the calls you suspect are responsible
+for the loss. When the code logs `undefined`, the last callback called is
+probably responsible for the context loss.
+
+### `AsyncResource`
+
+
+
+The class `AsyncResource` is designed to be extended by the embedder's async
+resources. Using this, users can easily trigger the lifetime events of their
+own resources.
+
+The `init` hook will trigger when an `AsyncResource` is instantiated.
+
+The following is an overview of the `AsyncResource` API.
+
+```mjs|cjs
+import { AsyncResource, executionAsyncId } from 'node:async_hooks';
+
+// AsyncResource() is meant to be extended. Instantiating a
+// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
+// async_hook.executionAsyncId() is used.
+const asyncResource = new AsyncResource(
+ type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },
+);
+
+// Run a function in the execution context of the resource. This will
+// * establish the context of the resource
+// * trigger the AsyncHooks before callbacks
+// * call the provided function `fn` with the supplied arguments
+// * trigger the AsyncHooks after callbacks
+// * restore the original execution context
+asyncResource.runInAsyncScope(fn, thisArg, ...args);
+
+// Call AsyncHooks destroy callbacks.
+asyncResource.emitDestroy();
+
+// Return the unique ID assigned to the AsyncResource instance.
+asyncResource.asyncId();
+
+// Return the trigger ID for the AsyncResource instance.
+asyncResource.triggerAsyncId();
+--------------
+const { AsyncResource, executionAsyncId } = require('node:async_hooks');
+
+// AsyncResource() is meant to be extended. Instantiating a
+// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
+// async_hook.executionAsyncId() is used.
+const asyncResource = new AsyncResource(
+ type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },
+);
+
+// Run a function in the execution context of the resource. This will
+// * establish the context of the resource
+// * trigger the AsyncHooks before callbacks
+// * call the provided function `fn` with the supplied arguments
+// * trigger the AsyncHooks after callbacks
+// * restore the original execution context
+asyncResource.runInAsyncScope(fn, thisArg, ...args);
+
+// Call AsyncHooks destroy callbacks.
+asyncResource.emitDestroy();
+
+// Return the unique ID assigned to the AsyncResource instance.
+asyncResource.asyncId();
+
+// Return the trigger ID for the AsyncResource instance.
+asyncResource.triggerAsyncId();
+```
+
+#### `new AsyncResource(type[, options])`
+
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of async event.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `triggerAsyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ID of the execution context that created this
+ async event. **Default:** `executionAsyncId()`.
+ * `requireManualDestroy` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to `true`, disables `emitDestroy`
+ when the object is garbage collected. This usually does not need to be set
+ (even if `emitDestroy` is called manually), unless the resource's `asyncId`
+ is retrieved and the sensitive API's `emitDestroy` is called with it.
+ When set to `false`, the `emitDestroy` call on garbage collection
+ will only take place if there is at least one active `destroy` hook.
+ **Default:** `false`.
+
+Example usage:
+
+```js
+class DBQuery extends AsyncResource {
+ constructor(db) {
+ super('DBQuery');
+ this.db = db;
+ }
+
+ getInfo(query, callback) {
+ this.db.get(query, (err, data) => {
+ this.runInAsyncScope(callback, null, err, data);
+ });
+ }
+
+ close() {
+ this.db = null;
+ this.emitDestroy();
+ }
+}
+```
+
+#### Static method: `AsyncResource.bind(fn[, type[, thisArg]])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to bind to the current execution context.
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) An optional name to associate with the underlying
+ `AsyncResource`.
+* `thisArg` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Binds the given function to the current execution context.
+
+#### `asyncResource.bind(fn[, thisArg])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to bind to the current `AsyncResource`.
+* `thisArg` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+
+Binds the given function to execute to this `AsyncResource`'s scope.
+
+#### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])`
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to call in the execution context of this async
+ resource.
+* `thisArg` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The receiver to be used for the function call.
+* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional arguments to pass to the function.
+
+Call the provided function with the provided arguments in the execution context
+of the async resource. This will establish the context, trigger the AsyncHooks
+before callbacks, call the function, trigger the AsyncHooks after callbacks, and
+then restore the original execution context.
+
+#### `asyncResource.emitDestroy()`
+
+* Returns: [`AsyncResource`](/api/v20/async_hooks#asyncresource) A reference to `asyncResource`.
+
+Call all `destroy` hooks. This should only ever be called once. An error will
+be thrown if it is called more than once. This **must** be manually called. If
+the resource is left to be collected by the GC then the `destroy` hooks will
+never be called.
+
+#### `asyncResource.asyncId()`
+
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The unique `asyncId` assigned to the resource.
+
+#### `asyncResource.triggerAsyncId()`
+
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The same `triggerAsyncId` that is passed to the
+ `AsyncResource` constructor.
+
+
+
+#### Using `AsyncResource` for a `Worker` thread pool
+
+The following example shows how to use the `AsyncResource` class to properly
+provide async tracking for a [`Worker`][] pool. Other resource pools, such as
+database connection pools, can follow a similar model.
+
+Assuming that the task is adding two numbers, using a file named
+`task_processor.js` with the following content:
+
+```mjs|cjs
+import { parentPort } from 'node:worker_threads';
+parentPort.on('message', (task) => {
+ parentPort.postMessage(task.a + task.b);
+});
+--------------
+const { parentPort } = require('node:worker_threads');
+parentPort.on('message', (task) => {
+ parentPort.postMessage(task.a + task.b);
+});
+```
+
+a Worker pool around it could use the following structure:
+
+```mjs|cjs
+import { AsyncResource } from 'node:async_hooks';
+import { EventEmitter } from 'node:events';
+import path from 'node:path';
+import { Worker } from 'node:worker_threads';
+
+const kTaskInfo = Symbol('kTaskInfo');
+const kWorkerFreedEvent = Symbol('kWorkerFreedEvent');
+
+class WorkerPoolTaskInfo extends AsyncResource {
+ constructor(callback) {
+ super('WorkerPoolTaskInfo');
+ this.callback = callback;
+ }
+
+ done(err, result) {
+ this.runInAsyncScope(this.callback, null, err, result);
+ this.emitDestroy(); // `TaskInfo`s are used only once.
+ }
+}
+
+export default class WorkerPool extends EventEmitter {
+ constructor(numThreads) {
+ super();
+ this.numThreads = numThreads;
+ this.workers = [];
+ this.freeWorkers = [];
+ this.tasks = [];
+
+ for (let i = 0; i < numThreads; i++)
+ this.addNewWorker();
+
+ // Any time the kWorkerFreedEvent is emitted, dispatch
+ // the next task pending in the queue, if any.
+ this.on(kWorkerFreedEvent, () => {
+ if (this.tasks.length > 0) {
+ const { task, callback } = this.tasks.shift();
+ this.runTask(task, callback);
+ }
+ });
+ }
+
+ addNewWorker() {
+ const worker = new Worker(new URL('task_processor.js', import.meta.url));
+ worker.on('message', (result) => {
+ // In case of success: Call the callback that was passed to `runTask`,
+ // remove the `TaskInfo` associated with the Worker, and mark it as free
+ // again.
+ worker[kTaskInfo].done(null, result);
+ worker[kTaskInfo] = null;
+ this.freeWorkers.push(worker);
+ this.emit(kWorkerFreedEvent);
+ });
+ worker.on('error', (err) => {
+ // In case of an uncaught exception: Call the callback that was passed to
+ // `runTask` with the error.
+ if (worker[kTaskInfo])
+ worker[kTaskInfo].done(err, null);
+ else
+ this.emit('error', err);
+ // Remove the worker from the list and start a new Worker to replace the
+ // current one.
+ this.workers.splice(this.workers.indexOf(worker), 1);
+ this.addNewWorker();
+ });
+ this.workers.push(worker);
+ this.freeWorkers.push(worker);
+ this.emit(kWorkerFreedEvent);
+ }
+
+ runTask(task, callback) {
+ if (this.freeWorkers.length === 0) {
+ // No free threads, wait until a worker thread becomes free.
+ this.tasks.push({ task, callback });
+ return;
+ }
+
+ const worker = this.freeWorkers.pop();
+ worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);
+ worker.postMessage(task);
+ }
+
+ close() {
+ for (const worker of this.workers) worker.terminate();
+ }
+}
+--------------
+const { AsyncResource } = require('node:async_hooks');
+const { EventEmitter } = require('node:events');
+const path = require('node:path');
+const { Worker } = require('node:worker_threads');
+
+const kTaskInfo = Symbol('kTaskInfo');
+const kWorkerFreedEvent = Symbol('kWorkerFreedEvent');
+
+class WorkerPoolTaskInfo extends AsyncResource {
+ constructor(callback) {
+ super('WorkerPoolTaskInfo');
+ this.callback = callback;
+ }
+
+ done(err, result) {
+ this.runInAsyncScope(this.callback, null, err, result);
+ this.emitDestroy(); // `TaskInfo`s are used only once.
+ }
+}
+
+class WorkerPool extends EventEmitter {
+ constructor(numThreads) {
+ super();
+ this.numThreads = numThreads;
+ this.workers = [];
+ this.freeWorkers = [];
+ this.tasks = [];
+
+ for (let i = 0; i < numThreads; i++)
+ this.addNewWorker();
+
+ // Any time the kWorkerFreedEvent is emitted, dispatch
+ // the next task pending in the queue, if any.
+ this.on(kWorkerFreedEvent, () => {
+ if (this.tasks.length > 0) {
+ const { task, callback } = this.tasks.shift();
+ this.runTask(task, callback);
+ }
+ });
+ }
+
+ addNewWorker() {
+ const worker = new Worker(path.resolve(__dirname, 'task_processor.js'));
+ worker.on('message', (result) => {
+ // In case of success: Call the callback that was passed to `runTask`,
+ // remove the `TaskInfo` associated with the Worker, and mark it as free
+ // again.
+ worker[kTaskInfo].done(null, result);
+ worker[kTaskInfo] = null;
+ this.freeWorkers.push(worker);
+ this.emit(kWorkerFreedEvent);
+ });
+ worker.on('error', (err) => {
+ // In case of an uncaught exception: Call the callback that was passed to
+ // `runTask` with the error.
+ if (worker[kTaskInfo])
+ worker[kTaskInfo].done(err, null);
+ else
+ this.emit('error', err);
+ // Remove the worker from the list and start a new Worker to replace the
+ // current one.
+ this.workers.splice(this.workers.indexOf(worker), 1);
+ this.addNewWorker();
+ });
+ this.workers.push(worker);
+ this.freeWorkers.push(worker);
+ this.emit(kWorkerFreedEvent);
+ }
+
+ runTask(task, callback) {
+ if (this.freeWorkers.length === 0) {
+ // No free threads, wait until a worker thread becomes free.
+ this.tasks.push({ task, callback });
+ return;
+ }
+
+ const worker = this.freeWorkers.pop();
+ worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);
+ worker.postMessage(task);
+ }
+
+ close() {
+ for (const worker of this.workers) worker.terminate();
+ }
+}
+
+module.exports = WorkerPool;
+```
+
+Without the explicit tracking added by the `WorkerPoolTaskInfo` objects,
+it would appear that the callbacks are associated with the individual `Worker`
+objects. However, the creation of the `Worker`s is not associated with the
+creation of the tasks and does not provide information about when tasks
+were scheduled.
+
+This pool could be used as follows:
+
+```mjs|cjs
+import WorkerPool from './worker_pool.js';
+import os from 'node:os';
+
+const pool = new WorkerPool(os.availableParallelism());
+
+let finished = 0;
+for (let i = 0; i < 10; i++) {
+ pool.runTask({ a: 42, b: 100 }, (err, result) => {
+ console.log(i, err, result);
+ if (++finished === 10)
+ pool.close();
+ });
+}
+--------------
+const WorkerPool = require('./worker_pool.js');
+const os = require('node:os');
+
+const pool = new WorkerPool(os.availableParallelism());
+
+let finished = 0;
+for (let i = 0; i < 10; i++) {
+ pool.runTask({ a: 42, b: 100 }, (err, result) => {
+ console.log(i, err, result);
+ if (++finished === 10)
+ pool.close();
+ });
+}
+```
+
+#### Integrating `AsyncResource` with `EventEmitter`
+
+Event listeners triggered by an [`EventEmitter`][] may be run in a different
+execution context than the one that was active when `eventEmitter.on()` was
+called.
+
+The following example shows how to use the `AsyncResource` class to properly
+associate an event listener with the correct execution context. The same
+approach can be applied to a [`Stream`][] or a similar event-driven class.
+
+```mjs|cjs
+import { createServer } from 'node:http';
+import { AsyncResource, executionAsyncId } from 'node:async_hooks';
+
+const server = createServer((req, res) => {
+ req.on('close', AsyncResource.bind(() => {
+ // Execution context is bound to the current outer scope.
+ }));
+ req.on('close', () => {
+ // Execution context is bound to the scope that caused 'close' to emit.
+ });
+ res.end();
+}).listen(3000);
+--------------
+const { createServer } = require('node:http');
+const { AsyncResource, executionAsyncId } = require('node:async_hooks');
+
+const server = createServer((req, res) => {
+ req.on('close', AsyncResource.bind(() => {
+ // Execution context is bound to the current outer scope.
+ }));
+ req.on('close', () => {
+ // Execution context is bound to the scope that caused 'close' to emit.
+ });
+ res.end();
+}).listen(3000);
+```
+
+[`AsyncResource`]: #class-asyncresource
+[`EventEmitter`]: /api/v20/events#class-eventemitter
+[`Stream`]: /api/v20/stream#stream
+[`Worker`]: worker_threads.md#class-worker
+[`util.promisify()`]: /api/v20/util#utilpromisifyoriginal
diff --git a/content/api/v20/async_hooks.en.md b/content/api/v20/async_hooks.en.md
new file mode 100644
index 0000000000..bbd3906502
--- /dev/null
+++ b/content/api/v20/async_hooks.en.md
@@ -0,0 +1,897 @@
+---
+title: 'async_hooks'
+displayTitle: 'Async hooks'
+category: 'api'
+version: 'v20'
+---
+
+
+
+
+
+Experimental. Please migrate away from this API, if you can. We do not recommend using the [`createHook`][], [`AsyncHook`][], and [`executionAsyncResource`][] APIs as they have usability issues, safety risks, and performance implications. Async context tracking use cases are better served by the stable [`AsyncLocalStorage`][] API. If you have a use case for `createHook`, `AsyncHook`, or `executionAsyncResource` beyond the context tracking need solved by [`AsyncLocalStorage`][] or diagnostics data currently provided by [Diagnostics Channel][], please open an issue at describing your use case so we can create a more purpose-focused API.
+
+
+
+
+
+We strongly discourage the use of the `async_hooks` API.
+Other APIs that can cover most of its use cases include:
+
+* [`AsyncLocalStorage`][] tracks async context
+* [`process.getActiveResourcesInfo()`][] tracks active resources
+
+The `node:async_hooks` module provides an API to track asynchronous resources.
+It can be accessed using:
+
+```mjs|cjs
+import async_hooks from 'node:async_hooks';
+--------------
+const async_hooks = require('node:async_hooks');
+```
+
+### Terminology
+
+An asynchronous resource represents an object with an associated callback.
+This callback may be called multiple times, such as the `'connection'`
+event in `net.createServer()`, or just a single time like in `fs.open()`.
+A resource can also be closed before the callback is called. `AsyncHook` does
+not explicitly distinguish between these different cases but will represent them
+as the abstract concept that is a resource.
+
+If [`Worker`][]s are used, each thread has an independent `async_hooks`
+interface, and each thread will use a new set of async IDs.
+
+### Overview
+
+Following is a simple overview of the public API.
+
+```mjs|cjs
+import async_hooks from 'node:async_hooks';
+
+// Return the ID of the current execution context.
+const eid = async_hooks.executionAsyncId();
+
+// Return the ID of the handle responsible for triggering the callback of the
+// current execution scope to call.
+const tid = async_hooks.triggerAsyncId();
+
+// Create a new AsyncHook instance. All of these callbacks are optional.
+const asyncHook =
+ async_hooks.createHook({ init, before, after, destroy, promiseResolve });
+
+// Allow callbacks of this AsyncHook instance to call. This is not an implicit
+// action after running the constructor, and must be explicitly run to begin
+// executing callbacks.
+asyncHook.enable();
+
+// Disable listening for new asynchronous events.
+asyncHook.disable();
+
+//
+// The following are the callbacks that can be passed to createHook().
+//
+
+// init() is called during object construction. The resource may not have
+// completed construction when this callback runs. Therefore, all fields of the
+// resource referenced by "asyncId" may not have been populated.
+function init(asyncId, type, triggerAsyncId, resource) { }
+
+// before() is called just before the resource's callback is called. It can be
+// called 0-N times for handles (such as TCPWrap), and will be called exactly 1
+// time for requests (such as FSReqCallback).
+function before(asyncId) { }
+
+// after() is called just after the resource's callback has finished.
+function after(asyncId) { }
+
+// destroy() is called when the resource is destroyed.
+function destroy(asyncId) { }
+
+// promiseResolve() is called only for promise resources, when the
+// resolve() function passed to the Promise constructor is invoked
+// (either directly or through other means of resolving a promise).
+function promiseResolve(asyncId) { }
+--------------
+const async_hooks = require('node:async_hooks');
+
+// Return the ID of the current execution context.
+const eid = async_hooks.executionAsyncId();
+
+// Return the ID of the handle responsible for triggering the callback of the
+// current execution scope to call.
+const tid = async_hooks.triggerAsyncId();
+
+// Create a new AsyncHook instance. All of these callbacks are optional.
+const asyncHook =
+ async_hooks.createHook({ init, before, after, destroy, promiseResolve });
+
+// Allow callbacks of this AsyncHook instance to call. This is not an implicit
+// action after running the constructor, and must be explicitly run to begin
+// executing callbacks.
+asyncHook.enable();
+
+// Disable listening for new asynchronous events.
+asyncHook.disable();
+
+//
+// The following are the callbacks that can be passed to createHook().
+//
+
+// init() is called during object construction. The resource may not have
+// completed construction when this callback runs. Therefore, all fields of the
+// resource referenced by "asyncId" may not have been populated.
+function init(asyncId, type, triggerAsyncId, resource) { }
+
+// before() is called just before the resource's callback is called. It can be
+// called 0-N times for handles (such as TCPWrap), and will be called exactly 1
+// time for requests (such as FSReqCallback).
+function before(asyncId) { }
+
+// after() is called just after the resource's callback has finished.
+function after(asyncId) { }
+
+// destroy() is called when the resource is destroyed.
+function destroy(asyncId) { }
+
+// promiseResolve() is called only for promise resources, when the
+// resolve() function passed to the Promise constructor is invoked
+// (either directly or through other means of resolving a promise).
+function promiseResolve(asyncId) { }
+```
+
+### `async_hooks.createHook(callbacks)`
+
+
+
+* `callbacks` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The [Hook Callbacks][] to register
+ * `init` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`init` callback][].
+ * `before` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`before` callback][].
+ * `after` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`after` callback][].
+ * `destroy` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`destroy` callback][].
+ * `promiseResolve` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`promiseResolve` callback][].
+* Returns: [`AsyncHook`](/api/v20/async_hooks#async_hookscreatehookcallbacks) Instance used for disabling and enabling hooks
+
+Registers functions to be called for different lifetime events of each async
+operation.
+
+The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the
+respective asynchronous event during a resource's lifetime.
+
+All callbacks are optional. For example, if only resource cleanup needs to
+be tracked, then only the `destroy` callback needs to be passed. The
+specifics of all functions that can be passed to `callbacks` is in the
+[Hook Callbacks][] section.
+
+```mjs|cjs
+import { createHook } from 'node:async_hooks';
+
+const asyncHook = createHook({
+ init(asyncId, type, triggerAsyncId, resource) { },
+ destroy(asyncId) { },
+});
+--------------
+const async_hooks = require('node:async_hooks');
+
+const asyncHook = async_hooks.createHook({
+ init(asyncId, type, triggerAsyncId, resource) { },
+ destroy(asyncId) { },
+});
+```
+
+The callbacks will be inherited via the prototype chain:
+
+```js
+class MyAsyncCallbacks {
+ init(asyncId, type, triggerAsyncId, resource) { }
+ destroy(asyncId) {}
+}
+
+class MyAddedCallbacks extends MyAsyncCallbacks {
+ before(asyncId) { }
+ after(asyncId) { }
+}
+
+const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
+```
+
+Because promises are asynchronous resources whose lifecycle is tracked
+via the async hooks mechanism, the `init()`, `before()`, `after()`, and
+`destroy()` callbacks _must not_ be async functions that return promises.
+
+#### Error handling
+
+If any `AsyncHook` callbacks throw, the application will print the stack trace
+and exit. The exit path does follow that of an uncaught exception, but
+all `'uncaughtException'` listeners are removed, thus forcing the process to
+exit. The `'exit'` callbacks will still be called unless the application is run
+with `--abort-on-uncaught-exception`, in which case a stack trace will be
+printed and the application exits, leaving a core file.
+
+The reason for this error handling behavior is that these callbacks are running
+at potentially volatile points in an object's lifetime, for example during
+class construction and destruction. Because of this, it is deemed necessary to
+bring down the process quickly in order to prevent an unintentional abort in the
+future. This is subject to change in the future if a comprehensive analysis is
+performed to ensure an exception can follow the normal control flow without
+unintentional side effects.
+
+#### Printing in `AsyncHook` callbacks
+
+Because printing to the console is an asynchronous operation, `console.log()`
+will cause `AsyncHook` callbacks to be called. Using `console.log()` or
+similar asynchronous operations inside an `AsyncHook` callback function will
+cause an infinite recursion. An easy solution to this when debugging is to use a
+synchronous logging operation such as `fs.writeFileSync(file, msg, flag)`.
+This will print to the file and will not invoke `AsyncHook` recursively because
+it is synchronous.
+
+```mjs|cjs
+import { writeFileSync } from 'node:fs';
+import { format } from 'node:util';
+
+function debug(...args) {
+ // Use a function like this one when debugging inside an AsyncHook callback
+ writeFileSync('log.out', `${format(...args)}\n`, { flag: 'a' });
+}
+--------------
+const fs = require('node:fs');
+const util = require('node:util');
+
+function debug(...args) {
+ // Use a function like this one when debugging inside an AsyncHook callback
+ fs.writeFileSync('log.out', `${util.format(...args)}\n`, { flag: 'a' });
+}
+```
+
+If an asynchronous operation is needed for logging, it is possible to keep
+track of what caused the asynchronous operation using the information
+provided by `AsyncHook` itself. The logging should then be skipped when
+it was the logging itself that caused the `AsyncHook` callback to be called. By
+doing this, the otherwise infinite recursion is broken.
+
+### `AsyncHook`
+
+The class `AsyncHook` exposes an interface for tracking lifetime events
+of asynchronous operations.
+
+#### `asyncHook.enable()`
+
+* Returns: [`AsyncHook`](/api/v20/async_hooks#async_hookscreatehookcallbacks) A reference to `asyncHook`.
+
+Enable the callbacks for a given `AsyncHook` instance. If no callbacks are
+provided, enabling is a no-op.
+
+The `AsyncHook` instance is disabled by default. If the `AsyncHook` instance
+should be enabled immediately after creation, the following pattern can be used.
+
+```mjs|cjs
+import { createHook } from 'node:async_hooks';
+
+const hook = createHook(callbacks).enable();
+--------------
+const async_hooks = require('node:async_hooks');
+
+const hook = async_hooks.createHook(callbacks).enable();
+```
+
+#### `asyncHook.disable()`
+
+* Returns: [`AsyncHook`](/api/v20/async_hooks#async_hookscreatehookcallbacks) A reference to `asyncHook`.
+
+Disable the callbacks for a given `AsyncHook` instance from the global pool of
+`AsyncHook` callbacks to be executed. Once a hook has been disabled it will not
+be called again until enabled.
+
+For API consistency `disable()` also returns the `AsyncHook` instance.
+
+#### Hook callbacks
+
+Key events in the lifetime of asynchronous events have been categorized into
+four areas: instantiation, before/after the callback is called, and when the
+instance is destroyed.
+
+##### `init(asyncId, type, triggerAsyncId, resource)`
+
+* `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A unique ID for the async resource.
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of the async resource.
+* `triggerAsyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The unique ID of the async resource in whose
+ execution context this async resource was created.
+* `resource` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Reference to the resource representing the async
+ operation, needs to be released during _destroy_.
+
+Called when a class is constructed that has the _possibility_ to emit an
+asynchronous event. This _does not_ mean the instance must call
+`before`/`after` before `destroy` is called, only that the possibility
+exists.
+
+This behavior can be observed by doing something like opening a resource then
+closing it before the resource can be used. The following snippet demonstrates
+this.
+
+```mjs|cjs
+import { createServer } from 'node:net';
+
+createServer().listen(function() { this.close(); });
+// OR
+clearTimeout(setTimeout(() => {}, 10));
+--------------
+require('node:net').createServer().listen(function() { this.close(); });
+// OR
+clearTimeout(setTimeout(() => {}, 10));
+```
+
+Every new resource is assigned an ID that is unique within the scope of the
+current Node.js instance.
+
+###### `type`
+
+The `type` is a string identifying the type of resource that caused
+`init` to be called. Generally, it will correspond to the name of the
+resource's constructor.
+
+The `type` of resources created by Node.js itself can change in any Node.js
+release. Valid values include `TLSWRAP`,
+`TCPWRAP`, `TCPSERVERWRAP`, `GETADDRINFOREQWRAP`, `FSREQCALLBACK`,
+`Microtask`, and `Timeout`. Inspect the source code of the Node.js version used
+to get the full list.
+
+Furthermore users of [`AsyncResource`][] create async resources independent
+of Node.js itself.
+
+There is also the `PROMISE` resource type, which is used to track `Promise`
+instances and asynchronous work scheduled by them.
+
+Users are able to define their own `type` when using the public embedder API.
+
+It is possible to have type name collisions. Embedders are encouraged to use
+unique prefixes, such as the npm package name, to prevent collisions when
+listening to the hooks.
+
+###### `triggerAsyncId`
+
+`triggerAsyncId` is the `asyncId` of the resource that caused (or "triggered")
+the new resource to initialize and that caused `init` to call. This is different
+from `async_hooks.executionAsyncId()` that only shows _when_ a resource was
+created, while `triggerAsyncId` shows _why_ a resource was created.
+
+The following is a simple demonstration of `triggerAsyncId`:
+
+```mjs|cjs
+import { createHook, executionAsyncId } from 'node:async_hooks';
+import { stdout } from 'node:process';
+import net from 'node:net';
+import fs from 'node:fs';
+
+createHook({
+ init(asyncId, type, triggerAsyncId) {
+ const eid = executionAsyncId();
+ fs.writeSync(
+ stdout.fd,
+ `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
+ },
+}).enable();
+
+net.createServer((conn) => {}).listen(8080);
+--------------
+const { createHook, executionAsyncId } = require('node:async_hooks');
+const { stdout } = require('node:process');
+const net = require('node:net');
+const fs = require('node:fs');
+
+createHook({
+ init(asyncId, type, triggerAsyncId) {
+ const eid = executionAsyncId();
+ fs.writeSync(
+ stdout.fd,
+ `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
+ },
+}).enable();
+
+net.createServer((conn) => {}).listen(8080);
+```
+
+Output when hitting the server with `nc localhost 8080`:
+
+```console
+TCPSERVERWRAP(5): trigger: 1 execution: 1
+TCPWRAP(7): trigger: 5 execution: 0
+```
+
+The `TCPSERVERWRAP` is the server which receives the connections.
+
+The `TCPWRAP` is the new connection from the client. When a new
+connection is made, the `TCPWrap` instance is immediately constructed. This
+happens outside of any JavaScript stack. (An `executionAsyncId()` of `0` means
+that it is being executed from C++ with no JavaScript stack above it.) With only
+that information, it would be impossible to link resources together in
+terms of what caused them to be created, so `triggerAsyncId` is given the task
+of propagating what resource is responsible for the new resource's existence.
+
+###### `resource`
+
+`resource` is an object that represents the actual async resource that has
+been initialized. The API to access the object may be specified by the
+creator of the resource. Resources created by Node.js itself are internal
+and may change at any time. Therefore no API is specified for these.
+
+In some cases the resource object is reused for performance reasons, it is
+thus not safe to use it as a key in a `WeakMap` or add properties to it.
+
+###### Asynchronous context example
+
+The context tracking use case is covered by the stable API [`AsyncLocalStorage`][].
+This example only illustrates async hooks operation but [`AsyncLocalStorage`][]
+fits better to this use case.
+
+The following is an example with additional information about the calls to
+`init` between the `before` and `after` calls, specifically what the
+callback to `listen()` will look like. The output formatting is slightly more
+elaborate to make calling context easier to see.
+
+```mjs|cjs
+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);
+});
+--------------
+const async_hooks = require('node:async_hooks');
+const fs = require('node:fs');
+const net = require('node:net');
+const { fd } = process.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);
+});
+```
+
+Output from only starting the server:
+
+```console
+TCPSERVERWRAP(5): trigger: 1 execution: 1
+TickObject(6): trigger: 5 execution: 1
+before: 6
+ Timeout(7): trigger: 6 execution: 6
+after: 6
+destroy: 6
+before: 7
+>>> 7
+ TickObject(8): trigger: 7 execution: 7
+after: 7
+before: 8
+after: 8
+```
+
+As illustrated in the example, `executionAsyncId()` and `execution` each specify
+the value of the current execution context; which is delineated by calls to
+`before` and `after`.
+
+Only using `execution` to graph resource allocation results in the following:
+
+```console
+ root(1)
+ ^
+ |
+TickObject(6)
+ ^
+ |
+ Timeout(7)
+```
+
+The `TCPSERVERWRAP` is not part of this graph, even though it was the reason for
+`console.log()` being called. This is because binding to a port without a host
+name is a _synchronous_ operation, but to maintain a completely asynchronous
+API the user's callback is placed in a `process.nextTick()`. Which is why
+`TickObject` is present in the output and is a 'parent' for `.listen()`
+callback.
+
+The graph only shows _when_ a resource was created, not _why_, so to track
+the _why_ use `triggerAsyncId`. Which can be represented with the following
+graph:
+
+```console
+ bootstrap(1)
+ |
+ ˅
+TCPSERVERWRAP(5)
+ |
+ ˅
+ TickObject(6)
+ |
+ ˅
+ Timeout(7)
+```
+
+##### `before(asyncId)`
+
+* `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+When an asynchronous operation is initiated (such as a TCP server receiving a
+new connection) or completes (such as writing data to disk) a callback is
+called to notify the user. The `before` callback is called just before said
+callback is executed. `asyncId` is the unique identifier assigned to the
+resource about to execute the callback.
+
+The `before` callback will be called 0 to N times. The `before` callback
+will typically be called 0 times if the asynchronous operation was cancelled
+or, for example, if no connections are received by a TCP server. Persistent
+asynchronous resources like a TCP server will typically call the `before`
+callback multiple times, while other operations like `fs.open()` will call
+it only once.
+
+##### `after(asyncId)`
+
+* `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Called immediately after the callback specified in `before` is completed.
+
+If an uncaught exception occurs during execution of the callback, then `after`
+will run _after_ the `'uncaughtException'` event is emitted or a `domain`'s
+handler runs.
+
+##### `destroy(asyncId)`
+
+* `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Called after the resource corresponding to `asyncId` is destroyed. It is also
+called asynchronously from the embedder API `emitDestroy()`.
+
+Some resources depend on garbage collection for cleanup, so if a reference is
+made to the `resource` object passed to `init` it is possible that `destroy`
+will never be called, causing a memory leak in the application. If the resource
+does not depend on garbage collection, then this will not be an issue.
+
+Using the destroy hook results in additional overhead because it enables
+tracking of `Promise` instances via the garbage collector.
+
+##### `promiseResolve(asyncId)`
+
+
+
+* `asyncId` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Called when the `resolve` function passed to the `Promise` constructor is
+invoked (either directly or through other means of resolving a promise).
+
+`resolve()` does not do any observable synchronous work.
+
+The `Promise` is not necessarily fulfilled or rejected at this point if the
+`Promise` was resolved by assuming the state of another `Promise`.
+
+```js
+new Promise((resolve) => resolve(true)).then((a) => {});
+```
+
+calls the following callbacks:
+
+```text
+init for PROMISE with id 5, trigger id: 1
+ promise resolve 5 # corresponds to resolve(true)
+init for PROMISE with id 6, trigger id: 5 # the Promise returned by then()
+ before 6 # the then() callback is entered
+ promise resolve 6 # the then() callback resolves the promise by returning
+ after 6
+```
+
+#### `async_hooks.executionAsyncResource()`
+
+
+
+* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The resource representing the current execution.
+ Useful to store data within the resource.
+
+Resource objects returned by `executionAsyncResource()` are most often internal
+Node.js handle objects with undocumented APIs. Using any functions or properties
+on the object is likely to crash your application and should be avoided.
+
+Using `executionAsyncResource()` in the top-level execution context will
+return an empty object as there is no handle or request object to use,
+but having an object representing the top-level can be helpful.
+
+```mjs|cjs
+import { open } from 'node:fs';
+import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
+
+console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
+open(new URL(import.meta.url), 'r', (err, fd) => {
+ console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
+});
+--------------
+const { open } = require('node:fs');
+const { executionAsyncId, executionAsyncResource } = require('node:async_hooks');
+
+console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
+open(__filename, 'r', (err, fd) => {
+ console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
+});
+```
+
+This can be used to implement continuation local storage without the
+use of a tracking `Map` to store the metadata:
+
+```mjs|cjs
+import { createServer } from 'node:http';
+import {
+ executionAsyncId,
+ executionAsyncResource,
+ createHook,
+} from 'async_hooks';
+const sym = Symbol('state'); // Private symbol to avoid pollution
+
+createHook({
+ init(asyncId, type, triggerAsyncId, resource) {
+ const cr = executionAsyncResource();
+ if (cr) {
+ resource[sym] = cr[sym];
+ }
+ },
+}).enable();
+
+const server = createServer((req, res) => {
+ executionAsyncResource()[sym] = { state: req.url };
+ setTimeout(function() {
+ res.end(JSON.stringify(executionAsyncResource()[sym]));
+ }, 100);
+}).listen(3000);
+--------------
+const { createServer } = require('node:http');
+const {
+ executionAsyncId,
+ executionAsyncResource,
+ createHook,
+} = require('node:async_hooks');
+const sym = Symbol('state'); // Private symbol to avoid pollution
+
+createHook({
+ init(asyncId, type, triggerAsyncId, resource) {
+ const cr = executionAsyncResource();
+ if (cr) {
+ resource[sym] = cr[sym];
+ }
+ },
+}).enable();
+
+const server = createServer((req, res) => {
+ executionAsyncResource()[sym] = { state: req.url };
+ setTimeout(function() {
+ res.end(JSON.stringify(executionAsyncResource()[sym]));
+ }, 100);
+}).listen(3000);
+```
+
+#### `async_hooks.executionAsyncId()`
+
+
+
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `asyncId` of the current execution context. Useful to
+ track when something calls.
+
+```mjs|cjs
+import { executionAsyncId } from 'node:async_hooks';
+import fs from 'node:fs';
+
+console.log(executionAsyncId()); // 1 - bootstrap
+fs.open(path, 'r', (err, fd) => {
+ console.log(executionAsyncId()); // 6 - open()
+});
+--------------
+const async_hooks = require('node:async_hooks');
+const fs = require('node:fs');
+
+console.log(async_hooks.executionAsyncId()); // 1 - bootstrap
+fs.open(path, 'r', (err, fd) => {
+ console.log(async_hooks.executionAsyncId()); // 6 - open()
+});
+```
+
+The ID returned from `executionAsyncId()` is related to execution timing, not
+causality (which is covered by `triggerAsyncId()`):
+
+```js
+const server = net.createServer((conn) => {
+ // Returns the ID of the server, not of the new connection, because the
+ // callback runs in the execution scope of the server's MakeCallback().
+ async_hooks.executionAsyncId();
+
+}).listen(port, () => {
+ // Returns the ID of a TickObject (process.nextTick()) because all
+ // callbacks passed to .listen() are wrapped in a nextTick().
+ async_hooks.executionAsyncId();
+});
+```
+
+Promise contexts may not get precise `executionAsyncIds` by default.
+See the section on [promise execution tracking][].
+
+#### `async_hooks.triggerAsyncId()`
+
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ID of the resource responsible for calling the callback
+ that is currently being executed.
+
+```js
+const server = net.createServer((conn) => {
+ // The resource that caused (or triggered) this callback to be called
+ // was that of the new connection. Thus the return value of triggerAsyncId()
+ // is the asyncId of "conn".
+ async_hooks.triggerAsyncId();
+
+}).listen(port, () => {
+ // Even though all callbacks passed to .listen() are wrapped in a nextTick()
+ // the callback itself exists because the call to the server's .listen()
+ // was made. So the return value would be the ID of the server.
+ async_hooks.triggerAsyncId();
+});
+```
+
+Promise contexts may not get valid `triggerAsyncId`s by default. See
+the section on [promise execution tracking][].
+
+#### `async_hooks.asyncWrapProviders`
+
+
+
+* Returns: A map of provider types to the corresponding numeric id.
+ This map contains all the event types that might be emitted by the `async_hooks.init()` event.
+
+This feature suppresses the deprecated usage of `process.binding('async_wrap').Providers`.
+See: [DEP0111][]
+
+### Promise execution tracking
+
+By default, promise executions are not assigned `asyncId`s due to the relatively
+expensive nature of the [promise introspection API][PromiseHooks] provided by
+V8. This means that programs using promises or `async`/`await` will not get
+correct execution and trigger ids for promise callback contexts by default.
+
+```mjs|cjs
+import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
+
+Promise.resolve(1729).then(() => {
+ console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
+});
+// produces:
+// eid 1 tid 0
+--------------
+const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');
+
+Promise.resolve(1729).then(() => {
+ console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
+});
+// produces:
+// eid 1 tid 0
+```
+
+Observe that the `then()` callback claims to have executed in the context of the
+outer scope even though there was an asynchronous hop involved. Also,
+the `triggerAsyncId` value is `0`, which means that we are missing context about
+the resource that caused (triggered) the `then()` callback to be executed.
+
+Installing async hooks via `async_hooks.createHook` enables promise execution
+tracking:
+
+```mjs|cjs
+import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';
+createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
+Promise.resolve(1729).then(() => {
+ console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
+});
+// produces:
+// eid 7 tid 6
+--------------
+const { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');
+
+createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
+Promise.resolve(1729).then(() => {
+ console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
+});
+// produces:
+// eid 7 tid 6
+```
+
+In this example, adding any actual hook function enabled the tracking of
+promises. There are two promises in the example above; the promise created by
+`Promise.resolve()` and the promise returned by the call to `then()`. In the
+example above, the first promise got the `asyncId` `6` and the latter got
+`asyncId` `7`. During the execution of the `then()` callback, we are executing
+in the context of promise with `asyncId` `7`. This promise was triggered by
+async resource `6`.
+
+Another subtlety with promises is that `before` and `after` callbacks are run
+only on chained promises. That means promises not created by `then()`/`catch()`
+will not have the `before` and `after` callbacks fired on them. For more details
+see the details of the V8 [PromiseHooks][] API.
+
+### JavaScript embedder API
+
+Library developers that handle their own asynchronous resources performing tasks
+like I/O, connection pooling, or managing callback queues may use the
+`AsyncResource` JavaScript API so that all the appropriate callbacks are called.
+
+#### `AsyncResource`
+
+The documentation for this class has moved [`AsyncResource`][].
+
+### `AsyncLocalStorage`
+
+The documentation for this class has moved [`AsyncLocalStorage`][].
+
+[DEP0111]: /api/v20/deprecations#dep0111-processbinding
+[Diagnostics Channel]: diagnostics_channel.md
+[Hook Callbacks]: #hook-callbacks
+[PromiseHooks]: https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit
+[`AsyncHook`]: #class-asynchook
+[`AsyncLocalStorage`]: async_context.md#class-asynclocalstorage
+[`AsyncResource`]: async_context.md#class-asyncresource
+[`Worker`]: worker_threads.md#class-worker
+[`after` callback]: #afterasyncid
+[`before` callback]: #beforeasyncid
+[`createHook`]: #async_hookscreatehookcallbacks
+[`destroy` callback]: #destroyasyncid
+[`executionAsyncResource`]: #async_hooksexecutionasyncresource
+[`init` callback]: #initasyncid-type-triggerasyncid-resource
+[`process.getActiveResourcesInfo()`]: /api/v20/process#processgetactiveresourcesinfo
+[`promiseResolve` callback]: #promiseresolveasyncid
+[promise execution tracking]: #promise-execution-tracking
diff --git a/content/api/v20/buffer.en.md b/content/api/v20/buffer.en.md
new file mode 100644
index 0000000000..4f39d651a7
--- /dev/null
+++ b/content/api/v20/buffer.en.md
@@ -0,0 +1,4621 @@
+---
+title: 'buffer'
+displayTitle: 'Buffer'
+category: 'api'
+version: 'v20'
+---
+
+
+
+
+
+Stable
+
+
+
+
+
+`Buffer` objects are used to represent a fixed-length sequence of bytes. Many
+Node.js APIs support `Buffer`s.
+
+The `Buffer` class is a subclass of JavaScript's [`Uint8Array`][] class and
+extends it with methods that cover additional use cases. Node.js APIs accept
+plain [`Uint8Array`][]s wherever `Buffer`s are supported as well.
+
+While the `Buffer` class is available within the global scope, it is still
+recommended to explicitly reference it via an import or require statement.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Creates a zero-filled Buffer of length 10.
+const buf1 = Buffer.alloc(10);
+
+// Creates a Buffer of length 10,
+// filled with bytes which all have the value `1`.
+const buf2 = Buffer.alloc(10, 1);
+
+// Creates an uninitialized buffer of length 10.
+// This is faster than calling Buffer.alloc() but the returned
+// Buffer instance might contain old data that needs to be
+// overwritten using fill(), write(), or other functions that fill the Buffer's
+// contents.
+const buf3 = Buffer.allocUnsafe(10);
+
+// Creates a Buffer containing the bytes [1, 2, 3].
+const buf4 = Buffer.from([1, 2, 3]);
+
+// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
+// are all truncated using `(value & 255)` to fit into the range 0–255.
+const buf5 = Buffer.from([257, 257.5, -255, '1']);
+
+// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
+// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
+// [116, 195, 169, 115, 116] (in decimal notation)
+const buf6 = Buffer.from('tést');
+
+// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
+const buf7 = Buffer.from('tést', 'latin1');
+--------------
+const { Buffer } = require('node:buffer');
+
+// Creates a zero-filled Buffer of length 10.
+const buf1 = Buffer.alloc(10);
+
+// Creates a Buffer of length 10,
+// filled with bytes which all have the value `1`.
+const buf2 = Buffer.alloc(10, 1);
+
+// Creates an uninitialized buffer of length 10.
+// This is faster than calling Buffer.alloc() but the returned
+// Buffer instance might contain old data that needs to be
+// overwritten using fill(), write(), or other functions that fill the Buffer's
+// contents.
+const buf3 = Buffer.allocUnsafe(10);
+
+// Creates a Buffer containing the bytes [1, 2, 3].
+const buf4 = Buffer.from([1, 2, 3]);
+
+// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
+// are all truncated using `(value & 255)` to fit into the range 0–255.
+const buf5 = Buffer.from([257, 257.5, -255, '1']);
+
+// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
+// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
+// [116, 195, 169, 115, 116] (in decimal notation)
+const buf6 = Buffer.from('tést');
+
+// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
+const buf7 = Buffer.from('tést', 'latin1');
+```
+
+### Buffers and character encodings
+
+
+
+When converting between `Buffer`s and strings, a character encoding may be
+specified. If no character encoding is specified, UTF-8 will be used as the
+default.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('hello world', 'utf8');
+
+console.log(buf.toString('hex'));
+// Prints: 68656c6c6f20776f726c64
+console.log(buf.toString('base64'));
+// Prints: aGVsbG8gd29ybGQ=
+
+console.log(Buffer.from('fhqwhgads', 'utf8'));
+// Prints:
+console.log(Buffer.from('fhqwhgads', 'utf16le'));
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('hello world', 'utf8');
+
+console.log(buf.toString('hex'));
+// Prints: 68656c6c6f20776f726c64
+console.log(buf.toString('base64'));
+// Prints: aGVsbG8gd29ybGQ=
+
+console.log(Buffer.from('fhqwhgads', 'utf8'));
+// Prints:
+console.log(Buffer.from('fhqwhgads', 'utf16le'));
+// Prints:
+```
+
+Node.js buffers accept all case variations of encoding strings that they
+receive. For example, UTF-8 can be specified as `'utf8'`, `'UTF8'`, or `'uTf8'`.
+
+The character encodings currently supported by Node.js are the following:
+
+* `'utf8'` (alias: `'utf-8'`): Multi-byte encoded Unicode characters. Many web
+ pages and other document formats use [UTF-8][]. This is the default character
+ encoding. When decoding a `Buffer` into a string that does not exclusively
+ contain valid UTF-8 data, the Unicode replacement character `U+FFFD` � will be
+ used to represent those errors.
+
+* `'utf16le'` (alias: `'utf-16le'`): Multi-byte encoded Unicode characters.
+ Unlike `'utf8'`, each character in the string will be encoded using either 2
+ or 4 bytes. Node.js only supports the [little-endian][endianness] variant of
+ [UTF-16][].
+
+* `'latin1'`: Latin-1 stands for [ISO-8859-1][]. This character encoding only
+ supports the Unicode characters from `U+0000` to `U+00FF`. Each character is
+ encoded using a single byte. Characters that do not fit into that range are
+ truncated and will be mapped to characters in that range.
+
+Converting a `Buffer` into a string using one of the above is referred to as
+decoding, and converting a string into a `Buffer` is referred to as encoding.
+
+Node.js also supports the following binary-to-text encodings. For
+binary-to-text encodings, the naming convention is reversed: Converting a
+`Buffer` into a string is typically referred to as encoding, and converting a
+string into a `Buffer` as decoding.
+
+* `'base64'`: [Base64][] encoding. When creating a `Buffer` from a string,
+ this encoding will also correctly accept "URL and Filename Safe Alphabet" as
+ specified in [RFC 4648, Section 5][]. Whitespace characters such as spaces,
+ tabs, and new lines contained within the base64-encoded string are ignored.
+
+* `'base64url'`: [base64url][] encoding as specified in
+ [RFC 4648, Section 5][]. When creating a `Buffer` from a string, this
+ encoding will also correctly accept regular base64-encoded strings. When
+ encoding a `Buffer` to a string, this encoding will omit padding.
+
+* `'hex'`: Encode each byte as two hexadecimal characters. Data truncation
+ may occur when decoding strings that do not exclusively consist of an even
+ number of hexadecimal characters. See below for an example.
+
+The following legacy character encodings are also supported:
+
+* `'ascii'`: For 7-bit [ASCII][] data only. When encoding a string into a
+ `Buffer`, this is equivalent to using `'latin1'`. When decoding a `Buffer`
+ into a string, using this encoding will additionally unset the highest bit of
+ each byte before decoding as `'latin1'`.
+ Generally, there should be no reason to use this encoding, as `'utf8'`
+ (or, if the data is known to always be ASCII-only, `'latin1'`) will be a
+ better choice when encoding or decoding ASCII-only text. It is only provided
+ for legacy compatibility.
+
+* `'binary'`: Alias for `'latin1'`.
+ The name of this encoding can be very misleading, as all of the
+ encodings listed here convert between strings and binary data. For converting
+ between strings and `Buffer`s, typically `'utf8'` is the right choice.
+
+* `'ucs2'`, `'ucs-2'`: Aliases of `'utf16le'`. UCS-2 used to refer to a variant
+ of UTF-16 that did not support characters that had code points larger than
+ U+FFFF. In Node.js, these code points are always supported.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+Buffer.from('1ag123', 'hex');
+// Prints , data truncated when first non-hexadecimal value
+// ('g') encountered.
+
+Buffer.from('1a7', 'hex');
+// Prints , data truncated when data ends in single digit ('7').
+
+Buffer.from('1634', 'hex');
+// Prints , all data represented.
+--------------
+const { Buffer } = require('node:buffer');
+
+Buffer.from('1ag123', 'hex');
+// Prints , data truncated when first non-hexadecimal value
+// ('g') encountered.
+
+Buffer.from('1a7', 'hex');
+// Prints , data truncated when data ends in single digit ('7').
+
+Buffer.from('1634', 'hex');
+// Prints , all data represented.
+```
+
+Modern Web browsers follow the [WHATWG Encoding Standard][] which aliases
+both `'latin1'` and `'ISO-8859-1'` to `'win-1252'`. This means that while doing
+something like `http.get()`, if the returned charset is one of those listed in
+the WHATWG specification it is possible that the server actually returned
+`'win-1252'`-encoded data, and using `'latin1'` encoding may incorrectly decode
+the characters.
+
+### Buffers and TypedArrays
+
+
+
+`Buffer` instances are also JavaScript [`Uint8Array`][] and [`TypedArray`][]
+instances. All [`TypedArray`][] methods are available on `Buffer`s. There are,
+however, subtle incompatibilities between the `Buffer` API and the
+[`TypedArray`][] API.
+
+In particular:
+
+* While [`TypedArray.prototype.slice()`][] creates a copy of part of the `TypedArray`,
+ [`Buffer.prototype.slice()`][`buf.slice()`] creates a view over the existing `Buffer`
+ without copying. This behavior can be surprising, and only exists for legacy
+ compatibility. [`TypedArray.prototype.subarray()`][] can be used to achieve
+ the behavior of [`Buffer.prototype.slice()`][`buf.slice()`] on both `Buffer`s
+ and other `TypedArray`s and should be preferred.
+* [`buf.toString()`][] is incompatible with its `TypedArray` equivalent.
+* A number of methods, e.g. [`buf.indexOf()`][], support additional arguments.
+
+There are two ways to create new [`TypedArray`][] instances from a `Buffer`:
+
+* Passing a `Buffer` to a [`TypedArray`][] constructor will copy the `Buffer`s
+ contents, interpreted as an array of integers, and not as a byte sequence
+ of the target type.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4]);
+const uint32array = new Uint32Array(buf);
+
+console.log(uint32array);
+
+// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3, 4]);
+const uint32array = new Uint32Array(buf);
+
+console.log(uint32array);
+
+// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]
+```
+
+* Passing the `Buffer`s underlying [`ArrayBuffer`][] will create a
+ [`TypedArray`][] that shares its memory with the `Buffer`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('hello', 'utf16le');
+const uint16array = new Uint16Array(
+ buf.buffer,
+ buf.byteOffset,
+ buf.length / Uint16Array.BYTES_PER_ELEMENT);
+
+console.log(uint16array);
+
+// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('hello', 'utf16le');
+const uint16array = new Uint16Array(
+ buf.buffer,
+ buf.byteOffset,
+ buf.length / Uint16Array.BYTES_PER_ELEMENT);
+
+console.log(uint16array);
+
+// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
+```
+
+It is possible to create a new `Buffer` that shares the same allocated
+memory as a [`TypedArray`][] instance by using the `TypedArray` object's
+`.buffer` property in the same way. [`Buffer.from()`][`Buffer.from(arrayBuf)`]
+behaves like `new Uint8Array()` in this context.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const arr = new Uint16Array(2);
+
+arr[0] = 5000;
+arr[1] = 4000;
+
+// Copies the contents of `arr`.
+const buf1 = Buffer.from(arr);
+
+// Shares memory with `arr`.
+const buf2 = Buffer.from(arr.buffer);
+
+console.log(buf1);
+// Prints:
+console.log(buf2);
+// Prints:
+
+arr[1] = 6000;
+
+console.log(buf1);
+// Prints:
+console.log(buf2);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const arr = new Uint16Array(2);
+
+arr[0] = 5000;
+arr[1] = 4000;
+
+// Copies the contents of `arr`.
+const buf1 = Buffer.from(arr);
+
+// Shares memory with `arr`.
+const buf2 = Buffer.from(arr.buffer);
+
+console.log(buf1);
+// Prints:
+console.log(buf2);
+// Prints:
+
+arr[1] = 6000;
+
+console.log(buf1);
+// Prints:
+console.log(buf2);
+// Prints:
+```
+
+When creating a `Buffer` using a [`TypedArray`][]'s `.buffer`, it is
+possible to use only a portion of the underlying [`ArrayBuffer`][] by passing in
+`byteOffset` and `length` parameters.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const arr = new Uint16Array(20);
+const buf = Buffer.from(arr.buffer, 0, 16);
+
+console.log(buf.length);
+// Prints: 16
+--------------
+const { Buffer } = require('node:buffer');
+
+const arr = new Uint16Array(20);
+const buf = Buffer.from(arr.buffer, 0, 16);
+
+console.log(buf.length);
+// Prints: 16
+```
+
+The `Buffer.from()` and [`TypedArray.from()`][] have different signatures and
+implementations. Specifically, the [`TypedArray`][] variants accept a second
+argument that is a mapping function that is invoked on every element of the
+typed array:
+
+* `TypedArray.from(source[, mapFn[, thisArg]])`
+
+The `Buffer.from()` method, however, does not support the use of a mapping
+function:
+
+* [`Buffer.from(array)`][]
+* [`Buffer.from(buffer)`][]
+* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
+* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`]
+
+### Buffers and iteration
+
+`Buffer` instances can be iterated over using `for..of` syntax:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3]);
+
+for (const b of buf) {
+ console.log(b);
+}
+// Prints:
+// 1
+// 2
+// 3
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3]);
+
+for (const b of buf) {
+ console.log(b);
+}
+// Prints:
+// 1
+// 2
+// 3
+```
+
+Additionally, the [`buf.values()`][], [`buf.keys()`][], and
+[`buf.entries()`][] methods can be used to create iterators.
+
+### `Blob`
+
+
+
+A [`Blob`][] encapsulates immutable, raw data that can be safely shared across
+multiple worker threads.
+
+#### `new buffer.Blob([sources[, options]])`
+
+
+
+* `sources` string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[] An
+ array of string, [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView), or [`Blob`](/api/v20/buffer#blob) objects,
+ or any mix of such objects, that will be stored within the `Blob`.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `endings` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) One of either `'transparent'` or `'native'`. When set
+ to `'native'`, line endings in string source parts will be converted to
+ the platform native line-ending as specified by `require('node:os').EOL`.
+ * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The Blob content-type. The intent is for `type` to convey
+ the MIME media type of the data, however no validation of the type format
+ is performed.
+
+Creates a new `Blob` object containing a concatenation of the given sources.
+
+[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView), and [`Buffer`](/api/v20/buffer#buffer) sources are copied into
+the 'Blob' and can therefore be safely modified after the 'Blob' is created.
+
+String sources are encoded as UTF-8 byte sequences and copied into the Blob.
+Unmatched surrogate pairs within each string part will be replaced by Unicode
+U+FFFD replacement characters.
+
+#### `blob.arrayBuffer()`
+
+
+
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+
+Returns a promise that fulfills with an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of
+the `Blob` data.
+
+#### `blob.size`
+
+
+
+The total size of the `Blob` in bytes.
+
+#### `blob.slice([start[, end[, type]]])`
+
+
+
+* `start` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The starting index.
+* `end` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ending index.
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The content-type for the new `Blob`
+
+Creates and returns a new `Blob` containing a subset of this `Blob` objects
+data. The original `Blob` is not altered.
+
+#### `blob.stream()`
+
+
+
+* Returns: [`ReadableStream`](/api/v20/webstreams#readablestream)
+
+Returns a new `ReadableStream` that allows the content of the `Blob` to be read.
+
+#### `blob.text()`
+
+
+
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+
+Returns a promise that fulfills with the contents of the `Blob` decoded as a
+UTF-8 string.
+
+#### `blob.type`
+
+
+
+* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+The content-type of the `Blob`.
+
+#### `Blob` objects and `MessageChannel`
+
+Once a [`Blob`](/api/v20/buffer#blob) object is created, it can be sent via `MessagePort` to multiple
+destinations without transferring or immediately copying the data. The data
+contained by the `Blob` is copied only when the `arrayBuffer()` or `text()`
+methods are called.
+
+```mjs|cjs
+import { Blob } from 'node:buffer';
+import { setTimeout as delay } from 'node:timers/promises';
+
+const blob = new Blob(['hello there']);
+
+const mc1 = new MessageChannel();
+const mc2 = new MessageChannel();
+
+mc1.port1.onmessage = async ({ data }) => {
+ console.log(await data.arrayBuffer());
+ mc1.port1.close();
+};
+
+mc2.port1.onmessage = async ({ data }) => {
+ await delay(1000);
+ console.log(await data.arrayBuffer());
+ mc2.port1.close();
+};
+
+mc1.port2.postMessage(blob);
+mc2.port2.postMessage(blob);
+
+// The Blob is still usable after posting.
+blob.text().then(console.log);
+--------------
+const { Blob } = require('node:buffer');
+const { setTimeout: delay } = require('node:timers/promises');
+
+const blob = new Blob(['hello there']);
+
+const mc1 = new MessageChannel();
+const mc2 = new MessageChannel();
+
+mc1.port1.onmessage = async ({ data }) => {
+ console.log(await data.arrayBuffer());
+ mc1.port1.close();
+};
+
+mc2.port1.onmessage = async ({ data }) => {
+ await delay(1000);
+ console.log(await data.arrayBuffer());
+ mc2.port1.close();
+};
+
+mc1.port2.postMessage(blob);
+mc2.port2.postMessage(blob);
+
+// The Blob is still usable after posting.
+blob.text().then(console.log);
+```
+
+### `Buffer`
+
+The `Buffer` class is a global type for dealing with binary data directly.
+It can be constructed in a variety of ways.
+
+#### Static method: `Buffer.alloc(size[, fill[, encoding]])`
+
+
+
+* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`.
+* `fill` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A value to pre-fill the new `Buffer`
+ with. **Default:** `0`.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `fill` is a string, this is its encoding.
+ **Default:** `'utf8'`.
+
+Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
+`Buffer` will be zero-filled.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(5);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.alloc(5);
+
+console.log(buf);
+// Prints:
+```
+
+If `size` is larger than
+[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_OUT_OF_RANGE`][]
+is thrown.
+
+If `fill` is specified, the allocated `Buffer` will be initialized by calling
+[`buf.fill(fill)`][`buf.fill()`].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(5, 'a');
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.alloc(5, 'a');
+
+console.log(buf);
+// Prints:
+```
+
+If both `fill` and `encoding` are specified, the allocated `Buffer` will be
+initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
+
+console.log(buf);
+// Prints:
+```
+
+Calling [`Buffer.alloc()`][] can be measurably slower than the alternative
+[`Buffer.allocUnsafe()`][] but ensures that the newly created `Buffer` instance
+contents will never contain sensitive data from previous allocations, including
+data that might not have been allocated for `Buffer`s.
+
+A `TypeError` will be thrown if `size` is not a number.
+
+#### Static method: `Buffer.allocUnsafe(size)`
+
+
+
+* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`.
+
+Allocates a new `Buffer` of `size` bytes. If `size` is larger than
+[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_OUT_OF_RANGE`][]
+is thrown.
+
+The underlying memory for `Buffer` instances created in this way is _not
+initialized_. The contents of the newly created `Buffer` are unknown and
+_may contain sensitive data_. Use [`Buffer.alloc()`][] instead to initialize
+`Buffer` instances with zeroes.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(10);
+
+console.log(buf);
+// Prints (contents may vary):
+
+buf.fill(0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(10);
+
+console.log(buf);
+// Prints (contents may vary):
+
+buf.fill(0);
+
+console.log(buf);
+// Prints:
+```
+
+A `TypeError` will be thrown if `size` is not a number.
+
+The `Buffer` module pre-allocates an internal `Buffer` instance of
+size [`Buffer.poolSize`][] that is used as a pool for the fast allocation of new
+`Buffer` instances created using [`Buffer.allocUnsafe()`][], [`Buffer.from(array)`][],
+and [`Buffer.concat()`][] only when `size` is less than or equal to
+`Buffer.poolSize >> 1` (floor of [`Buffer.poolSize`][] divided by two).
+
+Use of this pre-allocated internal memory pool is a key difference between
+calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
+Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`
+pool, while `Buffer.allocUnsafe(size).fill(fill)` _will_ use the internal
+`Buffer` pool if `size` is less than or equal to half [`Buffer.poolSize`][]. The
+difference is subtle but can be important when an application requires the
+additional performance that [`Buffer.allocUnsafe()`][] provides.
+
+#### Static method: `Buffer.allocUnsafeSlow(size)`
+
+
+
+* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`.
+
+Allocates a new `Buffer` of `size` bytes. If `size` is larger than
+[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_OUT_OF_RANGE`][]
+is thrown. A zero-length `Buffer` is created if `size` is 0.
+
+The underlying memory for `Buffer` instances created in this way is _not
+initialized_. The contents of the newly created `Buffer` are unknown and
+_may contain sensitive data_. Use [`buf.fill(0)`][`buf.fill()`] to initialize
+such `Buffer` instances with zeroes.
+
+When using [`Buffer.allocUnsafe()`][] to allocate new `Buffer` instances,
+allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This
+allows applications to avoid the garbage collection overhead of creating many
+individually allocated `Buffer` instances. This approach improves both
+performance and memory usage by eliminating the need to track and clean up as
+many individual `ArrayBuffer` objects.
+
+However, in the case where a developer may need to retain a small chunk of
+memory from a pool for an indeterminate amount of time, it may be appropriate
+to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and
+then copying out the relevant bits.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Need to keep around a few small chunks of memory.
+const store = [];
+
+socket.on('readable', () => {
+ let data;
+ while (null !== (data = readable.read())) {
+ // Allocate for retained data.
+ const sb = Buffer.allocUnsafeSlow(10);
+
+ // Copy the data into the new allocation.
+ data.copy(sb, 0, 0, 10);
+
+ store.push(sb);
+ }
+});
+--------------
+const { Buffer } = require('node:buffer');
+
+// Need to keep around a few small chunks of memory.
+const store = [];
+
+socket.on('readable', () => {
+ let data;
+ while (null !== (data = readable.read())) {
+ // Allocate for retained data.
+ const sb = Buffer.allocUnsafeSlow(10);
+
+ // Copy the data into the new allocation.
+ data.copy(sb, 0, 0, 10);
+
+ store.push(sb);
+ }
+});
+```
+
+A `TypeError` will be thrown if `size` is not a number.
+
+#### Static method: `Buffer.byteLength(string[, encoding])`
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v20/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) A
+ value to calculate the length of.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `string` is a string, this is its encoding.
+ **Default:** `'utf8'`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes contained within `string`.
+
+Returns the byte length of a string when encoded using `encoding`.
+This is not the same as [`String.prototype.length`][], which does not account
+for the encoding that is used to convert the string into bytes.
+
+For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input.
+For strings that contain non-base64/hex-encoded data (e.g. whitespace), the
+return value might be greater than the length of a `Buffer` created from the
+string.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const str = '\u00bd + \u00bc = \u00be';
+
+console.log(`${str}: ${str.length} characters, ` +
+ `${Buffer.byteLength(str, 'utf8')} bytes`);
+// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
+--------------
+const { Buffer } = require('node:buffer');
+
+const str = '\u00bd + \u00bc = \u00be';
+
+console.log(`${str}: ${str.length} characters, ` +
+ `${Buffer.byteLength(str, 'utf8')} bytes`);
+// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
+```
+
+When `string` is a `Buffer`/[`DataView`][]/[`TypedArray`][]/[`ArrayBuffer`][]/
+[`SharedArrayBuffer`][], the byte length as reported by `.byteLength`
+is returned.
+
+#### Static method: `Buffer.compare(buf1, buf2)`
+
+
+
+* `buf1` [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `buf2` [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Either `-1`, `0`, or `1`, depending on the result of the
+ comparison. See [`buf.compare()`][] for details.
+
+Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of
+`Buffer` instances. This is equivalent to calling
+[`buf1.compare(buf2)`][`buf.compare()`].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from('1234');
+const buf2 = Buffer.from('0123');
+const arr = [buf1, buf2];
+
+console.log(arr.sort(Buffer.compare));
+// Prints: [ , ]
+// (This result is equal to: [buf2, buf1].)
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from('1234');
+const buf2 = Buffer.from('0123');
+const arr = [buf1, buf2];
+
+console.log(arr.sort(Buffer.compare));
+// Prints: [ , ]
+// (This result is equal to: [buf2, buf1].)
+```
+
+#### Static method: `Buffer.concat(list[, totalLength])`
+
+
+
+* `list` Buffer\[] | Uint8Array\[] List of `Buffer` or [`Uint8Array`][]
+ instances to concatenate.
+* `totalLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Total length of the `Buffer` instances in `list`
+ when concatenated.
+* Returns: [`Buffer`](/api/v20/buffer#buffer)
+
+Returns a new `Buffer` which is the result of concatenating all the `Buffer`
+instances in the `list` together.
+
+If the list has no items, or if the `totalLength` is 0, then a new zero-length
+`Buffer` is returned.
+
+If `totalLength` is not provided, it is calculated from the `Buffer` instances
+in `list` by adding their lengths.
+
+If `totalLength` is provided, it is coerced to an unsigned integer. If the
+combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
+truncated to `totalLength`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create a single `Buffer` from a list of three `Buffer` instances.
+
+const buf1 = Buffer.alloc(10);
+const buf2 = Buffer.alloc(14);
+const buf3 = Buffer.alloc(18);
+const totalLength = buf1.length + buf2.length + buf3.length;
+
+console.log(totalLength);
+// Prints: 42
+
+const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
+
+console.log(bufA);
+// Prints:
+console.log(bufA.length);
+// Prints: 42
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create a single `Buffer` from a list of three `Buffer` instances.
+
+const buf1 = Buffer.alloc(10);
+const buf2 = Buffer.alloc(14);
+const buf3 = Buffer.alloc(18);
+const totalLength = buf1.length + buf2.length + buf3.length;
+
+console.log(totalLength);
+// Prints: 42
+
+const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
+
+console.log(bufA);
+// Prints:
+console.log(bufA.length);
+// Prints: 42
+```
+
+`Buffer.concat()` may also use the internal `Buffer` pool like
+[`Buffer.allocUnsafe()`][] does.
+
+#### Static method: `Buffer.copyBytesFrom(view[, offset[, length]])`
+
+
+
+* `view` [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) The [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) to copy.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The starting offset within `view`. **Default:**: `0`.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of elements from `view` to copy.
+ **Default:** `view.length - offset`.
+
+Copies the underlying memory of `view` into a new `Buffer`.
+
+```js
+const u16 = new Uint16Array([0, 0xffff]);
+const buf = Buffer.copyBytesFrom(u16, 1, 1);
+u16[1] = 0;
+console.log(buf.length); // 2
+console.log(buf[0]); // 255
+console.log(buf[1]); // 255
+```
+
+#### Static method: `Buffer.from(array)`
+
+
+
+* `array` integer\[]
+
+Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`.
+Array entries outside that range will be truncated to fit into it.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
+const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
+--------------
+const { Buffer } = require('node:buffer');
+
+// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
+const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
+```
+
+If `array` is an `Array`-like object (that is, one with a `length` property of
+type `number`), it is treated as if it is an array, unless it is a `Buffer` or
+a `Uint8Array`. This means all other `TypedArray` variants get treated as an
+`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use
+[`Buffer.copyBytesFrom()`][].
+
+A `TypeError` will be thrown if `array` is not an `Array` or another type
+appropriate for `Buffer.from()` variants.
+
+`Buffer.from(array)` and [`Buffer.from(string)`][] may also use the internal
+`Buffer` pool like [`Buffer.allocUnsafe()`][] does.
+
+#### Static method: `Buffer.from(arrayBuffer[, byteOffset[, length]])`
+
+
+
+* `arrayBuffer` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) An [`ArrayBuffer`][],
+ [`SharedArrayBuffer`][], for example the `.buffer` property of a
+ [`TypedArray`][].
+* `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Index of first byte to expose. **Default:** `0`.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to expose.
+ **Default:** `arrayBuffer.byteLength - byteOffset`.
+
+This creates a view of the [`ArrayBuffer`][] without copying the underlying
+memory. For example, when passed a reference to the `.buffer` property of a
+[`TypedArray`][] instance, the newly created `Buffer` will share the same
+allocated memory as the [`TypedArray`][]'s underlying `ArrayBuffer`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const arr = new Uint16Array(2);
+
+arr[0] = 5000;
+arr[1] = 4000;
+
+// Shares memory with `arr`.
+const buf = Buffer.from(arr.buffer);
+
+console.log(buf);
+// Prints:
+
+// Changing the original Uint16Array changes the Buffer also.
+arr[1] = 6000;
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const arr = new Uint16Array(2);
+
+arr[0] = 5000;
+arr[1] = 4000;
+
+// Shares memory with `arr`.
+const buf = Buffer.from(arr.buffer);
+
+console.log(buf);
+// Prints:
+
+// Changing the original Uint16Array changes the Buffer also.
+arr[1] = 6000;
+
+console.log(buf);
+// Prints:
+```
+
+The optional `byteOffset` and `length` arguments specify a memory range within
+the `arrayBuffer` that will be shared by the `Buffer`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const ab = new ArrayBuffer(10);
+const buf = Buffer.from(ab, 0, 2);
+
+console.log(buf.length);
+// Prints: 2
+--------------
+const { Buffer } = require('node:buffer');
+
+const ab = new ArrayBuffer(10);
+const buf = Buffer.from(ab, 0, 2);
+
+console.log(buf.length);
+// Prints: 2
+```
+
+A `TypeError` will be thrown if `arrayBuffer` is not an [`ArrayBuffer`][] or a
+[`SharedArrayBuffer`][] or another type appropriate for `Buffer.from()`
+variants.
+
+It is important to remember that a backing `ArrayBuffer` can cover a range
+of memory that extends beyond the bounds of a `TypedArray` view. A new
+`Buffer` created using the `buffer` property of a `TypedArray` may extend
+beyond the range of the `TypedArray`:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
+const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
+console.log(arrA.buffer === arrB.buffer); // true
+
+const buf = Buffer.from(arrB.buffer);
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
+const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
+console.log(arrA.buffer === arrB.buffer); // true
+
+const buf = Buffer.from(arrB.buffer);
+console.log(buf);
+// Prints:
+```
+
+#### Static method: `Buffer.from(buffer)`
+
+
+
+* `buffer` [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) An existing `Buffer` or [`Uint8Array`][] from
+ which to copy data.
+
+Copies the passed `buffer` data onto a new `Buffer` instance.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from('buffer');
+const buf2 = Buffer.from(buf1);
+
+buf1[0] = 0x61;
+
+console.log(buf1.toString());
+// Prints: auffer
+console.log(buf2.toString());
+// Prints: buffer
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from('buffer');
+const buf2 = Buffer.from(buf1);
+
+buf1[0] = 0x61;
+
+console.log(buf1.toString());
+// Prints: auffer
+console.log(buf2.toString());
+// Prints: buffer
+```
+
+A `TypeError` will be thrown if `buffer` is not a `Buffer` or another type
+appropriate for `Buffer.from()` variants.
+
+#### Static method: `Buffer.from(object[, offsetOrEncoding[, length]])`
+
+
+
+* `object` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object supporting `Symbol.toPrimitive` or `valueOf()`.
+* `offsetOrEncoding` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A byte-offset or encoding.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A length.
+
+For objects whose `valueOf()` function returns a value not strictly equal to
+`object`, returns `Buffer.from(object.valueOf(), offsetOrEncoding, length)`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from(new String('this is a test'));
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from(new String('this is a test'));
+// Prints:
+```
+
+For objects that support `Symbol.toPrimitive`, returns
+`Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+class Foo {
+ [Symbol.toPrimitive]() {
+ return 'this is a test';
+ }
+}
+
+const buf = Buffer.from(new Foo(), 'utf8');
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+class Foo {
+ [Symbol.toPrimitive]() {
+ return 'this is a test';
+ }
+}
+
+const buf = Buffer.from(new Foo(), 'utf8');
+// Prints:
+```
+
+A `TypeError` will be thrown if `object` does not have the mentioned methods or
+is not of another type appropriate for `Buffer.from()` variants.
+
+#### Static method: `Buffer.from(string[, encoding])`
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string to encode.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding of `string`. **Default:** `'utf8'`.
+
+Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
+the character encoding to be used when converting `string` into bytes.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from('this is a tést');
+const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
+
+console.log(buf1.toString());
+// Prints: this is a tést
+console.log(buf2.toString());
+// Prints: this is a tést
+console.log(buf1.toString('latin1'));
+// Prints: this is a tést
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from('this is a tést');
+const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
+
+console.log(buf1.toString());
+// Prints: this is a tést
+console.log(buf2.toString());
+// Prints: this is a tést
+console.log(buf1.toString('latin1'));
+// Prints: this is a tést
+```
+
+A `TypeError` will be thrown if `string` is not a string or another type
+appropriate for `Buffer.from()` variants.
+
+#### Static method: `Buffer.isBuffer(obj)`
+
+
+
+* `obj` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+Returns `true` if `obj` is a `Buffer`, `false` otherwise.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+Buffer.isBuffer(Buffer.alloc(10)); // true
+Buffer.isBuffer(Buffer.from('foo')); // true
+Buffer.isBuffer('a string'); // false
+Buffer.isBuffer([]); // false
+Buffer.isBuffer(new Uint8Array(1024)); // false
+--------------
+const { Buffer } = require('node:buffer');
+
+Buffer.isBuffer(Buffer.alloc(10)); // true
+Buffer.isBuffer(Buffer.from('foo')); // true
+Buffer.isBuffer('a string'); // false
+Buffer.isBuffer([]); // false
+Buffer.isBuffer(new Uint8Array(1024)); // false
+```
+
+#### Static method: `Buffer.isEncoding(encoding)`
+
+
+
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A character encoding name to check.
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+Returns `true` if `encoding` is the name of a supported character encoding,
+or `false` otherwise.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+console.log(Buffer.isEncoding('utf8'));
+// Prints: true
+
+console.log(Buffer.isEncoding('hex'));
+// Prints: true
+
+console.log(Buffer.isEncoding('utf/8'));
+// Prints: false
+
+console.log(Buffer.isEncoding(''));
+// Prints: false
+--------------
+const { Buffer } = require('node:buffer');
+
+console.log(Buffer.isEncoding('utf8'));
+// Prints: true
+
+console.log(Buffer.isEncoding('hex'));
+// Prints: true
+
+console.log(Buffer.isEncoding('utf/8'));
+// Prints: false
+
+console.log(Buffer.isEncoding(''));
+// Prints: false
+```
+
+#### Class property: `Buffer.poolSize`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `8192`
+
+This is the size (in bytes) of pre-allocated internal `Buffer` instances used
+for pooling. This value may be modified.
+
+#### `buf[index]`
+
+* `index` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+The index operator `[index]` can be used to get and set the octet at position
+`index` in `buf`. The values refer to individual bytes, so the legal value
+range is between `0x00` and `0xFF` (hex) or `0` and `255` (decimal).
+
+This operator is inherited from `Uint8Array`, so its behavior on out-of-bounds
+access is the same as `Uint8Array`. In other words, `buf[index]` returns
+`undefined` when `index` is negative or greater or equal to `buf.length`, and
+`buf[index] = value` does not modify the buffer if `index` is negative or
+`>= buf.length`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Copy an ASCII string into a `Buffer` one byte at a time.
+// (This only works for ASCII-only strings. In general, one should use
+// `Buffer.from()` to perform this conversion.)
+
+const str = 'Node.js';
+const buf = Buffer.allocUnsafe(str.length);
+
+for (let i = 0; i < str.length; i++) {
+ buf[i] = str.charCodeAt(i);
+}
+
+console.log(buf.toString('utf8'));
+// Prints: Node.js
+--------------
+const { Buffer } = require('node:buffer');
+
+// Copy an ASCII string into a `Buffer` one byte at a time.
+// (This only works for ASCII-only strings. In general, one should use
+// `Buffer.from()` to perform this conversion.)
+
+const str = 'Node.js';
+const buf = Buffer.allocUnsafe(str.length);
+
+for (let i = 0; i < str.length; i++) {
+ buf[i] = str.charCodeAt(i);
+}
+
+console.log(buf.toString('utf8'));
+// Prints: Node.js
+```
+
+#### `buf.buffer`
+
+* [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) The underlying `ArrayBuffer` object based on which this `Buffer`
+ object is created.
+
+This `ArrayBuffer` is not guaranteed to correspond exactly to the original
+`Buffer`. See the notes on `buf.byteOffset` for details.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const arrayBuffer = new ArrayBuffer(16);
+const buffer = Buffer.from(arrayBuffer);
+
+console.log(buffer.buffer === arrayBuffer);
+// Prints: true
+--------------
+const { Buffer } = require('node:buffer');
+
+const arrayBuffer = new ArrayBuffer(16);
+const buffer = Buffer.from(arrayBuffer);
+
+console.log(buffer.buffer === arrayBuffer);
+// Prints: true
+```
+
+#### `buf.byteOffset`
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The `byteOffset` of the `Buffer`s underlying `ArrayBuffer` object.
+
+When setting `byteOffset` in `Buffer.from(ArrayBuffer, byteOffset, length)`,
+or sometimes when allocating a `Buffer` smaller than `Buffer.poolSize`, the
+buffer does not start from a zero offset on the underlying `ArrayBuffer`.
+
+This can cause problems when accessing the underlying `ArrayBuffer` directly
+using `buf.buffer`, as other parts of the `ArrayBuffer` may be unrelated
+to the `Buffer` object itself.
+
+A common issue when creating a `TypedArray` object that shares its memory with
+a `Buffer` is that in this case one needs to specify the `byteOffset` correctly:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create a buffer smaller than `Buffer.poolSize`.
+const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
+
+// When casting the Node.js Buffer to an Int8Array, use the byteOffset
+// to refer only to the part of `nodeBuffer.buffer` that contains the memory
+// for `nodeBuffer`.
+new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create a buffer smaller than `Buffer.poolSize`.
+const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
+
+// When casting the Node.js Buffer to an Int8Array, use the byteOffset
+// to refer only to the part of `nodeBuffer.buffer` that contains the memory
+// for `nodeBuffer`.
+new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
+```
+
+#### `buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])`
+
+
+
+* `target` [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or [`Uint8Array`][] with which to
+ compare `buf`.
+* `targetStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `target` at which to begin
+ comparison. **Default:** `0`.
+* `targetEnd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `target` at which to end comparison
+ (not inclusive). **Default:** `target.length`.
+* `sourceStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `buf` at which to begin comparison.
+ **Default:** `0`.
+* `sourceEnd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `buf` at which to end comparison
+ (not inclusive). **Default:** [`buf.length`][].
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Compares `buf` with `target` and returns a number indicating whether `buf`
+comes before, after, or is the same as `target` in sort order.
+Comparison is based on the actual sequence of bytes in each `Buffer`.
+
+* `0` is returned if `target` is the same as `buf`
+* `1` is returned if `target` should come _before_ `buf` when sorted.
+* `-1` is returned if `target` should come _after_ `buf` when sorted.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from('ABC');
+const buf2 = Buffer.from('BCD');
+const buf3 = Buffer.from('ABCD');
+
+console.log(buf1.compare(buf1));
+// Prints: 0
+console.log(buf1.compare(buf2));
+// Prints: -1
+console.log(buf1.compare(buf3));
+// Prints: -1
+console.log(buf2.compare(buf1));
+// Prints: 1
+console.log(buf2.compare(buf3));
+// Prints: 1
+console.log([buf1, buf2, buf3].sort(Buffer.compare));
+// Prints: [ , , ]
+// (This result is equal to: [buf1, buf3, buf2].)
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from('ABC');
+const buf2 = Buffer.from('BCD');
+const buf3 = Buffer.from('ABCD');
+
+console.log(buf1.compare(buf1));
+// Prints: 0
+console.log(buf1.compare(buf2));
+// Prints: -1
+console.log(buf1.compare(buf3));
+// Prints: -1
+console.log(buf2.compare(buf1));
+// Prints: 1
+console.log(buf2.compare(buf3));
+// Prints: 1
+console.log([buf1, buf2, buf3].sort(Buffer.compare));
+// Prints: [ , , ]
+// (This result is equal to: [buf1, buf3, buf2].)
+```
+
+The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`
+arguments can be used to limit the comparison to specific ranges within `target`
+and `buf` respectively.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
+const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
+
+console.log(buf1.compare(buf2, 5, 9, 0, 4));
+// Prints: 0
+console.log(buf1.compare(buf2, 0, 6, 4));
+// Prints: -1
+console.log(buf1.compare(buf2, 5, 6, 5));
+// Prints: 1
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
+const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
+
+console.log(buf1.compare(buf2, 5, 9, 0, 4));
+// Prints: 0
+console.log(buf1.compare(buf2, 0, 6, 4));
+// Prints: -1
+console.log(buf1.compare(buf2, 5, 6, 5));
+// Prints: 1
+```
+
+[`ERR_OUT_OF_RANGE`][] is thrown if `targetStart < 0`, `sourceStart < 0`,
+`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`.
+
+#### `buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])`
+
+
+
+* `target` [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or [`Uint8Array`][] to copy into.
+* `targetStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `target` at which to begin
+ writing. **Default:** `0`.
+* `sourceStart` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `buf` from which to begin copying.
+ **Default:** `0`.
+* `sourceEnd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The offset within `buf` at which to stop copying (not
+ inclusive). **Default:** [`buf.length`][].
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes copied.
+
+Copies data from a region of `buf` to a region in `target`, even if the `target`
+memory region overlaps with `buf`.
+
+[`TypedArray.prototype.set()`][] performs the same operation, and is available
+for all TypedArrays, including Node.js `Buffer`s, although it takes
+different function arguments.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create two `Buffer` instances.
+const buf1 = Buffer.allocUnsafe(26);
+const buf2 = Buffer.allocUnsafe(26).fill('!');
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
+buf1.copy(buf2, 8, 16, 20);
+// This is equivalent to:
+// buf2.set(buf1.subarray(16, 20), 8);
+
+console.log(buf2.toString('ascii', 0, 25));
+// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create two `Buffer` instances.
+const buf1 = Buffer.allocUnsafe(26);
+const buf2 = Buffer.allocUnsafe(26).fill('!');
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
+buf1.copy(buf2, 8, 16, 20);
+// This is equivalent to:
+// buf2.set(buf1.subarray(16, 20), 8);
+
+console.log(buf2.toString('ascii', 0, 25));
+// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
+```
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create a `Buffer` and copy data from one region to an overlapping region
+// within the same `Buffer`.
+
+const buf = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf[i] = i + 97;
+}
+
+buf.copy(buf, 0, 4, 10);
+
+console.log(buf.toString());
+// Prints: efghijghijklmnopqrstuvwxyz
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create a `Buffer` and copy data from one region to an overlapping region
+// within the same `Buffer`.
+
+const buf = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf[i] = i + 97;
+}
+
+buf.copy(buf, 0, 4, 10);
+
+console.log(buf.toString());
+// Prints: efghijghijklmnopqrstuvwxyz
+```
+
+#### `buf.entries()`
+
+
+
+* Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol)
+
+Creates and returns an [iterator][] of `[index, byte]` pairs from the contents
+of `buf`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Log the entire contents of a `Buffer`.
+
+const buf = Buffer.from('buffer');
+
+for (const pair of buf.entries()) {
+ console.log(pair);
+}
+// Prints:
+// [0, 98]
+// [1, 117]
+// [2, 102]
+// [3, 102]
+// [4, 101]
+// [5, 114]
+--------------
+const { Buffer } = require('node:buffer');
+
+// Log the entire contents of a `Buffer`.
+
+const buf = Buffer.from('buffer');
+
+for (const pair of buf.entries()) {
+ console.log(pair);
+}
+// Prints:
+// [0, 98]
+// [1, 117]
+// [2, 102]
+// [3, 102]
+// [4, 101]
+// [5, 114]
+```
+
+#### `buf.equals(otherBuffer)`
+
+
+
+* `otherBuffer` [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or [`Uint8Array`][] with which to
+ compare `buf`.
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,
+`false` otherwise. Equivalent to
+[`buf.compare(otherBuffer) === 0`][`buf.compare()`].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from('ABC');
+const buf2 = Buffer.from('414243', 'hex');
+const buf3 = Buffer.from('ABCD');
+
+console.log(buf1.equals(buf2));
+// Prints: true
+console.log(buf1.equals(buf3));
+// Prints: false
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from('ABC');
+const buf2 = Buffer.from('414243', 'hex');
+const buf3 = Buffer.from('ABCD');
+
+console.log(buf1.equals(buf2));
+// Prints: true
+console.log(buf1.equals(buf3));
+// Prints: false
+```
+
+#### `buf.fill(value[, offset[, end]][, encoding])`
+
+
+
+* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The value with which to fill `buf`.
+ Empty value (string, Uint8Array, Buffer) is coerced to `0`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to fill `buf`.
+ **Default:** `0`.
+* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to stop filling `buf` (not inclusive). **Default:**
+ [`buf.length`][].
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding for `value` if `value` is a string.
+ **Default:** `'utf8'`.
+* Returns: [`Buffer`](/api/v20/buffer#buffer) A reference to `buf`.
+
+Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
+the entire `buf` will be filled:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Fill a `Buffer` with the ASCII character 'h'.
+
+const b = Buffer.allocUnsafe(50).fill('h');
+
+console.log(b.toString());
+// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
+
+// Fill a buffer with empty string
+const c = Buffer.allocUnsafe(5).fill('');
+
+console.log(c.fill(''));
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+// Fill a `Buffer` with the ASCII character 'h'.
+
+const b = Buffer.allocUnsafe(50).fill('h');
+
+console.log(b.toString());
+// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
+
+// Fill a buffer with empty string
+const c = Buffer.allocUnsafe(5).fill('');
+
+console.log(c.fill(''));
+// Prints:
+```
+
+`value` is coerced to a `uint32` value if it is not a string, `Buffer`, or
+integer. If the resulting integer is greater than `255` (decimal), `buf` will be
+filled with `value & 255`.
+
+If the final write of a `fill()` operation falls on a multi-byte character,
+then only the bytes of that character that fit into `buf` are written:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Fill a `Buffer` with character that takes up two bytes in UTF-8.
+
+console.log(Buffer.allocUnsafe(5).fill('\u0222'));
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+// Fill a `Buffer` with character that takes up two bytes in UTF-8.
+
+console.log(Buffer.allocUnsafe(5).fill('\u0222'));
+// Prints:
+```
+
+If `value` contains invalid characters, it is truncated; if no valid
+fill data remains, an exception is thrown:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(5);
+
+console.log(buf.fill('a'));
+// Prints:
+console.log(buf.fill('aazz', 'hex'));
+// Prints:
+console.log(buf.fill('zz', 'hex'));
+// Throws an exception.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(5);
+
+console.log(buf.fill('a'));
+// Prints:
+console.log(buf.fill('aazz', 'hex'));
+// Prints:
+console.log(buf.fill('zz', 'hex'));
+// Throws an exception.
+```
+
+#### `buf.includes(value[, byteOffset][, encoding])`
+
+
+
+* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) What to search for.
+* `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to begin searching in `buf`. If negative, then
+ offset is calculated from the end of `buf`. **Default:** `0`.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `value` is a string, this is its encoding.
+ **Default:** `'utf8'`.
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if `value` was found in `buf`, `false` otherwise.
+
+Equivalent to [`buf.indexOf() !== -1`][`buf.indexOf()`].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('this is a buffer');
+
+console.log(buf.includes('this'));
+// Prints: true
+console.log(buf.includes('is'));
+// Prints: true
+console.log(buf.includes(Buffer.from('a buffer')));
+// Prints: true
+console.log(buf.includes(97));
+// Prints: true (97 is the decimal ASCII value for 'a')
+console.log(buf.includes(Buffer.from('a buffer example')));
+// Prints: false
+console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
+// Prints: true
+console.log(buf.includes('this', 4));
+// Prints: false
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('this is a buffer');
+
+console.log(buf.includes('this'));
+// Prints: true
+console.log(buf.includes('is'));
+// Prints: true
+console.log(buf.includes(Buffer.from('a buffer')));
+// Prints: true
+console.log(buf.includes(97));
+// Prints: true (97 is the decimal ASCII value for 'a')
+console.log(buf.includes(Buffer.from('a buffer example')));
+// Prints: false
+console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
+// Prints: true
+console.log(buf.includes('this', 4));
+// Prints: false
+```
+
+#### `buf.indexOf(value[, byteOffset][, encoding])`
+
+
+
+* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) What to search for.
+* `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to begin searching in `buf`. If negative, then
+ offset is calculated from the end of `buf`. **Default:** `0`.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `value` is a string, this is the encoding used to
+ determine the binary representation of the string that will be searched for in
+ `buf`. **Default:** `'utf8'`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The index of the first occurrence of `value` in `buf`, or
+ `-1` if `buf` does not contain `value`.
+
+If `value` is:
+
+* a string, `value` is interpreted according to the character encoding in
+ `encoding`.
+* a `Buffer` or [`Uint8Array`][], `value` will be used in its entirety.
+ To compare a partial `Buffer`, use [`buf.subarray`][].
+* a number, `value` will be interpreted as an unsigned 8-bit integer
+ value between `0` and `255`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('this is a buffer');
+
+console.log(buf.indexOf('this'));
+// Prints: 0
+console.log(buf.indexOf('is'));
+// Prints: 2
+console.log(buf.indexOf(Buffer.from('a buffer')));
+// Prints: 8
+console.log(buf.indexOf(97));
+// Prints: 8 (97 is the decimal ASCII value for 'a')
+console.log(buf.indexOf(Buffer.from('a buffer example')));
+// Prints: -1
+console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
+// Prints: 8
+
+const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
+
+console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
+// Prints: 4
+console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
+// Prints: 6
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('this is a buffer');
+
+console.log(buf.indexOf('this'));
+// Prints: 0
+console.log(buf.indexOf('is'));
+// Prints: 2
+console.log(buf.indexOf(Buffer.from('a buffer')));
+// Prints: 8
+console.log(buf.indexOf(97));
+// Prints: 8 (97 is the decimal ASCII value for 'a')
+console.log(buf.indexOf(Buffer.from('a buffer example')));
+// Prints: -1
+console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
+// Prints: 8
+
+const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
+
+console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
+// Prints: 4
+console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
+// Prints: 6
+```
+
+If `value` is not a string, number, or `Buffer`, this method will throw a
+`TypeError`. If `value` is a number, it will be coerced to a valid byte value,
+an integer between 0 and 255.
+
+If `byteOffset` is not a number, it will be coerced to a number. If the result
+of coercion is `NaN` or `0`, then the entire buffer will be searched. This
+behavior matches [`String.prototype.indexOf()`][].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const b = Buffer.from('abcdef');
+
+// Passing a value that's a number, but not a valid byte.
+// Prints: 2, equivalent to searching for 99 or 'c'.
+console.log(b.indexOf(99.9));
+console.log(b.indexOf(256 + 99));
+
+// Passing a byteOffset that coerces to NaN or 0.
+// Prints: 1, searching the whole buffer.
+console.log(b.indexOf('b', undefined));
+console.log(b.indexOf('b', {}));
+console.log(b.indexOf('b', null));
+console.log(b.indexOf('b', []));
+--------------
+const { Buffer } = require('node:buffer');
+
+const b = Buffer.from('abcdef');
+
+// Passing a value that's a number, but not a valid byte.
+// Prints: 2, equivalent to searching for 99 or 'c'.
+console.log(b.indexOf(99.9));
+console.log(b.indexOf(256 + 99));
+
+// Passing a byteOffset that coerces to NaN or 0.
+// Prints: 1, searching the whole buffer.
+console.log(b.indexOf('b', undefined));
+console.log(b.indexOf('b', {}));
+console.log(b.indexOf('b', null));
+console.log(b.indexOf('b', []));
+```
+
+If `value` is an empty string or empty `Buffer` and `byteOffset` is less
+than `buf.length`, `byteOffset` will be returned. If `value` is empty and
+`byteOffset` is at least `buf.length`, `buf.length` will be returned.
+
+#### `buf.keys()`
+
+
+
+* Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol)
+
+Creates and returns an [iterator][] of `buf` keys (indices).
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('buffer');
+
+for (const key of buf.keys()) {
+ console.log(key);
+}
+// Prints:
+// 0
+// 1
+// 2
+// 3
+// 4
+// 5
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('buffer');
+
+for (const key of buf.keys()) {
+ console.log(key);
+}
+// Prints:
+// 0
+// 1
+// 2
+// 3
+// 4
+// 5
+```
+
+#### `buf.lastIndexOf(value[, byteOffset][, encoding])`
+
+
+
+* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) What to search for.
+* `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where to begin searching in `buf`. If negative, then
+ offset is calculated from the end of `buf`. **Default:**
+ `buf.length - 1`.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `value` is a string, this is the encoding used to
+ determine the binary representation of the string that will be searched for in
+ `buf`. **Default:** `'utf8'`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The index of the last occurrence of `value` in `buf`, or
+ `-1` if `buf` does not contain `value`.
+
+Identical to [`buf.indexOf()`][], except the last occurrence of `value` is found
+rather than the first occurrence.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('this buffer is a buffer');
+
+console.log(buf.lastIndexOf('this'));
+// Prints: 0
+console.log(buf.lastIndexOf('buffer'));
+// Prints: 17
+console.log(buf.lastIndexOf(Buffer.from('buffer')));
+// Prints: 17
+console.log(buf.lastIndexOf(97));
+// Prints: 15 (97 is the decimal ASCII value for 'a')
+console.log(buf.lastIndexOf(Buffer.from('yolo')));
+// Prints: -1
+console.log(buf.lastIndexOf('buffer', 5));
+// Prints: 5
+console.log(buf.lastIndexOf('buffer', 4));
+// Prints: -1
+
+const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
+
+console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
+// Prints: 6
+console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
+// Prints: 4
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('this buffer is a buffer');
+
+console.log(buf.lastIndexOf('this'));
+// Prints: 0
+console.log(buf.lastIndexOf('buffer'));
+// Prints: 17
+console.log(buf.lastIndexOf(Buffer.from('buffer')));
+// Prints: 17
+console.log(buf.lastIndexOf(97));
+// Prints: 15 (97 is the decimal ASCII value for 'a')
+console.log(buf.lastIndexOf(Buffer.from('yolo')));
+// Prints: -1
+console.log(buf.lastIndexOf('buffer', 5));
+// Prints: 5
+console.log(buf.lastIndexOf('buffer', 4));
+// Prints: -1
+
+const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
+
+console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
+// Prints: 6
+console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
+// Prints: 4
+```
+
+If `value` is not a string, number, or `Buffer`, this method will throw a
+`TypeError`. If `value` is a number, it will be coerced to a valid byte value,
+an integer between 0 and 255.
+
+If `byteOffset` is not a number, it will be coerced to a number. Any arguments
+that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer.
+This behavior matches [`String.prototype.lastIndexOf()`][].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const b = Buffer.from('abcdef');
+
+// Passing a value that's a number, but not a valid byte.
+// Prints: 2, equivalent to searching for 99 or 'c'.
+console.log(b.lastIndexOf(99.9));
+console.log(b.lastIndexOf(256 + 99));
+
+// Passing a byteOffset that coerces to NaN.
+// Prints: 1, searching the whole buffer.
+console.log(b.lastIndexOf('b', undefined));
+console.log(b.lastIndexOf('b', {}));
+
+// Passing a byteOffset that coerces to 0.
+// Prints: -1, equivalent to passing 0.
+console.log(b.lastIndexOf('b', null));
+console.log(b.lastIndexOf('b', []));
+--------------
+const { Buffer } = require('node:buffer');
+
+const b = Buffer.from('abcdef');
+
+// Passing a value that's a number, but not a valid byte.
+// Prints: 2, equivalent to searching for 99 or 'c'.
+console.log(b.lastIndexOf(99.9));
+console.log(b.lastIndexOf(256 + 99));
+
+// Passing a byteOffset that coerces to NaN.
+// Prints: 1, searching the whole buffer.
+console.log(b.lastIndexOf('b', undefined));
+console.log(b.lastIndexOf('b', {}));
+
+// Passing a byteOffset that coerces to 0.
+// Prints: -1, equivalent to passing 0.
+console.log(b.lastIndexOf('b', null));
+console.log(b.lastIndexOf('b', []));
+```
+
+If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned.
+
+#### `buf.length`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Returns the number of bytes in `buf`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create a `Buffer` and write a shorter string to it using UTF-8.
+
+const buf = Buffer.alloc(1234);
+
+console.log(buf.length);
+// Prints: 1234
+
+buf.write('some string', 0, 'utf8');
+
+console.log(buf.length);
+// Prints: 1234
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create a `Buffer` and write a shorter string to it using UTF-8.
+
+const buf = Buffer.alloc(1234);
+
+console.log(buf.length);
+// Prints: 1234
+
+buf.write('some string', 0, 'utf8');
+
+console.log(buf.length);
+// Prints: 1234
+```
+
+#### `buf.parent`
+
+
+
+
+
+Deprecated: Use [`buf.buffer`][] instead.
+
+
+
+The `buf.parent` property is a deprecated alias for `buf.buffer`.
+
+#### `buf.readBigInt64BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed
+values.
+
+#### `buf.readBigInt64LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Reads a signed, little-endian 64-bit integer from `buf` at the specified
+`offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed
+values.
+
+#### `buf.readBigUInt64BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Reads an unsigned, big-endian 64-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readBigUint64BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
+
+console.log(buf.readBigUInt64BE(0));
+// Prints: 4294967295n
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
+
+console.log(buf.readBigUInt64BE(0));
+// Prints: 4294967295n
+```
+
+#### `buf.readBigUInt64LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Reads an unsigned, little-endian 64-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readBigUint64LE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
+
+console.log(buf.readBigUInt64LE(0));
+// Prints: 18446744069414584320n
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
+
+console.log(buf.readBigUInt64LE(0));
+// Prints: 18446744069414584320n
+```
+
+#### `buf.readDoubleBE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a 64-bit, big-endian double from `buf` at the specified `offset`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
+
+console.log(buf.readDoubleBE(0));
+// Prints: 8.20788039913184e-304
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
+
+console.log(buf.readDoubleBE(0));
+// Prints: 8.20788039913184e-304
+```
+
+#### `buf.readDoubleLE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a 64-bit, little-endian double from `buf` at the specified `offset`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
+
+console.log(buf.readDoubleLE(0));
+// Prints: 5.447603722011605e-270
+console.log(buf.readDoubleLE(1));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
+
+console.log(buf.readDoubleLE(0));
+// Prints: 5.447603722011605e-270
+console.log(buf.readDoubleLE(1));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readFloatBE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a 32-bit, big-endian float from `buf` at the specified `offset`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4]);
+
+console.log(buf.readFloatBE(0));
+// Prints: 2.387939260590663e-38
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3, 4]);
+
+console.log(buf.readFloatBE(0));
+// Prints: 2.387939260590663e-38
+```
+
+#### `buf.readFloatLE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a 32-bit, little-endian float from `buf` at the specified `offset`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4]);
+
+console.log(buf.readFloatLE(0));
+// Prints: 1.539989614439558e-36
+console.log(buf.readFloatLE(1));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, 2, 3, 4]);
+
+console.log(buf.readFloatLE(0));
+// Prints: 1.539989614439558e-36
+console.log(buf.readFloatLE(1));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readInt8([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a signed 8-bit integer from `buf` at the specified `offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed values.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([-1, 5]);
+
+console.log(buf.readInt8(0));
+// Prints: -1
+console.log(buf.readInt8(1));
+// Prints: 5
+console.log(buf.readInt8(2));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([-1, 5]);
+
+console.log(buf.readInt8(0));
+// Prints: -1
+console.log(buf.readInt8(1));
+// Prints: 5
+console.log(buf.readInt8(2));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readInt16BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed values.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0, 5]);
+
+console.log(buf.readInt16BE(0));
+// Prints: 5
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0, 5]);
+
+console.log(buf.readInt16BE(0));
+// Prints: 5
+```
+
+#### `buf.readInt16LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a signed, little-endian 16-bit integer from `buf` at the specified
+`offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed values.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0, 5]);
+
+console.log(buf.readInt16LE(0));
+// Prints: 1280
+console.log(buf.readInt16LE(1));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0, 5]);
+
+console.log(buf.readInt16LE(0));
+// Prints: 1280
+console.log(buf.readInt16LE(1));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readInt32BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed values.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0, 0, 0, 5]);
+
+console.log(buf.readInt32BE(0));
+// Prints: 5
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0, 0, 0, 5]);
+
+console.log(buf.readInt32BE(0));
+// Prints: 5
+```
+
+#### `buf.readInt32LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads a signed, little-endian 32-bit integer from `buf` at the specified
+`offset`.
+
+Integers read from a `Buffer` are interpreted as two's complement signed values.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0, 0, 0, 5]);
+
+console.log(buf.readInt32LE(0));
+// Prints: 83886080
+console.log(buf.readInt32LE(1));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0, 0, 0, 5]);
+
+console.log(buf.readInt32LE(0));
+// Prints: 83886080
+console.log(buf.readInt32LE(1));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readIntBE(offset, byteLength)`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads `byteLength` number of bytes from `buf` at the specified `offset`
+and interprets the result as a big-endian, two's complement signed value
+supporting up to 48 bits of accuracy.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readIntBE(0, 6).toString(16));
+// Prints: 1234567890ab
+console.log(buf.readIntBE(1, 6).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+console.log(buf.readIntBE(1, 0).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readIntBE(0, 6).toString(16));
+// Prints: 1234567890ab
+console.log(buf.readIntBE(1, 6).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+console.log(buf.readIntBE(1, 0).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readIntLE(offset, byteLength)`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads `byteLength` number of bytes from `buf` at the specified `offset`
+and interprets the result as a little-endian, two's complement signed value
+supporting up to 48 bits of accuracy.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readIntLE(0, 6).toString(16));
+// Prints: -546f87a9cbee
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readIntLE(0, 6).toString(16));
+// Prints: -546f87a9cbee
+```
+
+#### `buf.readUInt8([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
+
+This function is also available under the `readUint8` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, -2]);
+
+console.log(buf.readUInt8(0));
+// Prints: 1
+console.log(buf.readUInt8(1));
+// Prints: 254
+console.log(buf.readUInt8(2));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([1, -2]);
+
+console.log(buf.readUInt8(0));
+// Prints: 1
+console.log(buf.readUInt8(1));
+// Prints: 254
+console.log(buf.readUInt8(2));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readUInt16BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads an unsigned, big-endian 16-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readUint16BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56]);
+
+console.log(buf.readUInt16BE(0).toString(16));
+// Prints: 1234
+console.log(buf.readUInt16BE(1).toString(16));
+// Prints: 3456
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56]);
+
+console.log(buf.readUInt16BE(0).toString(16));
+// Prints: 1234
+console.log(buf.readUInt16BE(1).toString(16));
+// Prints: 3456
+```
+
+#### `buf.readUInt16LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads an unsigned, little-endian 16-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readUint16LE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56]);
+
+console.log(buf.readUInt16LE(0).toString(16));
+// Prints: 3412
+console.log(buf.readUInt16LE(1).toString(16));
+// Prints: 5634
+console.log(buf.readUInt16LE(2).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56]);
+
+console.log(buf.readUInt16LE(0).toString(16));
+// Prints: 3412
+console.log(buf.readUInt16LE(1).toString(16));
+// Prints: 5634
+console.log(buf.readUInt16LE(2).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readUInt32BE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads an unsigned, big-endian 32-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readUint32BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
+
+console.log(buf.readUInt32BE(0).toString(16));
+// Prints: 12345678
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
+
+console.log(buf.readUInt32BE(0).toString(16));
+// Prints: 12345678
+```
+
+#### `buf.readUInt32LE([offset])`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads an unsigned, little-endian 32-bit integer from `buf` at the specified
+`offset`.
+
+This function is also available under the `readUint32LE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
+
+console.log(buf.readUInt32LE(0).toString(16));
+// Prints: 78563412
+console.log(buf.readUInt32LE(1).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
+
+console.log(buf.readUInt32LE(0).toString(16));
+// Prints: 78563412
+console.log(buf.readUInt32LE(1).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readUIntBE(offset, byteLength)`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads `byteLength` number of bytes from `buf` at the specified `offset`
+and interprets the result as an unsigned big-endian integer supporting
+up to 48 bits of accuracy.
+
+This function is also available under the `readUintBE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readUIntBE(0, 6).toString(16));
+// Prints: 1234567890ab
+console.log(buf.readUIntBE(1, 6).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readUIntBE(0, 6).toString(16));
+// Prints: 1234567890ab
+console.log(buf.readUIntBE(1, 6).toString(16));
+// Throws ERR_OUT_OF_RANGE.
+```
+
+#### `buf.readUIntLE(offset, byteLength)`
+
+
+
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to read. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Reads `byteLength` number of bytes from `buf` at the specified `offset`
+and interprets the result as an unsigned, little-endian integer supporting
+up to 48 bits of accuracy.
+
+This function is also available under the `readUintLE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readUIntLE(0, 6).toString(16));
+// Prints: ab9078563412
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
+
+console.log(buf.readUIntLE(0, 6).toString(16));
+// Prints: ab9078563412
+```
+
+#### `buf.subarray([start[, end]])`
+
+
+
+* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will start. **Default:** `0`.
+* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will end (not inclusive).
+ **Default:** [`buf.length`][].
+* Returns: [`Buffer`](/api/v20/buffer#buffer)
+
+Returns a new `Buffer` that references the same memory as the original, but
+offset and cropped by the `start` and `end` indices.
+
+Specifying `end` greater than [`buf.length`][] will return the same result as
+that of `end` equal to [`buf.length`][].
+
+This method is inherited from [`TypedArray.prototype.subarray()`][].
+
+Modifying the new `Buffer` slice will modify the memory in the original `Buffer`
+because the allocated memory of the two objects overlap.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
+// from the original `Buffer`.
+
+const buf1 = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+const buf2 = buf1.subarray(0, 3);
+
+console.log(buf2.toString('ascii', 0, buf2.length));
+// Prints: abc
+
+buf1[0] = 33;
+
+console.log(buf2.toString('ascii', 0, buf2.length));
+// Prints: !bc
+--------------
+const { Buffer } = require('node:buffer');
+
+// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
+// from the original `Buffer`.
+
+const buf1 = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+const buf2 = buf1.subarray(0, 3);
+
+console.log(buf2.toString('ascii', 0, buf2.length));
+// Prints: abc
+
+buf1[0] = 33;
+
+console.log(buf2.toString('ascii', 0, buf2.length));
+// Prints: !bc
+```
+
+Specifying negative indexes causes the slice to be generated relative to the
+end of `buf` rather than the beginning.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('buffer');
+
+console.log(buf.subarray(-6, -1).toString());
+// Prints: buffe
+// (Equivalent to buf.subarray(0, 5).)
+
+console.log(buf.subarray(-6, -2).toString());
+// Prints: buff
+// (Equivalent to buf.subarray(0, 4).)
+
+console.log(buf.subarray(-5, -2).toString());
+// Prints: uff
+// (Equivalent to buf.subarray(1, 4).)
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('buffer');
+
+console.log(buf.subarray(-6, -1).toString());
+// Prints: buffe
+// (Equivalent to buf.subarray(0, 5).)
+
+console.log(buf.subarray(-6, -2).toString());
+// Prints: buff
+// (Equivalent to buf.subarray(0, 4).)
+
+console.log(buf.subarray(-5, -2).toString());
+// Prints: uff
+// (Equivalent to buf.subarray(1, 4).)
+```
+
+#### `buf.slice([start[, end]])`
+
+
+
+* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will start. **Default:** `0`.
+* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Where the new `Buffer` will end (not inclusive).
+ **Default:** [`buf.length`][].
+* Returns: [`Buffer`](/api/v20/buffer#buffer)
+
+
+
+Deprecated: Use [`buf.subarray`][] instead.
+
+
+
+Returns a new `Buffer` that references the same memory as the original, but
+offset and cropped by the `start` and `end` indices.
+
+This method is not compatible with the `Uint8Array.prototype.slice()`,
+which is a superclass of `Buffer`. To copy the slice, use
+`Uint8Array.prototype.slice()`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('buffer');
+
+const copiedBuf = Uint8Array.prototype.slice.call(buf);
+copiedBuf[0]++;
+console.log(copiedBuf.toString());
+// Prints: cuffer
+
+console.log(buf.toString());
+// Prints: buffer
+
+// With buf.slice(), the original buffer is modified.
+const notReallyCopiedBuf = buf.slice();
+notReallyCopiedBuf[0]++;
+console.log(notReallyCopiedBuf.toString());
+// Prints: cuffer
+console.log(buf.toString());
+// Also prints: cuffer (!)
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('buffer');
+
+const copiedBuf = Uint8Array.prototype.slice.call(buf);
+copiedBuf[0]++;
+console.log(copiedBuf.toString());
+// Prints: cuffer
+
+console.log(buf.toString());
+// Prints: buffer
+
+// With buf.slice(), the original buffer is modified.
+const notReallyCopiedBuf = buf.slice();
+notReallyCopiedBuf[0]++;
+console.log(notReallyCopiedBuf.toString());
+// Prints: cuffer
+console.log(buf.toString());
+// Also prints: cuffer (!)
+```
+
+#### `buf.swap16()`
+
+
+
+* Returns: [`Buffer`](/api/v20/buffer#buffer) A reference to `buf`.
+
+Interprets `buf` as an array of unsigned 16-bit integers and swaps the
+byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][]
+is not a multiple of 2.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap16();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap16();
+// Throws ERR_INVALID_BUFFER_SIZE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap16();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap16();
+// Throws ERR_INVALID_BUFFER_SIZE.
+```
+
+One convenient use of `buf.swap16()` is to perform a fast in-place conversion
+between UTF-16 little-endian and UTF-16 big-endian:
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
+buf.swap16(); // Convert to big-endian UTF-16 text.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
+buf.swap16(); // Convert to big-endian UTF-16 text.
+```
+
+#### `buf.swap32()`
+
+
+
+* Returns: [`Buffer`](/api/v20/buffer#buffer) A reference to `buf`.
+
+Interprets `buf` as an array of unsigned 32-bit integers and swaps the
+byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][]
+is not a multiple of 4.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap32();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap32();
+// Throws ERR_INVALID_BUFFER_SIZE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap32();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap32();
+// Throws ERR_INVALID_BUFFER_SIZE.
+```
+
+#### `buf.swap64()`
+
+
+
+* Returns: [`Buffer`](/api/v20/buffer#buffer) A reference to `buf`.
+
+Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_.
+Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 8.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap64();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap64();
+// Throws ERR_INVALID_BUFFER_SIZE.
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
+
+console.log(buf1);
+// Prints:
+
+buf1.swap64();
+
+console.log(buf1);
+// Prints:
+
+const buf2 = Buffer.from([0x1, 0x2, 0x3]);
+
+buf2.swap64();
+// Throws ERR_INVALID_BUFFER_SIZE.
+```
+
+#### `buf.toJSON()`
+
+
+
+* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+
+Returns a JSON representation of `buf`. [`JSON.stringify()`][] implicitly calls
+this function when stringifying a `Buffer` instance.
+
+`Buffer.from()` accepts objects in the format returned from this method.
+In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
+const json = JSON.stringify(buf);
+
+console.log(json);
+// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
+
+const copy = JSON.parse(json, (key, value) => {
+ return value && value.type === 'Buffer' ?
+ Buffer.from(value) :
+ value;
+});
+
+console.log(copy);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
+const json = JSON.stringify(buf);
+
+console.log(json);
+// Prints: {"type":"Buffer","data":[1,2,3,4,5]}
+
+const copy = JSON.parse(json, (key, value) => {
+ return value && value.type === 'Buffer' ?
+ Buffer.from(value) :
+ value;
+});
+
+console.log(copy);
+// Prints:
+```
+
+#### `buf.toString([encoding[, start[, end]]])`
+
+
+
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The character encoding to use. **Default:** `'utf8'`.
+* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The byte offset to start decoding at. **Default:** `0`.
+* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The byte offset to stop decoding at (not inclusive).
+ **Default:** [`buf.length`][].
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Decodes `buf` to a string according to the specified character encoding in
+`encoding`. `start` and `end` may be passed to decode only a subset of `buf`.
+
+If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8,
+then each invalid byte is replaced with the replacement character `U+FFFD`.
+
+The maximum length of a string instance (in UTF-16 code units) is available
+as [`buffer.constants.MAX_STRING_LENGTH`][].
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf1 = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+console.log(buf1.toString('utf8'));
+// Prints: abcdefghijklmnopqrstuvwxyz
+console.log(buf1.toString('utf8', 0, 5));
+// Prints: abcde
+
+const buf2 = Buffer.from('tést');
+
+console.log(buf2.toString('hex'));
+// Prints: 74c3a97374
+console.log(buf2.toString('utf8', 0, 3));
+// Prints: té
+console.log(buf2.toString(undefined, 0, 3));
+// Prints: té
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf1 = Buffer.allocUnsafe(26);
+
+for (let i = 0; i < 26; i++) {
+ // 97 is the decimal ASCII value for 'a'.
+ buf1[i] = i + 97;
+}
+
+console.log(buf1.toString('utf8'));
+// Prints: abcdefghijklmnopqrstuvwxyz
+console.log(buf1.toString('utf8', 0, 5));
+// Prints: abcde
+
+const buf2 = Buffer.from('tést');
+
+console.log(buf2.toString('hex'));
+// Prints: 74c3a97374
+console.log(buf2.toString('utf8', 0, 3));
+// Prints: té
+console.log(buf2.toString(undefined, 0, 3));
+// Prints: té
+```
+
+#### `buf.values()`
+
+
+
+* Returns: [`Iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol)
+
+Creates and returns an [iterator][] for `buf` values (bytes). This function is
+called automatically when a `Buffer` is used in a `for..of` statement.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from('buffer');
+
+for (const value of buf.values()) {
+ console.log(value);
+}
+// Prints:
+// 98
+// 117
+// 102
+// 102
+// 101
+// 114
+
+for (const value of buf) {
+ console.log(value);
+}
+// Prints:
+// 98
+// 117
+// 102
+// 102
+// 101
+// 114
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.from('buffer');
+
+for (const value of buf.values()) {
+ console.log(value);
+}
+// Prints:
+// 98
+// 117
+// 102
+// 102
+// 101
+// 114
+
+for (const value of buf) {
+ console.log(value);
+}
+// Prints:
+// 98
+// 117
+// 102
+// 102
+// 101
+// 114
+```
+
+#### `buf.write(string[, offset[, length]][, encoding])`
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) String to write to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write `string`.
+ **Default:** `0`.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Maximum number of bytes to write (written bytes will not
+ exceed `buf.length - offset`). **Default:** `buf.length - offset`.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The character encoding of `string`. **Default:** `'utf8'`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes written.
+
+Writes `string` to `buf` at `offset` according to the character encoding in
+`encoding`. The `length` parameter is the number of bytes to write. If `buf` did
+not contain enough space to fit the entire string, only part of `string` will be
+written. However, partially encoded characters will not be written.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(256);
+
+const len = buf.write('\u00bd + \u00bc = \u00be', 0);
+
+console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
+// Prints: 12 bytes: ½ + ¼ = ¾
+
+const buffer = Buffer.alloc(10);
+
+const length = buffer.write('abcd', 8);
+
+console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
+// Prints: 2 bytes : ab
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.alloc(256);
+
+const len = buf.write('\u00bd + \u00bc = \u00be', 0);
+
+console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
+// Prints: 12 bytes: ½ + ¼ = ¾
+
+const buffer = Buffer.alloc(10);
+
+const length = buffer.write('abcd', 8);
+
+console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
+// Prints: 2 bytes : ab
+```
+
+#### `buf.writeBigInt64BE(value[, offset])`
+
+
+
+* `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian.
+
+`value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigInt64BE(0x0102030405060708n, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigInt64BE(0x0102030405060708n, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeBigInt64LE(value[, offset])`
+
+
+
+* `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian.
+
+`value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigInt64LE(0x0102030405060708n, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigInt64LE(0x0102030405060708n, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeBigUInt64BE(value[, offset])`
+
+
+
+* `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian.
+
+This function is also available under the `writeBigUint64BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeBigUInt64LE(value[, offset])`
+
+
+
+* `value` [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy: `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
+
+console.log(buf);
+// Prints:
+```
+
+This function is also available under the `writeBigUint64LE` alias.
+
+#### `buf.writeDoubleBE(value[, offset])`
+
+
+
+* `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
+must be a JavaScript number. Behavior is undefined when `value` is anything
+other than a JavaScript number.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeDoubleBE(123.456, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeDoubleBE(123.456, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeDoubleLE(value[, offset])`
+
+
+
+* `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 8`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
+must be a JavaScript number. Behavior is undefined when `value` is anything
+other than a JavaScript number.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeDoubleLE(123.456, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeDoubleLE(123.456, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeFloatBE(value[, offset])`
+
+
+
+* `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is
+undefined when `value` is anything other than a JavaScript number.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeFloatBE(0xcafebabe, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeFloatBE(0xcafebabe, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeFloatLE(value[, offset])`
+
+
+
+* `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is
+undefined when `value` is anything other than a JavaScript number.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeFloatLE(0xcafebabe, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeFloatLE(0xcafebabe, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeInt8(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset`. `value` must be a valid
+signed 8-bit integer. Behavior is undefined when `value` is anything other than
+a signed 8-bit integer.
+
+`value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt8(2, 0);
+buf.writeInt8(-2, 1);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt8(2, 0);
+buf.writeInt8(-2, 1);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeInt16BE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
+must be a valid signed 16-bit integer. Behavior is undefined when `value` is
+anything other than a signed 16-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt16BE(0x0102, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt16BE(0x0102, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeInt16LE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
+must be a valid signed 16-bit integer. Behavior is undefined when `value` is
+anything other than a signed 16-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt16LE(0x0304, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt16LE(0x0304, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeInt32BE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
+must be a valid signed 32-bit integer. Behavior is undefined when `value` is
+anything other than a signed 32-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeInt32BE(0x01020304, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeInt32BE(0x01020304, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeInt32LE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
+must be a valid signed 32-bit integer. Behavior is undefined when `value` is
+anything other than a signed 32-bit integer.
+
+The `value` is interpreted and written as a two's complement signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeInt32LE(0x05060708, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeInt32LE(0x05060708, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeIntBE(value, offset, byteLength)`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to write. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
+as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when
+`value` is anything other than a signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeIntBE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeIntBE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeIntLE(value, offset, byteLength)`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to write. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
+as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
+when `value` is anything other than a signed integer.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUInt8(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 1`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset`. `value` must be a
+valid unsigned 8-bit integer. Behavior is undefined when `value` is anything
+other than an unsigned 8-bit integer.
+
+This function is also available under the `writeUint8` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt8(0x3, 0);
+buf.writeUInt8(0x4, 1);
+buf.writeUInt8(0x23, 2);
+buf.writeUInt8(0x42, 3);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt8(0x3, 0);
+buf.writeUInt8(0x4, 1);
+buf.writeUInt8(0x23, 2);
+buf.writeUInt8(0x42, 3);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUInt16BE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
+must be a valid unsigned 16-bit integer. Behavior is undefined when `value`
+is anything other than an unsigned 16-bit integer.
+
+This function is also available under the `writeUint16BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt16BE(0xdead, 0);
+buf.writeUInt16BE(0xbeef, 2);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt16BE(0xdead, 0);
+buf.writeUInt16BE(0xbeef, 2);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUInt16LE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 2`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
+must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is
+anything other than an unsigned 16-bit integer.
+
+This function is also available under the `writeUint16LE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt16LE(0xdead, 0);
+buf.writeUInt16LE(0xbeef, 2);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt16LE(0xdead, 0);
+buf.writeUInt16LE(0xbeef, 2);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUInt32BE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as big-endian. The `value`
+must be a valid unsigned 32-bit integer. Behavior is undefined when `value`
+is anything other than an unsigned 32-bit integer.
+
+This function is also available under the `writeUint32BE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt32BE(0xfeedface, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt32BE(0xfeedface, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUInt32LE(value[, offset])`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - 4`. **Default:** `0`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `value` to `buf` at the specified `offset` as little-endian. The `value`
+must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is
+anything other than an unsigned 32-bit integer.
+
+This function is also available under the `writeUint32LE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt32LE(0xfeedface, 0);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt32LE(0xfeedface, 0);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUIntBE(value, offset, byteLength)`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to write. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
+as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined
+when `value` is anything other than an unsigned integer.
+
+This function is also available under the `writeUintBE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntBE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntBE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+#### `buf.writeUIntLE(value, offset, byteLength)`
+
+
+
+* `value` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number to be written to `buf`.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to skip before starting to write. Must
+ satisfy `0 <= offset <= buf.length - byteLength`.
+* `byteLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to write. Must satisfy
+ `0 < byteLength <= 6`.
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) `offset` plus the number of bytes written.
+
+Writes `byteLength` bytes of `value` to `buf` at the specified `offset`
+as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
+when `value` is anything other than an unsigned integer.
+
+This function is also available under the `writeUintLE` alias.
+
+```mjs|cjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+--------------
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+#### `new Buffer(array)`
+
+
+
+
+
+Deprecated: Use [`Buffer.from(array)`][] instead.
+
+
+
+* `array` integer\[] An array of bytes to copy from.
+
+See [`Buffer.from(array)`][].
+
+#### `new Buffer(arrayBuffer[, byteOffset[, length]])`
+
+
+
+
+
+Deprecated: Use [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`] instead.
+
+
+
+* `arrayBuffer` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) An [`ArrayBuffer`][],
+ [`SharedArrayBuffer`][] or the `.buffer` property of a [`TypedArray`][].
+* `byteOffset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Index of first byte to expose. **Default:** `0`.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to expose.
+ **Default:** `arrayBuffer.byteLength - byteOffset`.
+
+See
+[`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`].
+
+#### `new Buffer(buffer)`
+
+
+
+
+
+Deprecated: Use [`Buffer.from(buffer)`][] instead.
+
+
+
+* `buffer` [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) An existing `Buffer` or [`Uint8Array`][] from
+ which to copy data.
+
+See [`Buffer.from(buffer)`][].
+
+#### `new Buffer(size)`
+
+
+
+
+
+Deprecated: Use [`Buffer.alloc()`][] instead (also see [`Buffer.allocUnsafe()`][]).
+
+
+
+* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `Buffer`.
+
+See [`Buffer.alloc()`][] and [`Buffer.allocUnsafe()`][]. This variant of the
+constructor is equivalent to [`Buffer.alloc()`][].
+
+#### `new Buffer(string[, encoding])`
+
+
+
+
+
+Deprecated: Use [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] instead.
+
+
+
+* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) String to encode.
+* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding of `string`. **Default:** `'utf8'`.
+
+See [`Buffer.from(string[, encoding])`][`Buffer.from(string)`].
+
+### `File`
+
+
+
+* Extends: [`Blob`](/api/v20/buffer#blob)
+
+A [`File`][] provides information about files.
+
+#### `new buffer.File(sources, fileName[, options])`
+
+
+
+* `sources` string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[]|File\[]
+ An array of string, [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView), File, or [`Blob`](/api/v20/buffer#blob)
+ objects, or any mix of such objects, that will be stored within the `File`.
+* `fileName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the file.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `endings` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) One of either `'transparent'` or `'native'`. When set
+ to `'native'`, line endings in string source parts will be converted to
+ the platform native line-ending as specified by `require('node:os').EOL`.
+ * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The File content-type.
+ * `lastModified` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The last modified date of the file.
+ **Default:** `Date.now()`.
+
+#### `file.name`
+
+
+
+* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+The name of the `File`.
+
+#### `file.lastModified`
+
+
+
+* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+The last modified date of the `File`.
+
+### `node:buffer` module APIs
+
+While, the `Buffer` object is available as a global, there are additional
+`Buffer`-related APIs that are available only via the `node:buffer` module
+accessed using `require('node:buffer')`.
+
+#### `buffer.atob(data)`
+
+
+
+
+
+Legacy. Use `Buffer.from(data, 'base64')` instead.
+
+
+
+* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The Base64-encoded input string.
+
+Decodes a string of Base64-encoded data into bytes, and encodes those bytes
+into a string using Latin-1 (ISO-8859-1).
+
+The `data` may be any JavaScript-value that can be coerced into a string.
+
+**This function is only provided for compatibility with legacy web platform APIs
+and should never be used in new code, because they use strings to represent
+binary data and predate the introduction of typed arrays in JavaScript.
+For code running using Node.js APIs, converting between base64-encoded strings
+and binary data should be performed using `Buffer.from(str, 'base64')` and
+`buf.toString('base64')`.**
+
+#### `buffer.btoa(data)`
+
+
+
+
+
+Legacy. Use `buf.toString('base64')` instead.
+
+
+
+* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) An ASCII (Latin1) string.
+
+Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes
+into a string using Base64.
+
+The `data` may be any JavaScript-value that can be coerced into a string.
+
+**This function is only provided for compatibility with legacy web platform APIs
+and should never be used in new code, because they use strings to represent
+binary data and predate the introduction of typed arrays in JavaScript.
+For code running using Node.js APIs, converting between base64-encoded strings
+and binary data should be performed using `Buffer.from(str, 'base64')` and
+`buf.toString('base64')`.**
+
+#### `buffer.isAscii(input)`
+
+
+
+* input [`Buffer`](/api/v20/buffer#buffer) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) The input to validate.
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+This function returns `true` if `input` contains only valid ASCII-encoded data,
+including the case in which `input` is empty.
+
+Throws if the `input` is a detached array buffer.
+
+#### `buffer.isUtf8(input)`
+
+
+
+* input [`Buffer`](/api/v20/buffer#buffer) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) The input to validate.
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+This function returns `true` if `input` contains only valid UTF-8-encoded data,
+including the case in which `input` is empty.
+
+Throws if the `input` is a detached array buffer.
+
+#### `buffer.INSPECT_MAX_BYTES`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `50`
+
+Returns the maximum number of bytes that will be returned when
+`buf.inspect()` is called. This can be overridden by user modules. See
+[`util.inspect()`][] for more details on `buf.inspect()` behavior.
+
+#### `buffer.kMaxLength`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest size allowed for a single `Buffer` instance.
+
+An alias for [`buffer.constants.MAX_LENGTH`][].
+
+#### `buffer.kStringMaxLength`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest length allowed for a single `string` instance.
+
+An alias for [`buffer.constants.MAX_STRING_LENGTH`][].
+
+#### `buffer.resolveObjectURL(id)`
+
+
+
+
+
+Experimental
+
+
+
+* `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A `'blob:nodedata:...` URL string returned by a prior call to
+ `URL.createObjectURL()`.
+* Returns: [`Blob`](/api/v20/buffer#blob)
+
+Resolves a `'blob:nodedata:...'` an associated [`Blob`](/api/v20/buffer#blob) object registered using
+a prior call to `URL.createObjectURL()`.
+
+#### `buffer.transcode(source, fromEnc, toEnc)`
+
+
+
+* `source` [`Buffer`](/api/v20/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) A `Buffer` or `Uint8Array` instance.
+* `fromEnc` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The current encoding.
+* `toEnc` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) To target encoding.
+* Returns: [`Buffer`](/api/v20/buffer#buffer)
+
+Re-encodes the given `Buffer` or `Uint8Array` instance from one character
+encoding to another. Returns a new `Buffer` instance.
+
+Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if
+conversion from `fromEnc` to `toEnc` is not permitted.
+
+Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,
+`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`.
+
+The transcoding process will use substitution characters if a given byte
+sequence cannot be adequately represented in the target encoding. For instance:
+
+```mjs|cjs
+import { Buffer, transcode } from 'node:buffer';
+
+const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
+console.log(newBuf.toString('ascii'));
+// Prints: '?'
+--------------
+const { Buffer, transcode } = require('node:buffer');
+
+const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
+console.log(newBuf.toString('ascii'));
+// Prints: '?'
+```
+
+Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced
+with `?` in the transcoded `Buffer`.
+
+#### `SlowBuffer`
+
+
+
+
+
+Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.
+
+
+
+See [`Buffer.allocUnsafeSlow()`][]. This was never a class in the sense that
+the constructor always returned a `Buffer` instance, rather than a `SlowBuffer`
+instance.
+
+##### `new SlowBuffer(size)`
+
+
+
+
+
+Deprecated: Use [`Buffer.allocUnsafeSlow()`][] instead.
+
+
+
+* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The desired length of the new `SlowBuffer`.
+
+See [`Buffer.allocUnsafeSlow()`][].
+
+#### Buffer constants
+
+
+
+##### `buffer.constants.MAX_LENGTH`
+
+32 on 64-bit architectures."},{"version":"v14.0.0","pr-url":"https://github.com/nodejs/node/pull/32116","description":"Value is changed from 231 - 1 to 232 - 1 on 64-bit architectures."}],"update":{"type":"added","version":["v8.2.0"]}}} />
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest size allowed for a single `Buffer` instance.
+
+On 32-bit architectures, this value currently is 230 - 1 (about 1
+GiB).
+
+On 64-bit architectures, this value currently is 232 (about 4 GiB).
+
+It reflects [`v8::TypedArray::kMaxLength`][] under the hood.
+
+This value is also available as [`buffer.kMaxLength`][].
+
+##### `buffer.constants.MAX_STRING_LENGTH`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The largest length allowed for a single `string` instance.
+
+Represents the largest `length` that a `string` primitive can have, counted
+in UTF-16 code units.
+
+This value may depend on the JS engine that is being used.
+
+### `Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`
+
+In versions of Node.js prior to 6.0.0, `Buffer` instances were created using the
+`Buffer` constructor function, which allocates the returned `Buffer`
+differently based on what arguments are provided:
+
+* Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`)
+ allocates a new `Buffer` object of the specified size. Prior to Node.js 8.0.0,
+ the memory allocated for such `Buffer` instances is _not_ initialized and
+ _can contain sensitive data_. Such `Buffer` instances _must_ be subsequently
+ initialized by using either [`buf.fill(0)`][`buf.fill()`] or by writing to the
+ entire `Buffer` before reading data from the `Buffer`.
+ While this behavior is _intentional_ to improve performance,
+ development experience has demonstrated that a more explicit distinction is
+ required between creating a fast-but-uninitialized `Buffer` versus creating a
+ slower-but-safer `Buffer`. Since Node.js 8.0.0, `Buffer(num)` and `new
+ Buffer(num)` return a `Buffer` with initialized memory.
+* Passing a string, array, or `Buffer` as the first argument copies the
+ passed object's data into the `Buffer`.
+* Passing an [`ArrayBuffer`][] or a [`SharedArrayBuffer`][] returns a `Buffer`
+ that shares allocated memory with the given array buffer.
+
+Because the behavior of `new Buffer()` is different depending on the type of the
+first argument, security and reliability issues can be inadvertently introduced
+into applications when argument validation or `Buffer` initialization is not
+performed.
+
+For example, if an attacker can cause an application to receive a number where
+a string is expected, the application may call `new Buffer(100)`
+instead of `new Buffer("100")`, leading it to allocate a 100 byte buffer instead
+of allocating a 3 byte buffer with content `"100"`. This is commonly possible
+using JSON API calls. Since JSON distinguishes between numeric and string types,
+it allows injection of numbers where a naively written application that does not
+validate its input sufficiently might expect to always receive a string.
+Before Node.js 8.0.0, the 100 byte buffer might contain
+arbitrary pre-existing in-memory data, so may be used to expose in-memory
+secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot
+occur because the data is zero-filled. However, other attacks are still
+possible, such as causing very large buffers to be allocated by the server,
+leading to performance degradation or crashing on memory exhaustion.
+
+To make the creation of `Buffer` instances more reliable and less error-prone,
+the various forms of the `new Buffer()` constructor have been **deprecated**
+and replaced by separate `Buffer.from()`, [`Buffer.alloc()`][], and
+[`Buffer.allocUnsafe()`][] methods.
+
+_Developers should migrate all existing uses of the `new Buffer()` constructors
+to one of these new APIs._
+
+* [`Buffer.from(array)`][] returns a new `Buffer` that _contains a copy_ of the
+ provided octets.
+* [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]
+ returns a new `Buffer` that _shares the same allocated memory_ as the given
+ [`ArrayBuffer`][].
+* [`Buffer.from(buffer)`][] returns a new `Buffer` that _contains a copy_ of the
+ contents of the given `Buffer`.
+* [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new
+ `Buffer` that _contains a copy_ of the provided string.
+* [`Buffer.alloc(size[, fill[, encoding]])`][`Buffer.alloc()`] returns a new
+ initialized `Buffer` of the specified size. This method is slower than
+ [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] but guarantees that newly
+ created `Buffer` instances never contain old data that is potentially
+ sensitive. A `TypeError` will be thrown if `size` is not a number.
+* [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] and
+ [`Buffer.allocUnsafeSlow(size)`][`Buffer.allocUnsafeSlow()`] each return a
+ new uninitialized `Buffer` of the specified `size`. Because the `Buffer` is
+ uninitialized, the allocated segment of memory might contain old data that is
+ potentially sensitive.
+
+`Buffer` instances returned by [`Buffer.allocUnsafe()`][] and
+[`Buffer.from(array)`][] _may_ be allocated off a shared internal memory pool
+if `size` is less than or equal to half [`Buffer.poolSize`][]. Instances
+returned by [`Buffer.allocUnsafeSlow()`][] _never_ use the shared internal
+memory pool.
+
+#### The `--zero-fill-buffers` command-line option
+
+
+
+Node.js can be started using the `--zero-fill-buffers` command-line option to
+cause all newly-allocated `Buffer` instances to be zero-filled upon creation by
+default. Without the option, buffers created with [`Buffer.allocUnsafe()`][],
+[`Buffer.allocUnsafeSlow()`][], and `new SlowBuffer(size)` are not zero-filled.
+Use of this flag can have a measurable negative impact on performance. Use the
+`--zero-fill-buffers` option only when necessary to enforce that newly allocated
+`Buffer` instances cannot contain old data that is potentially sensitive.
+
+```console
+$ node --zero-fill-buffers
+> Buffer.allocUnsafe(5);
+
+```
+
+#### What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` "unsafe"?
+
+When calling [`Buffer.allocUnsafe()`][] and [`Buffer.allocUnsafeSlow()`][], the
+segment of allocated memory is _uninitialized_ (it is not zeroed-out). While
+this design makes the allocation of memory quite fast, the allocated segment of
+memory might contain old data that is potentially sensitive. Using a `Buffer`
+created by [`Buffer.allocUnsafe()`][] without _completely_ overwriting the
+memory can allow this old data to be leaked when the `Buffer` memory is read.
+
+While there are clear performance advantages to using
+[`Buffer.allocUnsafe()`][], extra care _must_ be taken in order to avoid
+introducing security vulnerabilities into an application.
+
+[ASCII]: https://en.wikipedia.org/wiki/ASCII
+[Base64]: https://en.wikipedia.org/wiki/Base64
+[ISO-8859-1]: https://en.wikipedia.org/wiki/ISO-8859-1
+[RFC 4648, Section 5]: https://tools.ietf.org/html/rfc4648#section-5
+[UTF-16]: https://en.wikipedia.org/wiki/UTF-16
+[UTF-8]: https://en.wikipedia.org/wiki/UTF-8
+[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/
+[`ArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
+[`Blob`]: https://developer.mozilla.org/en-US/docs/Web/API/Blob
+[`Buffer.alloc()`]: #static-method-bufferallocsize-fill-encoding
+[`Buffer.allocUnsafe()`]: #static-method-bufferallocunsafesize
+[`Buffer.allocUnsafeSlow()`]: #static-method-bufferallocunsafeslowsize
+[`Buffer.concat()`]: #static-method-bufferconcatlist-totallength
+[`Buffer.copyBytesFrom()`]: #static-method-buffercopybytesfromview-offset-length
+[`Buffer.from(array)`]: #static-method-bufferfromarray
+[`Buffer.from(arrayBuf)`]: #static-method-bufferfromarraybuffer-byteoffset-length
+[`Buffer.from(buffer)`]: #static-method-bufferfrombuffer
+[`Buffer.from(string)`]: #static-method-bufferfromstring-encoding
+[`Buffer.poolSize`]: #class-property-bufferpoolsize
+[`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView
+[`ERR_INVALID_BUFFER_SIZE`]: /api/v20/errors#err_invalid_buffer_size
+[`ERR_OUT_OF_RANGE`]: /api/v20/errors#err_out_of_range
+[`File`]: https://developer.mozilla.org/en-US/docs/Web/API/File
+[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
+[`SharedArrayBuffer`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
+[`String.prototype.indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
+[`String.prototype.lastIndexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
+[`String.prototype.length`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length
+[`TypedArray.from()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from
+[`TypedArray.prototype.set()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set
+[`TypedArray.prototype.slice()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice
+[`TypedArray.prototype.subarray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray
+[`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
+[`Uint8Array`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
+[`buf.buffer`]: #bufbuffer
+[`buf.compare()`]: #bufcomparetarget-targetstart-targetend-sourcestart-sourceend
+[`buf.entries()`]: #bufentries
+[`buf.fill()`]: #buffillvalue-offset-end-encoding
+[`buf.indexOf()`]: #bufindexofvalue-byteoffset-encoding
+[`buf.keys()`]: #bufkeys
+[`buf.length`]: #buflength
+[`buf.slice()`]: #bufslicestart-end
+[`buf.subarray`]: #bufsubarraystart-end
+[`buf.toString()`]: #buftostringencoding-start-end
+[`buf.values()`]: #bufvalues
+[`buffer.constants.MAX_LENGTH`]: #bufferconstantsmax_length
+[`buffer.constants.MAX_STRING_LENGTH`]: #bufferconstantsmax_string_length
+[`buffer.kMaxLength`]: #bufferkmaxlength
+[`util.inspect()`]: /api/v20/util#utilinspectobject-options
+[`v8::TypedArray::kMaxLength`]: https://v8.github.io/api/head/classv8_1_1TypedArray.html#a54a48f4373da0850663c4393d843b9b0
+[base64url]: https://tools.ietf.org/html/rfc4648#section-5
+[endianness]: https://en.wikipedia.org/wiki/Endianness
+[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
diff --git a/content/api/v20/child_process.en.md b/content/api/v20/child_process.en.md
new file mode 100644
index 0000000000..13ec38d6a9
--- /dev/null
+++ b/content/api/v20/child_process.en.md
@@ -0,0 +1,1638 @@
+---
+title: 'child_process'
+displayTitle: 'Child process'
+category: 'api'
+version: 'v20'
+---
+
+