diff --git a/.eslintignore b/.eslintignore
index 093b99f34c..928f056b6d 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -1,2 +1,6 @@
+.cache
public
content/blog
+content/api
+docs/
+meetings/
diff --git a/.remarkignore b/.remarkignore
new file mode 100644
index 0000000000..11c127642a
--- /dev/null
+++ b/.remarkignore
@@ -0,0 +1,4 @@
+content/api
+content/blog
+docs/
+meetings/
diff --git a/OKR.md b/OKR.md
deleted file mode 100644
index 8e162d6e92..0000000000
--- a/OKR.md
+++ /dev/null
@@ -1,39 +0,0 @@
-# Nodejs.dev Objectives and Key Results
-
-The Nodejs.dev project uses Objectives and Key Results to provide direction and guidance to the work we do, enabling our work and the work of our initiatives to have a north star for us to work towards.
-
-## Key Concepts
-
-OKRs consist of two elements:
-
-* Objectives
- * Objectives are qualitative, ambitious, and memorable definitions of the things we as a committee would like to achieve.
-* Key Results
- * Key Results are a set of metrics by which we can measure progress toward their objectives. Like objectives, they should be ambitious and overestimate what we can accomplish.
-
-### External References
-
-Here are some external references that may help provide further context on OKRs.
-
-* [Guide: Set goals with OKRs](https://rework.withgoogle.com/guides/set-goals-with-okrs/steps/introduction/)
-* [What is OKR?](https://felipecastro.com/en/okr/what-is-okr/)
-* [What Are OKRs? How to Use OKRs for Planning (and Achieving) Your Goals](https://plan.io/blog/what-are-okrs/)
-
-## OKRs (2020 Set 1):
-
-* **Objective:** Continuity of process
-
- * **Key Result:** Staging and CI each have a published technical administration summary and a how-to guide.
- * **Key Result:** Consider using issue templates to facilitate operations.
-
-* **Objective:** Identify areas of progress and future goals
-
- * **Key Result:** Create a feature roadmap
- * **Key Result:** Track features & priorities in one place (project?)
- * **Key Result:** Make available the top two features in nodejs.org:
- 1. Docs —
- 2. Download —
-
-* **Objective:** Make explicit the channels of interfacing internally and with larger org
- * **Key Result:** Write down implicit team norms
- * **Key Result:** How do we propose and review non-feature changes in PRs?
diff --git a/content/api/.gitkeep b/content/api/.gitkeep
new file mode 100644
index 0000000000..f935021a8f
--- /dev/null
+++ b/content/api/.gitkeep
@@ -0,0 +1 @@
+!.gitignore
diff --git a/content/api/v18/addons.en.md b/content/api/v18/addons.en.md
new file mode 100644
index 0000000000..a214eb545a
--- /dev/null
+++ b/content/api/v18/addons.en.md
@@ -0,0 +1,1382 @@
+---
+title: 'addons'
+displayTitle: 'C++ addons'
+category: 'api'
+editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/addons.md'
+version: 'v18'
+---
+
+
+
+
+
+_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 filesystem, 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()`.
+
+#### 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
+
+
+
+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`:
+
+```console
+$ 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/modules#requireid)
+[v8-docs]: https://v8docs.nodesource.com/
diff --git a/content/api/v18/assert.en.md b/content/api/v18/assert.en.md
new file mode 100644
index 0000000000..cb9971009d
--- /dev/null
+++ b/content/api/v18/assert.en.md
@@ -0,0 +1,2297 @@
+---
+title: 'assert'
+displayTitle: 'Assert'
+category: 'api'
+editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/assert.md'
+version: 'v18'
+---
+
+
+
+
+
+
+
+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
+import { strict as assert } from 'node:assert';
+```
+
+```cjs
+const assert = require('node:assert').strict;
+```
+
+```mjs
+import assert from 'node:assert/strict';
+```
+
+```cjs
+const assert = require('node:assert/strict');
+```
+
+Example error diff:
+
+```mjs
+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
+// ]
+```
+
+```cjs
+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
+import assert from 'node:assert';
+```
+
+```cjs
+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/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
+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);
+}
+```
+
+```cjs
+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`
+
+
+
+
+
+This feature is currently experimental and behavior might still change.
+
+#### `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
+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();
+});
+```
+
+```cjs
+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
+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);
+```
+
+```cjs
+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
+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: this, arguments: [1, 2, 3 ] }]);
+```
+
+```cjs
+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: this, 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
+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()
+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
+// }
+// ]
+```
+
+```cjs
+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()
+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
+import assert from 'node:assert';
+
+const tracker = new assert.CallTracker();
+
+function func() {}
+const callsfunc = tracker.calls(func);
+
+callsfunc();
+// Tracker was called once
+tracker.getCalls(callsfunc).length === 1;
+
+tracker.reset(callsfunc);
+tracker.getCalls(callsfunc).length === 0;
+```
+
+```cjs
+const assert = require('node:assert');
+
+function func() {}
+const callsfunc = tracker.calls(func);
+
+callsfunc();
+// Tracker was called once
+tracker.getCalls(callsfunc).length === 1;
+
+tracker.reset(callsfunc);
+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
+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();
+```
+
+```cjs
+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**
+
+
+
+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
+import assert from 'node:assert';
+// WARNING: This does not throw an AssertionError!
+
+assert.deepEqual('+00000000', false);
+```
+
+```cjs
+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
+import assert from 'node:assert';
+
+const obj1 = {
+ a: {
+ b: 1
+ }
+};
+const obj2 = {
+ a: {
+ b: 2
+ }
+};
+const obj3 = {
+ a: {
+ b: 1
+ }
+};
+const obj4 = Object.create(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 {}
+```
+
+```cjs
+const assert = require('node:assert');
+
+const obj1 = {
+ a: {
+ b: 1
+ }
+};
+const obj2 = {
+ a: {
+ b: 2
+ }
+};
+const obj3 = {
+ a: {
+ b: 1
+ }
+};
+const obj4 = Object.create(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
+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
+// }
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+import assert from 'node:assert/strict';
+
+await assert.doesNotReject(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError
+);
+```
+
+```cjs
+const assert = require('node:assert/strict');
+
+(async () => {
+ await assert.doesNotReject(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError
+ );
+})();
+```
+
+```mjs
+import assert from 'node:assert/strict';
+
+assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
+ .then(() => {
+ // ...
+ });
+```
+
+```cjs
+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
+import assert from 'node:assert/strict';
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ SyntaxError
+);
+```
+
+```cjs
+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
+import assert from 'node:assert/strict';
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ TypeError
+);
+```
+
+```cjs
+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
+import assert from 'node:assert/strict';
+
+assert.doesNotThrow(
+ () => {
+ throw new TypeError('Wrong value');
+ },
+ /Wrong value/,
+ 'Whoops'
+);
+// Throws: AssertionError: Got unwanted exception: Whoops
+```
+
+```cjs
+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**
+
+
+
+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
+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 } }
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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]]])`
+
+
+
+ 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
+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
+```
+
+```cjs
+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
+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)
+// ...
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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**
+
+
+
+Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
+
+```mjs
+import assert from 'node:assert';
+
+const obj1 = {
+ a: {
+ b: 1
+ }
+};
+const obj2 = {
+ a: {
+ b: 2
+ }
+};
+const obj3 = {
+ a: {
+ b: 1
+ }
+};
+const obj4 = Object.create(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
+```
+
+```cjs
+const assert = require('node:assert');
+
+const obj1 = {
+ a: {
+ b: 1
+ }
+};
+const obj2 = {
+ a: {
+ b: 2
+ }
+};
+const obj3 = {
+ a: {
+ b: 1
+ }
+};
+const obj4 = Object.create(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
+import assert from 'node:assert/strict';
+
+assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
+// OK
+```
+
+```cjs
+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**
+
+
+
+Tests shallow, coercive inequality with the [`!=` operator][]. `NaN` is
+specially handled and treated as being identical if both sides are `NaN`.
+
+```mjs
+import assert from 'node:assert';
+
+assert.notEqual(1, 2);
+// OK
+
+assert.notEqual(1, 1);
+// AssertionError: 1 != 1
+
+assert.notEqual(1, '1');
+// AssertionError: 1 != '1'
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+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)
+```
+
+```cjs
+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
+import assert from 'node:assert/strict';
+
+// Using `assert()` works the same:
+assert(0);
+// AssertionError: The expression evaluated to a falsy value:
+//
+// assert(0)
+```
+
+```cjs
+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
+import assert from 'node:assert/strict';
+
+await assert.rejects(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ {
+ name: 'TypeError',
+ message: 'Wrong value'
+ }
+);
+```
+
+```cjs
+const assert = require('node:assert/strict');
+
+(async () => {
+ await assert.rejects(
+ async () => {
+ throw new TypeError('Wrong value');
+ },
+ {
+ name: 'TypeError',
+ message: 'Wrong value'
+ }
+ );
+})();
+```
+
+```mjs
+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;
+ }
+);
+```
+
+```cjs
+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
+import assert from 'node:assert/strict';
+
+assert.rejects(
+ Promise.reject(new Error('Wrong value')),
+ Error
+).then(() => {
+ // ...
+});
+```
+
+```cjs
+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.snapshot(value, name)`
+
+
+
+
+
+* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) the value to snapshot
+* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) the name of snapshot.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+
+reads a snapshot from a file, and compares `value` to the snapshot.
+`value` is serialized with [`util.inspect()`][]
+If the value is not strictly equal to the snapshot,
+`assert.snapshot()` will return a rejected `Promise`
+with an [`AssertionError`][].
+
+If the snapshot file does not exist, the snapshot is written.
+
+In case it is needed to force a snapshot update,
+use [`--update-assert-snapshot`][];
+
+By default, a snapshot is read and written to a file,
+using the same name as the main entrypoint with `.snapshot` as the extension.
+
+### `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
+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
+```
+
+```cjs
+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
+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
+);
+```
+
+```cjs
+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
+import assert from 'node:assert/strict';
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ Error
+);
+```
+
+```cjs
+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
+import assert from 'node:assert/strict';
+
+assert.throws(
+ () => {
+ throw new Error('Wrong value');
+ },
+ /^Error: Wrong value$/
+);
+```
+
+```cjs
+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
+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'
+);
+```
+
+```cjs
+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
+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]
+```
+
+```cjs
+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
+[`--update-assert-snapshot`]: (/api/cli#--update-assert-snapshot)
+[`===` 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/errors#err_invalid_return_value)
+[`Error.captureStackTrace`]: (/api/errors#errorcapturestacktracetargetobject-constructoropt)
+[`Error`]: (/api/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/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/tty#writestreamgetcolordepthenv)
+[`process.on('exit')`]: (/api/process#event-exit)
+[`tracker.calls()`]: #trackercallsfn-exact
+[`tracker.verify()`]: #trackerverify
+[`util.inspect()`]: (/api/util#utilinspectobject-options)
+[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/v18/async_context.en.md b/content/api/v18/async_context.en.md
new file mode 100644
index 0000000000..0bd163f87e
--- /dev/null
+++ b/content/api/v18/async_context.en.md
@@ -0,0 +1,758 @@
+---
+title: 'async_context'
+displayTitle: 'Asynchronous context tracking'
+category: 'api'
+editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/async_context.md'
+version: 'v18'
+---
+
+
+
+
+
+
+
+### 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
+import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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.
+
+#### `asyncLocalStorage.disable()`
+
+
+
+
+
+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)`
+
+
+
+
+
+* `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])`
+
+
+
+
+
+* `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
+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();
+```
+
+```cjs
+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.
+
+The returned function will have an `asyncResource` property referencing
+the `AsyncResource` to which the function is bound.
+
+#### `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.
+
+The returned function will have an `asyncResource` property referencing
+the `AsyncResource` to which the function is bound.
+
+#### `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/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
+import { parentPort } from 'node:worker_threads';
+parentPort.on('message', (task) => {
+ parentPort.postMessage(task.a + task.b);
+});
+```
+
+```cjs
+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
+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_processer.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();
+ }
+}
+```
+
+```cjs
+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
+import WorkerPool from './worker_pool.js';
+import os from 'node:os';
+
+const pool = new WorkerPool(os.cpus().length);
+
+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();
+ });
+}
+```
+
+```cjs
+const WorkerPool = require('./worker_pool.js');
+const os = require('node:os');
+
+const pool = new WorkerPool(os.cpus().length);
+
+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
+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);
+```
+
+```cjs
+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/events#class-eventemitter)
+[`Stream`]: (/api/stream#stream)
+[`Worker`]: worker_threads.md#class-worker
+[`util.promisify()`]: (/api/util#utilpromisifyoriginal)
diff --git a/content/api/v18/async_hooks.en.md b/content/api/v18/async_hooks.en.md
new file mode 100644
index 0000000000..41508f2d3f
--- /dev/null
+++ b/content/api/v18/async_hooks.en.md
@@ -0,0 +1,865 @@
+---
+title: 'async_hooks'
+displayTitle: 'Async hooks'
+category: 'api'
+editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/async_hooks.md'
+version: 'v18'
+---
+
+
+
+
+
+
+
+The `node:async_hooks` module provides an API to track asynchronous resources.
+It can be accessed using:
+
+```mjs
+import async_hooks from 'node:async_hooks';
+```
+
+```cjs
+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
+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) { }
+```
+
+```cjs
+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/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
+import { createHook } from 'node:async_hooks';
+
+const asyncHook = createHook({
+ init(asyncId, type, triggerAsyncId, resource) { },
+ destroy(asyncId) { }
+});
+```
+
+```cjs
+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
+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' });
+}
+```
+
+```cjs
+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/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
+import { createHook } from 'node:async_hooks';
+
+const hook = createHook(callbacks).enable();
+```
+
+```cjs
+const async_hooks = require('node:async_hooks');
+
+const hook = async_hooks.createHook(callbacks).enable();
+```
+
+#### `asyncHook.disable()`
+
+* Returns: [`AsyncHook`](/api/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
+import { createServer } from 'node:net';
+
+createServer().listen(function() { this.close(); });
+// OR
+clearTimeout(setTimeout(() => {}, 10));
+```
+
+```cjs
+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.
+
+Valid values are:
+
+```text
+FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,
+HTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,
+SHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,
+TTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,
+RANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject
+```
+
+These values can change in any Node.js release. Furthermore users of [`AsyncResource`][]
+likely provide other values.
+
+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
+import { createHook, executionAsyncId } from 'node:async_hooks';
+import { stdout } from 'node:process';
+import net from 'node:net';
+
+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);
+```
+
+```cjs
+const { createHook, executionAsyncId } = require('node:async_hooks');
+const { stdout } = require('node:process');
+const net = require('node:net');
+
+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. This can contain useful information that can vary based on
+the value of `type`. For instance, for the `GETADDRINFOREQWRAP` resource type,
+`resource` provides the host name used when looking up the IP address for the
+host in `net.Server.listen()`. The API for accessing this information is
+not supported, but using the Embedder API, users can provide
+and document their own resource objects. For example, such a resource object
+could contain the SQL query being executed.
+
+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 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.
+
+```js
+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, `$indentStrbefore: $asyncId\n`);
+ indent += 2;
+ },
+ after(asyncId) {
+ indent -= 2;
+ const indentStr = ' '.repeat(indent);
+ fs.writeSync(fd, `$indentStrafter: $asyncId\n`);
+ },
+ destroy(asyncId) {
+ const indentStr = ' '.repeat(indent);
+ fs.writeSync(fd, `$indentStrdestroy: $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.
+
+##### `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
+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
+});
+```
+
+```cjs
+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
+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);
+```
+
+```cjs
+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
+import { executionAsyncId } from 'node:async_hooks';
+
+console.log(executionAsyncId()); // 1 - bootstrap
+fs.open(path, 'r', (err, fd) => {
+ console.log(executionAsyncId()); // 6 - open()
+});
+```
+
+```cjs
+const async_hooks = require('node:async_hooks');
+
+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
+import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
+
+Promise.resolve(1729).then(() => {
+ console.log(`eid ${executionAsyncId()} tid ${triggerAsyncId()}`);
+});
+// produces:
+// eid 1 tid 0
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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/deprecations#dep0111-processbinding)
+[Hook Callbacks]: #hook-callbacks
+[PromiseHooks]: https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit
+[`AsyncLocalStorage`]: async_context.md#class-asynclocalstorage
+[`AsyncResource`]: async_context.md#class-asyncresource
+[`Worker`]: worker_threads.md#class-worker
+[`after` callback]: #afterasyncid
+[`before` callback]: #beforeasyncid
+[`destroy` callback]: #destroyasyncid
+[`init` callback]: #initasyncid-type-triggerasyncid-resource
+[`promiseResolve` callback]: #promiseresolveasyncid
+[promise execution tracking]: #promise-execution-tracking
diff --git a/content/api/v18/buffer.en.md b/content/api/v18/buffer.en.md
new file mode 100644
index 0000000000..1a6dec5bff
--- /dev/null
+++ b/content/api/v18/buffer.en.md
@@ -0,0 +1,4668 @@
+---
+title: 'buffer'
+displayTitle: 'Buffer'
+category: 'api'
+editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/buffer.md'
+version: 'v18'
+---
+
+
+
+
+
+
+
+`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
+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');
+```
+
+```cjs
+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
+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:
+```
+
+```cjs
+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'`. See [binary strings][] for more background
+ on this topic. 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
+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.
+```
+
+```cjs
+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
+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 ]
+```
+
+```cjs
+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
+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 ]
+```
+
+```cjs
+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
+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:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const arr = new Uint16Array(20);
+const buf = Buffer.from(arr.buffer, 0, 16);
+
+console.log(buf.length);
+// Prints: 16
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3]);
+
+for (const b of buf) {
+ console.log(b);
+}
+// Prints:
+// 1
+// 2
+// 3
+```
+
+```cjs
+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/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/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/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/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
+import { Blob, Buffer } 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);
+```
+
+```cjs
+const { Blob, Buffer } = 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|Buffer|Uint8Array|integer} 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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(5);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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_INVALID_ARG_VALUE`][]
+is thrown.
+
+If `fill` is specified, the allocated `Buffer` will be initialized by calling
+[`buf.fill(fill)`][`buf.fill()`].
+
+```mjs
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(5, 'a');
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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_INVALID_ARG_VALUE`][]
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(10);
+
+console.log(buf);
+// Prints (contents may vary):
+
+buf.fill(0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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)`][], [`Buffer.concat()`][], and the deprecated
+`new Buffer(size)` constructor 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_INVALID_ARG_VALUE`][]
+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
+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);
+ }
+});
+```
+
+```cjs
+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/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
+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
+```
+
+```cjs
+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|Uint8Array}
+* `buf2` {Buffer|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
+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].)
+```
+
+```cjs
+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/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
+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
+```
+
+```cjs
+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.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
+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]);
+```
+
+```cjs
+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]);
+```
+
+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
+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:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const ab = new ArrayBuffer(10);
+const buf = Buffer.from(ab, 0, 2);
+
+console.log(buf.length);
+// Prints: 2
+```
+
+```cjs
+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
+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:
+```
+
+```cjs
+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|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from
+ which to copy data.
+
+Copies the passed `buffer` data onto a new `Buffer` instance.
+
+```mjs
+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
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from(new String('this is a test'));
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+class Foo {
+ [Symbol.toPrimitive]() {
+ return 'this is a test';
+ }
+}
+
+const buf = Buffer.from(new Foo(), 'utf8');
+// Prints:
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const arrayBuffer = new ArrayBuffer(16);
+const buffer = Buffer.from(arrayBuffer);
+
+console.log(buffer.buffer === arrayBuffer);
+// Prints: true
+```
+
+```cjs
+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
+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);
+```
+
+```cjs
+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|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
+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].)
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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|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
+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!!!!!!!!!!!!!
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+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]
+```
+
+```cjs
+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|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
+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
+```
+
+```cjs
+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|Buffer|Uint8Array|integer} The value with which to fill `buf`.
+* `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/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
+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
+```
+
+```cjs
+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
+```
+
+`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
+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:
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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|Buffer|Uint8Array|integer} 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
+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
+```
+
+```cjs
+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|Buffer|Uint8Array|integer} 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
+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
+```
+
+```cjs
+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
+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', []));
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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|Buffer|Uint8Array|integer} 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
+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
+```
+
+```cjs
+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
+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', []));
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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`
+
+
+
+
+
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
+
+console.log(buf.readBigUInt64BE(0));
+// Prints: 4294967295n
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
+
+console.log(buf.readBigUInt64LE(0));
+// Prints: 18446744069414584320n
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([1, 2, 3, 4]);
+
+console.log(buf.readFloatBE(0));
+// Prints: 2.387939260590663e-38
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0, 5]);
+
+console.log(buf.readInt16BE(0));
+// Prints: 5
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0, 0, 0, 5]);
+
+console.log(buf.readInt32BE(0));
+// Prints: 5
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
+
+console.log(buf.readUInt32BE(0).toString(16));
+// Prints: 12345678
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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/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
+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
+```
+
+```cjs
+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
+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).)
+```
+
+```cjs
+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/buffer#buffer)
+
+
+
+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
+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 (!)
+```
+
+```cjs
+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/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
+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.
+```
+
+```cjs
+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
+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.
+```
+
+```cjs
+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/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
+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.
+```
+
+```cjs
+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/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
+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.
+```
+
+```cjs
+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
+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:
+```
+
+```cjs
+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
+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é
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+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
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigInt64BE(0x0102030405060708n, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigInt64LE(0x0102030405060708n, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeDoubleBE(123.456, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(8);
+
+buf.writeDoubleLE(123.456, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeFloatBE(0xcafebabe, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeFloatLE(0xcafebabe, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt8(2, 0);
+buf.writeInt8(-2, 1);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt16BE(0x0102, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(2);
+
+buf.writeInt16LE(0x0304, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeInt32BE(0x01020304, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeInt32LE(0x05060708, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeIntBE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+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:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt16BE(0xdead, 0);
+buf.writeUInt16BE(0xbeef, 2);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt16LE(0xdead, 0);
+buf.writeUInt16LE(0xbeef, 2);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt32BE(0xfeedface, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(4);
+
+buf.writeUInt32LE(0xfeedface, 0);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntBE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+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
+import { Buffer } from 'node:buffer';
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+```cjs
+const { Buffer } = require('node:buffer');
+
+const buf = Buffer.allocUnsafe(6);
+
+buf.writeUIntLE(0x1234567890ab, 0, 6);
+
+console.log(buf);
+// Prints:
+```
+
+#### `new Buffer(array)`
+
+
+
+
+
+* `array` integer\[] An array of bytes to copy from.
+
+See [`Buffer.from(array)`][].
+
+#### `new Buffer(arrayBuffer[, byteOffset[, length]])`
+
+
+
+ [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`]\n> 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)`
+
+
+
+
+
+* `buffer` {Buffer|Uint8Array} An existing `Buffer` or [`Uint8Array`][] from
+ which to copy data.
+
+See [`Buffer.from(buffer)`][].
+
+#### `new Buffer(size)`
+
+
+
+ [`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])`
+
+
+
+ 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)`].
+
+### `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)`
+
+
+
+
+
+* `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)`
+
+
+
+
+
+* `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.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)`
+
+
+
+
+
+* `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/buffer#blob)
+
+Resolves a `'blob:nodedata:...'` an associated [`Blob`](/api/buffer#blob) object registered using
+a prior call to `URL.createObjectURL()`.
+
+#### `buffer.transcode(source, fromEnc, toEnc)`
+
+
+
+* `source` {Buffer|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/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
+import { Buffer, transcode } from 'node:buffer';
+
+const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
+console.log(newBuf.toString('ascii'));
+// Prints: '?'
+```
+
+```cjs
+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`
+
+
+
+
+
+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)`
+
+
+
+
+
+* `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.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_ARG_VALUE`]: (/api/errors#err_invalid_arg_value)
+[`ERR_INVALID_BUFFER_SIZE`]: (/api/errors#err_invalid_buffer_size)
+[`ERR_OUT_OF_RANGE`]: (/api/errors#err_out_of_range)
+[`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/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
+[binary strings]: https://developer.mozilla.org/en-US/docs/Web/API/DOMString/Binary
+[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/v18/child_process.en.md b/content/api/v18/child_process.en.md
new file mode 100644
index 0000000000..f5d3a88d96
--- /dev/null
+++ b/content/api/v18/child_process.en.md
@@ -0,0 +1,1636 @@
+---
+title: 'child_process'
+displayTitle: 'Child process'
+category: 'api'
+editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/child_process.md'
+version: 'v18'
+---
+
+
+
+
+
+
+
+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
+is primarily provided by the [`child_process.spawn()`][] function:
+
+```js
+const { spawn } = require('node:child_process');
+const ls = spawn('ls', ['-lh', '/usr']);
+
+ls.stdout.on('data', (data) => {
+ console.log(`stdout: $data`);
+});
+
+ls.stderr.on('data', (data) => {
+ console.error(`stderr: $data`);
+});
+
+ls.on('close', (code) => {
+ console.log(`child process exited with code $code`);
+});
+```
+
+By default, pipes for `stdin`, `stdout`, and `stderr` are established between
+the parent Node.js process and the spawned subprocess. These pipes have
+limited (and platform-specific) capacity. If the subprocess writes to
+stdout in excess of that limit without the output being captured, the
+subprocess blocks waiting for the pipe buffer to accept more data. This is
+identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }`
+option if the output will not be consumed.
+
+The command lookup is performed using the `options.env.PATH` environment
+variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is
+used. If `options.env` is set without `PATH`, lookup on Unix is performed
+on a default search path search of `/usr/bin:/bin` (see your operating system's
+manual for execvpe/execvp), on Windows the current processes environment
+variable `PATH` is used.
+
+On Windows, environment variables are case-insensitive. Node.js
+lexicographically sorts the `env` keys and uses the first one that
+case-insensitively matches. Only first (in lexicographic order) entry will be
+passed to the subprocess. This might lead to issues on Windows when passing
+objects to the `env` option that have multiple variants of the same key, such as
+`PATH` and `Path`.
+
+The [`child_process.spawn()`][] method spawns the child process asynchronously,
+without blocking the Node.js event loop. The [`child_process.spawnSync()`][]
+function provides equivalent functionality in a synchronous manner that blocks
+the event loop until the spawned process either exits or is terminated.
+
+For convenience, the `node:child_process` module provides a handful of
+synchronous and asynchronous alternatives to [`child_process.spawn()`][] and
+[`child_process.spawnSync()`][]. Each of these alternatives are implemented on
+top of [`child_process.spawn()`][] or [`child_process.spawnSync()`][].
+
+* [`child_process.exec()`][]: spawns a shell and runs a command within that
+ shell, passing the `stdout` and `stderr` to a callback function when
+ complete.
+* [`child_process.execFile()`][]: similar to [`child_process.exec()`][] except
+ that it spawns the command directly without first spawning a shell by
+ default.
+* [`child_process.fork()`][]: spawns a new Node.js process and invokes a
+ specified module with an IPC communication channel established that allows
+ sending messages between parent and child.
+* [`child_process.execSync()`][]: a synchronous version of
+ [`child_process.exec()`][] that will block the Node.js event loop.
+* [`child_process.execFileSync()`][]: a synchronous version of
+ [`child_process.execFile()`][] that will block the Node.js event loop.
+
+For certain use cases, such as automating shell scripts, the
+[synchronous counterparts][] may be more convenient. In many cases, however,
+the synchronous methods can have significant impact on performance due to
+stalling the event loop while spawned processes complete.
+
+### Asynchronous process creation
+
+The [`child_process.spawn()`][], [`child_process.fork()`][], [`child_process.exec()`][],
+and [`child_process.execFile()`][] methods all follow the idiomatic asynchronous
+programming pattern typical of other Node.js APIs.
+
+Each of the methods returns a [`ChildProcess`][] instance. These objects
+implement the Node.js [`EventEmitter`][] API, allowing the parent process to
+register listener functions that are called when certain events occur during
+the life cycle of the child process.
+
+The [`child_process.exec()`][] and [`child_process.execFile()`][] methods
+additionally allow for an optional `callback` function to be specified that is
+invoked when the child process terminates.
+
+#### Spawning `.bat` and `.cmd` files on Windows
+
+The importance of the distinction between [`child_process.exec()`][] and
+[`child_process.execFile()`][] can vary based on platform. On Unix-type
+operating systems (Unix, Linux, macOS) [`child_process.execFile()`][] can be
+more efficient because it does not spawn a shell by default. On Windows,
+however, `.bat` and `.cmd` files are not executable on their own without a
+terminal, and therefore cannot be launched using [`child_process.execFile()`][].
+When running on Windows, `.bat` and `.cmd` files can be invoked using
+[`child_process.spawn()`][] with the `shell` option set, with
+[`child_process.exec()`][], or by spawning `cmd.exe` and passing the `.bat` or
+`.cmd` file as an argument (which is what the `shell` option and
+[`child_process.exec()`][] do). In any case, if the script filename contains
+spaces it needs to be quoted.
+
+```js
+// On Windows Only...
+const { spawn } = require('node:child_process');
+const bat = spawn('cmd.exe', ['/c', 'my.bat']);
+
+bat.stdout.on('data', (data) => {
+ console.log(data.toString());
+});
+
+bat.stderr.on('data', (data) => {
+ console.error(data.toString());
+});
+
+bat.on('exit', (code) => {
+ console.log(`Child exited with code $code`);
+});
+```
+
+```js
+// OR...
+const { exec, spawn } = require('node:child_process');
+exec('my.bat', (err, stdout, stderr) => {
+ if (err) {
+ console.error(err);
+ return;
+ }
+ console.log(stdout);
+});
+
+// Script with spaces in the filename:
+const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true });
+// or:
+exec('"my script.cmd" a b', (err, stdout, stderr) => {
+ // ...
+});
+```
+
+#### `child_process.exec(command[, options][, callback])`
+
+
+
+* `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run, with space-separated arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Current working directory of the child process.
+ **Default:** `process.cwd()`.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
+ * `shell` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Shell to execute the command with. See
+ [Shell requirements][] and [Default Windows shell][]. **Default:**
+ `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.
+ * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting the child process using an
+ AbortSignal.
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
+ * `maxBuffer` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Largest amount of data in bytes allowed on stdout or
+ stderr. If exceeded, the child process is terminated and any output is
+ truncated. See caveat at [`maxBuffer` and Unicode][].
+ **Default:** `1024 * 1024`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `'SIGTERM'`
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) called with the output when process terminates.
+ * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+ * `stdout` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+ * `stderr` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* Returns: [`ChildProcess`](/api/child_process#childprocess)
+
+Spawns a shell then executes the `command` within that shell, buffering any
+generated output. The `command` string passed to the exec function is processed
+directly by the shell and special characters (vary based on
+[shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters))
+need to be dealt with accordingly:
+
+```js
+const { exec } = require('node:child_process');
+
+exec('"/path/to/test file/test.sh" arg1 arg2');
+// Double quotes are used so that the space in the path is not interpreted as
+// a delimiter of multiple arguments.
+
+exec('echo "The \\$HOME variable is $HOME"');
+// The $HOME variable is escaped in the first instance, but not in the second.
+```
+
+**Never pass unsanitized user input to this function. Any input containing shell
+metacharacters may be used to trigger arbitrary command execution.**
+
+If a `callback` function is provided, it is called with the arguments
+`(error, stdout, stderr)`. On success, `error` will be `null`. On error,
+`error` will be an instance of [`Error`][]. The `error.code` property will be
+the exit code of the process. By convention, any exit code other than `0`
+indicates an error. `error.signal` will be the signal that terminated the
+process.
+
+The `stdout` and `stderr` arguments passed to the callback will contain the
+stdout and stderr output of the child process. By default, Node.js will decode
+the output as UTF-8 and pass strings to the callback. The `encoding` option
+can be used to specify the character encoding used to decode the stdout and
+stderr output. If `encoding` is `'buffer'`, or an unrecognized character
+encoding, `Buffer` objects will be passed to the callback instead.
+
+```js
+const { exec } = require('node:child_process');
+exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
+ if (error) {
+ console.error(`exec error: $error`);
+ return;
+ }
+ console.log(`stdout: $stdout`);
+ console.error(`stderr: $stderr`);
+});
+```
+
+If `timeout` is greater than `0`, the parent will send the signal
+identified by the `killSignal` property (the default is `'SIGTERM'`) if the
+child runs longer than `timeout` milliseconds.
+
+Unlike the exec(3) POSIX system call, `child_process.exec()` does not replace
+the existing process and uses a shell to execute the command.
+
+If this method is invoked as its [`util.promisify()`][]ed version, it returns
+a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned
+`ChildProcess` instance is attached to the `Promise` as a `child` property. In
+case of an error (including any error resulting in an exit code other than 0), a
+rejected promise is returned, with the same `error` object given in the
+callback, but with two additional properties `stdout` and `stderr`.
+
+```js
+const util = require('node:util');
+const exec = util.promisify(require('node:child_process').exec);
+
+async function lsExample() {
+ const { stdout, stderr } = await exec('ls');
+ console.log('stdout:', stdout);
+ console.error('stderr:', stderr);
+}
+lsExample();
+```
+
+If the `signal` option is enabled, calling `.abort()` on the corresponding
+`AbortController` is similar to calling `.kill()` on the child process except
+the error passed to the callback will be an `AbortError`:
+
+```js
+const { exec } = require('node:child_process');
+const controller = new AbortController();
+const { signal } = controller;
+const child = exec('grep ssh', { signal }, (error) => {
+ console.log(error); // an AbortError
+});
+controller.abort();
+```
+
+#### `child_process.execFile(file[, args][, options][, callback])`
+
+
+
+* `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name or path of the executable file to run.
+* `args` string\[] List of string arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Current working directory of the child process.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
+ * `maxBuffer` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Largest amount of data in bytes allowed on stdout or
+ stderr. If exceeded, the child process is terminated and any output is
+ truncated. See caveat at [`maxBuffer` and Unicode][].
+ **Default:** `1024 * 1024`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `'SIGTERM'`
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+ * `windowsVerbatimArguments` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) No quoting or escaping of arguments is
+ done on Windows. Ignored on Unix. **Default:** `false`.
+ * `shell` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `true`, runs `command` inside of a shell. Uses
+ `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
+ shell can be specified as a string. See [Shell requirements][] and
+ [Default Windows shell][]. **Default:** `false` (no shell).
+ * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting the child process using an
+ AbortSignal.
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called with the output when process terminates.
+ * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+ * `stdout` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+ * `stderr` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* Returns: [`ChildProcess`](/api/child_process#childprocess)
+
+The `child_process.execFile()` function is similar to [`child_process.exec()`][]
+except that it does not spawn a shell by default. Rather, the specified
+executable `file` is spawned directly as a new process making it slightly more
+efficient than [`child_process.exec()`][].
+
+The same options as [`child_process.exec()`][] are supported. Since a shell is
+not spawned, behaviors such as I/O redirection and file globbing are not
+supported.
+
+```js
+const { execFile } = require('node:child_process');
+const child = execFile('node', ['--version'], (error, stdout, stderr) => {
+ if (error) {
+ throw error;
+ }
+ console.log(stdout);
+});
+```
+
+The `stdout` and `stderr` arguments passed to the callback will contain the
+stdout and stderr output of the child process. By default, Node.js will decode
+the output as UTF-8 and pass strings to the callback. The `encoding` option
+can be used to specify the character encoding used to decode the stdout and
+stderr output. If `encoding` is `'buffer'`, or an unrecognized character
+encoding, `Buffer` objects will be passed to the callback instead.
+
+If this method is invoked as its [`util.promisify()`][]ed version, it returns
+a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned
+`ChildProcess` instance is attached to the `Promise` as a `child` property. In
+case of an error (including any error resulting in an exit code other than 0), a
+rejected promise is returned, with the same `error` object given in the
+callback, but with two additional properties `stdout` and `stderr`.
+
+```js
+const util = require('node:util');
+const execFile = util.promisify(require('node:child_process').execFile);
+async function getVersion() {
+ const { stdout } = await execFile('node', ['--version']);
+ console.log(stdout);
+}
+getVersion();
+```
+
+**If the `shell` option is enabled, do not pass unsanitized user input to this
+function. Any input containing shell metacharacters may be used to trigger
+arbitrary command execution.**
+
+If the `signal` option is enabled, calling `.abort()` on the corresponding
+`AbortController` is similar to calling `.kill()` on the child process except
+the error passed to the callback will be an `AbortError`:
+
+```js
+const { execFile } = require('node:child_process');
+const controller = new AbortController();
+const { signal } = controller;
+const child = execFile('node', ['--version'], { signal }, (error) => {
+ console.log(error); // an AbortError
+});
+controller.abort();
+```
+
+#### `child_process.fork(modulePath[, args][, options])`
+
+
+
+* `modulePath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) The module to run in the child.
+* `args` string\[] List of string arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Current working directory of the child process.
+ * `detached` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Prepare child to run independently of its parent
+ process. Specific behavior depends on the platform, see
+ [`options.detached`][]).
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `execPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Executable used to create the child process.
+ * `execArgv` string\[] List of string arguments passed to the executable.
+ **Default:** `process.execArgv`.
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `serialization` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Specify the kind of serialization used for sending
+ messages between processes. Possible values are `'json'` and `'advanced'`.
+ See [Advanced serialization][] for more details. **Default:** `'json'`.
+ * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows closing the child process using an
+ AbortSignal.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal value to be used when the spawned
+ process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`.
+ * `silent` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, stdin, stdout, and stderr of the child will be
+ piped to the parent, otherwise they will be inherited from the parent, see
+ the `'pipe'` and `'inherit'` options for [`child_process.spawn()`][]'s
+ [`stdio`][] for more details. **Default:** `false`.
+ * `stdio` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [`child_process.spawn()`][]'s [`stdio`][].
+ When this option is provided, it overrides `silent`. If the array variant
+ is used, it must contain exactly one item with value `'ipc'` or an error
+ will be thrown. For instance `[0, 1, 2, 'ipc']`.
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `windowsVerbatimArguments` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) No quoting or escaping of arguments is
+ done on Windows. Ignored on Unix. **Default:** `false`.
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) In milliseconds the maximum amount of time the process
+ is allowed to run. **Default:** `undefined`.
+* Returns: [`ChildProcess`](/api/child_process#childprocess)
+
+The `child_process.fork()` method is a special case of
+[`child_process.spawn()`][] used specifically to spawn new Node.js processes.
+Like [`child_process.spawn()`][], a [`ChildProcess`][] object is returned. The
+returned [`ChildProcess`][] will have an additional communication channel
+built-in that allows messages to be passed back and forth between the parent and
+child. See [`subprocess.send()`][] for details.
+
+Keep in mind that spawned Node.js child processes are
+independent of the parent with exception of the IPC communication channel
+that is established between the two. Each process has its own memory, with
+their own V8 instances. Because of the additional resource allocations
+required, spawning a large number of child Node.js processes is not
+recommended.
+
+By default, `child_process.fork()` will spawn new Node.js instances using the
+[`process.execPath`][] of the parent process. The `execPath` property in the
+`options` object allows for an alternative execution path to be used.
+
+Node.js processes launched with a custom `execPath` will communicate with the
+parent process using the file descriptor (fd) identified using the
+environment variable `NODE_CHANNEL_FD` on the child process.
+
+Unlike the fork(2) POSIX system call, `child_process.fork()` does not clone the
+current process.
+
+The `shell` option available in [`child_process.spawn()`][] is not supported by
+`child_process.fork()` and will be ignored if set.
+
+If the `signal` option is enabled, calling `.abort()` on the corresponding
+`AbortController` is similar to calling `.kill()` on the child process except
+the error passed to the callback will be an `AbortError`:
+
+```js
+if (process.argv[2] === 'child') {
+ setTimeout(() => {
+ console.log(`Hello from ${process.argv[2]}!`);
+ }, 1_000);
+} else {
+ const { fork } = require('node:child_process');
+ const controller = new AbortController();
+ const { signal } = controller;
+ const child = fork(__filename, ['child'], { signal });
+ child.on('error', (err) => {
+ // This will be called with err being an AbortError if the controller aborts
+ });
+ controller.abort(); // Stops the child process
+}
+```
+
+#### `child_process.spawn(command[, args][, options])`
+
+
+
+* `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run.
+* `args` string\[] List of string arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Current working directory of the child process.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `argv0` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Explicitly set the value of `argv[0]` sent to the child
+ process. This will be set to `command` if not specified.
+ * `stdio` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Child's stdio configuration (see
+ [`options.stdio`][`stdio`]).
+ * `detached` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Prepare child to run independently of its parent
+ process. Specific behavior depends on the platform, see
+ [`options.detached`][]).
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `serialization` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Specify the kind of serialization used for sending
+ messages between processes. Possible values are `'json'` and `'advanced'`.
+ See [Advanced serialization][] for more details. **Default:** `'json'`.
+ * `shell` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `true`, runs `command` inside of a shell. Uses
+ `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
+ shell can be specified as a string. See [Shell requirements][] and
+ [Default Windows shell][]. **Default:** `false` (no shell).
+ * `windowsVerbatimArguments` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) No quoting or escaping of arguments is
+ done on Windows. Ignored on Unix. This is set to `true` automatically
+ when `shell` is specified and is CMD. **Default:** `false`.
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+ * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting the child process using an
+ AbortSignal.
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) In milliseconds the maximum amount of time the process
+ is allowed to run. **Default:** `undefined`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal value to be used when the spawned
+ process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`.
+* Returns: [`ChildProcess`](/api/child_process#childprocess)
+
+The `child_process.spawn()` method spawns a new process using the given
+`command`, with command-line arguments in `args`. If omitted, `args` defaults
+to an empty array.
+
+**If the `shell` option is enabled, do not pass unsanitized user input to this
+function. Any input containing shell metacharacters may be used to trigger
+arbitrary command execution.**
+
+A third argument may be used to specify additional options, with these defaults:
+
+```js
+const defaults = {
+ cwd: undefined,
+ env: process.env
+};
+```
+
+Use `cwd` to specify the working directory from which the process is spawned.
+If not given, the default is to inherit the current working directory. If given,
+but the path does not exist, the child process emits an `ENOENT` error
+and exits immediately. `ENOENT` is also emitted when the command
+does not exist.
+
+Use `env` to specify environment variables that will be visible to the new
+process, the default is [`process.env`][].
+
+`undefined` values in `env` will be ignored.
+
+Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the
+exit code:
+
+```js
+const { spawn } = require('node:child_process');
+const ls = spawn('ls', ['-lh', '/usr']);
+
+ls.stdout.on('data', (data) => {
+ console.log(`stdout: $data`);
+});
+
+ls.stderr.on('data', (data) => {
+ console.error(`stderr: $data`);
+});
+
+ls.on('close', (code) => {
+ console.log(`child process exited with code $code`);
+});
+```
+
+Example: A very elaborate way to run `ps ax | grep ssh`
+
+```js
+const { spawn } = require('node:child_process');
+const ps = spawn('ps', ['ax']);
+const grep = spawn('grep', ['ssh']);
+
+ps.stdout.on('data', (data) => {
+ grep.stdin.write(data);
+});
+
+ps.stderr.on('data', (data) => {
+ console.error(`ps stderr: $data`);
+});
+
+ps.on('close', (code) => {
+ if (code !== 0) {
+ console.log(`ps process exited with code $code`);
+ }
+ grep.stdin.end();
+});
+
+grep.stdout.on('data', (data) => {
+ console.log(data.toString());
+});
+
+grep.stderr.on('data', (data) => {
+ console.error(`grep stderr: $data`);
+});
+
+grep.on('close', (code) => {
+ if (code !== 0) {
+ console.log(`grep process exited with code $code`);
+ }
+});
+```
+
+Example of checking for failed `spawn`:
+
+```js
+const { spawn } = require('node:child_process');
+const subprocess = spawn('bad_command');
+
+subprocess.on('error', (err) => {
+ console.error('Failed to start subprocess.');
+});
+```
+
+Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process
+title while others (Windows, SunOS) will use `command`.
+
+Node.js currently overwrites `argv[0]` with `process.execPath` on startup, so
+`process.argv[0]` in a Node.js child process will not match the `argv0`
+parameter passed to `spawn` from the parent, retrieve it with the
+`process.argv0` property instead.
+
+If the `signal` option is enabled, calling `.abort()` on the corresponding
+`AbortController` is similar to calling `.kill()` on the child process except
+the error passed to the callback will be an `AbortError`:
+
+```js
+const { spawn } = require('node:child_process');
+const controller = new AbortController();
+const { signal } = controller;
+const grep = spawn('grep', ['ssh'], { signal });
+grep.on('error', (err) => {
+ // This will be called with err being an AbortError if the controller aborts
+});
+controller.abort(); // Stops the child process
+```
+
+##### `options.detached`
+
+
+
+On Windows, setting `options.detached` to `true` makes it possible for the
+child process to continue running after the parent exits. The child will have
+its own console window. Once enabled for a child process, it cannot be
+disabled.
+
+On non-Windows platforms, if `options.detached` is set to `true`, the child
+process will be made the leader of a new process group and session. Child
+processes may continue running after the parent exits regardless of whether
+they are detached or not. See setsid(2) for more information.
+
+By default, the parent will wait for the detached child to exit. To prevent the
+parent from waiting for a given `subprocess` to exit, use the
+`subprocess.unref()` method. Doing so will cause the parent's event loop to not
+include the child in its reference count, allowing the parent to exit
+independently of the child, unless there is an established IPC channel between
+the child and the parent.
+
+When using the `detached` option to start a long-running process, the process
+will not stay running in the background after the parent exits unless it is
+provided with a `stdio` configuration that is not connected to the parent.
+If the parent's `stdio` is inherited, the child will remain attached to the
+controlling terminal.
+
+Example of a long-running process, by detaching and also ignoring its parent
+`stdio` file descriptors, in order to ignore the parent's termination:
+
+```js
+const { spawn } = require('node:child_process');
+
+const subprocess = spawn(process.argv[0], ['child_program.js'], {
+ detached: true,
+ stdio: 'ignore'
+});
+
+subprocess.unref();
+```
+
+Alternatively one can redirect the child process' output into files:
+
+```js
+const fs = require('node:fs');
+const { spawn } = require('node:child_process');
+const out = fs.openSync('./out.log', 'a');
+const err = fs.openSync('./out.log', 'a');
+
+const subprocess = spawn('prg', [], {
+ detached: true,
+ stdio: [ 'ignore', out, err ]
+});
+
+subprocess.unref();
+```
+
+##### `options.stdio`
+
+
+
+The `options.stdio` option is used to configure the pipes that are established
+between the parent and child process. By default, the child's stdin, stdout,
+and stderr are redirected to corresponding [`subprocess.stdin`][],
+[`subprocess.stdout`][], and [`subprocess.stderr`][] streams on the
+[`ChildProcess`][] object. This is equivalent to setting the `options.stdio`
+equal to `['pipe', 'pipe', 'pipe']`.
+
+For convenience, `options.stdio` may be one of the following strings:
+
+* `'pipe'`: equivalent to `['pipe', 'pipe', 'pipe']` (the default)
+* `'overlapped'`: equivalent to `['overlapped', 'overlapped', 'overlapped']`
+* `'ignore'`: equivalent to `['ignore', 'ignore', 'ignore']`
+* `'inherit'`: equivalent to `['inherit', 'inherit', 'inherit']` or `[0, 1, 2]`
+
+Otherwise, the value of `options.stdio` is an array where each index corresponds
+to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,
+and stderr, respectively. Additional fds can be specified to create additional
+pipes between the parent and child. The value is one of the following:
+
+1. `'pipe'`: Create a pipe between the child process and the parent process.
+ The parent end of the pipe is exposed to the parent as a property on the
+ `child_process` object as [`subprocess.stdio[fd]`][`subprocess.stdio`]. Pipes
+ created for fds 0, 1, and 2 are also available as [`subprocess.stdin`][],
+ [`subprocess.stdout`][] and [`subprocess.stderr`][], respectively.
+ Currently, these are not actual Unix pipes and therefore the child process
+ can not use them by their descriptor files,
+ e.g. `/dev/fd/2` or `/dev/stdout`.
+2. `'overlapped'`: Same as `'pipe'` except that the `FILE_FLAG_OVERLAPPED` flag
+ is set on the handle. This is necessary for overlapped I/O on the child
+ process's stdio handles. See the
+ [docs](https://docs.microsoft.com/en-us/windows/win32/fileio/synchronous-and-asynchronous-i-o)
+ for more details. This is exactly the same as `'pipe'` on non-Windows
+ systems.
+3. `'ipc'`: Create an IPC channel for passing messages/file descriptors
+ between parent and child. A [`ChildProcess`][] may have at most one IPC
+ stdio file descriptor. Setting this option enables the
+ [`subprocess.send()`][] method. If the child is a Node.js process, the
+ presence of an IPC channel will enable [`process.send()`][] and
+ [`process.disconnect()`][] methods, as well as [`'disconnect'`][] and
+ [`'message'`][] events within the child.
+
+ Accessing the IPC channel fd in any way other than [`process.send()`][]
+ or using the IPC channel with a child process that is not a Node.js instance
+ is not supported.
+4. `'ignore'`: Instructs Node.js to ignore the fd in the child. While Node.js
+ will always open fds 0, 1, and 2 for the processes it spawns, setting the fd
+ to `'ignore'` will cause Node.js to open `/dev/null` and attach it to the
+ child's fd.
+5. `'inherit'`: Pass through the corresponding stdio stream to/from the
+ parent process. In the first three positions, this is equivalent to
+ `process.stdin`, `process.stdout`, and `process.stderr`, respectively. In
+ any other position, equivalent to `'ignore'`.
+6. [`Stream`](/api/stream#stream) object: Share a readable or writable stream that refers to a tty,
+ file, socket, or a pipe with the child process. The stream's underlying
+ file descriptor is duplicated in the child process to the fd that
+ corresponds to the index in the `stdio` array. The stream must have an
+ underlying descriptor (file streams do not until the `'open'` event has
+ occurred).
+7. Positive integer: The integer value is interpreted as a file descriptor
+ that is currently open in the parent process. It is shared with the child
+ process, similar to how [`Stream`](/api/stream#stream) objects can be shared. Passing sockets
+ is not supported on Windows.
+8. `null`, `undefined`: Use default value. For stdio fds 0, 1, and 2 (in other
+ words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
+ default is `'ignore'`.
+
+```js
+const { spawn } = require('node:child_process');
+
+// Child will use parent's stdios.
+spawn('prg', [], { stdio: 'inherit' });
+
+// Spawn child sharing only stderr.
+spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
+
+// Open an extra fd=4, to interact with programs presenting a
+// startd-style interface.
+spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
+```
+
+_It is worth noting that when an IPC channel is established between the
+parent and child processes, and the child is a Node.js process, the child
+is launched with the IPC channel unreferenced (using `unref()`) until the
+child registers an event handler for the [`'disconnect'`][] event
+or the [`'message'`][] event. This allows the child to exit
+normally without the process being held open by the open IPC channel._
+
+On Unix-like operating systems, the [`child_process.spawn()`][] method
+performs memory operations synchronously before decoupling the event loop
+from the child. Applications with a large memory footprint may find frequent
+[`child_process.spawn()`][] calls to be a bottleneck. For more information,
+see [V8 issue 7381](https://bugs.chromium.org/p/v8/issues/detail?id=7381).
+
+See also: [`child_process.exec()`][] and [`child_process.fork()`][].
+
+### Synchronous process creation
+
+The [`child_process.spawnSync()`][], [`child_process.execSync()`][], and
+[`child_process.execFileSync()`][] methods are synchronous and will block the
+Node.js event loop, pausing execution of any additional code until the spawned
+process exits.
+
+Blocking calls like these are mostly useful for simplifying general-purpose
+scripting tasks and for simplifying the loading/processing of application
+configuration at startup.
+
+#### `child_process.execFileSync(file[, args][, options])`
+
+
+
+* `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name or path of the executable file to run.
+* `args` string\[] List of string arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Current working directory of the child process.
+ * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/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) The value which will be passed
+ as stdin to the spawned process. Supplying this value will override
+ `stdio[0]`.
+ * `stdio` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Child's stdio configuration. `stderr` by default will
+ be output to the parent process' stderr unless `stdio` is specified.
+ **Default:** `'pipe'`.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) In milliseconds the maximum amount of time the process
+ is allowed to run. **Default:** `undefined`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal value to be used when the spawned
+ process will be killed. **Default:** `'SIGTERM'`.
+ * `maxBuffer` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Largest amount of data in bytes allowed on stdout or
+ stderr. If exceeded, the child process is terminated. See caveat at
+ [`maxBuffer` and Unicode][]. **Default:** `1024 * 1024`.
+ * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding used for all stdio inputs and outputs.
+ **Default:** `'buffer'`.
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+ * `shell` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `true`, runs `command` inside of a shell. Uses
+ `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
+ shell can be specified as a string. See [Shell requirements][] and
+ [Default Windows shell][]. **Default:** `false` (no shell).
+* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The stdout from the command.
+
+The `child_process.execFileSync()` method is generally identical to
+[`child_process.execFile()`][] with the exception that the method will not
+return until the child process has fully closed. When a timeout has been
+encountered and `killSignal` is sent, the method won't return until the process
+has completely exited.
+
+If the child process intercepts and handles the `SIGTERM` signal and
+does not exit, the parent process will still wait until the child process has
+exited.
+
+If the process times out or has a non-zero exit code, this method will throw an
+[`Error`][] that will include the full result of the underlying
+[`child_process.spawnSync()`][].
+
+**If the `shell` option is enabled, do not pass unsanitized user input to this
+function. Any input containing shell metacharacters may be used to trigger
+arbitrary command execution.**
+
+#### `child_process.execSync(command[, options])`
+
+
+
+* `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Current working directory of the child process.
+ * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/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) The value which will be passed
+ as stdin to the spawned process. Supplying this value will override
+ `stdio[0]`.
+ * `stdio` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Child's stdio configuration. `stderr` by default will
+ be output to the parent process' stderr unless `stdio` is specified.
+ **Default:** `'pipe'`.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `shell` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Shell to execute the command with. See
+ [Shell requirements][] and [Default Windows shell][]. **Default:**
+ `'/bin/sh'` on Unix, `process.env.ComSpec` on Windows.
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process. (See setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process. (See setgid(2)).
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) In milliseconds the maximum amount of time the process
+ is allowed to run. **Default:** `undefined`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal value to be used when the spawned
+ process will be killed. **Default:** `'SIGTERM'`.
+ * `maxBuffer` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Largest amount of data in bytes allowed on stdout or
+ stderr. If exceeded, the child process is terminated and any output is
+ truncated. See caveat at [`maxBuffer` and Unicode][].
+ **Default:** `1024 * 1024`.
+ * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding used for all stdio inputs and outputs.
+ **Default:** `'buffer'`.
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+* Returns: [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The stdout from the command.
+
+The `child_process.execSync()` method is generally identical to
+[`child_process.exec()`][] with the exception that the method will not return
+until the child process has fully closed. When a timeout has been encountered
+and `killSignal` is sent, the method won't return until the process has
+completely exited. If the child process intercepts and handles the `SIGTERM`
+signal and doesn't exit, the parent process will wait until the child process
+has exited.
+
+If the process times out or has a non-zero exit code, this method will throw.
+The [`Error`][] object will contain the entire result from
+[`child_process.spawnSync()`][].
+
+**Never pass unsanitized user input to this function. Any input containing shell
+metacharacters may be used to trigger arbitrary command execution.**
+
+#### `child_process.spawnSync(command[, args][, options])`
+
+
+
+* `command` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command to run.
+* `args` string\[] List of string arguments.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `cwd` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Current working directory of the child process.
+ * `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/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) The value which will be passed
+ as stdin to the spawned process. Supplying this value will override
+ `stdio[0]`.
+ * `argv0` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Explicitly set the value of `argv[0]` sent to the child
+ process. This will be set to `command` if not specified.
+ * `stdio` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Child's stdio configuration.
+ * `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Environment key-value pairs. **Default:** `process.env`.
+ * `uid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the user identity of the process (see setuid(2)).
+ * `gid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the group identity of the process (see setgid(2)).
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) In milliseconds the maximum amount of time the process
+ is allowed to run. **Default:** `undefined`.
+ * `killSignal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal value to be used when the spawned
+ process will be killed. **Default:** `'SIGTERM'`.
+ * `maxBuffer` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Largest amount of data in bytes allowed on stdout or
+ stderr. If exceeded, the child process is terminated and any output is
+ truncated. See caveat at [`maxBuffer` and Unicode][].
+ **Default:** `1024 * 1024`.
+ * `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding used for all stdio inputs and outputs.
+ **Default:** `'buffer'`.
+ * `shell` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If `true`, runs `command` inside of a shell. Uses
+ `'/bin/sh'` on Unix, and `process.env.ComSpec` on Windows. A different
+ shell can be specified as a string. See [Shell requirements][] and
+ [Default Windows shell][]. **Default:** `false` (no shell).
+ * `windowsVerbatimArguments` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) No quoting or escaping of arguments is
+ done on Windows. Ignored on Unix. This is set to `true` automatically
+ when `shell` is specified and is CMD. **Default:** `false`.
+ * `windowsHide` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Hide the subprocess console window that would
+ normally be created on Windows systems. **Default:** `false`.
+* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `pid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Pid of the child process.
+ * `output` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Array of results from stdio output.
+ * `stdout` [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The contents of `output[1]`.
+ * `stderr` [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The contents of `output[2]`.
+ * `status` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The exit code of the subprocess, or `null` if the
+ subprocess terminated due to a signal.
+ * `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The signal used to kill the subprocess, or `null` if
+ the subprocess did not terminate due to a signal.
+ * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The error object if the child process failed or timed out.
+
+The `child_process.spawnSync()` method is generally identical to
+[`child_process.spawn()`][] with the exception that the function will not return
+until the child process has fully closed. When a timeout has been encountered
+and `killSignal` is sent, the method won't return until the process has
+completely exited. If the process intercepts and handles the `SIGTERM` signal
+and doesn't exit, the parent process will wait until the child process has
+exited.
+
+**If the `shell` option is enabled, do not pass unsanitized user input to this
+function. Any input containing shell metacharacters may be used to trigger
+arbitrary command execution.**
+
+### `ChildProcess`
+
+
+
+* Extends: [`EventEmitter`](/api/events#eventemitter)
+
+Instances of the `ChildProcess` represent spawned child processes.
+
+Instances of `ChildProcess` are not intended to be created directly. Rather,
+use the [`child_process.spawn()`][], [`child_process.exec()`][],
+[`child_process.execFile()`][], or [`child_process.fork()`][] methods to create
+instances of `ChildProcess`.
+
+#### `'close'`
+
+
+
+* `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The exit code if the child exited on its own.
+* `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The signal by which the child process was terminated.
+
+The `'close'` event is emitted after a process has ended _and_ the stdio
+streams of a child process have been closed. This is distinct from the
+[`'exit'`][] event, since multiple processes might share the same stdio
+streams. The `'close'` event will always emit after [`'exit'`][] was
+already emitted, or [`'error'`][] if the child failed to spawn.
+
+```js
+const { spawn } = require('node:child_process');
+const ls = spawn('ls', ['-lh', '/usr']);
+
+ls.stdout.on('data', (data) => {
+ console.log(`stdout: $data`);
+});
+
+ls.on('close', (code) => {
+ console.log(`child process close all stdio with code $code`);
+});
+
+ls.on('exit', (code) => {
+ console.log(`child process exited with code $code`);
+});
+```
+
+#### `'disconnect'`
+
+
+
+The `'disconnect'` event is emitted after calling the
+[`subprocess.disconnect()`][] method in parent process or
+[`process.disconnect()`][] in child process. After disconnecting it is no longer
+possible to send or receive messages, and the [`subprocess.connected`][]
+property is `false`.
+
+#### `'error'`
+
+* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The error.
+
+The `'error'` event is emitted whenever:
+
+1. The process could not be spawned, or
+2. The process could not be killed, or
+3. Sending a message to the child process failed.
+
+The `'exit'` event may or may not fire after an error has occurred. When
+listening to both the `'exit'` and `'error'` events, guard
+against accidentally invoking handler functions multiple times.
+
+See also [`subprocess.kill()`][] and [`subprocess.send()`][].
+
+#### `'exit'`
+
+
+
+* `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The exit code if the child exited on its own.
+* `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The signal by which the child process was terminated.
+
+The `'exit'` event is emitted after the child process ends. If the process
+exited, `code` is the final exit code of the process, otherwise `null`. If the
+process terminated due to receipt of a signal, `signal` is the string name of
+the signal, otherwise `null`. One of the two will always be non-`null`.
+
+When the `'exit'` event is triggered, child process stdio streams might still be
+open.
+
+Node.js establishes signal handlers for `SIGINT` and `SIGTERM` and Node.js
+processes will not terminate immediately due to receipt of those signals.
+Rather, Node.js will perform a sequence of cleanup actions and then will
+re-raise the handled signal.
+
+See waitpid(2).
+
+#### `'message'`
+
+
+
+* `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A parsed JSON object or primitive value.
+* `sendHandle` [`Handle`](/api/net#serverlistenhandle-backlog-callback) A [`net.Socket`][] or [`net.Server`][] object, or
+ undefined.
+
+The `'message'` event is triggered when a child process uses
+[`process.send()`][] to send messages.
+
+The message goes through serialization and parsing. The resulting
+message might not be the same as what is originally sent.
+
+If the `serialization` option was set to `'advanced'` used when spawning the
+child process, the `message` argument can contain data that JSON is not able
+to represent.
+See [Advanced serialization][] for more details.
+
+#### `'spawn'`
+
+
+
+The `'spawn'` event is emitted once the child process has spawned successfully.
+If the child process does not spawn successfully, the `'spawn'` event is not
+emitted and the `'error'` event is emitted instead.
+
+If emitted, the `'spawn'` event comes before all other events and before any
+data is received via `stdout` or `stderr`.
+
+The `'spawn'` event will fire regardless of whether an error occurs **within**
+the spawned process. For example, if `bash some-command` spawns successfully,
+the `'spawn'` event will fire, though `bash` may fail to spawn `some-command`.
+This caveat also applies when using `{ shell: true }`.
+
+#### `subprocess.channel`
+
+
+
+* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A pipe representing the IPC channel to the child process.
+
+The `subprocess.channel` property is a reference to the child's IPC channel. If
+no IPC channel currently exists, this property is `undefined`.
+
+##### `subprocess.channel.ref()`
+
+
+
+This method makes the IPC channel keep the event loop of the parent process
+running if `.unref()` has been called before.
+
+##### `subprocess.channel.unref()`
+
+
+
+This method makes the IPC channel not keep the event loop of the parent process
+running, and lets it finish even while the channel is open.
+
+#### `subprocess.connected`
+
+
+
+* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `false` after `subprocess.disconnect()` is called.
+
+The `subprocess.connected` property indicates whether it is still possible to
+send and receive messages from a child process. When `subprocess.connected` is
+`false`, it is no longer possible to send or receive messages.
+
+#### `subprocess.disconnect()`
+
+
+
+Closes the IPC channel between parent and child, allowing the child to exit
+gracefully once there are no other connections keeping it alive. After calling
+this method the `subprocess.connected` and `process.connected` properties in
+both the parent and child (respectively) will be set to `false`, and it will be
+no longer possible to pass messages between the processes.
+
+The `'disconnect'` event will be emitted when there are no messages in the
+process of being received. This will most often be triggered immediately after
+calling `subprocess.disconnect()`.
+
+When the child process is a Node.js instance (e.g. spawned using
+[`child_process.fork()`][]), the `process.disconnect()` method can be invoked
+within the child process to close the IPC channel as well.
+
+#### `subprocess.exitCode`
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+The `subprocess.exitCode` property indicates the exit code of the child process.
+If the child process is still running, the field will be `null`.
+
+#### `subprocess.kill([signal])`
+
+
+
+* `signal` [`number`](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)
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+The `subprocess.kill()` method sends a signal to the child process. If no
+argument is given, the process will be sent the `'SIGTERM'` signal. See
+signal(7) for a list of available signals. This function returns `true` if
+kill(2) succeeds, and `false` otherwise.
+
+```js
+const { spawn } = require('node:child_process');
+const grep = spawn('grep', ['ssh']);
+
+grep.on('close', (code, signal) => {
+ console.log(
+ `child process terminated due to receipt of signal $signal`);
+});
+
+// Send SIGHUP to process.
+grep.kill('SIGHUP');
+```
+
+The [`ChildProcess`][] object may emit an [`'error'`][] event if the signal
+cannot be delivered. Sending a signal to a child process that has already exited
+is not an error but may have unforeseen consequences. Specifically, if the
+process identifier (PID) has been reassigned to another process, the signal will
+be delivered to that process instead which can have unexpected results.
+
+While the function is called `kill`, the signal delivered to the child process
+may not actually terminate the process.
+
+See kill(2) for reference.
+
+On Windows, where POSIX signals do not exist, the `signal` argument will be
+ignored, and the process will be killed forcefully and abruptly (similar to
+`'SIGKILL'`).
+See [Signal Events][] for more details.
+
+On Linux, child processes of child processes will not be terminated
+when attempting to kill their parent. This is likely to happen when running a
+new process in a shell or with the use of the `shell` option of `ChildProcess`:
+
+```js
+'use strict';
+const { spawn } = require('node:child_process');
+
+const subprocess = spawn(
+ 'sh',
+ [
+ '-c',
+ `node -e "setInterval(() => {
+ console.log(process.pid, 'is alive')
+ }, 500);"`,
+ ], {
+ stdio: ['inherit', 'inherit', 'inherit']
+ }
+);
+
+setTimeout(() => {
+ subprocess.kill(); // Does not terminate the Node.js process in the shell.
+}, 2000);
+```
+
+#### `subprocess.killed`
+
+
+
+* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `true` after `subprocess.kill()` is used to successfully
+ send a signal to the child process.
+
+The `subprocess.killed` property indicates whether the child process
+successfully received a signal from `subprocess.kill()`. The `killed` property
+does not indicate that the child process has been terminated.
+
+#### `subprocess.pid`
+
+
+
+* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+
+Returns the process identifier (PID) of the child process. If the child process
+fails to spawn due to errors, then the value is `undefined` and `error` is
+emitted.
+
+```js
+const { spawn } = require('node:child_process');
+const grep = spawn('grep', ['ssh']);
+
+console.log(`Spawned child pid: $grep.pid`);
+grep.stdin.end();
+```
+
+#### `subprocess.ref()`
+
+
+
+Calling `subprocess.ref()` after making a call to `subprocess.unref()` will
+restore the removed reference count for the child process, forcing the parent
+to wait for the child to exit before exiting itself.
+
+```js
+const { spawn } = require('node:child_process');
+
+const subprocess = spawn(process.argv[0], ['child_program.js'], {
+ detached: true,
+ stdio: 'ignore'
+});
+
+subprocess.unref();
+subprocess.ref();
+```
+
+#### `subprocess.send(message[, sendHandle[, options]][, callback])`
+
+
+
+* `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+* `sendHandle` [`Handle`](/api/net#serverlistenhandle-backlog-callback)
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `options` argument, if present, is an object used to
+ parameterize the sending of certain types of handles. `options` supports
+ the following properties:
+ * `keepOpen` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) A value that can be used when passing instances of
+ `net.Socket`. When `true`, the socket is kept open in the sending process.
+ **Default:** `false`.
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+When an IPC channel has been established between the parent and child (
+i.e. when using [`child_process.fork()`][]), the `subprocess.send()` method can
+be used to send messages to the child process. When the child process is a
+Node.js instance, these messages can be received via the [`'message'`][] event.
+
+The message goes through serialization and parsing. The resulting
+message might not be the same as what is originally sent.
+
+For example, in the parent script:
+
+```js
+const cp = require('node:child_process');
+const n = cp.fork(`${__dirname}/sub.js`);
+
+n.on('message', (m) => {
+ console.log('PARENT got message:', m);
+});
+
+// Causes the child to print: CHILD got message: { hello: 'world' }
+n.send({ hello: 'world' });
+```
+
+And then the child script, `'sub.js'` might look like this:
+
+```js
+process.on('message', (m) => {
+ console.log('CHILD got message:', m);
+});
+
+// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
+process.send({ foo: 'bar', baz: NaN });
+```
+
+Child Node.js processes will have a [`process.send()`][] method of their own
+that allows the child to send messages back to the parent.
+
+There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages
+containing a `NODE_` prefix in the `cmd` property are reserved for use within
+Node.js core and will not be emitted in the child's [`'message'`][]
+event. Rather, such messages are emitted using the
+`'internalMessage'` event and are consumed internally by Node.js.
+Applications should avoid using such messages or listening for
+`'internalMessage'` events as it is subject to change without notice.
+
+The optional `sendHandle` argument that may be passed to `subprocess.send()` is
+for passing a TCP server or socket object to the child process. The child will
+receive the object as the second argument passed to the callback function
+registered on the [`'message'`][] event. Any data that is received
+and buffered in the socket will not be sent to the child.
+
+The optional `callback` is a function that is invoked after the message is
+sent but before the child may have received it. The function is called with a
+single argument: `null` on success, or an [`Error`][] object on failure.
+
+If no `callback` function is provided and the message cannot be sent, an
+`'error'` event will be emitted by the [`ChildProcess`][] object. This can
+happen, for instance, when the child process has already exited.
+
+`subprocess.send()` will return `false` if the channel has closed or when the
+backlog of unsent messages exceeds a threshold that makes it unwise to send
+more. Otherwise, the method returns `true`. The `callback` function can be
+used to implement flow control.
+
+##### Example: sending a server object
+
+The `sendHandle` argument can be used, for instance, to pass the handle of
+a TCP server object to the child process as illustrated in the example below:
+
+```js
+const subprocess = require('node:child_process').fork('subprocess.js');
+
+// Open up the server object and send the handle.
+const server = require('node:net').createServer();
+server.on('connection', (socket) => {
+ socket.end('handled by parent');
+});
+server.listen(1337, () => {
+ subprocess.send('server', server);
+});
+```
+
+The child would then receive the server object as:
+
+```js
+process.on('message', (m, server) => {
+ if (m === 'server') {
+ server.on('connection', (socket) => {
+ socket.end('handled by child');
+ });
+ }
+});
+```
+
+Once the server is now shared between the parent and child, some connections
+can be handled by the parent and some by the child.
+
+While the example above uses a server created using the `node:net` module,
+`node:dgram` module servers use exactly the same workflow with the exceptions of
+listening on a `'message'` event instead of `'connection'` and using
+`server.bind()` instead of `server.listen()`. This is, however, currently only
+supported on Unix platforms.
+
+##### Example: sending a socket object
+
+Similarly, the `sendHandler` argument can be used to pass the handle of a
+socket to the child process. The example below spawns two children that each
+handle connections with "normal" or "special" priority:
+
+```js
+const { fork } = require('node:child_process');
+const normal = fork('subprocess.js', ['normal']);
+const special = fork('subprocess.js', ['special']);
+
+// Open up the server and send sockets to child. Use pauseOnConnect to prevent
+// the sockets from being read before they are sent to the child process.
+const server = require('node:net').createServer({ pauseOnConnect: true });
+server.on('connection', (socket) => {
+
+ // If this is special priority...
+ if (socket.remoteAddress === '74.125.127.100') {
+ special.send('socket', socket);
+ return;
+ }
+ // This is normal priority.
+ normal.send('socket', socket);
+});
+server.listen(1337);
+```
+
+The `subprocess.js` would receive the socket handle as the second argument
+passed to the event callback function:
+
+```js
+process.on('message', (m, socket) => {
+ if (m === 'socket') {
+ if (socket) {
+ // Check that the client socket exists.
+ // It is possible for the socket to be closed between the time it is
+ // sent and the time it is received in the child process.
+ socket.end(`Request handled with ${process.argv[2]} priority`);
+ }
+ }
+});
+```
+
+Do not use `.maxConnections` on a socket that has been passed to a subprocess.
+The parent cannot track when the socket is destroyed.
+
+Any `'message'` handlers in the subprocess should verify that `socket` exists,
+as the connection may have been closed during the time it takes to send the
+connection to the child.
+
+#### `subprocess.signalCode`
+
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
+
+The `subprocess.signalCode` property indicates the signal received by
+the child process if any, else `null`.
+
+#### `subprocess.spawnargs`
+
+* [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
+
+The `subprocess.spawnargs` property represents the full list of command-line
+arguments the child process was launched with.
+
+#### `subprocess.spawnfile`
+
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+The `subprocess.spawnfile` property indicates the executable file name of
+the child process that is launched.
+
+For [`child_process.fork()`][], its value will be equal to
+[`process.execPath`][].
+For [`child_process.spawn()`][], its value will be the name of
+the executable file.
+For [`child_process.exec()`][], its value will be the name of the shell
+in which the child process is launched.
+
+#### `subprocess.stderr`
+
+
+
+* [`stream.Readable`](/api/stream#streamreadable) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+
+A `Readable Stream` that represents the child process's `stderr`.
+
+If the child was spawned with `stdio[2]` set to anything other than `'pipe'`,
+then this will be `null`.
+
+`subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will
+refer to the same value.
+
+The `subprocess.stderr` property can be `null` or `undefined`
+if the child process could not be successfully spawned.
+
+#### `subprocess.stdin`
+
+
+
+* [`stream.Writable`](/api/stream#streamwritable) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+
+A `Writable Stream` that represents the child process's `stdin`.
+
+If a child process waits to read all of its input, the child will not continue
+until this stream has been closed via `end()`.
+
+If the child was spawned with `stdio[0]` set to anything other than `'pipe'`,
+then this will be `null`.
+
+`subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will
+refer to the same value.
+
+The `subprocess.stdin` property can be `null` or `undefined`
+if the child process could not be successfully spawned.
+
+#### `subprocess.stdio`
+
+
+
+* [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
+
+A sparse array of pipes to the child process, corresponding with positions in
+the [`stdio`][] option passed to [`child_process.spawn()`][] that have been set
+to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and
+`subprocess.stdio[2]` are also available as `subprocess.stdin`,
+`subprocess.stdout`, and `subprocess.stderr`, respectively.
+
+In the following example, only the child's fd `1` (stdout) is configured as a
+pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values
+in the array are `null`.
+
+```js
+const assert = require('node:assert');
+const fs = require('node:fs');
+const child_process = require('node:child_process');
+
+const subprocess = child_process.spawn('ls', {
+ stdio: [
+ 0, // Use parent's stdin for child.
+ 'pipe', // Pipe child's stdout to parent.
+ fs.openSync('err.out', 'w'), // Direct child's stderr to a file.
+ ]
+});
+
+assert.strictEqual(subprocess.stdio[0], null);
+assert.strictEqual(subprocess.stdio[0], subprocess.stdin);
+
+assert(subprocess.stdout);
+assert.strictEqual(subprocess.stdio[1], subprocess.stdout);
+
+assert.strictEqual(subprocess.stdio[2], null);
+assert.strictEqual(subprocess.stdio[2], subprocess.stderr);
+```
+
+The `subprocess.stdio` property can be `undefined` if the child process could
+not be successfully spawned.
+
+#### `subprocess.stdout`
+
+
+
+* [`stream.Readable`](/api/stream#streamreadable) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+
+A `Readable Stream` that represents the child process's `stdout`.
+
+If the child was spawned with `stdio[1]` set to anything other than `'pipe'`,
+then this will be `null`.
+
+`subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will
+refer to the same value.
+
+```js
+const { spawn } = require('node:child_process');
+
+const subprocess = spawn('ls');
+
+subprocess.stdout.on('data', (data) => {
+ console.log(`Received chunk $data`);
+});
+```
+
+The `subprocess.stdout` property can be `null` or `undefined`
+if the child process could not be successfully spawned.
+
+#### `subprocess.unref()`
+
+
+
+By default, the parent will wait for the detached child to exit. To prevent the
+parent from waiting for a given `subprocess` to exit, use the
+`subprocess.unref()` method. Doing so will cause the parent's event loop to not
+include the child in its reference count, allowing the parent to exit
+independently of the child, unless there is an established IPC channel between
+the child and the parent.
+
+```js
+const { spawn } = require('node:child_process');
+
+const subprocess = spawn(process.argv[0], ['child_program.js'], {
+ detached: true,
+ stdio: 'ignore'
+});
+
+subprocess.unref();
+```
+
+### `maxBuffer` and Unicode
+
+The `maxBuffer` option specifies the largest number of bytes allowed on `stdout`
+or `stderr`. If this value is exceeded, then the child process is terminated.
+This impacts output that includes multibyte character encodings such as UTF-8 or
+UTF-16. For instance, `console.log('中文测试')` will send 13 UTF-8 encoded bytes
+to `stdout` although there are only 4 characters.
+
+### Shell requirements
+
+The shell should understand the `-c` switch. If the shell is `'cmd.exe'`, it
+should understand the `/d /s /c` switches and command-line parsing should be
+compatible.
+
+### Default Windows shell
+
+Although Microsoft specifies `%COMSPEC%` must contain the path to
+`'cmd.exe'` in the root environment, child processes are not always subject to
+the same requirement. Thus, in `child_process` functions where a shell can be
+spawned, `'cmd.exe'` is used as a fallback if `process.env.ComSpec` is
+unavailable.
+
+### Advanced serialization
+
+
+
+Child processes support a serialization mechanism for IPC that is based on the
+[serialization API of the `node:v8` module][v8.serdes], based on the
+[HTML structured clone algorithm][]. This is generally more powerful and
+supports more built-in JavaScript object types, such as `BigInt`, `Map`
+and `Set`, `ArrayBuffer` and `TypedArray`, `Buffer`, `Error`, `RegExp` etc.
+
+However, this format is not a full superset of JSON, and e.g. properties set on
+objects of such built-in types will not be passed on through the serialization
+step. Additionally, performance may not be equivalent to that of JSON, depending
+on the structure of the passed data.
+Therefore, this feature requires opting in by setting the
+`serialization` option to `'advanced'` when calling [`child_process.spawn()`][]
+or [`child_process.fork()`][].
+
+[Advanced serialization]: #advanced-serialization
+[Default Windows shell]: #default-windows-shell
+[HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
+[Shell requirements]: #shell-requirements
+[Signal Events]: (/api/process#signal-events)
+[`'disconnect'`]: (/api/process#event-disconnect)
+[`'error'`]: #event-error
+[`'exit'`]: #event-exit
+[`'message'`]: (/api/process#event-message)
+[`ChildProcess`]: #class-childprocess
+[`Error`]: (/api/errors#class-error)
+[`EventEmitter`]: (/api/events#class-eventemitter)
+[`child_process.exec()`]: #child_processexeccommand-options-callback
+[`child_process.execFile()`]: #child_processexecfilefile-args-options-callback
+[`child_process.execFileSync()`]: #child_processexecfilesyncfile-args-options
+[`child_process.execSync()`]: #child_processexecsynccommand-options
+[`child_process.fork()`]: #child_processforkmodulepath-args-options
+[`child_process.spawn()`]: #child_processspawncommand-args-options
+[`child_process.spawnSync()`]: #child_processspawnsynccommand-args-options
+[`maxBuffer` and Unicode]: #maxbuffer-and-unicode
+[`net.Server`]: (/api/net#class-netserver)
+[`net.Socket`]: (/api/net#class-netsocket)
+[`options.detached`]: #optionsdetached
+[`process.disconnect()`]: (/api/process#processdisconnect)
+[`process.env`]: (/api/process#processenv)
+[`process.execPath`]: (/api/process#processexecpath)
+[`process.send()`]: (/api/process#processsendmessage-sendhandle-options-callback)
+[`stdio`]: #optionsstdio
+[`subprocess.connected`]: #subprocessconnected
+[`subprocess.disconnect()`]: #subprocessdisconnect
+[`subprocess.kill()`]: #subprocesskillsignal
+[`subprocess.send()`]: #subprocesssendmessage-sendhandle-options-callback
+[`subprocess.stderr`]: #subprocessstderr
+[`subprocess.stdin`]: #subprocessstdin
+[`subprocess.stdio`]: #subprocessstdio
+[`subprocess.stdout`]: #subprocessstdout
+[`util.promisify()`]: (/api/util#utilpromisifyoriginal)
+[synchronous counterparts]: #synchronous-process-creation
+[v8.serdes]: v8.md#serialization-api
diff --git a/content/api/v18/cli.en.md b/content/api/v18/cli.en.md
new file mode 100644
index 0000000000..345bc84761
--- /dev/null
+++ b/content/api/v18/cli.en.md
@@ -0,0 +1,1802 @@
+---
+title: 'cli'
+displayTitle: 'Command-line API'
+category: 'api'
+editPage: 'https://github.com/nodejs/node/blob/v18.8.0/doc/api/cli.md'
+version: 'v18'
+---
+
+
+
+
+
+Node.js comes with a variety of CLI options. These options expose built-in
+debugging, multiple ways to execute scripts, and other helpful runtime options.
+
+To view this documentation as a manual page in a terminal, run `man node`.
+
+### Synopsis
+
+`node [options] [V8 options] [ | -e "script" | -] [--] [arguments]`
+
+`node inspect [