diff --git a/.eslintignore b/.eslintignore
index 38625b1002..9d06233755 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -2,3 +2,4 @@
public
docs/
meetings/
+build/
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
deleted file mode 100644
index 4604b5c98c..0000000000
--- a/.github/dependabot.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-version: 2
-updates:
- - package-ecosystem: github-actions
- directory: '/'
- schedule:
- interval: daily
- open-pull-requests-limit: 99
-
- - package-ecosystem: npm
- directory: '/'
- schedule:
- interval: monthly
- open-pull-requests-limit: 99
diff --git a/README.md b/README.md
index 6ea8cec7b9..35f4177fa3 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,11 @@
+### Repository Archival Notice ⚠️
+
+This repository is discontinued and archived. Please follow-up the recent announcement [here](https://github.com/nodejs/nodejs.org/discussions/5131) as development continues on the [`nodejs/nodejs.org`](https://github.com/nodejs/nodejs.org) repository.
+
+Thank you all for your contributions over the years!
+
+----------
+
diff --git a/apiUrls.js b/apiUrls.js
index 0e263788cb..fcd49fa3d6 100644
--- a/apiUrls.js
+++ b/apiUrls.js
@@ -6,7 +6,7 @@ module.exports = {
'https://raw.githubusercontent.com/nodejs/Release/main/schedule.json',
nodeReleaseData: 'https://nodejs.org/dist/index.json',
nodeBannersData:
- 'https://raw.githubusercontent.com/nodejs/nodejs.org/main/locale/en/site.json',
+ 'https://raw.githubusercontent.com/nodejs/nodejs.org/main/site.json',
jsonLink: (fileName, version) =>
`https://nodejs.org/docs/latest-${version}.x/api/${fileName}.json`,
};
diff --git a/content/about/about.en.md b/content/about/about.en.md
index 656e3ce025..691a6ac730 100644
--- a/content/about/about.en.md
+++ b/content/about/about.en.md
@@ -11,7 +11,7 @@ scalable network applications. In the following "hello world" example, many
connections can be handled concurrently. Upon each connection, the callback is
fired, but if there is no work to be done, Node.js will sleep.
-```javascript
+```js
const http = require('http');
const hostname = '127.0.0.1';
diff --git a/content/about/about.ja.md b/content/about/about.ja.md
index 48deb2b26d..8794d90980 100644
--- a/content/about/about.ja.md
+++ b/content/about/about.ja.md
@@ -8,7 +8,7 @@ category: about
Node.js は、非同期のイベントドリブン JavaScript ランタイムとして、スケーラブルなネットワークアプリケーションを構築するために設計されています。次の "hello world" の例では、多くの接続を同時に処理できます。接続を並列に処理することができます。各接続の際に、コールバックが呼び出されます。しかし、何もすることがない場合は、Node.js はスリープします。
-```javascript
+```js
const http = require('http');
const hostname = '127.0.0.1';
diff --git a/content/about/about.pt.md b/content/about/about.pt.md
index 0e739f85bc..1c887439e5 100644
--- a/content/about/about.pt.md
+++ b/content/about/about.pt.md
@@ -8,7 +8,7 @@ category: about
Como executor de JavaScript orientado a eventos assíncronos, a Node está desenhada para construir aplicações de rede escaláveis. No seguinte exemplo "hello world" ou "olá mundo" em Português, várias conexões podem ser manipuladas simultaneamente. Sobre cada conexão, uma função de resposta é disparada, mas se não existe nada a ser feito, a Node.js adormecerá.
-```javascript
+```js
const http = require('http');
const hostname = '127.0.0.1';
diff --git a/content/about/branding.en.md b/content/about/branding.en.md
new file mode 100644
index 0000000000..874fde9150
--- /dev/null
+++ b/content/about/branding.en.md
@@ -0,0 +1,163 @@
+---
+title: branding
+displayTitle: Branding of Node.js
+description: 'Branding | Node.js'
+authors: AugustinMauroy, XhmikosR, mikeal, fhemberger, Fishrock123, yous, tomgco, tniessen, SMcCandlish, saadq, Trott, Gornstats, piperchester, naoufal, lpinca, j9t, bnoordhuis, harshadsabne, Chris911, MrJithil
+category: about
+---
+
+Please review the [trademark policy](https://trademark-policy.openjsf.org/) for information about permissible use of Node.js® logos and marks.
+
+## Color
+
+The following colors are the color palette for the Node.js website. And should be used for other documents.
+
+### Brand colors
+
+
+
+### Neutral colors
+
+
+
+### Status colors
+
+**Danger**
+
+
+
+**Warning**
+
+
+
+**Info**
+
+
+
+### Accent colors
+
+**Accent 1**
+
+
+
+**Accent 2**
+
+
+
+## Font
+
+**Font Name**: Open Sans
+
+**Download**: [www.google.com/fonts/specimen/Open+Sans](https://www.google.com/fonts/specimen/Open+Sans)
+
+## Nodejs logos
+
+### Logos with JS hexagon at right
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+### Logos with JS hexagon at bottom
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+## Assets
+
+### Hexagon
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+### JS from Node.js logo
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/content/about/resources.en.md b/content/about/resources.en.md
deleted file mode 100644
index e33c0dbaf1..0000000000
--- a/content/about/resources.en.md
+++ /dev/null
@@ -1,32 +0,0 @@
----
-title: resources
-displayTitle: Resources
-description: 'Resources | Node.js'
-authors: XhmikosR, mikeal, fhemberger, Fishrock123, yous, tomgco, tniessen, SMcCandlish, saadq, Trott, Gornstats, piperchester, naoufal, lpinca, j9t, bnoordhuis, harshadsabne, Chris911, MrJithil
-category: about
----
-
-## Logo Downloads
-
-Please review the [trademark policy](https://trademark-policy.openjsf.org/) for information about permissible use of Node.js® logos and marks.
-
-Guidelines for the visual display of the Node.js mark are described in the [Visual Guidelines](/static/documents/foundation-visual-guidelines.pdf).
-
-
diff --git a/content/about/resources.fr.md b/content/about/resources.fr.md
deleted file mode 100644
index 2eb8b13d52..0000000000
--- a/content/about/resources.fr.md
+++ /dev/null
@@ -1,32 +0,0 @@
----
-title: resources
-displayTitle: Ressources
-description: "Ressources | Node.js"
-authors: XhmikosR, mikeal, fhemberger, Fishrock123, yous, tomgco, tniessen, SMcCandlish, saadq, Trott, Gornstats, piperchester, naoufal, lpinca, j9t, bnoordhuis, harshadsabne, Chris911, MrJithil, AugustinMauroy
-category: about
----
-
-## Téléchargements de logos
-
-Veuillez consulter la [politique de marque](https://trademark-policy.openjsf.org/) pour obtenir des informations sur l'utilisation autorisée des logos et des marques de Node.js®.
-
-Les directives relatives à l'affichage de la marque Node.js sont décrites dans les [Directives visuelles] (/static/documents/foundation-visual-guidelines.pdf).
-
-
diff --git a/content/api/v16/assert.en.md b/content/api/v16/assert.en.md
index 955bc8b765..30296972d4 100644
--- a/content/api/v16/assert.en.md
+++ b/content/api/v16/assert.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:assert` module provides a set of assertion functions for verifying
invariants.
@@ -31,25 +31,21 @@ assertion mode, error messages for objects display the objects, often truncated.
To use strict assertion mode:
-```mjs
+```mjs|cjs
import { strict as assert } from 'node:assert';
-```
-
-```cjs
+--------------
const assert = require('node:assert').strict;
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
```
Example error diff:
-```mjs
+```mjs|cjs
import { strict as assert } from 'node:assert';
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
@@ -66,9 +62,7 @@ assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// ...
// 5
// ]
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
@@ -103,11 +97,9 @@ Legacy assertion mode uses the [`==` operator][] in:
To use legacy assertion mode:
-```mjs
+```mjs|cjs
import assert from 'node:assert';
-```
-
-```cjs
+--------------
const assert = require('node:assert');
```
@@ -153,7 +145,7 @@ and:
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
+```mjs|cjs
import assert from 'node:assert';
// Generate an AssertionError to compare the error message later:
@@ -176,9 +168,7 @@ try {
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:
@@ -224,7 +214,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
import process from 'node:process';
@@ -242,9 +232,7 @@ callsfunc();
process.on('exit', () => {
tracker.verify();
});
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const tracker = new assert.CallTracker();
@@ -276,7 +264,7 @@ function has not been called exactly `exact` times when
[`tracker.verify()`][] is called, then [`tracker.verify()`][] will throw an
error.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
// Creates call tracker.
@@ -287,9 +275,7 @@ 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.
@@ -314,7 +300,7 @@ const callsfunc = tracker.calls(func);
* `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
+```mjs|cjs
import assert from 'node:assert';
const tracker = new assert.CallTracker();
@@ -325,9 +311,7 @@ callsfunc(1, 2, 3);
assert.deepStrictEqual(tracker.getCalls(callsfunc),
[{ thisArg: this, arguments: [1, 2, 3 ] }]);
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Creates call tracker.
@@ -358,7 +342,7 @@ assert.deepStrictEqual(tracker.getCalls(callsfunc),
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
+```mjs|cjs
import assert from 'node:assert';
// Creates call tracker.
@@ -382,9 +366,7 @@ tracker.report();
// stack: stack trace
// }
// ]
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Creates call tracker.
@@ -420,7 +402,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
const tracker = new assert.CallTracker();
@@ -434,9 +416,7 @@ tracker.getCalls(callsfunc).length === 1;
tracker.reset(callsfunc);
tracker.getCalls(callsfunc).length === 0;
-```
-
-```cjs
+--------------
const assert = require('node:assert');
function func() {}
@@ -458,7 +438,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
// Creates call tracker.
@@ -474,9 +454,7 @@ callsfunc();
// Will throw an error since callsfunc() was only called once.
tracker.verify();
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Creates call tracker.
@@ -552,14 +530,12 @@ are also recursively evaluated by the following rules.
The following example does not throw an [`AssertionError`][] because the
primitives are compared using the [`==` operator][].
-```mjs
+```mjs|cjs
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!
@@ -569,7 +545,7 @@ assert.deepEqual('+00000000', false);
"Deep" equality means that the enumerable "own" properties of child objects
are evaluated also:
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const obj1 = {
@@ -602,9 +578,7 @@ assert.deepEqual(obj1, obj3);
// Prototypes are ignored:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const obj1 = {
@@ -675,7 +649,7 @@ are recursively evaluated also by the following rules.
* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values. See
below for further details.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
// This fails because 1 !== '1'.
@@ -765,9 +739,7 @@ assert.deepStrictEqual(weakMap1, weakMap3);
// - [items unknown],
// - unequal: true
// }
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
// This fails because 1 !== '1'.
@@ -875,7 +847,7 @@ parameter is an instance of an [`Error`][] then it will be thrown instead of the
Expects the `string` input not to match the regular expression.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotMatch('I will fail', /fail/);
@@ -886,9 +858,7 @@ assert.doesNotMatch(123, /pass/);
assert.doesNotMatch('I will pass', /different/);
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotMatch('I will fail', /fail/);
@@ -937,7 +907,7 @@ function. See [`assert.throws()`][] for more details.
Besides the async nature to await the completion behaves identically to
[`assert.doesNotThrow()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
await assert.doesNotReject(
@@ -946,9 +916,7 @@ await assert.doesNotReject(
},
SyntaxError
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
(async () => {
@@ -961,16 +929,14 @@ const assert = require('node:assert/strict');
})();
```
-```mjs
+```mjs|cjs
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')))
@@ -1008,7 +974,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotThrow(
@@ -1017,9 +983,7 @@ assert.doesNotThrow(
},
SyntaxError
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotThrow(
@@ -1033,7 +997,7 @@ assert.doesNotThrow(
However, the following will result in an [`AssertionError`][] with the message
'Got unwanted exception...':
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotThrow(
@@ -1042,9 +1006,7 @@ assert.doesNotThrow(
},
TypeError
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotThrow(
@@ -1059,7 +1021,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotThrow(
@@ -1070,9 +1032,7 @@ assert.doesNotThrow(
'Whoops'
);
// Throws: AssertionError: Got unwanted exception: Whoops
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotThrow(
@@ -1109,7 +1069,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
assert.equal(1, 1);
@@ -1123,9 +1083,7 @@ 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);
@@ -1157,7 +1115,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.fail();
@@ -1168,9 +1126,7 @@ assert.fail('boom');
assert.fail(new TypeError('need array'));
// TypeError: need array
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.fail();
@@ -1211,7 +1167,7 @@ the other arguments will be stored as properties on the thrown object. If
removed from stacktrace (see [`Error.captureStackTrace`][]). If no arguments are
given, the default message `Failed` will be used.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.fail('a', 'b');
@@ -1228,9 +1184,7 @@ assert.fail(1, 2, 'whoops', '>');
assert.fail(1, 2, new TypeError('need array'));
// TypeError: need array
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.fail('a', 'b');
@@ -1254,7 +1208,7 @@ influence on the error message.
Example use of `stackStartFn` for truncating the exception's stacktrace:
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
function suppressFrame() {
@@ -1265,9 +1219,7 @@ suppressFrame();
// at repl:1:1
// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
// ...
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
function suppressFrame() {
@@ -1291,7 +1243,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.ifError(null);
@@ -1315,9 +1267,7 @@ let err;
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
// at ifErrorFrame
// at errorFrame
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.ifError(null);
@@ -1353,7 +1303,7 @@ let err;
Expects the `string` input to match the regular expression.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.match('I will fail', /pass/);
@@ -1364,9 +1314,7 @@ assert.match(123, /pass/);
assert.match('I will pass', /pass/);
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.match('I will fail', /pass/);
@@ -1408,7 +1356,7 @@ Legacy: Use [`assert.notDeepStrictEqual()`][] instead.
Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const obj1 = {
@@ -1439,9 +1387,7 @@ assert.notDeepEqual(obj1, obj3);
assert.notDeepEqual(obj1, obj4);
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const obj1 = {
@@ -1490,14 +1436,12 @@ instead of the `AssertionError`.
Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
-```mjs
+```mjs|cjs
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' });
@@ -1533,7 +1477,7 @@ Legacy: Use [`assert.notStrictEqual()`][] instead.
Tests shallow, coercive inequality with the [`!=` operator][]. `NaN` is
specially handled and treated as being identical if both sides are `NaN`.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
assert.notEqual(1, 2);
@@ -1544,9 +1488,7 @@ assert.notEqual(1, 1);
assert.notEqual(1, '1');
// AssertionError: 1 != '1'
-```
-
-```cjs
+--------------
const assert = require('node:assert');
assert.notEqual(1, 2);
@@ -1576,7 +1518,7 @@ parameter is an instance of an [`Error`][] then it will be thrown instead of the
Tests strict inequality between the `actual` and `expected` parameters as
determined by [`Object.is()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.notStrictEqual(1, 2);
@@ -1589,9 +1531,7 @@ assert.notStrictEqual(1, 1);
assert.notStrictEqual(1, '1');
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.notStrictEqual(1, 2);
@@ -1633,7 +1573,7 @@ If no arguments are passed in at all `message` will be set to the string:
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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.ok(true);
@@ -1666,9 +1606,7 @@ assert.ok(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(0)
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.ok(true);
@@ -1703,7 +1641,7 @@ assert.ok(0);
// assert.ok(0)
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
// Using `assert()` works the same:
@@ -1711,9 +1649,7 @@ assert(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert(0)
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Using `assert()` works the same:
@@ -1752,7 +1688,7 @@ each property will be tested for including the non-enumerable `message` and
If specified, `message` will be the message provided by the [`AssertionError`][]
if the `asyncFn` fails to reject.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
await assert.rejects(
@@ -1764,9 +1700,7 @@ await assert.rejects(
message: 'Wrong value'
}
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
(async () => {
@@ -1782,7 +1716,7 @@ const assert = require('node:assert/strict');
})();
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
await assert.rejects(
@@ -1795,9 +1729,7 @@ await assert.rejects(
return true;
}
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
(async () => {
@@ -1814,7 +1746,7 @@ const assert = require('node:assert/strict');
})();
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.rejects(
@@ -1823,9 +1755,7 @@ assert.rejects(
).then(() => {
// ...
});
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.rejects(
@@ -1853,7 +1783,7 @@ argument gets considered.
Tests strict equality between the `actual` and `expected` parameters as
determined by [`Object.is()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.strictEqual(1, 2);
@@ -1879,9 +1809,7 @@ assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
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);
@@ -1938,7 +1866,7 @@ fails.
Custom validation object/error instance:
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
const err = new TypeError('Wrong value');
@@ -2005,9 +1933,7 @@ assert.throws(
// an error as validation object.
err
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
const err = new TypeError('Wrong value');
@@ -2078,7 +2004,7 @@ assert.throws(
Validate instanceof using constructor:
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.throws(
@@ -2087,9 +2013,7 @@ assert.throws(
},
Error
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.throws(
@@ -2105,7 +2029,7 @@ Validate error message using [`RegExp`][]:
Using a regular expression runs `.toString` on the error object, and will
therefore also include the error name.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.throws(
@@ -2114,9 +2038,7 @@ assert.throws(
},
/^Error: Wrong value$/
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.throws(
@@ -2132,7 +2054,7 @@ Custom error validation:
The function must return `true` to indicate all internal validations passed.
It will otherwise fail with an [`AssertionError`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.throws(
@@ -2151,9 +2073,7 @@ assert.throws(
},
'unexpected error'
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.throws(
@@ -2181,7 +2101,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
function throwingFirst() {
@@ -2215,9 +2135,7 @@ 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() {
diff --git a/content/api/v16/async_context.en.md b/content/api/v16/async_context.en.md
index 2aeda73f00..45990b68f9 100644
--- a/content/api/v16/async_context.en.md
+++ b/content/api/v16/async_context.en.md
@@ -13,7 +13,7 @@ Stable
-
+
### Introduction
@@ -26,11 +26,9 @@ in other languages.
The `AsyncLocalStorage` and `AsyncResource` classes are part of the
`node:async_hooks` module:
-```mjs
+```mjs|cjs
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
-```
-
-```cjs
+--------------
const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');
```
@@ -49,7 +47,7 @@ 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
+```mjs|cjs
import http from 'node:http';
import { AsyncLocalStorage } from 'node:async_hooks';
@@ -79,9 +77,7 @@ http.get('http://localhost:8080');
// 1: start
// 0: finish
// 1: finish
-```
-
-```cjs
+--------------
const http = require('node:http');
const { AsyncLocalStorage } = require('node:async_hooks');
@@ -331,7 +327,7 @@ The `init` hook will trigger when an `AsyncResource` is instantiated.
The following is an overview of the `AsyncResource` API.
-```mjs
+```mjs|cjs
import { AsyncResource, executionAsyncId } from 'node:async_hooks';
// AsyncResource() is meant to be extended. Instantiating a
@@ -357,9 +353,7 @@ 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
@@ -492,14 +486,12 @@ 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
+```mjs|cjs
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);
@@ -508,7 +500,7 @@ parentPort.on('message', (task) => {
a Worker pool around it could use the following structure:
-```mjs
+```mjs|cjs
import { AsyncResource } from 'node:async_hooks';
import { EventEmitter } from 'node:events';
import path from 'node:path';
@@ -594,9 +586,7 @@ export default class WorkerPool extends EventEmitter {
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');
@@ -694,7 +684,7 @@ were scheduled.
This pool could be used as follows:
-```mjs
+```mjs|cjs
import WorkerPool from './worker_pool.js';
import os from 'node:os';
@@ -708,9 +698,7 @@ for (let i = 0; i < 10; i++) {
pool.close();
});
}
-```
-
-```cjs
+--------------
const WorkerPool = require('./worker_pool.js');
const os = require('node:os');
@@ -736,7 +724,7 @@ 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
+```mjs|cjs
import { createServer } from 'node:http';
import { AsyncResource, executionAsyncId } from 'node:async_hooks';
@@ -749,9 +737,7 @@ const server = createServer((req, res) => {
});
res.end();
}).listen(3000);
-```
-
-```cjs
+--------------
const { createServer } = require('node:http');
const { AsyncResource, executionAsyncId } = require('node:async_hooks');
diff --git a/content/api/v16/async_hooks.en.md b/content/api/v16/async_hooks.en.md
index 218d39af59..cc13fc86a0 100644
--- a/content/api/v16/async_hooks.en.md
+++ b/content/api/v16/async_hooks.en.md
@@ -13,16 +13,14 @@ Experimental
-
+
The `node:async_hooks` module provides an API to track asynchronous resources.
It can be accessed using:
-```mjs
+```mjs|cjs
import async_hooks from 'node:async_hooks';
-```
-
-```cjs
+--------------
const async_hooks = require('node:async_hooks');
```
@@ -42,7 +40,7 @@ interface, and each thread will use a new set of async IDs.
Following is a simple overview of the public API.
-```mjs
+```mjs|cjs
import async_hooks from 'node:async_hooks';
// Return the ID of the current execution context.
@@ -88,9 +86,7 @@ function destroy(asyncId) { }
// 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.
@@ -161,16 +157,14 @@ 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
+```mjs|cjs
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({
@@ -226,7 +220,7 @@ 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
+```mjs|cjs
import { writeFileSync } from 'node:fs';
import { format } from 'node:util';
@@ -234,9 +228,7 @@ 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');
@@ -267,13 +259,11 @@ 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
+```mjs|cjs
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();
@@ -313,15 +303,13 @@ 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
+```mjs|cjs
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));
@@ -367,7 +355,7 @@ created, while `triggerAsyncId` shows _why_ a resource was created.
The following is a simple demonstration of `triggerAsyncId`:
-```mjs
+```mjs|cjs
import { createHook, executionAsyncId } from 'node:async_hooks';
import { stdout } from 'node:process';
import net from 'node:net';
@@ -382,9 +370,7 @@ createHook({
}).enable();
net.createServer((conn) => {}).listen(8080);
-```
-
-```cjs
+--------------
const { createHook, executionAsyncId } = require('node:async_hooks');
const { stdout } = require('node:process');
const net = require('node:net');
@@ -619,7 +605,7 @@ 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
+```mjs|cjs
import { open } from 'node:fs';
import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
@@ -627,9 +613,7 @@ 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');
@@ -642,7 +626,7 @@ open(__filename, 'r', (err, fd) => {
This can be used to implement continuation local storage without the
use of a tracking `Map` to store the metadata:
-```mjs
+```mjs|cjs
import { createServer } from 'node:http';
import {
executionAsyncId,
@@ -666,9 +650,7 @@ const server = createServer((req, res) => {
res.end(JSON.stringify(executionAsyncResource()[sym]));
}, 100);
}).listen(3000);
-```
-
-```cjs
+--------------
const { createServer } = require('node:http');
const {
executionAsyncId,
@@ -701,16 +683,14 @@ const server = createServer((req, res) => {
* 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
+```mjs|cjs
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
@@ -778,7 +758,7 @@ 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
+```mjs|cjs
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
Promise.resolve(1729).then(() => {
@@ -786,9 +766,7 @@ Promise.resolve(1729).then(() => {
});
// produces:
// eid 1 tid 0
-```
-
-```cjs
+--------------
const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');
Promise.resolve(1729).then(() => {
@@ -806,7 +784,7 @@ the resource that caused (triggered) the `then()` callback to be executed.
Installing async hooks via `async_hooks.createHook` enables promise execution
tracking:
-```mjs
+```mjs|cjs
import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
Promise.resolve(1729).then(() => {
@@ -814,9 +792,7 @@ Promise.resolve(1729).then(() => {
});
// produces:
// eid 7 tid 6
-```
-
-```cjs
+--------------
const { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
diff --git a/content/api/v16/buffer.en.md b/content/api/v16/buffer.en.md
index 112d6fb4ac..c00e1ae2f2 100644
--- a/content/api/v16/buffer.en.md
+++ b/content/api/v16/buffer.en.md
@@ -13,7 +13,7 @@ Stable
-
+
`Buffer` objects are used to represent a fixed-length sequence of bytes. Many
Node.js APIs support `Buffer`s.
@@ -25,7 +25,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Creates a zero-filled Buffer of length 10.
@@ -56,9 +56,7 @@ 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.
@@ -99,7 +97,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello world', 'utf8');
@@ -113,9 +111,7 @@ 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');
@@ -194,7 +190,7 @@ The following legacy character encodings are also supported:
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
Buffer.from('1ag123', 'hex');
@@ -206,9 +202,7 @@ Buffer.from('1a7', 'hex');
Buffer.from('1634', 'hex');
// Prints , all data represented.
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
Buffer.from('1ag123', 'hex');
@@ -255,7 +249,7 @@ There are two ways to create new [`TypedArray`][] instances from a `Buffer`:
contents, interpreted as an array of integers, and not as a byte sequence
of the target type.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
@@ -264,9 +258,7 @@ 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]);
@@ -280,7 +272,7 @@ console.log(uint32array);
* Passing the `Buffer`s underlying [`ArrayBuffer`][] will create a
[`TypedArray`][] that shares its memory with the `Buffer`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello', 'utf16le');
@@ -292,9 +284,7 @@ const uint16array = new Uint16Array(
console.log(uint16array);
// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('hello', 'utf16le');
@@ -313,7 +303,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
@@ -338,9 +328,7 @@ console.log(buf1);
// Prints:
console.log(buf2);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
@@ -371,7 +359,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(20);
@@ -379,9 +367,7 @@ 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);
@@ -410,7 +396,7 @@ function:
`Buffer` instances can be iterated over using `for..of` syntax:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3]);
@@ -422,9 +408,7 @@ for (const b of buf) {
// 1
// 2
// 3
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3]);
@@ -530,7 +514,7 @@ 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
+```mjs|cjs
import { Blob, Buffer } from 'node:buffer';
import { setTimeout as delay } from 'node:timers/promises';
@@ -555,9 +539,7 @@ 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');
@@ -602,16 +584,14 @@ It can be constructed in a variety of ways.
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
`Buffer` will be zero-filled.
-```mjs
+```mjs|cjs
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);
@@ -627,16 +607,14 @@ is thrown.
If `fill` is specified, the allocated `Buffer` will be initialized by calling
[`buf.fill(fill)`][`buf.fill()`].
-```mjs
+```mjs|cjs
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');
@@ -648,16 +626,14 @@ console.log(buf);
If both `fill` and `encoding` are specified, the allocated `Buffer` will be
initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`].
-```mjs
+```mjs|cjs
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');
@@ -688,7 +664,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(10);
@@ -700,9 +676,7 @@ buf.fill(0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(10);
@@ -760,7 +734,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Need to keep around a few small chunks of memory.
@@ -778,9 +752,7 @@ socket.on('readable', () => {
store.push(sb);
}
});
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Need to keep around a few small chunks of memory.
@@ -821,7 +793,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const str = '\u00bd + \u00bc = \u00be';
@@ -829,9 +801,7 @@ 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';
@@ -858,7 +828,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('1234');
@@ -868,9 +838,7 @@ 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');
@@ -905,7 +873,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a single `Buffer` from a list of three `Buffer` instances.
@@ -924,9 +892,7 @@ 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.
@@ -959,14 +925,12 @@ console.log(bufA.length);
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
@@ -995,7 +959,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
@@ -1014,9 +978,7 @@ arr[1] = 6000;
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
@@ -1040,7 +1002,7 @@ console.log(buf);
The optional `byteOffset` and `length` arguments specify a memory range within
the `arrayBuffer` that will be shared by the `Buffer`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const ab = new ArrayBuffer(10);
@@ -1048,9 +1010,7 @@ const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const ab = new ArrayBuffer(10);
@@ -1069,7 +1029,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
@@ -1079,9 +1039,7 @@ 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
@@ -1102,7 +1060,7 @@ console.log(buf);
Copies the passed `buffer` data onto a new `Buffer` instance.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('buffer');
@@ -1114,9 +1072,7 @@ console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: buffer
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf1 = Buffer.from('buffer');
@@ -1144,14 +1100,12 @@ appropriate for `Buffer.from()` variants.
For objects whose `valueOf()` function returns a value not strictly equal to
`object`, returns `Buffer.from(object.valueOf(), offsetOrEncoding, length)`.
-```mjs
+```mjs|cjs
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'));
@@ -1161,7 +1115,7 @@ const buf = Buffer.from(new String('this is a test'));
For objects that support `Symbol.toPrimitive`, returns
`Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
class Foo {
@@ -1172,9 +1126,7 @@ class Foo {
const buf = Buffer.from(new Foo(), 'utf8');
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
class Foo {
@@ -1200,7 +1152,7 @@ is not of another type appropriate for `Buffer.from()` variants.
Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
the character encoding to be used when converting `string` into bytes.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('this is a tést');
@@ -1212,9 +1164,7 @@ 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');
@@ -1240,7 +1190,7 @@ appropriate for `Buffer.from()` variants.
Returns `true` if `obj` is a `Buffer`, `false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
Buffer.isBuffer(Buffer.alloc(10)); // true
@@ -1248,9 +1198,7 @@ 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
@@ -1270,7 +1218,7 @@ Buffer.isBuffer(new Uint8Array(1024)); // false
Returns `true` if `encoding` is the name of a supported character encoding,
or `false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
console.log(Buffer.isEncoding('utf8'));
@@ -1284,9 +1232,7 @@ console.log(Buffer.isEncoding('utf/8'));
console.log(Buffer.isEncoding(''));
// Prints: false
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
console.log(Buffer.isEncoding('utf8'));
@@ -1325,7 +1271,7 @@ access is the same as `Uint8Array`. In other words, `buf[index]` returns
`buf[index] = value` does not modify the buffer if `index` is negative or
`>= buf.length`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Copy an ASCII string into a `Buffer` one byte at a time.
@@ -1341,9 +1287,7 @@ for (let i = 0; i < str.length; 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.
@@ -1369,7 +1313,7 @@ console.log(buf.toString('utf8'));
This `ArrayBuffer` is not guaranteed to correspond exactly to the original
`Buffer`. See the notes on `buf.byteOffset` for details.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arrayBuffer = new ArrayBuffer(16);
@@ -1377,9 +1321,7 @@ const buffer = Buffer.from(arrayBuffer);
console.log(buffer.buffer === arrayBuffer);
// Prints: true
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const arrayBuffer = new ArrayBuffer(16);
@@ -1404,7 +1346,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a buffer smaller than `Buffer.poolSize`.
@@ -1414,9 +1356,7 @@ const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// 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`.
@@ -1452,7 +1392,7 @@ Comparison is based on the actual sequence of bytes in each `Buffer`.
* `1` is returned if `target` should come _before_ `buf` when sorted.
* `-1` is returned if `target` should come _after_ `buf` when sorted.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('ABC');
@@ -1472,9 +1412,7 @@ console.log(buf2.compare(buf3));
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');
@@ -1500,7 +1438,7 @@ The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`
arguments can be used to limit the comparison to specific ranges within `target`
and `buf` respectively.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
@@ -1512,9 +1450,7 @@ 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]);
@@ -1551,7 +1487,7 @@ memory region overlaps with `buf`.
for all TypedArrays, including Node.js `Buffer`s, although it takes
different function arguments.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create two `Buffer` instances.
@@ -1570,9 +1506,7 @@ buf1.copy(buf2, 8, 16, 20);
console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Create two `Buffer` instances.
@@ -1593,7 +1527,7 @@ console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
```
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a `Buffer` and copy data from one region to an overlapping region
@@ -1610,9 +1544,7 @@ 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
@@ -1640,7 +1572,7 @@ console.log(buf.toString());
Creates and returns an [iterator][] of `[index, byte]` pairs from the contents
of `buf`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Log the entire contents of a `Buffer`.
@@ -1657,9 +1589,7 @@ for (const pair of buf.entries()) {
// [3, 102]
// [4, 101]
// [5, 114]
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Log the entire contents of a `Buffer`.
@@ -1690,7 +1620,7 @@ Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,
`false` otherwise. Equivalent to
[`buf.compare(otherBuffer) === 0`][`buf.compare()`].
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('ABC');
@@ -1701,9 +1631,7 @@ 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');
@@ -1732,7 +1660,7 @@ console.log(buf1.equals(buf3));
Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
the entire `buf` will be filled:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with the ASCII character 'h'.
@@ -1741,9 +1669,7 @@ 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'.
@@ -1761,16 +1687,14 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
@@ -1782,7 +1706,7 @@ console.log(Buffer.allocUnsafe(5).fill('\u0222'));
If `value` contains invalid characters, it is truncated; if no valid
fill data remains, an exception is thrown:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(5);
@@ -1793,9 +1717,7 @@ 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);
@@ -1821,7 +1743,7 @@ console.log(buf.fill('zz', 'hex'));
Equivalent to [`buf.indexOf() !== -1`][`buf.indexOf()`].
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this is a buffer');
@@ -1840,9 +1762,7 @@ 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');
@@ -1885,7 +1805,7 @@ If `value` is:
* a number, `value` will be interpreted as an unsigned 8-bit integer
value between `0` and `255`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this is a buffer');
@@ -1909,9 +1829,7 @@ 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');
@@ -1945,7 +1863,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
@@ -1961,9 +1879,7 @@ 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');
@@ -1993,7 +1909,7 @@ than `buf.length`, `byteOffset` will be returned. If `value` is empty and
Creates and returns an [iterator][] of `buf` keys (indices).
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -2008,9 +1924,7 @@ for (const key of buf.keys()) {
// 3
// 4
// 5
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
@@ -2044,7 +1958,7 @@ for (const key of buf.keys()) {
Identical to [`buf.indexOf()`][], except the last occurrence of `value` is found
rather than the first occurrence.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this buffer is a buffer');
@@ -2070,9 +1984,7 @@ 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');
@@ -2108,7 +2020,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
@@ -2127,9 +2039,7 @@ console.log(b.lastIndexOf('b', {}));
// 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');
@@ -2160,7 +2070,7 @@ If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned.
Returns the number of bytes in `buf`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a `Buffer` and write a shorter string to it using UTF-8.
@@ -2174,9 +2084,7 @@ 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.
@@ -2244,16 +2152,14 @@ Reads an unsigned, big-endian 64-bit integer from `buf` at the specified
This function is also available under the `readBigUint64BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64BE(0));
// Prints: 4294967295n
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
@@ -2275,16 +2181,14 @@ Reads an unsigned, little-endian 64-bit integer from `buf` at the specified
This function is also available under the `readBigUint64LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64LE(0));
// Prints: 18446744069414584320n
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
@@ -2303,16 +2207,14 @@ console.log(buf.readBigUInt64LE(0));
Reads a 64-bit, big-endian double from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleBE(0));
// Prints: 8.20788039913184e-304
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
@@ -2331,7 +2233,7 @@ console.log(buf.readDoubleBE(0));
Reads a 64-bit, little-endian double from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
@@ -2340,9 +2242,7 @@ 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]);
@@ -2363,16 +2263,14 @@ console.log(buf.readDoubleLE(1));
Reads a 32-bit, big-endian float from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
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]);
@@ -2391,7 +2289,7 @@ console.log(buf.readFloatBE(0));
Reads a 32-bit, little-endian float from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
@@ -2400,9 +2298,7 @@ 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]);
@@ -2425,7 +2321,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([-1, 5]);
@@ -2436,9 +2332,7 @@ 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]);
@@ -2463,16 +2357,14 @@ 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
+```mjs|cjs
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]);
@@ -2494,7 +2386,7 @@ Reads a signed, little-endian 16-bit integer from `buf` at the specified
Integers read from a `Buffer` are interpreted as two's complement signed values.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 5]);
@@ -2503,9 +2395,7 @@ 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]);
@@ -2528,16 +2418,14 @@ 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
+```mjs|cjs
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]);
@@ -2559,7 +2447,7 @@ Reads a signed, little-endian 32-bit integer from `buf` at the specified
Integers read from a `Buffer` are interpreted as two's complement signed values.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 0, 0, 5]);
@@ -2568,9 +2456,7 @@ 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]);
@@ -2595,7 +2481,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2606,9 +2492,7 @@ 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]);
@@ -2635,16 +2519,14 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntLE(0, 6).toString(16));
// Prints: -546f87a9cbee
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2665,7 +2547,7 @@ Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
This function is also available under the `readUint8` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, -2]);
@@ -2676,9 +2558,7 @@ 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]);
@@ -2704,7 +2584,7 @@ Reads an unsigned, big-endian 16-bit integer from `buf` at the specified
This function is also available under the `readUint16BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56]);
@@ -2713,9 +2593,7 @@ 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]);
@@ -2739,7 +2617,7 @@ Reads an unsigned, little-endian 16-bit integer from `buf` at the specified
This function is also available under the `readUint16LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56]);
@@ -2750,9 +2628,7 @@ 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]);
@@ -2778,16 +2654,14 @@ Reads an unsigned, big-endian 32-bit integer from `buf` at the specified
This function is also available under the `readUint32BE` alias.
-```mjs
+```mjs|cjs
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]);
@@ -2809,7 +2683,7 @@ Reads an unsigned, little-endian 32-bit integer from `buf` at the specified
This function is also available under the `readUint32LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
@@ -2818,9 +2692,7 @@ 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]);
@@ -2847,7 +2719,7 @@ up to 48 bits of accuracy.
This function is also available under the `readUintBE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2856,9 +2728,7 @@ 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]);
@@ -2885,16 +2755,14 @@ up to 48 bits of accuracy.
This function is also available under the `readUintLE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntLE(0, 6).toString(16));
// Prints: ab9078563412
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2923,7 +2791,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
@@ -2945,9 +2813,7 @@ 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
@@ -2974,7 +2840,7 @@ console.log(buf2.toString('ascii', 0, buf2.length));
Specifying negative indexes causes the slice to be generated relative to the
end of `buf` rather than the beginning.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -2990,9 +2856,7 @@ console.log(buf.subarray(-6, -2).toString());
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');
@@ -3032,7 +2896,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -3052,9 +2916,7 @@ console.log(notReallyCopiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Also prints: cuffer (!)
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
@@ -3086,7 +2948,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
@@ -3103,9 +2965,7 @@ 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]);
@@ -3127,14 +2987,12 @@ buf2.swap16();
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
@@ -3151,7 +3009,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
@@ -3168,9 +3026,7 @@ 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]);
@@ -3198,7 +3054,7 @@ buf2.swap32();
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
@@ -3215,9 +3071,7 @@ 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]);
@@ -3248,7 +3102,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
@@ -3265,9 +3119,7 @@ const copy = JSON.parse(json, (key, value) => {
console.log(copy);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
@@ -3305,7 +3157,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.allocUnsafe(26);
@@ -3328,9 +3180,7 @@ 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);
@@ -3364,7 +3214,7 @@ console.log(buf2.toString(undefined, 0, 3));
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -3390,9 +3240,7 @@ for (const value of buf) {
// 102
// 101
// 114
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
@@ -3437,7 +3285,7 @@ Writes `string` to `buf` at `offset` according to the character encoding in
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(256);
@@ -3453,9 +3301,7 @@ 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);
@@ -3486,7 +3332,7 @@ Writes `value` to `buf` at the specified `offset` as big-endian.
`value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3495,9 +3341,7 @@ buf.writeBigInt64BE(0x0102030405060708n, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3521,7 +3365,7 @@ Writes `value` to `buf` at the specified `offset` as little-endian.
`value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3530,9 +3374,7 @@ buf.writeBigInt64LE(0x0102030405060708n, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3556,7 +3398,7 @@ Writes `value` to `buf` at the specified `offset` as big-endian.
This function is also available under the `writeBigUint64BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3565,9 +3407,7 @@ buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3589,7 +3429,7 @@ console.log(buf);
Writes `value` to `buf` at the specified `offset` as little-endian
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3598,9 +3438,7 @@ buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3626,7 +3464,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3635,9 +3473,7 @@ buf.writeDoubleBE(123.456, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3661,7 +3497,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3670,9 +3506,7 @@ buf.writeDoubleLE(123.456, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3695,7 +3529,7 @@ console.log(buf);
Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is
undefined when `value` is anything other than a JavaScript number.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3704,9 +3538,7 @@ buf.writeFloatBE(0xcafebabe, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3729,7 +3561,7 @@ console.log(buf);
Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is
undefined when `value` is anything other than a JavaScript number.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3738,9 +3570,7 @@ buf.writeFloatLE(0xcafebabe, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3766,7 +3596,7 @@ a signed 8-bit integer.
`value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
@@ -3776,9 +3606,7 @@ buf.writeInt8(-2, 1);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
@@ -3805,7 +3633,7 @@ anything other than a signed 16-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
@@ -3814,9 +3642,7 @@ buf.writeInt16BE(0x0102, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
@@ -3842,7 +3668,7 @@ anything other than a signed 16-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
@@ -3851,9 +3677,7 @@ buf.writeInt16LE(0x0304, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
@@ -3879,7 +3703,7 @@ anything other than a signed 32-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3888,9 +3712,7 @@ buf.writeInt32BE(0x01020304, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3916,7 +3738,7 @@ anything other than a signed 32-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3925,9 +3747,7 @@ buf.writeInt32LE(0x05060708, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3953,7 +3773,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -3962,9 +3782,7 @@ buf.writeIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -3990,7 +3808,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -3999,9 +3817,7 @@ buf.writeIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4027,7 +3843,7 @@ other than an unsigned 8-bit integer.
This function is also available under the `writeUint8` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4039,9 +3855,7 @@ buf.writeUInt8(0x42, 3);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4070,7 +3884,7 @@ is anything other than an unsigned 16-bit integer.
This function is also available under the `writeUint16BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4080,9 +3894,7 @@ buf.writeUInt16BE(0xbeef, 2);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4109,7 +3921,7 @@ anything other than an unsigned 16-bit integer.
This function is also available under the `writeUint16LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4119,9 +3931,7 @@ buf.writeUInt16LE(0xbeef, 2);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4148,7 +3958,7 @@ is anything other than an unsigned 32-bit integer.
This function is also available under the `writeUint32BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4157,9 +3967,7 @@ buf.writeUInt32BE(0xfeedface, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4185,7 +3993,7 @@ anything other than an unsigned 32-bit integer.
This function is also available under the `writeUint32LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4194,9 +4002,7 @@ buf.writeUInt32LE(0xfeedface, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4224,7 +4030,7 @@ when `value` is anything other than an unsigned integer.
This function is also available under the `writeUintBE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -4233,9 +4039,7 @@ buf.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4263,7 +4067,7 @@ when `value` is anything other than an unsigned integer.
This function is also available under the `writeUintLE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -4272,9 +4076,7 @@ buf.writeUIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4481,15 +4283,13 @@ Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,
The transcoding process will use substitution characters if a given byte
sequence cannot be adequately represented in the target encoding. For instance:
-```mjs
+```mjs|cjs
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');
diff --git a/content/api/v16/child_process.en.md b/content/api/v16/child_process.en.md
index 57dca36cc1..07133468c5 100644
--- a/content/api/v16/child_process.en.md
+++ b/content/api/v16/child_process.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:child_process` module provides the ability to spawn subprocesses in
a manner that is similar, but not identical, to popen(3). This capability
@@ -117,7 +117,7 @@ When running on Windows, `.bat` and `.cmd` files can be invoked using
[`child_process.exec()`][] do). In any case, if the script filename contains
spaces it needs to be quoted.
-```js
+```js|js
// On Windows Only...
const { spawn } = require('node:child_process');
const bat = spawn('cmd.exe', ['/c', 'my.bat']);
@@ -133,9 +133,7 @@ bat.stderr.on('data', (data) => {
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) => {
diff --git a/content/api/v16/cluster.en.md b/content/api/v16/cluster.en.md
index ec6c45fb67..c5f23e2c3b 100644
--- a/content/api/v16/cluster.en.md
+++ b/content/api/v16/cluster.en.md
@@ -13,7 +13,7 @@ Stable
-
+
Clusters of Node.js processes can be used to run multiple instances of Node.js
that can distribute workloads among their application threads. When process
@@ -23,7 +23,7 @@ allows running multiple application threads within a single Node.js instance.
The cluster module allows easy creation of child processes that all share
server ports.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import http from 'node:http';
import { cpus } from 'node:os';
@@ -52,9 +52,7 @@ if (cluster.isPrimary) {
console.log(`Worker ${process.pid} started`);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const http = require('node:http');
const numCPUs = require('node:os').cpus().length;
@@ -195,7 +193,7 @@ Within a worker, `process.on('error')` may also be used.
Similar to the `cluster.on('exit')` event, but specific to this worker.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
if (cluster.isPrimary) {
@@ -210,9 +208,7 @@ if (cluster.isPrimary) {
}
});
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
if (cluster.isPrimary) {
@@ -237,13 +233,11 @@ if (cluster.isPrimary) {
Similar to the `cluster.on('listening')` event, but specific to this worker.
-```mjs
+```mjs|cjs
cluster.fork().on('listening', (address) => {
// Worker is listening
});
-```
-
-```cjs
+--------------
cluster.fork().on('listening', (address) => {
// Worker is listening
});
@@ -267,7 +261,7 @@ See [`process` event: `'message'`][].
Here is an example using the message system. It keeps a count in the primary
process of the number of HTTP requests received by the workers:
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import http from 'node:http';
import { cpus } from 'node:os';
@@ -309,9 +303,7 @@ if (cluster.isPrimary) {
process.send({ cmd: 'notifyRequest' });
}).listen(8000);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const http = require('node:http');
const process = require('node:process');
@@ -485,7 +477,7 @@ has been created. It is disconnected after the `'disconnect'` event is emitted.
This function returns `true` if the worker's process has terminated (either
because of exiting or being signaled). Otherwise, it returns `false`.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import http from 'node:http';
import { cpus } from 'node:os';
@@ -516,9 +508,7 @@ if (cluster.isPrimary) {
process.kill(process.pid);
}).listen(8000);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const http = require('node:http');
const numCPUs = require('node:os').cpus().length;
@@ -897,7 +887,7 @@ the `env` passed to [`.fork()`][].
The defaults above apply to the first call only; the defaults for later
calls are the current values at the time of `cluster.setupPrimary()` is called.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
cluster.setupPrimary({
@@ -911,9 +901,7 @@ cluster.setupPrimary({
args: ['--use', 'http']
});
cluster.fork(); // http worker
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
cluster.setupPrimary({
@@ -939,7 +927,7 @@ This can only be called from the primary process.
A reference to the current worker object. Not available in the primary process.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
if (cluster.isPrimary) {
@@ -949,9 +937,7 @@ if (cluster.isPrimary) {
} else if (cluster.isWorker) {
console.log(`I am worker #${cluster.worker.id}`);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
if (cluster.isPrimary) {
@@ -978,15 +964,13 @@ _and_ exited. The order between these two events cannot be determined in
advance. However, it is guaranteed that the removal from the `cluster.workers`
list happens before the last `'disconnect'` or `'exit'` event is emitted.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
for (const worker of Object.values(cluster.workers)) {
worker.send('big announcement to all workers');
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
for (const worker of Object.values(cluster.workers)) {
diff --git a/content/api/v16/console.en.md b/content/api/v16/console.en.md
index 24eb935369..ee394af4d6 100644
--- a/content/api/v16/console.en.md
+++ b/content/api/v16/console.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:console` module provides a simple debugging console that is similar to
the JavaScript console mechanism provided by web browsers.
@@ -83,11 +83,9 @@ The `Console` class can be used to create a simple logger with configurable
output streams and can be accessed using either `require('node:console').Console`
or `console.Console` (or their destructured counterparts):
-```js
+```js|js
const { Console } = require('node:console');
-```
-
-```js
+--------------
const { Console } = console;
```
diff --git a/content/api/v16/crypto.en.md b/content/api/v16/crypto.en.md
index 07143cbfb0..3058fa0813 100644
--- a/content/api/v16/crypto.en.md
+++ b/content/api/v16/crypto.en.md
@@ -13,13 +13,13 @@ Stable
-
+
The `node:crypto` module provides cryptographic functionality that includes a
set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
functions.
-```mjs
+```mjs|cjs
const { createHmac } = await import('node:crypto');
const secret = 'abcdefg';
@@ -29,9 +29,7 @@ const hash = createHmac('sha256', secret)
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
-```
-
-```cjs
+--------------
const crypto = require('node:crypto');
const secret = 'abcdefg';
@@ -101,15 +99,13 @@ data. The most common usage is handling output generated by the HTML5
* Returns: [`Buffer`](/api/v16/buffer#buffer) The challenge component of the `spkac` data structure, which
includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
@@ -126,15 +122,13 @@ console.log(challenge.toString('utf8'));
* Returns: [`Buffer`](/api/v16/buffer#buffer) The public key component of the `spkac` data structure,
which includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
@@ -151,16 +145,14 @@ console.log(publicKey);
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the given `spkac` data structure is valid,
`false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -185,14 +177,12 @@ the `crypto.Certificate` class as illustrated in the examples below.
Instances of the `Certificate` class can be created using the `new` keyword
or by calling `crypto.Certificate()` as a function:
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const cert1 = new Certificate();
const cert2 = Certificate();
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const cert1 = new Certificate();
@@ -208,16 +198,14 @@ const cert2 = Certificate();
* Returns: [`Buffer`](/api/v16/buffer#buffer) The challenge component of the `spkac` data structure, which
includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
@@ -235,16 +223,14 @@ console.log(challenge.toString('utf8'));
* Returns: [`Buffer`](/api/v16/buffer#buffer) The public key component of the `spkac` data structure,
which includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
@@ -262,7 +248,7 @@ console.log(publicKey);
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the given `spkac` data structure is valid,
`false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { Certificate } = await import('node:crypto');
@@ -270,9 +256,7 @@ const cert = Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -302,7 +286,7 @@ directly using the `new` keyword.
Example: Using `Cipher` objects as streams:
-```mjs
+```mjs|cjs
const {
scrypt,
randomFill,
@@ -333,9 +317,7 @@ scrypt(password, 'salt', 24, (err, key) => {
cipher.end();
});
});
-```
-
-```cjs
+--------------
const {
scrypt,
randomFill,
@@ -370,7 +352,7 @@ scrypt(password, 'salt', 24, (err, key) => {
Example: Using `Cipher` and piped streams:
-```mjs
+```mjs|cjs
import {
createReadStream,
createWriteStream,
@@ -407,9 +389,7 @@ scrypt(password, 'salt', 24, (err, key) => {
});
});
});
-```
-
-```cjs
+--------------
const {
createReadStream,
createWriteStream,
@@ -450,7 +430,7 @@ scrypt(password, 'salt', 24, (err, key) => {
Example: Using the [`cipher.update()`][] and [`cipher.final()`][] methods:
-```mjs
+```mjs|cjs
const {
scrypt,
randomFill,
@@ -475,9 +455,7 @@ scrypt(password, 'salt', 24, (err, key) => {
console.log(encrypted);
});
});
-```
-
-```cjs
+--------------
const {
scrypt,
randomFill,
@@ -618,7 +596,7 @@ directly using the `new` keyword.
Example: Using `Decipher` objects as streams:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
scryptSync,
@@ -653,9 +631,7 @@ const encrypted =
'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
decipher.write(encrypted, 'hex');
decipher.end();
-```
-
-```cjs
+--------------
const {
scryptSync,
createDecipheriv,
@@ -694,7 +670,7 @@ decipher.end();
Example: Using `Decipher` and piped streams:
-```mjs
+```mjs|cjs
import {
createReadStream,
createWriteStream,
@@ -718,9 +694,7 @@ const input = createReadStream('test.enc');
const output = createWriteStream('test.js');
input.pipe(decipher).pipe(output);
-```
-
-```cjs
+--------------
const {
createReadStream,
createWriteStream,
@@ -748,7 +722,7 @@ input.pipe(decipher).pipe(output);
Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
scryptSync,
@@ -771,9 +745,7 @@ let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
// Prints: some clear text data
-```
-
-```cjs
+--------------
const {
scryptSync,
createDecipheriv,
@@ -911,7 +883,7 @@ exchanges.
Instances of the `DiffieHellman` class can be created using the
[`crypto.createDiffieHellman()`][] function.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const {
@@ -932,9 +904,7 @@ const bobSecret = bob.computeSecret(aliceKey);
// OK
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const {
@@ -984,12 +954,17 @@ If `outputEncoding` is given a string is returned; otherwise, a
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value.
* Returns: [`Buffer`](/api/v16/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-Generates private and public Diffie-Hellman key values, and returns
+Generates private and public Diffie-Hellman key values unless they have been
+generated or computed already, and returns
the public key in the specified `encoding`. This key should be
transferred to the other party.
If `encoding` is provided a string is returned; otherwise a
[`Buffer`][] is returned.
+This function is a thin wrapper around [`DH_generate_key()`][]. In particular,
+once a private key has been generated or set, calling this function only updates
+the public key but does not generate a new private key.
+
#### `diffieHellman.getGenerator([encoding])`
@@ -1046,6 +1021,10 @@ Sets the Diffie-Hellman private key. If the `encoding` argument is provided,
to be a string. If no `encoding` is provided, `privateKey` is expected
to be a [`Buffer`][], `TypedArray`, or `DataView`.
+This function does not automatically compute the associated public key. Either
+[`diffieHellman.setPublicKey()`][] or [`diffieHellman.generateKeys()`][] can be
+used to manually provide the public key or to automatically derive it.
+
#### `diffieHellman.setPublicKey(publicKey[, encoding])`
@@ -1081,12 +1060,10 @@ It works the same as `DiffieHellman`, except that it does not allow changing
its keys after creation. In other words, it does not implement `setPublicKey()`
or `setPrivateKey()` methods.
-```mjs
+```mjs|cjs
const { createDiffieHellmanGroup } = await import('node:crypto');
const dh = createDiffieHellmanGroup('modp16');
-```
-
-```cjs
+--------------
const { createDiffieHellmanGroup } = require('node:crypto');
const dh = createDiffieHellmanGroup('modp16');
```
@@ -1117,7 +1094,7 @@ key exchanges.
Instances of the `ECDH` class can be created using the
[`crypto.createECDH()`][] function.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const {
@@ -1138,9 +1115,7 @@ const bobSecret = bob.computeSecret(aliceKey);
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const {
@@ -1192,7 +1167,7 @@ If the `inputEncoding` is not provided, `key` is expected to be a [`Buffer`][],
Example (uncompressing a key):
-```mjs
+```mjs|cjs
const {
createECDH,
ECDH
@@ -1211,9 +1186,7 @@ const uncompressedKey = ECDH.convertKey(compressedKey,
// The converted key and the uncompressed public key should be the same
console.log(uncompressedKey === ecdh.getPublicKey('hex'));
-```
-
-```cjs
+--------------
const {
createECDH,
ECDH,
@@ -1347,7 +1320,7 @@ set.
Example (obtaining a shared secret):
-```mjs
+```mjs|cjs
const {
createECDH,
createHash
@@ -1372,9 +1345,7 @@ const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
// aliceSecret and bobSecret should be the same shared secret value
console.log(aliceSecret === bobSecret);
-```
-
-```cjs
+--------------
const {
createECDH,
createHash,
@@ -1420,7 +1391,7 @@ objects are not to be created directly using the `new` keyword.
Example: Using `Hash` objects as streams:
-```mjs
+```mjs|cjs
const {
createHash
} = await import('node:crypto');
@@ -1440,9 +1411,7 @@ hash.on('readable', () => {
hash.write('some data to hash');
hash.end();
-```
-
-```cjs
+--------------
const {
createHash,
} = require('node:crypto');
@@ -1466,7 +1435,7 @@ hash.end();
Example: Using `Hash` and piped streams:
-```mjs
+```mjs|cjs
import { createReadStream } from 'node:fs';
import { stdout } from 'node:process';
const { createHash } = await import('node:crypto');
@@ -1475,9 +1444,7 @@ const hash = createHash('sha256');
const input = createReadStream('test.js');
input.pipe(hash).setEncoding('hex').pipe(stdout);
-```
-
-```cjs
+--------------
const { createReadStream } = require('node:fs');
const { createHash } = require('node:crypto');
const { stdout } = require('node:process');
@@ -1490,7 +1457,7 @@ input.pipe(hash).setEncoding('hex').pipe(stdout);
Example: Using the [`hash.update()`][] and [`hash.digest()`][] methods:
-```mjs
+```mjs|cjs
const {
createHash
} = await import('node:crypto');
@@ -1501,9 +1468,7 @@ hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
-```
-
-```cjs
+--------------
const {
createHash,
} = require('node:crypto');
@@ -1533,7 +1498,7 @@ specify the desired output length in bytes.
An error is thrown when an attempt is made to copy the `Hash` object after
its [`hash.digest()`][] method has been called.
-```mjs
+```mjs|cjs
// Calculate a rolling hash.
const {
createHash
@@ -1551,9 +1516,7 @@ hash.update('three');
console.log(hash.copy().digest('hex'));
// Etc.
-```
-
-```cjs
+--------------
// Calculate a rolling hash.
const {
createHash,
@@ -1622,7 +1585,7 @@ objects are not to be created directly using the `new` keyword.
Example: Using `Hmac` objects as streams:
-```mjs
+```mjs|cjs
const {
createHmac
} = await import('node:crypto');
@@ -1642,9 +1605,7 @@ hmac.on('readable', () => {
hmac.write('some data to hash');
hmac.end();
-```
-
-```cjs
+--------------
const {
createHmac,
} = require('node:crypto');
@@ -1668,7 +1629,7 @@ hmac.end();
Example: Using `Hmac` and piped streams:
-```mjs
+```mjs|cjs
import { createReadStream } from 'node:fs';
import { stdout } from 'node:process';
const {
@@ -1679,9 +1640,7 @@ const hmac = createHmac('sha256', 'a secret');
const input = createReadStream('test.js');
input.pipe(hmac).pipe(stdout);
-```
-
-```cjs
+--------------
const {
createReadStream,
} = require('node:fs');
@@ -1698,7 +1657,7 @@ input.pipe(hmac).pipe(stdout);
Example: Using the [`hmac.update()`][] and [`hmac.digest()`][] methods:
-```mjs
+```mjs|cjs
const {
createHmac
} = await import('node:crypto');
@@ -1709,9 +1668,7 @@ hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
-```
-
-```cjs
+--------------
const {
createHmac,
} = require('node:crypto');
@@ -1780,7 +1737,7 @@ be listed in the `transferList` argument.
Example: Converting a `CryptoKey` instance to a `KeyObject`:
-```mjs
+```mjs|cjs
const { webcrypto, KeyObject } = await import('node:crypto');
const { subtle } = webcrypto;
@@ -1793,9 +1750,7 @@ const key = await subtle.generateKey({
const keyObject = KeyObject.from(key);
console.log(keyObject.symmetricKeySize);
// Prints: 32 (symmetric key size in bytes)
-```
-
-```cjs
+--------------
const {
webcrypto: {
subtle,
@@ -1958,7 +1913,7 @@ to be created directly using the `new` keyword.
Example: Using `Sign` and [`Verify`][] objects as streams:
-```mjs
+```mjs|cjs
const {
generateKeyPairSync,
createSign,
@@ -1979,9 +1934,7 @@ verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature, 'hex'));
// Prints: true
-```
-
-```cjs
+--------------
const {
generateKeyPairSync,
createSign,
@@ -2006,7 +1959,7 @@ console.log(verify.verify(publicKey, signature, 'hex'));
Example: Using the [`sign.update()`][] and [`verify.update()`][] methods:
-```mjs
+```mjs|cjs
const {
generateKeyPairSync,
createSign,
@@ -2027,9 +1980,7 @@ verify.update('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature));
// Prints: true
-```
-
-```cjs
+--------------
const {
generateKeyPairSync,
createSign,
@@ -2202,15 +2153,13 @@ be passed instead of a public key.
Encapsulates an X509 certificate and provides read-only access to
its information.
-```mjs
+```mjs|cjs
const { X509Certificate } = await import('node:crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
console.log(x509.subject);
-```
-
-```cjs
+--------------
const { X509Certificate } = require('node:crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
@@ -2860,7 +2809,7 @@ display the available digest algorithms.
Example: generating the sha256 sum of a file
-```mjs
+```mjs|cjs
import {
createReadStream
} from 'node:fs';
@@ -2884,9 +2833,7 @@ input.on('readable', () => {
console.log(`${hash.digest('hex')} ${filename}`);
}
});
-```
-
-```cjs
+--------------
const {
createReadStream,
} = require('node:fs');
@@ -2935,7 +2882,7 @@ a [`KeyObject`][], its type must be `secret`.
Example: generating the sha256 HMAC of a file
-```mjs
+```mjs|cjs
import {
createReadStream
} from 'node:fs';
@@ -2959,9 +2906,7 @@ input.on('readable', () => {
console.log(`${hmac.digest('hex')} ${filename}`);
}
});
-```
-
-```cjs
+--------------
const {
createReadStream,
} = require('node:fs');
@@ -3119,7 +3064,7 @@ Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`
Asynchronously generates a new random secret key of the given `length`. The
`type` will determine which validations will be performed on the `length`.
-```mjs
+```mjs|cjs
const {
generateKey
} = await import('node:crypto');
@@ -3128,9 +3073,7 @@ generateKey('hmac', { length: 64 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});
-```
-
-```cjs
+--------------
const {
generateKey,
} = require('node:crypto');
@@ -3178,7 +3121,7 @@ the respective part of the key is returned as a [`KeyObject`][].
It is recommended to encode public keys as `'spki'` and private keys as
`'pkcs8'` with encryption for long-term storage:
-```mjs
+```mjs|cjs
const {
generateKeyPair
} = await import('node:crypto');
@@ -3198,9 +3141,7 @@ generateKeyPair('rsa', {
}, (err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
});
-```
-
-```cjs
+--------------
const {
generateKeyPair,
} = require('node:crypto');
@@ -3265,7 +3206,7 @@ When encoding public keys, it is recommended to use `'spki'`. When encoding
private keys, it is recommended to use `'pkcs8'` with a strong passphrase,
and to keep the passphrase confidential.
-```mjs
+```mjs|cjs
const {
generateKeyPairSync
} = await import('node:crypto');
@@ -3286,9 +3227,7 @@ const {
passphrase: 'top secret'
}
});
-```
-
-```cjs
+--------------
const {
generateKeyPairSync,
} = require('node:crypto');
@@ -3332,16 +3271,14 @@ it will be a buffer containing the data encoded as DER.
Synchronously generates a new random secret key of the given `length`. The
`type` will determine which validations will be performed on the `length`.
-```mjs
+```mjs|cjs
const {
generateKeySync
} = await import('node:crypto');
const key = generateKeySync('hmac', { length: 64 });
console.log(key.export().toString('hex')); // e89..........41e
-```
-
-```cjs
+--------------
const {
generateKeySync,
} = require('node:crypto');
@@ -3465,15 +3402,13 @@ unacceptable, `undefined` will be returned.
* Returns: string\[] An array with the names of the supported cipher
algorithms.
-```mjs
+```mjs|cjs
const {
getCiphers
} = await import('node:crypto');
console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
-```
-
-```cjs
+--------------
const {
getCiphers,
} = require('node:crypto');
@@ -3487,15 +3422,13 @@ console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
* Returns: string\[] An array with the names of the supported elliptic curves.
-```mjs
+```mjs|cjs
const {
getCurves
} = await import('node:crypto');
console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
-```
-
-```cjs
+--------------
const {
getCurves,
} = require('node:crypto');
@@ -3522,7 +3455,7 @@ and communication time.
Example (obtaining a shared secret):
-```mjs
+```mjs|cjs
const {
getDiffieHellman
} = await import('node:crypto');
@@ -3537,9 +3470,7 @@ const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);
-```
-
-```cjs
+--------------
const {
getDiffieHellman,
} = require('node:crypto');
@@ -3572,15 +3503,13 @@ console.log(aliceSecret === bobSecret);
* Returns: string\[] An array of the names of the supported hash algorithms,
such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms.
-```mjs
+```mjs|cjs
const {
getHashes
} = await import('node:crypto');
console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
-```
-
-```cjs
+--------------
const {
getHashes,
} = require('node:crypto');
@@ -3616,7 +3545,7 @@ otherwise `err` will be `null`. The successfully generated `derivedKey` will
be passed to the callback as an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any
of the input arguments specify invalid values or types.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
hkdf
@@ -3626,9 +3555,7 @@ hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
if (err) throw err;
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
});
-```
-
-```cjs
+--------------
const {
hkdf,
} = require('node:crypto');
@@ -3666,7 +3593,7 @@ The successfully generated `derivedKey` will be returned as an [`ArrayBuffer`](h
An error will be thrown if any of the input arguments specify invalid values or
types, or if the derived key cannot be generated.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
hkdfSync
@@ -3674,9 +3601,7 @@ const {
const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
-```
-
-```cjs
+--------------
const {
hkdfSync,
} = require('node:crypto');
@@ -3720,7 +3645,7 @@ random and at least 16 bytes long. See [NIST SP 800-132][] for details.
When passing strings for `password` or `salt`, please consider
[caveats when using strings as inputs to cryptographic APIs][].
-```mjs
+```mjs|cjs
const {
pbkdf2
} = await import('node:crypto');
@@ -3729,9 +3654,7 @@ pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
-```
-
-```cjs
+--------------
const {
pbkdf2,
} = require('node:crypto');
@@ -3746,16 +3669,14 @@ The `crypto.DEFAULT_ENCODING` property can be used to change the way the
`derivedKey` is passed to the callback. This property, however, has been
deprecated and use should be avoided.
-```mjs
+```mjs|cjs
import crypto from 'node:crypto';
crypto.DEFAULT_ENCODING = 'hex';
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey); // '3745e48...aa39b34'
});
-```
-
-```cjs
+--------------
const crypto = require('node:crypto');
crypto.DEFAULT_ENCODING = 'hex';
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
@@ -3800,16 +3721,14 @@ random and at least 16 bytes long. See [NIST SP 800-132][] for details.
When passing strings for `password` or `salt`, please consider
[caveats when using strings as inputs to cryptographic APIs][].
-```mjs
+```mjs|cjs
const {
pbkdf2Sync
} = await import('node:crypto');
const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex')); // '3745e48...08d59ae'
-```
-
-```cjs
+--------------
const {
pbkdf2Sync,
} = require('node:crypto');
@@ -3822,14 +3741,12 @@ The `crypto.DEFAULT_ENCODING` property may be used to change the way the
`derivedKey` is returned. This property, however, is deprecated and use
should be avoided.
-```mjs
+```mjs|cjs
import crypto from 'node:crypto';
crypto.DEFAULT_ENCODING = 'hex';
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
console.log(key); // '3745e48...aa39b34'
-```
-
-```cjs
+--------------
const crypto = require('node:crypto');
crypto.DEFAULT_ENCODING = 'hex';
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
@@ -3967,7 +3884,7 @@ and the `callback` function is invoked with two arguments: `err` and `buf`.
If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The
`buf` argument is a [`Buffer`][] containing the generated bytes.
-```mjs
+```mjs|cjs
// Asynchronous
const {
randomBytes
@@ -3977,9 +3894,7 @@ randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});
-```
-
-```cjs
+--------------
// Asynchronous
const {
randomBytes,
@@ -3995,7 +3910,7 @@ If the `callback` function is not provided, the random bytes are generated
synchronously and returned as a [`Buffer`][]. An error will be thrown if
there is a problem generating the bytes.
-```mjs
+```mjs|cjs
// Synchronous
const {
randomBytes
@@ -4004,9 +3919,7 @@ const {
const buf = randomBytes(256);
console.log(
`${buf.length} bytes of random data: ${buf.toString('hex')}`);
-```
-
-```cjs
+--------------
// Synchronous
const {
randomBytes,
@@ -4046,7 +3959,7 @@ request.
Synchronous version of [`crypto.randomFill()`][].
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');
@@ -4059,9 +3972,7 @@ console.log(buf.toString('hex'));
// The above is equivalent to the following:
randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));
-```
-
-```cjs
+--------------
const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4079,7 +3990,7 @@ console.log(buf.toString('hex'));
Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as
`buffer`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');
@@ -4093,9 +4004,7 @@ console.log(Buffer.from(randomFillSync(b).buffer,
const c = new ArrayBuffer(10);
console.log(Buffer.from(randomFillSync(c)).toString('hex'));
-```
-
-```cjs
+--------------
const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4128,7 +4037,7 @@ requires that a callback is passed in.
If the `callback` function is not provided, an error will be thrown.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');
@@ -4148,9 +4057,7 @@ randomFill(buf, 5, 5, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
-```
-
-```cjs
+--------------
const { randomFill } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4181,7 +4088,7 @@ result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array
contains finite numbers only, they are not drawn from a uniform random
distribution and have no meaningful lower or upper bounds.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');
@@ -4204,9 +4111,7 @@ randomFill(c, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf).toString('hex'));
});
-```
-
-```cjs
+--------------
const { randomFill } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4257,7 +4162,7 @@ be [safe integers][].
If the `callback` function is not provided, the random integer is
generated synchronously.
-```mjs
+```mjs|cjs
// Asynchronous
const {
randomInt
@@ -4267,9 +4172,7 @@ randomInt(3, (err, n) => {
if (err) throw err;
console.log(`Random number chosen from (0, 1, 2): ${n}`);
});
-```
-
-```cjs
+--------------
// Asynchronous
const {
randomInt,
@@ -4281,7 +4184,7 @@ randomInt(3, (err, n) => {
});
```
-```mjs
+```mjs|cjs
// Synchronous
const {
randomInt
@@ -4289,9 +4192,7 @@ const {
const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
-```
-
-```cjs
+--------------
// Synchronous
const {
randomInt,
@@ -4301,7 +4202,7 @@ const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
```
-```mjs
+```mjs|cjs
// With `min` argument
const {
randomInt
@@ -4309,9 +4210,7 @@ const {
const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);
-```
-
-```cjs
+--------------
// With `min` argument
const {
randomInt,
@@ -4374,7 +4273,7 @@ The `callback` function is called with two arguments: `err` and `derivedKey`.
An exception is thrown when any of the input arguments specify invalid values
or types.
-```mjs
+```mjs|cjs
const {
scrypt
} = await import('node:crypto');
@@ -4389,9 +4288,7 @@ scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
});
-```
-
-```cjs
+--------------
const {
scrypt,
} = require('node:crypto');
@@ -4443,7 +4340,7 @@ returned as a [`Buffer`][].
An exception is thrown when any of the input arguments specify invalid values
or types.
-```mjs
+```mjs|cjs
const {
scryptSync
} = await import('node:crypto');
@@ -4454,9 +4351,7 @@ console.log(key1.toString('hex')); // '3745e48...08d59ae'
// Using a custom N parameter. Must be a power of two.
const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
console.log(key2.toString('hex')); // '3745e48...aa39b34'
-```
-
-```cjs
+--------------
const {
scryptSync,
} = require('node:crypto');
@@ -4755,7 +4650,7 @@ mode must adhere to certain restrictions when using the cipher API:
applications _must_ call `final()` to compute or verify the
authentication tag.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
createCipheriv,
@@ -4797,9 +4692,7 @@ try {
}
console.log(receivedPlaintext);
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const {
createCipheriv,
@@ -5210,6 +5103,7 @@ See the [list of SSL OP Flags][] for details.
[Web Crypto API documentation]: /api/v16/webcrypto
[`BN_is_prime_ex`]: https://www.openssl.org/docs/man1.1.1/man3/BN_is_prime_ex.html
[`Buffer`]: /api/v16/buffer
+[`DH_generate_key()`]: https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html
[`DiffieHellmanGroup`]: #class-diffiehellmangroup
[`EVP_BytesToKey`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html
[`KeyObject`]: #class-keyobject
@@ -5244,6 +5138,7 @@ See the [list of SSL OP Flags][] for details.
[`crypto.scrypt()`]: #cryptoscryptpassword-salt-keylen-options-callback
[`decipher.final()`]: #decipherfinaloutputencoding
[`decipher.update()`]: #decipherupdatedata-inputencoding-outputencoding
+[`diffieHellman.generateKeys()`]: #diffiehellmangeneratekeysencoding
[`diffieHellman.setPublicKey()`]: #diffiehellmansetpublickeypublickey-encoding
[`ecdh.generateKeys()`]: #ecdhgeneratekeysencoding-format
[`ecdh.setPrivateKey()`]: #ecdhsetprivatekeyprivatekey-encoding
diff --git a/content/api/v16/dgram.en.md b/content/api/v16/dgram.en.md
index 004cd31453..de0f224bc7 100644
--- a/content/api/v16/dgram.en.md
+++ b/content/api/v16/dgram.en.md
@@ -15,11 +15,11 @@ Stable
-
+
The `node:dgram` module provides an implementation of UDP datagram sockets.
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
const server = dgram.createSocket('udp4');
@@ -40,9 +40,7 @@ server.on('listening', () => {
server.bind(41234);
// Prints: server listening 0.0.0.0:41234
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const server = dgram.createSocket('udp4');
@@ -148,7 +146,7 @@ When sharing a UDP socket across multiple `cluster` workers, the
`socket.addMembership()` function must be called only once or an
`EADDRINUSE` error will occur:
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import dgram from 'node:dgram';
@@ -161,9 +159,7 @@ if (cluster.isPrimary) {
s.addMembership('224.0.0.114');
});
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const dgram = require('node:dgram');
@@ -236,7 +232,7 @@ attempting to bind with a closed socket), an [`Error`][] may be thrown.
Example of a UDP server listening on port 41234:
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
const server = dgram.createSocket('udp4');
@@ -257,9 +253,7 @@ server.on('listening', () => {
server.bind(41234);
// Prints: server listening 0.0.0.0:41234
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const server = dgram.createSocket('udp4');
@@ -511,7 +505,7 @@ This method throws [`ERR_SOCKET_BAD_PORT`][] if called on an unbound socket.
Example of sending a UDP packet to a port on `localhost`;
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';
@@ -520,9 +514,7 @@ const client = dgram.createSocket('udp4');
client.send(message, 41234, 'localhost', (err) => {
client.close();
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
@@ -536,7 +528,7 @@ client.send(message, 41234, 'localhost', (err) => {
Example of sending a UDP packet composed of multiple buffers to a port on
`127.0.0.1`;
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';
@@ -546,9 +538,7 @@ const client = dgram.createSocket('udp4');
client.send([buf1, buf2], 41234, (err) => {
client.close();
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
@@ -568,7 +558,7 @@ however, sending multiple buffers is faster.
Example of sending a UDP packet using a socket connected to a port on
`localhost`:
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';
@@ -579,9 +569,7 @@ client.connect(41234, 'localhost', (err) => {
client.close();
});
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
diff --git a/content/api/v16/diagnostics_channel.en.md b/content/api/v16/diagnostics_channel.en.md
index 51d6d47a1a..0f007e70c8 100644
--- a/content/api/v16/diagnostics_channel.en.md
+++ b/content/api/v16/diagnostics_channel.en.md
@@ -13,18 +13,16 @@ Experimental
-
+
The `node:diagnostics_channel` module provides an API to create named channels
to report arbitrary message data for diagnostics purposes.
It can be accessed using:
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
```
@@ -46,7 +44,7 @@ other modules.
Following is a simple overview of the public API.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
// Get a reusable channel object
@@ -69,9 +67,7 @@ if (channel.hasSubscribers) {
// Unsubscribe from the channel
diagnostics_channel.unsubscribe('my-channel', onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
// Get a reusable channel object
@@ -109,15 +105,13 @@ the message you want to send might be expensive to prepare.
This API is optional but helpful when trying to publish messages from very
performance-sensitive code.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
if (diagnostics_channel.hasSubscribers('my-channel')) {
// There are subscribers, prepare and publish message
}
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
if (diagnostics_channel.hasSubscribers('my-channel')) {
@@ -136,13 +130,11 @@ This is the primary entry-point for anyone wanting to publish to a named
channel. It produces a channel object which is optimized to reduce overhead at
publish time as much as possible.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -161,15 +153,13 @@ Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an [`'uncaughtException'`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'diagnostics_channel';
diagnostics_channel.subscribe('my-channel', (message, name) => {
// Received data
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('diagnostics_channel');
diagnostics_channel.subscribe('my-channel', (message, name) => {
@@ -188,7 +178,7 @@ diagnostics_channel.subscribe('my-channel', (message, name) => {
Remove a message handler previously registered to this channel with
[`diagnostics_channel.subscribe(name, onMessage)`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'diagnostics_channel';
function onMessage(message, name) {
@@ -198,9 +188,7 @@ function onMessage(message, name) {
diagnostics_channel.subscribe('my-channel', onMessage);
diagnostics_channel.unsubscribe('my-channel', onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('diagnostics_channel');
function onMessage(message, name) {
@@ -236,7 +224,7 @@ the message you want to send might be expensive to prepare.
This API is optional but helpful when trying to publish messages from very
performance-sensitive code.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -244,9 +232,7 @@ const channel = diagnostics_channel.channel('my-channel');
if (channel.hasSubscribers) {
// There are subscribers, prepare and publish message
}
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -265,7 +251,7 @@ if (channel.hasSubscribers) {
Publish a message to any subscribers to the channel. This will trigger
message handlers synchronously so they will execute within the same context.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -273,9 +259,7 @@ const channel = diagnostics_channel.channel('my-channel');
channel.publish({
some: 'message'
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -303,7 +287,7 @@ Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an [`'uncaughtException'`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -311,9 +295,7 @@ const channel = diagnostics_channel.channel('my-channel');
channel.subscribe((message, name) => {
// Received data
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -339,7 +321,7 @@ Deprecated: Use [`diagnostics_channel.unsubscribe(name, onMessage)`][]
Remove a message handler previously registered to this channel with
[`channel.subscribe(onMessage)`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -351,9 +333,7 @@ function onMessage(message, name) {
channel.subscribe(onMessage);
channel.unsubscribe(onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
diff --git a/content/api/v16/dns.en.md b/content/api/v16/dns.en.md
index dbc91aeaba..165f9c7cd6 100644
--- a/content/api/v16/dns.en.md
+++ b/content/api/v16/dns.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:dns` module enables name resolution. For example, use it to look up IP
addresses of host names.
diff --git a/content/api/v16/domain.en.md b/content/api/v16/domain.en.md
index 941b15bf92..c0ff2ad67e 100644
--- a/content/api/v16/domain.en.md
+++ b/content/api/v16/domain.en.md
@@ -15,7 +15,7 @@ Deprecated
-
+
**This module is pending deprecation.** Once a replacement API has been
finalized, this module will be fully deprecated. Most developers should
diff --git a/content/api/v16/esm.en.md b/content/api/v16/esm.en.md
index fd57d2a73c..024d76f2d0 100644
--- a/content/api/v16/esm.en.md
+++ b/content/api/v16/esm.en.md
@@ -206,12 +206,10 @@ The default export can be used for, among other things, modifying the named
exports. Named exports of builtin modules are updated only by calling
[`module.syncBuiltinESMExports()`][].
-```js
+```js|js
import EventEmitter from 'node:events';
const e = new EventEmitter();
-```
-
-```js
+--------------
import { readFile } from 'node:fs';
readFile('./foo.txt', (err, source) => {
if (err) {
@@ -513,13 +511,11 @@ export const five = await Promise.resolve(5);
And a `b.mjs` with
-```js
+```js|bash
import { five } from './a.mjs';
console.log(five); // Logs `5`
-```
-
-```bash
+--------------
node b.mjs # works
```
@@ -583,14 +579,12 @@ These modules cannot access other modules that are not over `http:` or `https:`.
To still access local modules while avoiding the security concern, pass in
references to the local dependencies:
-```mjs
+```mjs|mjs
// file.mjs
import worker_threads from 'node:worker_threads';
import { configure, resize } from 'https://example.com/imagelib.mjs';
configure({ worker_threads });
-```
-
-```mjs
+--------------
// https://example.com/imagelib.mjs
let worker_threads;
export function configure(opts) {
@@ -908,7 +902,7 @@ functionality, there are substantial downsides to actually using this loader:
performance is much slower than loading files from disk, there is no caching,
and there is no security.
-```js
+```js|js
// https-loader.mjs
import { get } from 'node:https';
@@ -956,9 +950,7 @@ export function load(url, context, nextLoad) {
// Let Node.js handle all other URLs.
return nextLoad(url);
}
-```
-
-```js
+--------------
// main.mjs
import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';
@@ -981,7 +973,7 @@ This is less performant than transpiling source files before running
Node.js; a transpiler loader should only be used for development and testing
purposes.
-```js
+```js|coffee
// coffeescript-loader.mjs
import { readFile } from 'node:fs/promises';
import { dirname, extname, resolve as resolvePath } from 'node:path';
@@ -1079,9 +1071,7 @@ async function getPackageType(url) {
// If at the root, stop and return false
return dir.length > 1 && getPackageType(resolvePath(dir, '..'));
}
-```
-
-```coffee
+--------------
# main.coffee
import { scream } from './scream.coffee'
console.log scream 'hello, world'
diff --git a/content/api/v16/events.en.md b/content/api/v16/events.en.md
index b658b5a572..abac6f9475 100644
--- a/content/api/v16/events.en.md
+++ b/content/api/v16/events.en.md
@@ -15,7 +15,7 @@ Stable
-
+
Much of the Node.js core API is built around an idiomatic asynchronous
event-driven architecture in which certain kinds of objects (called "emitters")
@@ -39,7 +39,7 @@ The following example shows a simple `EventEmitter` instance with a single
listener. The `eventEmitter.on()` method is used to register listeners, while
the `eventEmitter.emit()` method is used to trigger the event.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
@@ -49,9 +49,7 @@ myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
@@ -181,7 +179,7 @@ myEmitter.emit('error', new Error('whoops!'));
It is possible to monitor `'error'` events without consuming the emitted error
by installing a listener using the symbol `events.errorMonitor`.
-```mjs
+```mjs|cjs
import { EventEmitter, errorMonitor } from 'node:events';
const myEmitter = new EventEmitter();
@@ -190,9 +188,7 @@ myEmitter.on(errorMonitor, (err) => {
});
myEmitter.emit('error', new Error('whoops!'));
// Still throws and crashes Node.js
-```
-
-```cjs
+--------------
const { EventEmitter, errorMonitor } = require('node:events');
const myEmitter = new EventEmitter();
@@ -240,7 +236,7 @@ ee2[Symbol.for('nodejs.rejection')] = console.log;
Setting `events.captureRejections = true` will change the default for all
new instances of `EventEmitter`.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
EventEmitter.captureRejections = true;
@@ -250,9 +246,7 @@ ee1.on('something', async (value) => {
});
ee1.on('error', console.log);
-```
-
-```cjs
+--------------
const events = require('node:events');
events.captureRejections = true;
const ee1 = new events.EventEmitter();
@@ -273,11 +267,9 @@ recommendation is to **not use `async` functions as `'error'` event handlers**.
The `EventEmitter` class is defined and exposed by the `node:events` module:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
```
@@ -362,7 +354,7 @@ to each.
Returns `true` if the event had listeners, `false` otherwise.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
@@ -393,9 +385,7 @@ myEmitter.emit('event', 1, 2, 3, 4, 5);
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const myEmitter = new EventEmitter();
@@ -437,7 +427,7 @@ myEmitter.emit('event', 1, 2, 3, 4, 5);
Returns an array listing the events for which the emitter has registered
listeners. The values in the array are strings or `Symbol`s.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
@@ -449,9 +439,7 @@ myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const myEE = new EventEmitter();
@@ -789,7 +777,7 @@ promise rejection happens when emitting an event and
It is possible to use [`events.captureRejectionSymbol`][rejectionsymbol] in
place of `Symbol.for('nodejs.rejection')`.
-```mjs
+```mjs|cjs
import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter {
@@ -806,9 +794,7 @@ class MyClass extends EventEmitter {
// Tear the resource down here.
}
}
-```
-
-```cjs
+--------------
const { EventEmitter, captureRejectionSymbol } = require('node:events');
class MyClass extends EventEmitter {
@@ -894,7 +880,7 @@ the emitter.
For `EventTarget`s this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.
-```mjs
+```mjs|cjs
import { getEventListeners, EventEmitter } from 'node:events';
{
@@ -909,9 +895,7 @@ import { getEventListeners, EventEmitter } from 'node:events';
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
-```
-
-```cjs
+--------------
const { getEventListeners, EventEmitter } = require('node:events');
{
@@ -947,7 +931,7 @@ This method is intentionally generic and works with the web platform
[EventTarget][WHATWG-EventTarget] interface, which has no special
`'error'` event semantics and does not listen to the `'error'` event.
-```mjs
+```mjs|cjs
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
@@ -970,9 +954,7 @@ try {
} catch (err) {
console.log('error happened', err);
}
-```
-
-```cjs
+--------------
const { once, EventEmitter } = require('node:events');
async function run() {
@@ -1005,7 +987,7 @@ is used to wait for another event. If `events.once()` is used to wait for the
'`error'` event itself, then it is treated as any other kind of event without
special handling:
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
@@ -1017,9 +999,7 @@ once(ee, 'error')
ee.emit('error', new Error('boom'));
// Prints: ok boom
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const ee = new EventEmitter();
@@ -1035,7 +1015,7 @@ ee.emit('error', new Error('boom'));
An [`AbortSignal`](/api/v16/globals#abortsignal) can be used to cancel waiting for the event:
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
@@ -1057,9 +1037,7 @@ async function foo(emitter, event, signal) {
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const ee = new EventEmitter();
@@ -1092,7 +1070,7 @@ because the `process.nextTick()` queue is drained before the `Promise` microtask
queue, and because `EventEmitter` emits all events synchronously, it is possible
for `events.once()` to miss an event.
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
import process from 'node:process';
@@ -1114,9 +1092,7 @@ process.nextTick(() => {
});
foo().then(() => console.log('done'));
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const myEE = new EventEmitter();
@@ -1143,7 +1119,7 @@ To catch both events, create each of the Promises _before_ awaiting either
of them, then it becomes possible to use `Promise.all()`, `Promise.race()`,
or `Promise.allSettled()`:
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
import process from 'node:process';
@@ -1160,9 +1136,7 @@ process.nextTick(() => {
});
foo().then(() => console.log('done'));
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const myEE = new EventEmitter();
@@ -1212,7 +1186,7 @@ Deprecated: Use [`emitter.listenerCount()`][] instead.
A class method that returns the number of listeners for the given `eventName`
registered on the given `emitter`.
-```mjs
+```mjs|cjs
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
@@ -1220,9 +1194,7 @@ myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
-```
-
-```cjs
+--------------
const { EventEmitter, listenerCount } = require('node:events');
const myEmitter = new EventEmitter();
@@ -1242,7 +1214,7 @@ console.log(listenerCount(myEmitter, 'event'));
* `signal` [`AbortSignal`](/api/v16/globals#abortsignal) Can be used to cancel awaiting events.
* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) that iterates `eventName` events emitted by the `emitter`
-```mjs
+```mjs|cjs
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
@@ -1261,9 +1233,7 @@ for await (const event of on(ee, 'foo')) {
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
-```
-
-```cjs
+--------------
const { on, EventEmitter } = require('node:events');
(async () => {
@@ -1292,7 +1262,7 @@ composed of the emitted event arguments.
An [`AbortSignal`](/api/v16/globals#abortsignal) can be used to cancel waiting on events:
-```mjs
+```mjs|cjs
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
@@ -1317,9 +1287,7 @@ const ac = new AbortController();
})();
process.nextTick(() => ac.abort());
-```
-
-```cjs
+--------------
const { on, EventEmitter } = require('node:events');
const ac = new AbortController();
@@ -1355,16 +1323,14 @@ process.nextTick(() => ac.abort());
or [`EventEmitter`](/api/v16/events#eventemitter) instances. If none are specified, `n` is set as the default
max for all newly created [`EventTarget`](/api/v16/events#eventtarget) and [`EventEmitter`](/api/v16/events#eventemitter) objects.
-```mjs
+```mjs|cjs
import { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
-```
-
-```cjs
+--------------
const {
setMaxListeners,
EventEmitter
@@ -1384,7 +1350,7 @@ Integrates `EventEmitter` with [`AsyncResource`](/api/v16/async_hooks#asyncresou
require manual async tracking. Specifically, all events emitted by instances
of `events.EventEmitterAsyncResource` will run within its [async context][].
-```mjs
+```mjs|cjs
import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
import { notStrictEqual, strictEqual } from 'node:assert';
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
@@ -1411,9 +1377,7 @@ Promise.resolve().then(() => {
ee1.emit('foo');
ee2.emit('foo');
});
-```
-
-```cjs
+--------------
const { EventEmitterAsyncResource, EventEmitter } = require('node:events');
const { notStrictEqual, strictEqual } = require('node:assert');
const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');
diff --git a/content/api/v16/fs.en.md b/content/api/v16/fs.en.md
index 25d7223d00..86fcdf1349 100644
--- a/content/api/v16/fs.en.md
+++ b/content/api/v16/fs.en.md
@@ -15,28 +15,24 @@ Stable
-
+
The `node:fs` module enables interacting with the file system in a
way modeled on standard POSIX functions.
To use the promise-based APIs:
-```mjs
+```mjs|cjs
import * as fs from 'node:fs/promises';
-```
-
-```cjs
+--------------
const fs = require('node:fs/promises');
```
To use the callback and sync APIs:
-```mjs
+```mjs|cjs
import * as fs from 'node:fs';
-```
-
-```cjs
+--------------
const fs = require('node:fs');
```
@@ -48,7 +44,7 @@ forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).
Promise-based operations return a promise that is fulfilled when the
asynchronous operation is complete.
-```mjs
+```mjs|cjs
import { unlink } from 'node:fs/promises';
try {
@@ -57,9 +53,7 @@ try {
} catch (error) {
console.error('there was an error:', error.message);
}
-```
-
-```cjs
+--------------
const { unlink } = require('node:fs/promises');
(async function(path) {
@@ -80,16 +74,14 @@ the completion callback depend on the method, but the first argument is always
reserved for an exception. If the operation is completed successfully, then
the first argument is `null` or `undefined`.
-```mjs
+```mjs|cjs
import { unlink } from 'node:fs';
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
-```
-
-```cjs
+--------------
const { unlink } = require('node:fs');
unlink('/tmp/hello', (err) => {
@@ -108,7 +100,7 @@ The synchronous APIs block the Node.js event loop and further JavaScript
execution until the operation is complete. Exceptions are thrown immediately
and can be handled using `try…catch`, or can be allowed to bubble up.
-```mjs
+```mjs|cjs
import { unlinkSync } from 'node:fs';
try {
@@ -117,9 +109,7 @@ try {
} catch (err) {
// handle the error
}
-```
-
-```cjs
+--------------
const { unlinkSync } = require('node:fs');
try {
@@ -873,7 +863,7 @@ property indicating whether parent directories should be created. Calling
`fsPromises.mkdir()` when `path` is a directory that exists results in a
rejection only when `recursive` is false.
-```mjs
+```mjs|cjs
import { mkdir } from 'node:fs/promises';
try {
@@ -884,9 +874,7 @@ try {
} catch (err) {
console.error(err.message);
}
-```
-
-```cjs
+--------------
const { mkdir } = require('node:fs/promises');
const { resolve, join } = require('node:path');
@@ -2983,16 +2971,14 @@ Truncates the file. No arguments other than a possible exception are
given to the completion callback. A file descriptor can also be passed as the
first argument. In this case, `fs.ftruncate()` is called.
-```mjs
+```mjs|cjs
import { truncate } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was truncated');
});
-```
-
-```cjs
+--------------
const { truncate } = require('node:fs');
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
@@ -5409,7 +5395,7 @@ fs.stat('/tmp/world', (err, stats) => {
It is important to correctly order the operations by awaiting the results
of one before invoking the other:
-```mjs
+```mjs|cjs
import { rename, stat } from 'node:fs/promises';
const from = '/tmp/hello';
@@ -5422,9 +5408,7 @@ try {
} catch (error) {
console.error('there was an error:', error.message);
}
-```
-
-```cjs
+--------------
const { rename, stat } = require('node:fs/promises');
(async function(from, to) {
@@ -5441,7 +5425,7 @@ const { rename, stat } = require('node:fs/promises');
Or, when using the callback APIs, move the `fs.stat()` call into the callback
of the `fs.rename()` operation:
-```mjs
+```mjs|cjs
import { rename, stat } from 'node:fs';
rename('/tmp/hello', '/tmp/world', (err) => {
@@ -5451,9 +5435,7 @@ rename('/tmp/hello', '/tmp/world', (err) => {
console.log(`stats: ${JSON.stringify(stats)}`);
});
});
-```
-
-```cjs
+--------------
const { rename, stat } = require('node:fs/promises');
rename('/tmp/hello', '/tmp/world', (err) => {
diff --git a/content/api/v16/http.en.md b/content/api/v16/http.en.md
index a89cc921f2..9e81112bcf 100644
--- a/content/api/v16/http.en.md
+++ b/content/api/v16/http.en.md
@@ -13,7 +13,7 @@ Stable
-
+
To use the HTTP server and client one must `require('node:http')`.
@@ -2606,7 +2606,7 @@ Returns a new instance of [`http.Server`][].
The `requestListener` is a function which is automatically
added to the [`'request'`][] event.
-```cjs
+```cjs|cjs
const http = require('node:http');
// Create a local server to receive data from
@@ -2618,9 +2618,7 @@ const server = http.createServer((req, res) => {
});
server.listen(8000);
-```
-
-```cjs
+--------------
const http = require('node:http');
// Create a local server to receive data from
diff --git a/content/api/v16/http2.en.md b/content/api/v16/http2.en.md
index 8532277951..39cfc6dff6 100644
--- a/content/api/v16/http2.en.md
+++ b/content/api/v16/http2.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:http2` module provides an implementation of the [HTTP/2][] protocol.
It can be accessed using:
diff --git a/content/api/v16/https.en.md b/content/api/v16/https.en.md
index 8458b5677c..ad61b9b038 100644
--- a/content/api/v16/https.en.md
+++ b/content/api/v16/https.en.md
@@ -13,7 +13,7 @@ Stable
-
+
HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.
diff --git a/content/api/v16/inspector.en.md b/content/api/v16/inspector.en.md
index 962518913b..fb08ec7b7a 100644
--- a/content/api/v16/inspector.en.md
+++ b/content/api/v16/inspector.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:inspector` module provides an API for interacting with the V8
inspector.
diff --git a/content/api/v16/module.en.md b/content/api/v16/module.en.md
index 6f2527a250..47cb669df6 100644
--- a/content/api/v16/module.en.md
+++ b/content/api/v16/module.en.md
@@ -29,13 +29,11 @@ if a module is maintained by a third party or not.
`module` in this context isn't the same object that's provided
by the [module wrapper][]. To access it, require the `Module` module:
-```mjs
+```mjs|cjs
// module.mjs
// In an ECMAScript module
import { builtinModules as builtin } from 'node:module';
-```
-
-```cjs
+--------------
// module.cjs
// In a CommonJS module
const builtin = require('node:module').builtinModules;
@@ -127,13 +125,11 @@ To enable source map parsing, Node.js must be run with the flag
[`--enable-source-maps`][], or with code coverage enabled by setting
[`NODE_V8_COVERAGE=dir`][].
-```mjs
+```mjs|cjs
// module.mjs
// In an ECMAScript module
import { findSourceMap, SourceMap } from 'node:module';
-```
-
-```cjs
+--------------
// module.cjs
// In a CommonJS module
const { findSourceMap, SourceMap } = require('node:module');
diff --git a/content/api/v16/modules.en.md b/content/api/v16/modules.en.md
index d38701c3cd..5d58a58901 100644
--- a/content/api/v16/modules.en.md
+++ b/content/api/v16/modules.en.md
@@ -757,11 +757,9 @@ See ["Accessing the main module"](#accessing-the-main-module).
In `entry.js` script:
-```js
+```js|bash
console.log(require.main);
-```
-
-```bash
+--------------
node entry.js
```
diff --git a/content/api/v16/n-api.en.md b/content/api/v16/n-api.en.md
index 4c7f3a8cdd..e0f4db9380 100644
--- a/content/api/v16/n-api.en.md
+++ b/content/api/v16/n-api.en.md
@@ -54,12 +54,10 @@ following `node-addon-api` code. The first section shows the
`node-addon-api` code and the second section shows what actually gets
used in the addon.
-```cpp
+```cpp|cpp
Object obj = Object::New(env);
obj["foo"] = String::New(env, "bar");
-```
-
-```cpp
+--------------
napi_status status;
napi_value object, string;
status = napi_create_object(env, &object);
@@ -390,16 +388,14 @@ implementation of Node-API or any implementation of Node-API outside of Node.js.
to the addon and which instantiates the addon by calling into `addon.c` when the
addon is loaded into a Node.js environment.
-```c
+```c|c
// addon.h
#ifndef _ADDON_H_
#define _ADDON_H_
#include
napi_value create_addon(napi_env env);
#endif // _ADDON_H_
-```
-
-```c
+--------------
// addon.c
#include "addon.h"
@@ -5732,12 +5728,10 @@ Experimental
-```c
+```c|text
NAPI_EXTERN napi_status
node_api_get_module_file_name(napi_env env, const char** result);
-```
-
* `[in] env`: The environment that the API is invoked under.
* `[out] result`: A URL containing the absolute path of the
location from which the add-on was loaded. For a file on the local
diff --git a/content/api/v16/navigation.json b/content/api/v16/navigation.json
index ffcac50f87..fb563b0c1b 100644
--- a/content/api/v16/navigation.json
+++ b/content/api/v16/navigation.json
@@ -1,4 +1,1571 @@
{
"version": "v16",
- "items": []
+ "items": [
+ {
+ "slug": "/api/v16/addons/",
+ "title": "C addons",
+ "type": "module",
+ "name": "addons"
+ },
+ {
+ "slug": "/api/v16/assert/",
+ "title": "Assert",
+ "type": "module",
+ "name": "assert"
+ },
+ {
+ "slug": "/api/v16/assert/#assertassertionerror",
+ "title": "assertAssertionError",
+ "type": "class",
+ "name": "assert"
+ },
+ {
+ "slug": "/api/v16/assert/#assertcalltracker",
+ "title": "assertCallTracker",
+ "type": "class",
+ "name": "assert"
+ },
+ {
+ "slug": "/api/v16/async_context/",
+ "title": "Asynchronous context tracking",
+ "type": "module",
+ "name": "async_context"
+ },
+ {
+ "slug": "/api/v16/async_context/#asynclocalstorage",
+ "title": "AsyncLocalStorage",
+ "type": "class",
+ "name": "async_context"
+ },
+ {
+ "slug": "/api/v16/async_context/#asyncresource",
+ "title": "AsyncResource",
+ "type": "class",
+ "name": "async_context"
+ },
+ {
+ "slug": "/api/v16/async_hooks/",
+ "title": "Async hooks",
+ "type": "module",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v16/async_hooks/#asynchook",
+ "title": "AsyncHook",
+ "type": "class",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v16/async_hooks/#asynclocalstorage",
+ "title": "AsyncLocalStorage",
+ "type": "class",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v16/async_hooks/#asyncresource",
+ "title": "AsyncResource",
+ "type": "class",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v16/buffer/",
+ "title": "Buffer",
+ "type": "module",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v16/buffer/#blob",
+ "title": "Blob",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v16/buffer/#buffer",
+ "title": "Buffer",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v16/buffer/#slowbuffer",
+ "title": "SlowBuffer",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v16/child_process/",
+ "title": "Child process",
+ "type": "module",
+ "name": "child_process"
+ },
+ {
+ "slug": "/api/v16/child_process/#childprocess",
+ "title": "ChildProcess",
+ "type": "class",
+ "name": "child_process"
+ },
+ {
+ "slug": "/api/v16/cli/",
+ "title": "Command-line API",
+ "type": "module",
+ "name": "cli"
+ },
+ {
+ "slug": "/api/v16/cluster/",
+ "title": "Cluster",
+ "type": "module",
+ "name": "cluster"
+ },
+ {
+ "slug": "/api/v16/cluster/#worker",
+ "title": "Worker",
+ "type": "class",
+ "name": "cluster"
+ },
+ {
+ "slug": "/api/v16/console/",
+ "title": "Console",
+ "type": "module",
+ "name": "console"
+ },
+ {
+ "slug": "/api/v16/console/#console",
+ "title": "Console",
+ "type": "class",
+ "name": "console"
+ },
+ {
+ "slug": "/api/v16/console/#console",
+ "title": "Console",
+ "type": "class",
+ "name": "console"
+ },
+ {
+ "slug": "/api/v16/corepack/",
+ "title": "Corepack",
+ "type": "module",
+ "name": "corepack"
+ },
+ {
+ "slug": "/api/v16/crypto/",
+ "title": "Crypto",
+ "type": "module",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#certificate",
+ "title": "Certificate",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#cipher",
+ "title": "Cipher",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#decipher",
+ "title": "Decipher",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#diffiehellman",
+ "title": "DiffieHellman",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#diffiehellmangroup",
+ "title": "DiffieHellmanGroup",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#ecdh",
+ "title": "ECDH",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#hash",
+ "title": "Hash",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#hmac",
+ "title": "Hmac",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#keyobject",
+ "title": "KeyObject",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#sign",
+ "title": "Sign",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#verify",
+ "title": "Verify",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/crypto/#x509certificate",
+ "title": "X509Certificate",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v16/debugger/",
+ "title": "Debugger",
+ "type": "module",
+ "name": "debugger"
+ },
+ {
+ "slug": "/api/v16/deprecations/",
+ "title": "Deprecated APIs",
+ "type": "module",
+ "name": "deprecations"
+ },
+ {
+ "slug": "/api/v16/dgram/",
+ "title": "UDPdatagram sockets",
+ "type": "module",
+ "name": "dgram"
+ },
+ {
+ "slug": "/api/v16/dgram/#dgramsocket",
+ "title": "dgramSocket",
+ "type": "class",
+ "name": "dgram"
+ },
+ {
+ "slug": "/api/v16/diagnostics_channel/",
+ "title": "Diagnostics Channel",
+ "type": "module",
+ "name": "diagnostics_channel"
+ },
+ {
+ "slug": "/api/v16/diagnostics_channel/#channel",
+ "title": "Channel",
+ "type": "class",
+ "name": "diagnostics_channel"
+ },
+ {
+ "slug": "/api/v16/dns/",
+ "title": "DNS",
+ "type": "module",
+ "name": "dns"
+ },
+ {
+ "slug": "/api/v16/dns/#dnspromisesresolver",
+ "title": "dnsPromisesResolver",
+ "type": "class",
+ "name": "dns"
+ },
+ {
+ "slug": "/api/v16/dns/#dnsresolver",
+ "title": "dnsResolver",
+ "type": "class",
+ "name": "dns"
+ },
+ {
+ "slug": "/api/v16/documentation/",
+ "title": "About this documentation",
+ "type": "module",
+ "name": "documentation"
+ },
+ {
+ "slug": "/api/v16/domain/",
+ "title": "Domain",
+ "type": "module",
+ "name": "domain"
+ },
+ {
+ "slug": "/api/v16/domain/#domain",
+ "title": "Domain",
+ "type": "class",
+ "name": "domain"
+ },
+ {
+ "slug": "/api/v16/embedding/",
+ "title": "C embedder API",
+ "type": "module",
+ "name": "embedding"
+ },
+ {
+ "slug": "/api/v16/errors/",
+ "title": "Errors",
+ "type": "module",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v16/errors/#assertionerror",
+ "title": "AssertionError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v16/errors/#error",
+ "title": "Error",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v16/errors/#rangeerror",
+ "title": "RangeError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v16/errors/#referenceerror",
+ "title": "ReferenceError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v16/errors/#syntaxerror",
+ "title": "SyntaxError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v16/errors/#systemerror",
+ "title": "SystemError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v16/errors/#typeerror",
+ "title": "TypeError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v16/esm/",
+ "title": "ECMAScript modules",
+ "type": "module",
+ "name": "esm"
+ },
+ {
+ "slug": "/api/v16/events/",
+ "title": "Events",
+ "type": "module",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v16/events/#customevent",
+ "title": "CustomEvent",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v16/events/#event",
+ "title": "Event",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v16/events/#eventemitter",
+ "title": "EventEmitter",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v16/events/#eventseventemitterasyncresource-extends-eventemitter",
+ "title": "eventsEventEmitterAsyncResource extends EventEmitter",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v16/events/#eventtarget",
+ "title": "EventTarget",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v16/events/#nodeeventtarget",
+ "title": "NodeEventTarget",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v16/fs/",
+ "title": "File system",
+ "type": "module",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v16/fs/#filehandle",
+ "title": "FileHandle",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v16/fs/#fsdir",
+ "title": "fsDir",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v16/fs/#fsdirent",
+ "title": "fsDirent",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v16/fs/#fsfswatcher",
+ "title": "fsFSWatcher",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v16/fs/#fsreadstream",
+ "title": "fsReadStream",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v16/fs/#fsstats",
+ "title": "fsStats",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v16/fs/#fsstatwatcher",
+ "title": "fsStatWatcher",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v16/fs/#fswritestream",
+ "title": "fsWriteStream",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v16/globals/",
+ "title": "Global objects",
+ "type": "module",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#abortcontroller",
+ "title": "AbortController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#abortcontroller",
+ "title": "AbortController",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#abortsignal",
+ "title": "AbortSignal",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#buffer",
+ "title": "Buffer",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#buffer",
+ "title": "Buffer",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#clearimmediateimmediateobject",
+ "title": "clearImmediate",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#clearintervalintervalobject",
+ "title": "clearInterval",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#cleartimeouttimeoutobject",
+ "title": "clearTimeout",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#console",
+ "title": "console",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#customevent",
+ "title": "CustomEvent",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#event",
+ "title": "Event",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#eventtarget",
+ "title": "EventTarget",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#global",
+ "title": "global",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#messagechannel",
+ "title": "MessageChannel",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#messageevent",
+ "title": "MessageEvent",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#messageport",
+ "title": "MessagePort",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#process",
+ "title": "process",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#queuemicrotaskcallback",
+ "title": "queueMicrotask",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#setimmediatecallback-args",
+ "title": "setImmediate",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#setintervalcallback-delay-args",
+ "title": "setInterval",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#settimeoutcallback-delay-args",
+ "title": "setTimeout",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#textdecoder",
+ "title": "TextDecoder",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#textencoder",
+ "title": "TextEncoder",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#url",
+ "title": "URL",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#urlsearchparams",
+ "title": "URLSearchParams",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/globals/#webassembly",
+ "title": "WebAssembly",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v16/http/",
+ "title": "HTTP",
+ "type": "module",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v16/http/#httpagent",
+ "title": "httpAgent",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v16/http/#httpclientrequest",
+ "title": "httpClientRequest",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v16/http/#httpincomingmessage",
+ "title": "httpIncomingMessage",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v16/http/#httpoutgoingmessage",
+ "title": "httpOutgoingMessage",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v16/http/#httpserver",
+ "title": "httpServer",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v16/http/#httpserverresponse",
+ "title": "httpServerResponse",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v16/http2/",
+ "title": "HTTP2",
+ "type": "module",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/http2/#clienthttp2session",
+ "title": "ClientHttp2Session",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/http2/#clienthttp2stream",
+ "title": "ClientHttp2Stream",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/http2/#http2http2serverrequest",
+ "title": "http2Http2ServerRequest",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/http2/#http2http2serverresponse",
+ "title": "http2Http2ServerResponse",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/http2/#http2secureserver",
+ "title": "Http2SecureServer",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/http2/#http2server",
+ "title": "Http2Server",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/http2/#http2session",
+ "title": "Http2Session",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/http2/#http2stream",
+ "title": "Http2Stream",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/http2/#serverhttp2session",
+ "title": "ServerHttp2Session",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/http2/#serverhttp2stream",
+ "title": "ServerHttp2Stream",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v16/https/",
+ "title": "HTTPS",
+ "type": "module",
+ "name": "https"
+ },
+ {
+ "slug": "/api/v16/https/#httpsagent",
+ "title": "httpsAgent",
+ "type": "class",
+ "name": "https"
+ },
+ {
+ "slug": "/api/v16/https/#httpsserver",
+ "title": "httpsServer",
+ "type": "class",
+ "name": "https"
+ },
+ {
+ "slug": "/api/v16/inspector/",
+ "title": "Inspector",
+ "type": "module",
+ "name": "inspector"
+ },
+ {
+ "slug": "/api/v16/inspector/#inspectorsession",
+ "title": "inspectorSession",
+ "type": "class",
+ "name": "inspector"
+ },
+ {
+ "slug": "/api/v16/intl/",
+ "title": "Internationalization support",
+ "type": "module",
+ "name": "intl"
+ },
+ {
+ "slug": "/api/v16/module/",
+ "title": "nodemodule API",
+ "type": "module",
+ "name": "module"
+ },
+ {
+ "slug": "/api/v16/module/#modulesourcemap",
+ "title": "moduleSourceMap",
+ "type": "class",
+ "name": "module"
+ },
+ {
+ "slug": "/api/v16/modules/",
+ "title": "CommonJS modules",
+ "type": "module",
+ "name": "modules"
+ },
+ {
+ "slug": "/api/v16/n-api/",
+ "title": "Node-API",
+ "type": "module",
+ "name": "n-api"
+ },
+ {
+ "slug": "/api/v16/net/",
+ "title": "Net",
+ "type": "module",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v16/net/#netblocklist",
+ "title": "netBlockList",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v16/net/#netserver",
+ "title": "netServer",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v16/net/#netsocket",
+ "title": "netSocket",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v16/net/#netsocketaddress",
+ "title": "netSocketAddress",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v16/os/",
+ "title": "OS",
+ "type": "module",
+ "name": "os"
+ },
+ {
+ "slug": "/api/v16/packages/",
+ "title": "Packages",
+ "type": "module",
+ "name": "packages"
+ },
+ {
+ "slug": "/api/v16/path/",
+ "title": "Path",
+ "type": "module",
+ "name": "path"
+ },
+ {
+ "slug": "/api/v16/perf_hooks/",
+ "title": "Performance measurement APIs",
+ "type": "module",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v16/perf_hooks/#histogram",
+ "title": "Histogram",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v16/perf_hooks/#intervalhistogram-extends-histogram",
+ "title": "IntervalHistogram extends Histogram",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v16/perf_hooks/#perf-hooksperformanceobserver",
+ "title": "perf_hooksPerformanceObserver",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v16/perf_hooks/#performanceentry",
+ "title": "PerformanceEntry",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v16/perf_hooks/#performancenodetiming",
+ "title": "PerformanceNodeTiming",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v16/perf_hooks/#performanceobserverentrylist",
+ "title": "PerformanceObserverEntryList",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v16/perf_hooks/#performanceresourcetiming",
+ "title": "PerformanceResourceTiming",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v16/perf_hooks/#recordablehistogram-extends-histogram",
+ "title": "RecordableHistogram extends Histogram",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v16/permissions/",
+ "title": "Permissions",
+ "type": "module",
+ "name": "permissions"
+ },
+ {
+ "slug": "/api/v16/policy/",
+ "title": "Policies",
+ "type": "module",
+ "name": "policy"
+ },
+ {
+ "slug": "/api/v16/process/",
+ "title": "Process",
+ "type": "module",
+ "name": "process"
+ },
+ {
+ "slug": "/api/v16/punycode/",
+ "title": "Punycode",
+ "type": "module",
+ "name": "punycode"
+ },
+ {
+ "slug": "/api/v16/querystring/",
+ "title": "Query string",
+ "type": "module",
+ "name": "querystring"
+ },
+ {
+ "slug": "/api/v16/readline/",
+ "title": "Readline",
+ "type": "module",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v16/readline/#interface",
+ "title": "Interface",
+ "type": "class",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v16/repl/",
+ "title": "REPL",
+ "type": "module",
+ "name": "repl"
+ },
+ {
+ "slug": "/api/v16/repl/#replserver",
+ "title": "REPLServer",
+ "type": "class",
+ "name": "repl"
+ },
+ {
+ "slug": "/api/v16/report/",
+ "title": "Diagnostic report",
+ "type": "module",
+ "name": "report"
+ },
+ {
+ "slug": "/api/v16/stream/",
+ "title": "Stream",
+ "type": "module",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v16/stream/#streamduplex",
+ "title": "streamDuplex",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v16/stream/#streamduplex",
+ "title": "streamDuplex",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v16/stream/#streampassthrough",
+ "title": "streamPassThrough",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v16/stream/#streamreadable",
+ "title": "streamReadable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v16/stream/#streamreadable",
+ "title": "streamReadable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v16/stream/#streamtransform",
+ "title": "streamTransform",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v16/stream/#streamtransform",
+ "title": "streamTransform",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v16/stream/#streamwritable",
+ "title": "streamWritable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v16/stream/#streamwritable",
+ "title": "streamWritable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v16/string_decoder/",
+ "title": "String decoder",
+ "type": "module",
+ "name": "string_decoder"
+ },
+ {
+ "slug": "/api/v16/string_decoder/#stringdecoder",
+ "title": "StringDecoder",
+ "type": "class",
+ "name": "string_decoder"
+ },
+ {
+ "slug": "/api/v16/synopsis/",
+ "title": "Usage and example",
+ "type": "module",
+ "name": "synopsis"
+ },
+ {
+ "slug": "/api/v16/test/",
+ "title": "Test runner",
+ "type": "module",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v16/test/#suitecontext",
+ "title": "SuiteContext",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v16/test/#tapstream",
+ "title": "TapStream",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v16/test/#testcontext",
+ "title": "TestContext",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v16/timers/",
+ "title": "Timers",
+ "type": "module",
+ "name": "timers"
+ },
+ {
+ "slug": "/api/v16/timers/#immediate",
+ "title": "Immediate",
+ "type": "class",
+ "name": "timers"
+ },
+ {
+ "slug": "/api/v16/timers/#timeout",
+ "title": "Timeout",
+ "type": "class",
+ "name": "timers"
+ },
+ {
+ "slug": "/api/v16/tls/",
+ "title": "TLS ",
+ "type": "module",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v16/tls/#tlscryptostream",
+ "title": "tlsCryptoStream",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v16/tls/#tlssecurepair",
+ "title": "tlsSecurePair",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v16/tls/#tlsserver",
+ "title": "tlsServer",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v16/tls/#tlstlssocket",
+ "title": "tlsTLSSocket",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v16/tracing/",
+ "title": "Trace events",
+ "type": "module",
+ "name": "tracing"
+ },
+ {
+ "slug": "/api/v16/tty/",
+ "title": "TTY",
+ "type": "module",
+ "name": "tty"
+ },
+ {
+ "slug": "/api/v16/tty/#ttyreadstream",
+ "title": "ttyReadStream",
+ "type": "class",
+ "name": "tty"
+ },
+ {
+ "slug": "/api/v16/tty/#ttywritestream",
+ "title": "ttyWriteStream",
+ "type": "class",
+ "name": "tty"
+ },
+ {
+ "slug": "/api/v16/url/",
+ "title": "URL",
+ "type": "module",
+ "name": "url"
+ },
+ {
+ "slug": "/api/v16/url/#url",
+ "title": "URL",
+ "type": "class",
+ "name": "url"
+ },
+ {
+ "slug": "/api/v16/url/#urlsearchparams",
+ "title": "URLSearchParams",
+ "type": "class",
+ "name": "url"
+ },
+ {
+ "slug": "/api/v16/util/",
+ "title": "Util",
+ "type": "module",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v16/util/#utiltextdecoder",
+ "title": "utilTextDecoder",
+ "type": "class",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v16/util/#utiltextencoder",
+ "title": "utilTextEncoder",
+ "type": "class",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v16/v8/",
+ "title": "V8",
+ "type": "module",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v16/v8/#v8defaultdeserializer",
+ "title": "v8DefaultDeserializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v16/v8/#v8defaultserializer",
+ "title": "v8DefaultSerializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v16/v8/#v8deserializer",
+ "title": "v8Deserializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v16/v8/#v8serializer",
+ "title": "v8Serializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v16/vm/",
+ "title": "VM ",
+ "type": "module",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v16/vm/#vmmodule",
+ "title": "vmModule",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v16/vm/#vmscript",
+ "title": "vmScript",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v16/vm/#vmsourcetextmodule",
+ "title": "vmSourceTextModule",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v16/vm/#vmsyntheticmodule",
+ "title": "vmSyntheticModule",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v16/wasi/",
+ "title": "WebAssembly System Interface ",
+ "type": "module",
+ "name": "wasi"
+ },
+ {
+ "slug": "/api/v16/wasi/#wasi",
+ "title": "WASI",
+ "type": "class",
+ "name": "wasi"
+ },
+ {
+ "slug": "/api/v16/webcrypto/",
+ "title": "Web Crypto API",
+ "type": "module",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#aescbcparams",
+ "title": "AesCbcParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#aesctrparams",
+ "title": "AesCtrParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#aesgcmparams",
+ "title": "AesGcmParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#aeskeygenparams",
+ "title": "AesKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#algorithmidentifier",
+ "title": "AlgorithmIdentifier",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#crypto",
+ "title": "Crypto",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#cryptokey",
+ "title": "CryptoKey",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#cryptokeypair",
+ "title": "CryptoKeyPair",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#ecdhkeyderiveparams",
+ "title": "EcdhKeyDeriveParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#ecdsaparams",
+ "title": "EcdsaParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#eckeygenparams",
+ "title": "EcKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#eckeyimportparams",
+ "title": "EcKeyImportParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#ed448params",
+ "title": "Ed448Params",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#hkdfparams",
+ "title": "HkdfParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#hmacimportparams",
+ "title": "HmacImportParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#hmackeygenparams",
+ "title": "HmacKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#pbkdf2params",
+ "title": "Pbkdf2Params",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#rsahashedimportparams",
+ "title": "RsaHashedImportParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#rsahashedkeygenparams",
+ "title": "RsaHashedKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#rsaoaepparams",
+ "title": "RsaOaepParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#rsapssparams",
+ "title": "RsaPssParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webcrypto/#subtlecrypto",
+ "title": "SubtleCrypto",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v16/webstreams/",
+ "title": "Web Streams API",
+ "type": "module",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#bytelengthqueuingstrategy",
+ "title": "ByteLengthQueuingStrategy",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#countqueuingstrategy",
+ "title": "CountQueuingStrategy",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#readablebytestreamcontroller",
+ "title": "ReadableByteStreamController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#readablestream",
+ "title": "ReadableStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#readablestreambyobreader",
+ "title": "ReadableStreamBYOBReader",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#readablestreambyobrequest",
+ "title": "ReadableStreamBYOBRequest",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#readablestreamdefaultcontroller",
+ "title": "ReadableStreamDefaultController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#readablestreamdefaultreader",
+ "title": "ReadableStreamDefaultReader",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#textdecoderstream",
+ "title": "TextDecoderStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#textencoderstream",
+ "title": "TextEncoderStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#transformstream",
+ "title": "TransformStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#transformstreamdefaultcontroller",
+ "title": "TransformStreamDefaultController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#writablestream",
+ "title": "WritableStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#writablestreamdefaultcontroller",
+ "title": "WritableStreamDefaultController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/webstreams/#writablestreamdefaultwriter",
+ "title": "WritableStreamDefaultWriter",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v16/worker_threads/",
+ "title": "Worker threads",
+ "type": "module",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v16/worker_threads/#broadcastchannel-extends-eventtarget",
+ "title": "BroadcastChannel extends EventTarget",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v16/worker_threads/#messagechannel",
+ "title": "MessageChannel",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v16/worker_threads/#messageport",
+ "title": "MessagePort",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v16/worker_threads/#worker",
+ "title": "Worker",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v16/zlib/",
+ "title": "Zlib",
+ "type": "module",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#brotlioptions",
+ "title": "BrotliOptions",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#options",
+ "title": "Options",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#zlibbrotlicompress",
+ "title": "zlibBrotliCompress",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#zlibbrotlidecompress",
+ "title": "zlibBrotliDecompress",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#zlibdeflate",
+ "title": "zlibDeflate",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#zlibdeflateraw",
+ "title": "zlibDeflateRaw",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#zlibgunzip",
+ "title": "zlibGunzip",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#zlibgzip",
+ "title": "zlibGzip",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#zlibinflate",
+ "title": "zlibInflate",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#zlibinflateraw",
+ "title": "zlibInflateRaw",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#zlibunzip",
+ "title": "zlibUnzip",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v16/zlib/#zlibzlibbase",
+ "title": "zlibZlibBase",
+ "type": "class",
+ "name": "zlib"
+ }
+ ]
}
\ No newline at end of file
diff --git a/content/api/v16/net.en.md b/content/api/v16/net.en.md
index 8961601604..fee71c3ff7 100644
--- a/content/api/v16/net.en.md
+++ b/content/api/v16/net.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:net` module provides an asynchronous network API for creating stream-based
TCP or [IPC][] servers ([`net.createServer()`][]) and clients
diff --git a/content/api/v16/os.en.md b/content/api/v16/os.en.md
index 373d4ac98b..2fafd3d86e 100644
--- a/content/api/v16/os.en.md
+++ b/content/api/v16/os.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:os` module provides operating system-related utility methods and
properties. It can be accessed using:
diff --git a/content/api/v16/packages.en.md b/content/api/v16/packages.en.md
index a5608d33fb..65c1fd9af5 100644
--- a/content/api/v16/packages.en.md
+++ b/content/api/v16/packages.en.md
@@ -478,7 +478,7 @@ targets, this expansion is dependent on only the files of the package itself.
To exclude private subfolders from patterns, `null` targets can be used:
-```json
+```json|js
// ./node_modules/es-module-package/package.json
{
"exports": {
@@ -486,9 +486,7 @@ To exclude private subfolders from patterns, `null` targets can be used:
"./features/private-internal/*": null
}
}
-```
-
-```js
+--------------
import featureInternal from 'es-module-package/features/private-internal/m.js';
// Throws: ERR_PACKAGE_PATH_NOT_EXPORTED
@@ -714,25 +712,21 @@ const { something } = require('a-package/foo.js'); // Loads from ./foo.js.
Finally, self-referencing also works with scoped packages. For example, this
code will also work:
-```json
+```json|cjs
// package.json
{
"name": "@my/package",
"exports": "./index.js"
}
-```
-
-```cjs
+--------------
// ./index.js
module.exports = 42;
```
-```cjs
+```cjs|console
// ./other.js
console.log(require('@my/package'));
-```
-
-```console
+--------------
$ node other.js
42
```
@@ -870,12 +864,10 @@ to be treated as ES modules, just as `"type": "commonjs"` would cause them
to be treated as CommonJS.
See [Enabling](esm.md#enabling).
-```cjs
+```cjs|js
// ./node_modules/pkg/index.cjs
exports.name = 'value';
-```
-
-```js
+--------------
// ./node_modules/pkg/wrapper.mjs
import cjsModule from './index.cjs';
export const name = cjsModule.name;
@@ -1142,14 +1134,12 @@ The nearest parent `package.json` is defined as the first `package.json` found
when searching in the current folder, that folder's parent, and so on up
until a node\_modules folder or the volume root is reached.
-```json
+```json|bash
// package.json
{
"type": "module"
}
-```
-
-```bash
+--------------
# In same folder as preceding package.json
node my-app.js # Runs as ES module
```
diff --git a/content/api/v16/path.en.md b/content/api/v16/path.en.md
index 95268945aa..36a4c0bb6e 100644
--- a/content/api/v16/path.en.md
+++ b/content/api/v16/path.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:path` module provides utilities for working with file and directory
paths. It can be accessed using:
@@ -375,7 +375,7 @@ The returned object will have the following properties:
For example, on POSIX:
-```js
+```js|text
path.parse('/home/user/dir/file.txt');
// Returns:
// { root: '/',
@@ -383,9 +383,7 @@ path.parse('/home/user/dir/file.txt');
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
-```
-
-```text
+--------------
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
@@ -397,7 +395,7 @@ path.parse('/home/user/dir/file.txt');
On Windows:
-```js
+```js|text
path.parse('C:\\path\\dir\\file.txt');
// Returns:
// { root: 'C:\\',
@@ -405,9 +403,7 @@ path.parse('C:\\path\\dir\\file.txt');
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
-```
-
-```text
+--------------
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
diff --git a/content/api/v16/perf_hooks.en.md b/content/api/v16/perf_hooks.en.md
index 52b5ce2652..8efbebc15f 100644
--- a/content/api/v16/perf_hooks.en.md
+++ b/content/api/v16/perf_hooks.en.md
@@ -13,7 +13,7 @@ Stable
-
+
This module provides an implementation of a subset of the W3C
[Web Performance APIs][] as well as additional APIs for
diff --git a/content/api/v16/permissions.en.md b/content/api/v16/permissions.en.md
index edb1cc0da9..82dbe1aac3 100644
--- a/content/api/v16/permissions.en.md
+++ b/content/api/v16/permissions.en.md
@@ -395,7 +395,7 @@ The following example, would allow access to `fs` for all `data:` resources:
Given an import map:
-```json
+```json|json
{
"imports": {
"react": "./app/node_modules/react/index.js"
@@ -406,9 +406,7 @@ Given an import map:
}
}
}
-```
-
-```json
+--------------
{
"dependencies": true,
"scopes": {
diff --git a/content/api/v16/process.en.md b/content/api/v16/process.en.md
index 582f47ca34..61b22944a9 100644
--- a/content/api/v16/process.en.md
+++ b/content/api/v16/process.en.md
@@ -9,16 +9,14 @@ version: 'v16'
-
+
The `process` object provides information about, and control over, the current
Node.js process.
-```mjs
+```mjs|cjs
import process from 'node:process';
-```
-
-```cjs
+--------------
const process = require('node:process');
```
@@ -45,7 +43,7 @@ termination, such as calling [`process.exit()`][] or uncaught exceptions.
The `'beforeExit'` should _not_ be used as an alternative to the `'exit'` event
unless the intention is to schedule additional work.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('beforeExit', (code) => {
@@ -62,9 +60,7 @@ console.log('This message is displayed first.');
// This message is displayed first.
// Process beforeExit event with code: 0
// Process exit event with code: 0
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('beforeExit', (code) => {
@@ -110,15 +106,13 @@ The listener callback function is invoked with the exit code specified either
by the [`process.exitCode`][] property, or the `exitCode` argument passed to the
[`process.exit()`][] method.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('exit', (code) => {
console.log(`About to exit with code: ${code}`);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('exit', (code) => {
@@ -131,7 +125,7 @@ process will exit immediately after calling the `'exit'` event listeners
causing any additional work still queued in the event loop to be abandoned.
In the following example, for instance, the timeout will never occur:
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('exit', (code) => {
@@ -139,9 +133,7 @@ process.on('exit', (code) => {
console.log('This will not run');
}, 0);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('exit', (code) => {
@@ -203,7 +195,7 @@ example, [`Promise.race()`][] can trigger a `'multipleResolves'` event.
Because of the unreliability of the event in cases like the
[`Promise.race()`][] example above it has been deprecated.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('multipleResolves', (type, promise, reason) => {
@@ -230,9 +222,7 @@ main().then(console.log);
// at new Promise ()
// at main (*)
// First call
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('multipleResolves', (type, promise, reason) => {
@@ -291,7 +281,7 @@ In asynchronous code, the `'unhandledRejection'` event is emitted when the list
of unhandled rejections grows, and the `'rejectionHandled'` event is emitted
when the list of unhandled rejections shrinks.
-```mjs
+```mjs|cjs
import process from 'node:process';
const unhandledRejections = new Map();
@@ -301,9 +291,7 @@ process.on('unhandledRejection', (reason, promise) => {
process.on('rejectionHandled', (promise) => {
unhandledRejections.delete(promise);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
const unhandledRejections = new Map();
@@ -344,7 +332,7 @@ behavior. Alternatively, change the [`process.exitCode`][] in the
provided exit code. Otherwise, in the presence of such handler the process will
exit with 0.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('uncaughtException', (err, origin) => {
@@ -362,9 +350,7 @@ setTimeout(() => {
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('uncaughtException', (err, origin) => {
@@ -436,7 +422,7 @@ Installing an `'uncaughtExceptionMonitor'` listener does not change the behavior
once an `'uncaughtException'` event is emitted. The process will
still crash if no `'uncaughtException'` listener is installed.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('uncaughtExceptionMonitor', (err, origin) => {
@@ -446,9 +432,7 @@ process.on('uncaughtExceptionMonitor', (err, origin) => {
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
// Still crashes Node.js
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('uncaughtExceptionMonitor', (err, origin) => {
@@ -476,7 +460,7 @@ are propagated through a `Promise` chain. The `'unhandledRejection'` event is
useful for detecting and keeping track of promises that were rejected whose
rejections have not yet been handled.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('unhandledRejection', (reason, promise) => {
@@ -487,9 +471,7 @@ process.on('unhandledRejection', (reason, promise) => {
somePromise.then((res) => {
return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)
}); // No `.catch()` or `.then()`
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('unhandledRejection', (reason, promise) => {
@@ -505,7 +487,7 @@ somePromise.then((res) => {
The following will also trigger the `'unhandledRejection'` event to be
emitted:
-```mjs
+```mjs|cjs
import process from 'node:process';
function SomeResource() {
@@ -515,9 +497,7 @@ function SomeResource() {
const resource = new SomeResource();
// no .catch or .then on resource.loaded for at least a turn
-```
-
-```cjs
+--------------
const process = require('node:process');
function SomeResource() {
@@ -554,7 +534,7 @@ are not part of the normal Node.js and JavaScript error handling flow.
Node.js can emit warnings whenever it detects bad coding practices that could
lead to sub-optimal application performance, bugs, or security vulnerabilities.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('warning', (warning) => {
@@ -562,9 +542,7 @@ process.on('warning', (warning) => {
console.warn(warning.message); // Print the warning message
console.warn(warning.stack); // Print the stack trace
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('warning', (warning) => {
@@ -671,7 +649,7 @@ The signal handler will receive the signal's name (`'SIGINT'`,
The name of each event will be the uppercase common name for the signal (e.g.
`'SIGINT'` for `SIGINT` signals).
-```mjs
+```mjs|cjs
import process from 'node:process';
// Begin reading from stdin so the process does not exit.
@@ -688,9 +666,7 @@ function handle(signal) {
process.on('SIGINT', handle);
process.on('SIGTERM', handle);
-```
-
-```cjs
+--------------
const process = require('node:process');
// Begin reading from stdin so the process does not exit.
@@ -793,7 +769,7 @@ appear only _once_; each will begin with one or more dashes. Flags
passed through to V8 will contain underscores instead of non-leading
dashes:
-```mjs
+```mjs|cjs
import { allowedNodeEnvironmentFlags } from 'node:process';
allowedNodeEnvironmentFlags.forEach((flag) => {
@@ -802,9 +778,7 @@ allowedNodeEnvironmentFlags.forEach((flag) => {
// --abort_on_uncaught_exception
// ...
});
-```
-
-```cjs
+--------------
const { allowedNodeEnvironmentFlags } = require('node:process');
allowedNodeEnvironmentFlags.forEach((flag) => {
@@ -833,13 +807,11 @@ The operating system CPU architecture for which the Node.js binary was compiled.
Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,
`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`.
-```mjs
+```mjs|cjs
import { arch } from 'node:process';
console.log(`This processor architecture is ${arch}`);
-```
-
-```cjs
+--------------
const { arch } = require('node:process');
console.log(`This processor architecture is ${arch}`);
@@ -860,16 +832,14 @@ arguments.
For example, assuming the following script for `process-args.js`:
-```mjs
+```mjs|cjs
import { argv } from 'node:process';
// print process.argv
argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
-```
-
-```cjs
+--------------
const { argv } = require('node:process');
// print process.argv
@@ -954,7 +924,7 @@ The `process.chdir()` method changes the current working directory of the
Node.js process or throws an exception if doing so fails (for instance, if
the specified `directory` does not exist).
-```mjs
+```mjs|cjs
import { chdir, cwd } from 'node:process';
console.log(`Starting directory: ${cwd()}`);
@@ -964,9 +934,7 @@ try {
} catch (err) {
console.error(`chdir: ${err}`);
}
-```
-
-```cjs
+--------------
const { chdir, cwd } = require('node:process');
console.log(`Starting directory: ${cwd()}`);
@@ -1062,7 +1030,7 @@ actual elapsed time if multiple CPU cores are performing work for this process.
The result of a previous call to `process.cpuUsage()` can be passed as the
argument to the function, to get a diff reading.
-```mjs
+```mjs|cjs
import { cpuUsage } from 'node:process';
const startUsage = cpuUsage();
@@ -1074,9 +1042,7 @@ while (Date.now() - now < 500);
console.log(cpuUsage(startUsage));
// { user: 514883, system: 11226 }
-```
-
-```cjs
+--------------
const { cpuUsage } = require('node:process');
const startUsage = cpuUsage();
@@ -1099,13 +1065,11 @@ console.log(cpuUsage(startUsage));
The `process.cwd()` method returns the current working directory of the Node.js
process.
-```mjs
+```mjs|cjs
import { cwd } from 'node:process';
console.log(`Current directory: ${cwd()}`);
-```
-
-```cjs
+--------------
const { cwd } = require('node:process');
console.log(`Current directory: ${cwd()}`);
@@ -1119,13 +1083,11 @@ console.log(`Current directory: ${cwd()}`);
The port used by the Node.js debugger when enabled.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.debugPort = 5858;
-```
-
-```cjs
+--------------
const process = require('node:process');
process.debugPort = 5858;
@@ -1172,7 +1134,7 @@ that exports a `foo` function. All the symbols are loaded before
the call returns, by passing the `RTLD_NOW` constant. In this example
the constant is assumed to be available.
-```mjs
+```mjs|cjs
import { dlopen } from 'node:process';
import { constants } from 'node:os';
import { fileURLToPath } from 'node:url';
@@ -1181,9 +1143,7 @@ const module = { exports: {} };
dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)),
constants.dlopen.RTLD_NOW);
module.exports.foo();
-```
-
-```cjs
+--------------
const { dlopen } = require('node:process');
const { constants } = require('node:os');
const { join } = require('node:path');
@@ -1211,7 +1171,7 @@ The `process.emitWarning()` method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
[`'warning'`][process_warning] event.
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning with a code and additional detail.
@@ -1222,9 +1182,7 @@ emitWarning('Something happened!', {
// Emits:
// (node:56338) [MY_WARNING] Warning: Something happened!
// This is some additional information
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning with a code and additional detail.
@@ -1241,7 +1199,7 @@ In this example, an `Error` object is generated internally by
`process.emitWarning()` and passed through to the
[`'warning'`][process_warning] handler.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('warning', (warning) => {
@@ -1251,9 +1209,7 @@ process.on('warning', (warning) => {
console.warn(warning.stack); // Stack trace
console.warn(warning.detail); // 'This is some additional information'
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('warning', (warning) => {
@@ -1283,15 +1239,13 @@ The `process.emitWarning()` method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
[`'warning'`][process_warning] event.
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning using a string.
emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning using a string.
@@ -1299,15 +1253,13 @@ emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
```
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning using a string and a type.
emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning using a string and a type.
@@ -1315,14 +1267,12 @@ emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!
```
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
emitWarning('Something happened!', 'CustomWarning', 'WARN001');
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');
@@ -1333,7 +1283,7 @@ In each of the previous examples, an `Error` object is generated internally by
`process.emitWarning()` and passed through to the [`'warning'`][process_warning]
handler.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('warning', (warning) => {
@@ -1342,9 +1292,7 @@ process.on('warning', (warning) => {
console.warn(warning.code);
console.warn(warning.stack);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('warning', (warning) => {
@@ -1359,7 +1307,7 @@ If `warning` is passed as an `Error` object, it will be passed through to the
`'warning'` event handler unmodified (and the optional `type`,
`code` and `ctor` arguments will be ignored):
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning using an Error object.
@@ -1370,9 +1318,7 @@ myWarning.code = 'WARN001';
emitWarning(myWarning);
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning using an Error object.
@@ -1406,7 +1352,7 @@ The following additional handling is implemented if the warning `type` is
As a best practice, warnings should be emitted only once per process. To do
so, place the `emitWarning()` behind a boolean.
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
function emitMyWarning() {
@@ -1419,9 +1365,7 @@ emitMyWarning();
// Emits: (node: 56339) Warning: Only warn once!
emitMyWarning();
// Emits nothing
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
function emitMyWarning() {
@@ -1473,14 +1417,12 @@ $ node -e 'process.env.foo = "bar"' && echo $foo
While the following will:
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.foo = 'bar';
@@ -1491,7 +1433,7 @@ Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.test = null;
@@ -1500,9 +1442,7 @@ console.log(env.test);
env.test = undefined;
console.log(env.test);
// => 'undefined'
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.test = null;
@@ -1515,16 +1455,14 @@ console.log(env.test);
Use `delete` to delete a property from `process.env`.
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.TEST = 1;
@@ -1535,15 +1473,13 @@ console.log(env.TEST);
On Windows operating systems, environment variables are case-insensitive.
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.TEST = 1;
@@ -1617,13 +1553,11 @@ called.
To exit with a 'failure' code:
-```mjs
+```mjs|cjs
import { exit } from 'node:process';
exit(1);
-```
-
-```cjs
+--------------
const { exit } = require('node:process');
exit(1);
@@ -1645,7 +1579,7 @@ For instance, the following example illustrates a _misuse_ of the
`process.exit()` method that could lead to data printed to stdout being
truncated and lost:
-```mjs
+```mjs|cjs
import { exit } from 'node:process';
// This is an example of what *not* to do:
@@ -1653,9 +1587,7 @@ if (someConditionNotMet()) {
printUsageToStdout();
exit(1);
}
-```
-
-```cjs
+--------------
const { exit } = require('node:process');
// This is an example of what *not* to do:
@@ -1674,7 +1606,7 @@ Rather than calling `process.exit()` directly, the code _should_ set the
`process.exitCode` and allow the process to exit naturally by avoiding
scheduling any additional work for the event loop:
-```mjs
+```mjs|cjs
import process from 'node:process';
// How to properly set the exit code while letting
@@ -1683,9 +1615,7 @@ if (someConditionNotMet()) {
printUsageToStdout();
process.exitCode = 1;
}
-```
-
-```cjs
+--------------
const process = require('node:process');
// How to properly set the exit code while letting
@@ -1732,7 +1662,7 @@ The `process.getActiveResourcesInfo()` method returns an array of strings
containing the types of the active resources that are currently keeping the
event loop alive.
-```mjs
+```mjs|cjs
import { getActiveResourcesInfo } from 'node:process';
import { setTimeout } from 'node:timers';
@@ -1742,9 +1672,7 @@ console.log('After:', getActiveResourcesInfo());
// Prints:
// Before: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap' ]
// After: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]
-```
-
-```cjs
+--------------
const { getActiveResourcesInfo } = require('node:process');
const { setTimeout } = require('node:timers');
@@ -1763,15 +1691,13 @@ console.log('After:', getActiveResourcesInfo());
The `process.getegid()` method returns the numerical effective group identity
of the Node.js process. (See getegid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getegid) {
console.log(`Current gid: ${process.getegid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getegid) {
@@ -1791,15 +1717,13 @@ Android).
The `process.geteuid()` method returns the numerical effective user identity of
the process. (See geteuid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.geteuid) {
console.log(`Current uid: ${process.geteuid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.geteuid) {
@@ -1819,15 +1743,13 @@ Android).
The `process.getgid()` method returns the numerical group identity of the
process. (See getgid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgid) {
console.log(`Current gid: ${process.getgid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgid) {
@@ -1848,15 +1770,13 @@ The `process.getgroups()` method returns an array with the supplementary group
IDs. POSIX leaves it unspecified if the effective group ID is included but
Node.js ensures it always is.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgroups) {
console.log(process.getgroups()); // [ 16, 21, 297 ]
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgroups) {
@@ -1876,15 +1796,13 @@ Android).
The `process.getuid()` method returns the numeric user identity of the process.
(See getuid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getuid) {
console.log(`Current uid: ${process.getuid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getuid) {
@@ -1934,7 +1852,7 @@ These times are relative to an arbitrary time in the
past, and not related to the time of day and therefore not subject to clock
drift. The primary use is for measuring performance between intervals:
-```mjs
+```mjs|cjs
import { hrtime } from 'node:process';
const NS_PER_SEC = 1e9;
@@ -1948,9 +1866,7 @@ setTimeout(() => {
console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
// Benchmark took 1000000552 nanoseconds
}, 1000);
-```
-
-```cjs
+--------------
const { hrtime } = require('node:process');
const NS_PER_SEC = 1e9;
@@ -1979,7 +1895,7 @@ Unlike [`process.hrtime()`][], it does not support an additional `time`
argument since the difference can just be computed directly
by subtraction of the two `bigint`s.
-```mjs
+```mjs|cjs
import { hrtime } from 'node:process';
const start = hrtime.bigint();
@@ -1992,9 +1908,7 @@ setTimeout(() => {
console.log(`Benchmark took ${end - start} nanoseconds`);
// Benchmark took 1154389282 nanoseconds
}, 1000);
-```
-
-```cjs
+--------------
const { hrtime } = require('node:process');
const start = hrtime.bigint();
@@ -2023,7 +1937,7 @@ access or the `CAP_SETGID` capability.
Use care when dropping privileges:
-```mjs
+```mjs|cjs
import { getgroups, initgroups, setgid } from 'node:process';
console.log(getgroups()); // [ 0 ]
@@ -2031,9 +1945,7 @@ initgroups('nodeuser', 1000); // switch user
console.log(getgroups()); // [ 27, 30, 46, 1000, 0 ]
setgid(1000); // drop root gid
console.log(getgroups()); // [ 27, 30, 46, 1000 ]
-```
-
-```cjs
+--------------
const { getgroups, initgroups, setgid } = require('node:process');
console.log(getgroups()); // [ 0 ]
@@ -2070,7 +1982,7 @@ Even though the name of this function is `process.kill()`, it is really just a
signal sender, like the `kill` system call. The signal sent may do something
other than kill the target process.
-```mjs
+```mjs|cjs
import process, { kill } from 'node:process';
process.on('SIGHUP', () => {
@@ -2083,9 +1995,7 @@ setTimeout(() => {
}, 100);
kill(process.pid, 'SIGHUP');
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('SIGHUP', () => {
@@ -2138,7 +2048,7 @@ is no entry script.
Returns an object describing the memory usage of the Node.js process measured in
bytes.
-```mjs
+```mjs|cjs
import { memoryUsage } from 'node:process';
console.log(memoryUsage());
@@ -2150,9 +2060,7 @@ console.log(memoryUsage());
// external: 49879,
// arrayBuffers: 9386
// }
-```
-
-```cjs
+--------------
const { memoryUsage } = require('node:process');
console.log(memoryUsage());
@@ -2201,14 +2109,12 @@ process, including all C++ and JavaScript objects and code.
This is the same value as the `rss` property provided by `process.memoryUsage()`
but `process.memoryUsage.rss()` is faster.
-```mjs
+```mjs|cjs
import { memoryUsage } from 'node:process';
console.log(memoryUsage.rss());
// 35655680
-```
-
-```cjs
+--------------
const { rss } = require('node:process');
console.log(memoryUsage.rss());
@@ -2228,7 +2134,7 @@ completion and before the event loop is allowed to continue. It's possible to
create an infinite loop if one were to recursively call `process.nextTick()`.
See the [Event Loop][] guide for more background.
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
console.log('start');
@@ -2240,9 +2146,7 @@ console.log('scheduled');
// start
// scheduled
// nextTick callback
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
console.log('start');
@@ -2260,7 +2164,7 @@ This is important when developing APIs in order to give users the opportunity
to assign event handlers _after_ an object has been constructed but before any
I/O has occurred:
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
function MyThing(options) {
@@ -2275,9 +2179,7 @@ const thing = new MyThing();
thing.getReadyForStuff();
// thing.startDoingStuff() gets called now, not before.
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
function MyThing(options) {
@@ -2325,7 +2227,7 @@ It is not clear whether `foo()` or `bar()` will be called first.
The following approach is much better:
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
function definitelyAsync(arg, cb) {
@@ -2336,9 +2238,7 @@ function definitelyAsync(arg, cb) {
fs.stat('file', cb);
}
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
function definitelyAsync(arg, cb) {
@@ -2359,7 +2259,7 @@ execute the then, catch, and finally handlers of resolved promises. Within
Node.js, every time the "next tick queue" is drained, the microtask queue
is drained immediately after.
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
Promise.resolve().then(() => console.log(2));
@@ -2369,9 +2269,7 @@ nextTick(() => console.log(1));
// 1
// 2
// 3
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
Promise.resolve().then(() => console.log(2));
@@ -2449,13 +2347,11 @@ flag's behavior.
The `process.pid` property returns the PID of the process.
-```mjs
+```mjs|cjs
import { pid } from 'node:process';
console.log(`This process is pid ${pid}`);
-```
-
-```cjs
+--------------
const { pid } = require('node:process');
console.log(`This process is pid ${pid}`);
@@ -2480,13 +2376,11 @@ Currently possible values are:
* `'sunos'`
* `'win32'`
-```mjs
+```mjs|cjs
import { platform } from 'node:process';
console.log(`This platform is ${platform}`);
-```
-
-```cjs
+--------------
const { platform } = require('node:process');
console.log(`This platform is ${platform}`);
@@ -2505,13 +2399,11 @@ Android operating system. However, Android support in Node.js
The `process.ppid` property returns the PID of the parent of the
current process.
-```mjs
+```mjs|cjs
import { ppid } from 'node:process';
console.log(`The parent process is pid ${ppid}`);
-```
-
-```cjs
+--------------
const { ppid } = require('node:process');
console.log(`The parent process is pid ${ppid}`);
@@ -2583,13 +2475,11 @@ Write reports in a compact format, single-line JSON, more easily consumable
by log processing systems than the default multi-line format designed for
human consumption.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Reports are compact? ${report.compact}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Reports are compact? ${report.compact}`);
@@ -2605,13 +2495,11 @@ Directory where the report is written. The default value is the empty string,
indicating that reports are written to the current working directory of the
Node.js process.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report directory is ${report.directory}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report directory is ${report.directory}`);
@@ -2630,13 +2518,11 @@ value is the empty string.
If the value of `process.report.filename` is set to `'stdout'` or `'stderr'`,
the report is written to the stdout or stderr of the process respectively.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report filename is ${report.filename}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report filename is ${report.filename}`);
@@ -2653,7 +2539,7 @@ Returns a JavaScript Object representation of a diagnostic report for the
running process. The report's JavaScript stack trace is taken from `err`, if
present.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
const data = report.getReport();
@@ -2662,9 +2548,7 @@ console.log(data.header.nodejsVersion);
// Similar to process.report.writeReport()
import fs from 'node:fs';
fs.writeFileSync('my-report.log', util.inspect(data), 'utf8');
-```
-
-```cjs
+--------------
const { report } = require('node:process');
const data = report.getReport();
@@ -2686,13 +2570,11 @@ Additional documentation is available in the [report documentation][].
If `true`, a diagnostic report is generated on fatal errors, such as out of
memory errors or failed C++ assertions.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report on fatal error: ${report.reportOnFatalError}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report on fatal error: ${report.reportOnFatalError}`);
@@ -2707,13 +2589,11 @@ console.log(`Report on fatal error: ${report.reportOnFatalError}`);
If `true`, a diagnostic report is generated when the process receives the
signal specified by `process.report.signal`.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report on signal: ${report.reportOnSignal}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report on signal: ${report.reportOnSignal}`);
@@ -2727,13 +2607,11 @@ console.log(`Report on signal: ${report.reportOnSignal}`);
If `true`, a diagnostic report is generated on uncaught exception.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report on exception: ${report.reportOnUncaughtException}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report on exception: ${report.reportOnUncaughtException}`);
@@ -2748,13 +2626,11 @@ console.log(`Report on exception: ${report.reportOnUncaughtException}`);
The signal used to trigger the creation of a diagnostic report. Defaults to
`'SIGUSR2'`.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report signal: ${report.signal}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report signal: ${report.signal}`);
@@ -2780,13 +2656,11 @@ JavaScript stack trace is taken from `err`, if present.
If the value of `filename` is set to `'stdout'` or `'stderr'`, the report is
written to the stdout or stderr of the process respectively.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
report.writeReport();
-```
-
-```cjs
+--------------
const { report } = require('node:process');
report.writeReport();
@@ -2841,7 +2715,7 @@ Additional documentation is available in the [report documentation][].
process becoming runnable or because the current process exceeded its
time slice. This field is not supported on Windows.
-```mjs
+```mjs|cjs
import { resourceUsage } from 'node:process';
console.log(resourceUsage());
@@ -2866,9 +2740,7 @@ console.log(resourceUsage());
involuntaryContextSwitches: 1
}
*/
-```
-
-```cjs
+--------------
const { resourceUsage } = require('node:process');
console.log(resourceUsage());
@@ -2930,7 +2802,7 @@ The `process.setegid()` method sets the effective group identity of the process.
name string. If a group name is specified, this method blocks while resolving
the associated a numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getegid && process.setegid) {
@@ -2942,9 +2814,7 @@ if (process.getegid && process.setegid) {
console.log(`Failed to set gid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getegid && process.setegid) {
@@ -2973,7 +2843,7 @@ The `process.seteuid()` method sets the effective user identity of the process.
string. If a username is specified, the method blocks while resolving the
associated numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.geteuid && process.seteuid) {
@@ -2985,9 +2855,7 @@ if (process.geteuid && process.seteuid) {
console.log(`Failed to set uid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.geteuid && process.seteuid) {
@@ -3016,7 +2884,7 @@ setgid(2).) The `id` can be passed as either a numeric ID or a group name
string. If a group name is specified, this method blocks while resolving the
associated numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgid && process.setgid) {
@@ -3028,9 +2896,7 @@ if (process.getgid && process.setgid) {
console.log(`Failed to set gid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgid && process.setgid) {
@@ -3060,7 +2926,7 @@ process to have `root` or the `CAP_SETGID` capability.
The `groups` array can contain numeric group IDs, group names, or both.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgroups && process.setgroups) {
@@ -3071,9 +2937,7 @@ if (process.getgroups && process.setgroups) {
console.log(`Failed to set groups: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgroups && process.setgroups) {
@@ -3101,7 +2965,7 @@ setuid(2).) The `id` can be passed as either a numeric ID or a username string.
If a username is specified, the method blocks while resolving the associated
numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getuid && process.setuid) {
@@ -3113,9 +2977,7 @@ if (process.getuid && process.setuid) {
console.log(`Failed to set uid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getuid && process.setuid) {
@@ -3236,13 +3098,11 @@ a [Writable][] stream.
For example, to copy `process.stdin` to `process.stdout`:
-```mjs
+```mjs|cjs
import { stdin, stdout } from 'node:process';
stdin.pipe(stdout);
-```
-
-```cjs
+--------------
const { stdin, stdout } = require('node:process');
stdin.pipe(stdout);
@@ -3393,7 +3253,7 @@ processes inherit the mask from the parent process.
`process.umask(mask)` sets the Node.js process's file mode creation mask. Child
processes inherit the mask from the parent process. Returns the previous mask.
-```mjs
+```mjs|cjs
import { umask } from 'node:process';
const newmask = 0o022;
@@ -3401,9 +3261,7 @@ const oldmask = umask(newmask);
console.log(
`Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`
);
-```
-
-```cjs
+--------------
const { umask } = require('node:process');
const newmask = 0o022;
@@ -3435,14 +3293,12 @@ seconds.
The `process.version` property contains the Node.js version string.
-```mjs
+```mjs|cjs
import { version } from 'node:process';
console.log(`Version: ${version}`);
// Version: v14.8.0
-```
-
-```cjs
+--------------
const { version } = require('node:process');
console.log(`Version: ${version}`);
@@ -3463,13 +3319,11 @@ Node.js and its dependencies. `process.versions.modules` indicates the current
ABI version, which is increased whenever a C++ API changes. Node.js will refuse
to load modules that were compiled against a different module ABI version.
-```mjs
+```mjs|cjs
import { versions } from 'node:process';
console.log(versions);
-```
-
-```cjs
+--------------
const { versions } = require('node:process');
console.log(versions);
diff --git a/content/api/v16/punycode.en.md b/content/api/v16/punycode.en.md
index 9d14574e4c..6123f579e6 100644
--- a/content/api/v16/punycode.en.md
+++ b/content/api/v16/punycode.en.md
@@ -15,7 +15,7 @@ Deprecated
-
+
**The version of the punycode module bundled in Node.js is being deprecated.**
In a future major version of Node.js this module will be removed. Users
diff --git a/content/api/v16/querystring.en.md b/content/api/v16/querystring.en.md
index 2b9f6b6520..619688b2f4 100644
--- a/content/api/v16/querystring.en.md
+++ b/content/api/v16/querystring.en.md
@@ -15,7 +15,7 @@ Legacy
-
+
The `node:querystring` module provides utilities for parsing and formatting URL
query strings. It can be accessed using:
diff --git a/content/api/v16/readline.en.md b/content/api/v16/readline.en.md
index bc16f0f9b9..37ec868884 100644
--- a/content/api/v16/readline.en.md
+++ b/content/api/v16/readline.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:readline` module provides an interface for reading data from a
[Readable][] stream (such as [`process.stdin`][]) one line at a time.
diff --git a/content/api/v16/repl.en.md b/content/api/v16/repl.en.md
index f43fb0ff24..44f3d5be08 100644
--- a/content/api/v16/repl.en.md
+++ b/content/api/v16/repl.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation
that is available both as a standalone program or includible in other
diff --git a/content/api/v16/stream.en.md b/content/api/v16/stream.en.md
index 58297c7586..754c8223ed 100644
--- a/content/api/v16/stream.en.md
+++ b/content/api/v16/stream.en.md
@@ -13,7 +13,7 @@ Stable
-
+
A stream is an abstract interface for working with streaming data in Node.js.
The `node:stream` module provides an API for implementing the stream interface.
@@ -401,7 +401,7 @@ This is a destructive and immediate way to destroy a stream. Previous calls to
Use `end()` instead of destroy if data should flush before close, or wait for
the `'drain'` event before destroying the stream.
-```cjs
+```cjs|cjs
const { Writable } = require('node:stream');
const myStream = new Writable();
@@ -409,9 +409,7 @@ const myStream = new Writable();
const fooErr = new Error('foo error');
myStream.destroy(fooErr);
myStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error
-```
-
-```cjs
+--------------
const { Writable } = require('node:stream');
const myStream = new Writable();
diff --git a/content/api/v16/string_decoder.en.md b/content/api/v16/string_decoder.en.md
index b3beb37ba1..70af2bf2b1 100644
--- a/content/api/v16/string_decoder.en.md
+++ b/content/api/v16/string_decoder.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:string_decoder` module provides an API for decoding `Buffer` objects
into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
diff --git a/content/api/v16/test.en.md b/content/api/v16/test.en.md
index 2c2ed4fbaa..ddff0a6be4 100644
--- a/content/api/v16/test.en.md
+++ b/content/api/v16/test.en.md
@@ -13,27 +13,23 @@ Experimental
-
+
The `node:test` module facilitates the creation of JavaScript tests that
report results in [TAP][] format. To access it:
-```mjs
+```mjs|cjs
import test from 'node:test';
-```
-
-```cjs
+--------------
const test = require('node:test');
```
This module is only available under the `node:` scheme. The following will not
work:
-```mjs
+```mjs|cjs
import test from 'test';
-```
-
-```cjs
+--------------
const test = require('test');
```
@@ -185,11 +181,9 @@ describe('A thing', () => {
`describe` and `it` are imported from the `node:test` module.
-```mjs
+```mjs|cjs
import { describe, it } from 'node:test';
-```
-
-```cjs
+--------------
const { describe, it } = require('node:test');
```
diff --git a/content/api/v16/timers.en.md b/content/api/v16/timers.en.md
index ecceb27df4..51a3135099 100644
--- a/content/api/v16/timers.en.md
+++ b/content/api/v16/timers.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `timer` module exposes a global API for scheduling functions to
be called at some future period of time. Because the timer functions are
@@ -306,15 +306,13 @@ The `timers/promises` API provides an alternative set of timer functions
that return `Promise` objects. The API is accessible via
`require('node:timers/promises')`.
-```mjs
+```mjs|cjs
import {
setTimeout,
setImmediate,
setInterval,
} from 'timers/promises';
-```
-
-```cjs
+--------------
const {
setTimeout,
setImmediate,
@@ -336,7 +334,7 @@ const {
* `signal` [`AbortSignal`](/api/v16/globals#abortsignal) An optional `AbortSignal` that can be used to
cancel the scheduled `Timeout`.
-```mjs
+```mjs|cjs
import {
setTimeout,
} from 'timers/promises';
@@ -344,9 +342,7 @@ import {
const res = await setTimeout(100, 'result');
console.log(res); // Prints 'result'
-```
-
-```cjs
+--------------
const {
setTimeout,
} = require('node:timers/promises');
@@ -368,7 +364,7 @@ setTimeout(100, 'result').then((res) => {
* `signal` [`AbortSignal`](/api/v16/globals#abortsignal) An optional `AbortSignal` that can be used to
cancel the scheduled `Immediate`.
-```mjs
+```mjs|cjs
import {
setImmediate,
} from 'timers/promises';
@@ -376,9 +372,7 @@ import {
const res = await setImmediate('result');
console.log(res); // Prints 'result'
-```
-
-```cjs
+--------------
const {
setImmediate,
} = require('node:timers/promises');
@@ -405,7 +399,7 @@ Returns an async iterator that generates values in an interval of `delay` ms.
* `signal` [`AbortSignal`](/api/v16/globals#abortsignal) An optional `AbortSignal` that can be used to
cancel the scheduled `Timeout` between operations.
-```mjs
+```mjs|cjs
import {
setInterval,
} from 'timers/promises';
@@ -418,9 +412,7 @@ for await (const startTime of setInterval(interval, Date.now())) {
break;
}
console.log(Date.now());
-```
-
-```cjs
+--------------
const {
setInterval,
} = require('node:timers/promises');
diff --git a/content/api/v16/tls.en.md b/content/api/v16/tls.en.md
index b793d83716..083c0214be 100644
--- a/content/api/v16/tls.en.md
+++ b/content/api/v16/tls.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:tls` module provides an implementation of the Transport Layer Security
(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
diff --git a/content/api/v16/tracing.en.md b/content/api/v16/tracing.en.md
index 7150c40c6b..8a4c33d004 100644
--- a/content/api/v16/tracing.en.md
+++ b/content/api/v16/tracing.en.md
@@ -13,7 +13,7 @@ Experimental
-
+
The `node:trace_events` module provides a mechanism to centralize tracing
information generated by V8, Node.js core, and userspace code.
diff --git a/content/api/v16/tty.en.md b/content/api/v16/tty.en.md
index 86e1124f89..a802c064b8 100644
--- a/content/api/v16/tty.en.md
+++ b/content/api/v16/tty.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`
classes. In most cases, it will not be necessary or possible to use this module
diff --git a/content/api/v16/url.en.md b/content/api/v16/url.en.md
index e1c6ab6332..5e4975997a 100644
--- a/content/api/v16/url.en.md
+++ b/content/api/v16/url.en.md
@@ -13,16 +13,14 @@ Stable
-
+
The `node:url` module provides utilities for URL resolution and parsing. It can
be accessed using:
-```mjs
+```mjs|cjs
import url from 'node:url';
-```
-
-```cjs
+--------------
const url = require('node:url');
```
@@ -74,13 +72,11 @@ const myURL =
Parsing the URL string using the Legacy API:
-```mjs
+```mjs|cjs
import url from 'node:url';
const myURL =
url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
-```
-
-```cjs
+--------------
const url = require('node:url');
const myURL =
url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
@@ -91,14 +87,12 @@ const myURL =
It is possible to construct a WHATWG URL from component parts using either the
property setters or a template literal string:
-```js
+```js|js
const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';
-```
-
-```js
+--------------
const pathname = '/a/b/c';
const search = '?d=e';
const hash = '#fgh';
@@ -147,12 +141,10 @@ const myURL = new URL('/foo', 'https://example.org/');
The URL constructor is accessible as a property on the global object.
It can also be imported from the built-in url module:
-```mjs
+```mjs|cjs
import { URL } from 'node:url';
console.log(URL === globalThis.URL); // Prints 'true'.
-```
-
-```cjs
+--------------
console.log(URL === require('node:url').URL); // Prints 'true'.
```
@@ -299,13 +291,11 @@ will be thrown.
Gets the read-only serialization of the URL's origin.
-```js
+```js|js
const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);
// Prints https://example.org
-```
-
-```js
+--------------
const idnURL = new URL('https://測試');
console.log(idnURL.origin);
// Prints https://xn--g6w251d
@@ -969,7 +959,7 @@ It performs the inverse operation to [`url.domainToUnicode()`][].
This feature is only available if the `node` executable was compiled with
[ICU][] enabled. If not, the domain names are passed through unchanged.
-```mjs
+```mjs|cjs
import url from 'node:url';
console.log(url.domainToASCII('español.com'));
@@ -978,9 +968,7 @@ console.log(url.domainToASCII('中文.com'));
// Prints xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
// Prints an empty string
-```
-
-```cjs
+--------------
const url = require('node:url');
console.log(url.domainToASCII('español.com'));
@@ -1006,7 +994,7 @@ It performs the inverse operation to [`url.domainToASCII()`][].
This feature is only available if the `node` executable was compiled with
[ICU][] enabled. If not, the domain names are passed through unchanged.
-```mjs
+```mjs|cjs
import url from 'node:url';
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
@@ -1015,9 +1003,7 @@ console.log(url.domainToUnicode('xn--fiq228c.com'));
// Prints 中文.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
// Prints an empty string
-```
-
-```cjs
+--------------
const url = require('node:url');
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
@@ -1038,7 +1024,7 @@ console.log(url.domainToUnicode('xn--iñvalid.com'));
This function ensures the correct decodings of percent-encoded characters as
well as ensuring a cross-platform valid absolute path string.
-```mjs
+```mjs|cjs
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
@@ -1054,9 +1040,7 @@ fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX)
new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
-```
-
-```cjs
+--------------
const { fileURLToPath } = require('node:url');
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows)
@@ -1096,7 +1080,7 @@ string serializations of the URL. These are not, however, customizable in
any way. The `url.format(URL[, options])` method allows for basic customization
of the output.
-```mjs
+```mjs|cjs
import url from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');
@@ -1108,9 +1092,7 @@ console.log(myURL.toString());
console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://測試/?abc'
-```
-
-```cjs
+--------------
const url = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');
@@ -1134,7 +1116,7 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
This function ensures that `path` is resolved absolutely, and that the URL
control characters are correctly encoded when converting into a File URL.
-```mjs
+```mjs|cjs
import { pathToFileURL } from 'node:url';
new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1
@@ -1142,9 +1124,7 @@ pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)
new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX)
-```
-
-```cjs
+--------------
const { pathToFileURL } = require('node:url');
new URL(__filename); // Incorrect: throws (POSIX)
new URL(__filename); // Incorrect: C:\... (Windows)
@@ -1182,7 +1162,7 @@ pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSI
This utility function converts a URL object into an ordinary options object as
expected by the [`http.request()`][] and [`https.request()`][] APIs.
-```mjs
+```mjs|cjs
import { urlToHttpOptions } from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');
@@ -1199,9 +1179,7 @@ console.log(urlToHttpOptions(myURL));
auth: 'a:b'
}
*/
-```
-
-```cjs
+--------------
const { urlToHttpOptions } = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');
diff --git a/content/api/v16/util.en.md b/content/api/v16/util.en.md
index 94fb3eaca8..5b05c2e985 100644
--- a/content/api/v16/util.en.md
+++ b/content/api/v16/util.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:util` module supports the needs of Node.js internal APIs. Many of the
utilities are useful for application and module developers as well. To access
@@ -919,7 +919,7 @@ Provides a higher level API for command-line argument parsing than interacting
with `process.argv` directly. Takes a specification for the expected arguments
and returns a structured object with the parsed options and positionals.
-```mjs
+```mjs|cjs
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
@@ -937,9 +937,7 @@ const {
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
-```
-
-```cjs
+--------------
const { parseArgs } = require('node:util');
const args = ['-f', '--bar', 'b'];
const options = {
@@ -992,7 +990,7 @@ For example to use the returned tokens to add support for a negated option
like `--no-color`, the tokens can be reprocessed to change the value stored
for the negated option.
-```mjs
+```mjs|cjs
import { parseArgs } from 'node:util';
const options = {
@@ -1022,9 +1020,7 @@ const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
-```
-
-```cjs
+--------------
const { parseArgs } = require('node:util');
const options = {
@@ -1630,7 +1626,7 @@ properties. Such objects are created either by Node.js internals or native
addons. In JavaScript, they are [frozen][`Object.freeze()`] objects with a
`null` prototype.
-```c
+```c|js
#include
#include
napi_value result;
@@ -1646,9 +1642,7 @@ static napi_value MyNapi(napi_env env, napi_callback_info info) {
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...
-```
-
-```js
+--------------
const native = require('napi_addon.node');
const data = native.myNapi();
util.types.isExternal(data); // returns true
diff --git a/content/api/v16/v8.en.md b/content/api/v16/v8.en.md
index c949db60ef..64a8696ad5 100644
--- a/content/api/v16/v8.en.md
+++ b/content/api/v16/v8.en.md
@@ -7,7 +7,7 @@ version: 'v16'
-
+
The `node:v8` module exposes APIs that are specific to the version of [V8][]
built into the Node.js binary. It can be accessed using:
@@ -634,13 +634,11 @@ stopHookSet();
**The `init` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onInit((promise, parent) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onInit((promise, parent) => {});
@@ -657,13 +655,11 @@ const stop = promiseHooks.onInit((promise, parent) => {});
**The `settled` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onSettled((promise) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onSettled((promise) => {});
@@ -680,13 +676,11 @@ const stop = promiseHooks.onSettled((promise) => {});
**The `before` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onBefore((promise) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onBefore((promise) => {});
@@ -703,13 +697,11 @@ const stop = promiseHooks.onBefore((promise) => {});
**The `after` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onAfter((promise) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onAfter((promise) => {});
@@ -739,15 +731,13 @@ be tracked, then only the `init` callback needs to be passed. The
specifics of all functions that can be passed to `callbacks` is in the
[Hook Callbacks][] section.
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stopAll = promiseHooks.createHook({
init(promise, parent) {}
});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stopAll = promiseHooks.createHook({
diff --git a/content/api/v16/vm.en.md b/content/api/v16/vm.en.md
index 03a84a63a7..e36e969610 100644
--- a/content/api/v16/vm.en.md
+++ b/content/api/v16/vm.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:vm` module enables compiling and running code within V8 Virtual
Machine contexts.
@@ -337,7 +337,7 @@ This implementation lies at a lower level than the [ECMAScript Module
loader][]. There is also no way to interact with the Loader yet, though
support is planned.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const contextifiedObject = vm.createContext({
@@ -406,9 +406,7 @@ await bar.link(linker);
// Prints 42.
await bar.evaluate();
-```
-
-```cjs
+--------------
const vm = require('node:vm');
const contextifiedObject = vm.createContext({
@@ -692,7 +690,7 @@ Properties assigned to the `import.meta` object that are objects may
allow the module to access information outside the specified `context`. Use
`vm.runInContext()` to create objects in a specific context.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const contextifiedObject = vm.createContext({ secret: 42 });
@@ -718,9 +716,7 @@ await module.evaluate();
// meta.prop = {};
// above with
// meta.prop = vm.runInContext('{}', contextifiedObject);
-```
-
-```cjs
+--------------
const vm = require('node:vm');
const contextifiedObject = vm.createContext({ secret: 42 });
(async () => {
@@ -841,7 +837,7 @@ This method is used after the module is linked to set the values of exports. If
it is called before the module is linked, an [`ERR_VM_MODULE_STATUS`][] error
will be thrown.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const m = new vm.SyntheticModule(['x'], () => {
@@ -852,9 +848,7 @@ await m.link(() => {});
await m.evaluate();
assert.strictEqual(m.namespace.x, 1);
-```
-
-```cjs
+--------------
const vm = require('node:vm');
(async () => {
const m = new vm.SyntheticModule(['x'], () => {
diff --git a/content/api/v16/wasi.en.md b/content/api/v16/wasi.en.md
index 53156f5c77..c2354579dd 100644
--- a/content/api/v16/wasi.en.md
+++ b/content/api/v16/wasi.en.md
@@ -13,13 +13,13 @@ Experimental
-
+
The WASI API provides an implementation of the [WebAssembly System Interface][]
specification. WASI gives sandboxed WebAssembly applications access to the
underlying operating system via a collection of POSIX-like functions.
-```mjs
+```mjs|cjs
import { readFile } from 'node:fs/promises';
import { WASI } from 'wasi';
import { argv, env } from 'node:process';
@@ -42,9 +42,7 @@ const wasm = await WebAssembly.compile(
const instance = await WebAssembly.instantiate(wasm, importObject);
wasi.start(instance);
-```
-
-```cjs
+--------------
'use strict';
const { readFile } = require('node:fs/promises');
const { WASI } = require('wasi');
diff --git a/content/api/v16/webstreams.en.md b/content/api/v16/webstreams.en.md
index 1af109c97e..ede2bfe2c9 100644
--- a/content/api/v16/webstreams.en.md
+++ b/content/api/v16/webstreams.en.md
@@ -15,15 +15,13 @@ Experimental
An implementation of the [WHATWG Streams Standard][].
-```mjs
+```mjs|cjs
import {
ReadableStream,
WritableStream,
TransformStream,
} from 'node:stream/web';
-```
-
-```cjs
+--------------
const {
ReadableStream,
WritableStream,
@@ -50,7 +48,7 @@ This example creates a simple `ReadableStream` that pushes the current
`performance.now()` timestamp once every second forever. An async iterable
is used to read the data from the stream.
-```mjs
+```mjs|cjs
import {
ReadableStream
} from 'node:stream/web';
@@ -74,9 +72,7 @@ const stream = new ReadableStream({
for await (const value of stream)
console.log(value);
-```
-
-```cjs
+--------------
const {
ReadableStream
} = require('node:stream/web');
@@ -167,7 +163,7 @@ stream's data.
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) `'byob'` or `undefined`
* Returns: [`ReadableStreamDefaultReader`](/api/v16/webstreams#readablestreamdefaultreader) | [`ReadableStreamBYOBReader`](/api/v16/webstreams#readablestreambyobreader)
-```mjs
+```mjs|cjs
import { ReadableStream } from 'node:stream/web';
const stream = new ReadableStream();
@@ -175,9 +171,7 @@ const stream = new ReadableStream();
const reader = stream.getReader();
console.log(await reader.read());
-```
-
-```cjs
+--------------
const { ReadableStream } = require('node:stream/web');
const stream = new ReadableStream();
@@ -220,7 +214,7 @@ pipeline is configured, `transform.readable` is returned.
Causes the `readableStream.locked` to be `true` while the pipe operation
is active.
-```mjs
+```mjs|cjs
import {
ReadableStream,
TransformStream,
@@ -242,9 +236,7 @@ const transformedStream = stream.pipeThrough(transform);
for await (const chunk of transformedStream)
console.log(chunk);
-```
-
-```cjs
+--------------
const {
ReadableStream,
TransformStream,
@@ -1154,7 +1146,7 @@ streams.
They are accessed using:
-```mjs
+```mjs|cjs
import {
arrayBuffer,
blob,
@@ -1162,9 +1154,7 @@ import {
json,
text,
} from 'node:stream/consumers';
-```
-
-```cjs
+--------------
const {
arrayBuffer,
blob,
@@ -1182,7 +1172,7 @@ const {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an `ArrayBuffer` containing the full
contents of the stream.
-```mjs
+```mjs|cjs
import { buffer as arrayBuffer } from 'node:stream/consumers';
import { Readable } from 'node:stream';
import { TextEncoder } from 'node:util';
@@ -1193,9 +1183,7 @@ const dataArray = encoder.encode('hello world from consumers!');
const readable = Readable.from(dataArray);
const data = await arrayBuffer(readable);
console.log(`from readable: ${data.byteLength}`);
-```
-
-```cjs
+--------------
const { arrayBuffer } = require('node:stream/consumers');
const { Readable } = require('stream');
const { TextEncoder } = require('util');
@@ -1216,7 +1204,7 @@ arrayBuffer(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`Blob`](/api/v16/buffer#blob) containing the full contents
of the stream.
-```mjs
+```mjs|cjs
import { blob } from 'node:stream/consumers';
const dataBlob = new Blob(['hello world from consumers!']);
@@ -1224,9 +1212,7 @@ const dataBlob = new Blob(['hello world from consumers!']);
const readable = dataBlob.stream();
const data = await blob(readable);
console.log(`from readable: ${data.size}`);
-```
-
-```cjs
+--------------
const { blob } = require('node:stream/consumers');
const dataBlob = new Blob(['hello world from consumers!']);
@@ -1245,7 +1231,7 @@ blob(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`Buffer`](/api/v16/buffer#buffer) containing the full
contents of the stream.
-```mjs
+```mjs|cjs
import { buffer } from 'node:stream/consumers';
import { Readable } from 'node:stream';
import { Buffer } from 'node:buffer';
@@ -1255,9 +1241,7 @@ const dataBuffer = Buffer.from('hello world from consumers!');
const readable = Readable.from(dataBuffer);
const data = await buffer(readable);
console.log(`from readable: ${data.length}`);
-```
-
-```cjs
+--------------
const { buffer } = require('node:stream/consumers');
const { Readable } = require('node:stream');
const { Buffer } = require('node:buffer');
@@ -1278,7 +1262,7 @@ buffer(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the contents of the stream parsed as a
UTF-8 encoded string that is then passed through `JSON.parse()`.
-```mjs
+```mjs|cjs
import { json } from 'node:stream/consumers';
import { Readable } from 'node:stream';
@@ -1294,9 +1278,7 @@ const items = Array.from(
const readable = Readable.from(JSON.stringify(items));
const data = await json(readable);
console.log(`from readable: ${data.length}`);
-```
-
-```cjs
+--------------
const { json } = require('node:stream/consumers');
const { Readable } = require('node:stream');
@@ -1323,16 +1305,14 @@ json(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the contents of the stream parsed as a
UTF-8 encoded string.
-```mjs
+```mjs|cjs
import { json, text, blob, buffer } from 'node:stream/consumers';
import { Readable } from 'node:stream';
const readable = Readable.from('Hello world from consumers!');
const data = await text(readable);
console.log(`from readable: ${data.length}`);
-```
-
-```cjs
+--------------
const { text } = require('node:stream/consumers');
const { Readable } = require('node:stream');
diff --git a/content/api/v16/worker_threads.en.md b/content/api/v16/worker_threads.en.md
index 82bdbe87b1..ecbbf744e3 100644
--- a/content/api/v16/worker_threads.en.md
+++ b/content/api/v16/worker_threads.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:worker_threads` module enables the use of threads that execute
JavaScript in parallel. To access it:
@@ -1087,7 +1087,7 @@ with `stdio`. This means that `stdio` output originating from a `Worker` can
get blocked by synchronous code on the receiving end that is blocking the
Node.js event loop.
-```mjs
+```mjs|cjs
import {
Worker,
isMainThread,
@@ -1102,9 +1102,7 @@ if (isMainThread) {
// This output will be blocked by the for loop in the main thread.
console.log('foo');
}
-```
-
-```cjs
+--------------
'use strict';
const {
diff --git a/content/api/v16/zlib.en.md b/content/api/v16/zlib.en.md
index e08627da6a..d02bc55897 100644
--- a/content/api/v16/zlib.en.md
+++ b/content/api/v16/zlib.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:zlib` module provides compression functionality implemented using
Gzip, Deflate/Inflate, and Brotli.
@@ -147,7 +147,7 @@ Using `zlib` encoding can be expensive, and the results ought to be cached.
See [Memory usage tuning][] for more information on the speed/memory/compression
tradeoffs involved in `zlib` usage.
-```js
+```js|js
// Client request example
const zlib = require('node:zlib');
const http = require('node:http');
@@ -184,9 +184,7 @@ request.on('response', (response) => {
break;
}
});
-```
-
-```js
+--------------
// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
diff --git a/content/api/v18/assert.en.md b/content/api/v18/assert.en.md
index a8e1c6af75..3a0b79c5c7 100644
--- a/content/api/v18/assert.en.md
+++ b/content/api/v18/assert.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:assert` module provides a set of assertion functions for verifying
invariants.
@@ -31,25 +31,21 @@ assertion mode, error messages for objects display the objects, often truncated.
To use strict assertion mode:
-```mjs
+```mjs|cjs
import { strict as assert } from 'node:assert';
-```
-
-```cjs
+--------------
const assert = require('node:assert').strict;
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
```
Example error diff:
-```mjs
+```mjs|cjs
import { strict as assert } from 'node:assert';
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
@@ -66,9 +62,7 @@ assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// ...
// 5
// ]
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
@@ -103,11 +97,9 @@ Legacy assertion mode uses the [`==` operator][] in:
To use legacy assertion mode:
-```mjs
+```mjs|cjs
import assert from 'node:assert';
-```
-
-```cjs
+--------------
const assert = require('node:assert');
```
@@ -153,7 +145,7 @@ and:
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
+```mjs|cjs
import assert from 'node:assert';
// Generate an AssertionError to compare the error message later:
@@ -176,9 +168,7 @@ try {
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:
@@ -224,7 +214,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
import process from 'node:process';
@@ -242,9 +232,7 @@ callsfunc();
process.on('exit', () => {
tracker.verify();
});
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const tracker = new assert.CallTracker();
@@ -276,7 +264,7 @@ function has not been called exactly `exact` times when
[`tracker.verify()`][] is called, then [`tracker.verify()`][] will throw an
error.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
// Creates call tracker.
@@ -287,9 +275,7 @@ 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.
@@ -314,7 +300,7 @@ const callsfunc = tracker.calls(func);
* `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
+```mjs|cjs
import assert from 'node:assert';
const tracker = new assert.CallTracker();
@@ -325,9 +311,7 @@ callsfunc(1, 2, 3);
assert.deepStrictEqual(tracker.getCalls(callsfunc),
[{ thisArg: this, arguments: [1, 2, 3 ] }]);
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Creates call tracker.
@@ -358,7 +342,7 @@ assert.deepStrictEqual(tracker.getCalls(callsfunc),
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
+```mjs|cjs
import assert from 'node:assert';
// Creates call tracker.
@@ -382,9 +366,7 @@ tracker.report();
// stack: stack trace
// }
// ]
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Creates call tracker.
@@ -420,7 +402,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
const tracker = new assert.CallTracker();
@@ -434,9 +416,7 @@ tracker.getCalls(callsfunc).length === 1;
tracker.reset(callsfunc);
tracker.getCalls(callsfunc).length === 0;
-```
-
-```cjs
+--------------
const assert = require('node:assert');
function func() {}
@@ -458,7 +438,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
// Creates call tracker.
@@ -474,9 +454,7 @@ callsfunc();
// Will throw an error since callsfunc() was only called once.
tracker.verify();
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Creates call tracker.
@@ -554,14 +532,12 @@ are also recursively evaluated by the following rules.
The following example does not throw an [`AssertionError`][] because the
primitives are compared using the [`==` operator][].
-```mjs
+```mjs|cjs
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!
@@ -571,7 +547,7 @@ assert.deepEqual('+00000000', false);
"Deep" equality means that the enumerable "own" properties of child objects
are evaluated also:
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const obj1 = {
@@ -604,9 +580,7 @@ assert.deepEqual(obj1, obj3);
// Prototypes are ignored:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const obj1 = {
@@ -679,7 +653,7 @@ are recursively evaluated also by the following rules.
* [`RegExp`][] lastIndex, flags, and source are always compared, even if these
are not enumerable properties.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
// This fails because 1 !== '1'.
@@ -769,9 +743,7 @@ assert.deepStrictEqual(weakMap1, weakMap3);
// - [items unknown],
// - unequal: true
// }
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
// This fails because 1 !== '1'.
@@ -879,7 +851,7 @@ parameter is an instance of an [`Error`][] then it will be thrown instead of the
Expects the `string` input not to match the regular expression.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotMatch('I will fail', /fail/);
@@ -890,9 +862,7 @@ assert.doesNotMatch(123, /pass/);
assert.doesNotMatch('I will pass', /different/);
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotMatch('I will fail', /fail/);
@@ -941,7 +911,7 @@ function. See [`assert.throws()`][] for more details.
Besides the async nature to await the completion behaves identically to
[`assert.doesNotThrow()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
await assert.doesNotReject(
@@ -950,9 +920,7 @@ await assert.doesNotReject(
},
SyntaxError,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
(async () => {
@@ -965,16 +933,14 @@ const assert = require('node:assert/strict');
})();
```
-```mjs
+```mjs|cjs
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')))
@@ -1012,7 +978,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotThrow(
@@ -1021,9 +987,7 @@ assert.doesNotThrow(
},
SyntaxError,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotThrow(
@@ -1037,7 +1001,7 @@ assert.doesNotThrow(
However, the following will result in an [`AssertionError`][] with the message
'Got unwanted exception...':
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotThrow(
@@ -1046,9 +1010,7 @@ assert.doesNotThrow(
},
TypeError,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotThrow(
@@ -1063,7 +1025,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotThrow(
@@ -1074,9 +1036,7 @@ assert.doesNotThrow(
'Whoops',
);
// Throws: AssertionError: Got unwanted exception: Whoops
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotThrow(
@@ -1113,7 +1073,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
assert.equal(1, 1);
@@ -1127,9 +1087,7 @@ 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);
@@ -1161,7 +1119,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.fail();
@@ -1172,9 +1130,7 @@ assert.fail('boom');
assert.fail(new TypeError('need array'));
// TypeError: need array
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.fail();
@@ -1215,7 +1171,7 @@ the other arguments will be stored as properties on the thrown object. If
removed from stacktrace (see [`Error.captureStackTrace`][]). If no arguments are
given, the default message `Failed` will be used.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.fail('a', 'b');
@@ -1232,9 +1188,7 @@ assert.fail(1, 2, 'whoops', '>');
assert.fail(1, 2, new TypeError('need array'));
// TypeError: need array
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.fail('a', 'b');
@@ -1258,7 +1212,7 @@ influence on the error message.
Example use of `stackStartFn` for truncating the exception's stacktrace:
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
function suppressFrame() {
@@ -1269,9 +1223,7 @@ suppressFrame();
// at repl:1:1
// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
// ...
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
function suppressFrame() {
@@ -1295,7 +1247,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.ifError(null);
@@ -1319,9 +1271,7 @@ let err;
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
// at ifErrorFrame
// at errorFrame
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.ifError(null);
@@ -1357,7 +1307,7 @@ let err;
Expects the `string` input to match the regular expression.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.match('I will fail', /pass/);
@@ -1368,9 +1318,7 @@ assert.match(123, /pass/);
assert.match('I will pass', /pass/);
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.match('I will fail', /pass/);
@@ -1412,7 +1360,7 @@ Legacy: Use [`assert.notDeepStrictEqual()`][] instead.
Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const obj1 = {
@@ -1443,9 +1391,7 @@ assert.notDeepEqual(obj1, obj3);
assert.notDeepEqual(obj1, obj4);
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const obj1 = {
@@ -1494,14 +1440,12 @@ instead of the `AssertionError`.
Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
-```mjs
+```mjs|cjs
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' });
@@ -1537,7 +1481,7 @@ Legacy: Use [`assert.notStrictEqual()`][] instead.
Tests shallow, coercive inequality with the [`!=` operator][]. `NaN` is
specially handled and treated as being identical if both sides are `NaN`.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
assert.notEqual(1, 2);
@@ -1548,9 +1492,7 @@ assert.notEqual(1, 1);
assert.notEqual(1, '1');
// AssertionError: 1 != '1'
-```
-
-```cjs
+--------------
const assert = require('node:assert');
assert.notEqual(1, 2);
@@ -1580,7 +1522,7 @@ parameter is an instance of an [`Error`][] then it will be thrown instead of the
Tests strict inequality between the `actual` and `expected` parameters as
determined by [`Object.is()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.notStrictEqual(1, 2);
@@ -1593,9 +1535,7 @@ assert.notStrictEqual(1, 1);
assert.notStrictEqual(1, '1');
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.notStrictEqual(1, 2);
@@ -1637,7 +1577,7 @@ If no arguments are passed in at all `message` will be set to the string:
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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.ok(true);
@@ -1670,9 +1610,7 @@ assert.ok(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(0)
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.ok(true);
@@ -1707,7 +1645,7 @@ assert.ok(0);
// assert.ok(0)
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
// Using `assert()` works the same:
@@ -1715,9 +1653,7 @@ assert(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert(0)
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Using `assert()` works the same:
@@ -1756,7 +1692,7 @@ each property will be tested for including the non-enumerable `message` and
If specified, `message` will be the message provided by the [`AssertionError`][]
if the `asyncFn` fails to reject.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
await assert.rejects(
@@ -1768,9 +1704,7 @@ await assert.rejects(
message: 'Wrong value',
},
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
(async () => {
@@ -1786,7 +1720,7 @@ const assert = require('node:assert/strict');
})();
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
await assert.rejects(
@@ -1799,9 +1733,7 @@ await assert.rejects(
return true;
},
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
(async () => {
@@ -1818,7 +1750,7 @@ const assert = require('node:assert/strict');
})();
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.rejects(
@@ -1827,9 +1759,7 @@ assert.rejects(
).then(() => {
// ...
});
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.rejects(
@@ -1857,7 +1787,7 @@ argument gets considered.
Tests strict equality between the `actual` and `expected` parameters as
determined by [`Object.is()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.strictEqual(1, 2);
@@ -1883,9 +1813,7 @@ assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
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);
@@ -1942,7 +1870,7 @@ fails.
Custom validation object/error instance:
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
const err = new TypeError('Wrong value');
@@ -2009,9 +1937,7 @@ assert.throws(
// an error as validation object.
err,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
const err = new TypeError('Wrong value');
@@ -2082,7 +2008,7 @@ assert.throws(
Validate instanceof using constructor:
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.throws(
@@ -2091,9 +2017,7 @@ assert.throws(
},
Error,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.throws(
@@ -2109,7 +2033,7 @@ Validate error message using [`RegExp`][]:
Using a regular expression runs `.toString` on the error object, and will
therefore also include the error name.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.throws(
@@ -2118,9 +2042,7 @@ assert.throws(
},
/^Error: Wrong value$/,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.throws(
@@ -2136,7 +2058,7 @@ Custom error validation:
The function must return `true` to indicate all internal validations passed.
It will otherwise fail with an [`AssertionError`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.throws(
@@ -2155,9 +2077,7 @@ assert.throws(
},
'unexpected error',
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.throws(
@@ -2185,7 +2105,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
function throwingFirst() {
@@ -2219,9 +2139,7 @@ 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() {
diff --git a/content/api/v18/async_context.en.md b/content/api/v18/async_context.en.md
index 8c2974558e..66389114f9 100644
--- a/content/api/v18/async_context.en.md
+++ b/content/api/v18/async_context.en.md
@@ -13,7 +13,7 @@ Stable
-
+
### Introduction
@@ -26,11 +26,9 @@ in other languages.
The `AsyncLocalStorage` and `AsyncResource` classes are part of the
`node:async_hooks` module:
-```mjs
+```mjs|cjs
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
-```
-
-```cjs
+--------------
const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');
```
@@ -49,7 +47,7 @@ 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
+```mjs|cjs
import http from 'node:http';
import { AsyncLocalStorage } from 'node:async_hooks';
@@ -79,9 +77,7 @@ http.get('http://localhost:8080');
// 1: start
// 0: finish
// 1: finish
-```
-
-```cjs
+--------------
const http = require('node:http');
const { AsyncLocalStorage } = require('node:async_hooks');
@@ -117,30 +113,66 @@ Each instance of `AsyncLocalStorage` maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.
-#### `new AsyncLocalStorage([options])`
+#### `new AsyncLocalStorage()`
-
+
+
+Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
+`run()` call or after an `enterWith()` call.
+
+#### Static method: `AsyncLocalStorage.bind(fn)`
+
+
-`options.onPropagate` is experimental.
+Experimental
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `onPropagate` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional callback invoked before a store is
- propagated to a new async resource. Returning `true` allows propagation,
- returning `false` avoids it. Default is to propagate always.
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to bind to the current execution context.
+* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A new function that calls `fn` within the captured
+ execution context.
-Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
-`run()` call or after an `enterWith()` call.
+Binds the given function to the current execution context.
+
+#### Static method: `AsyncLocalStorage.snapshot()`
+
+
+
+
+
+Experimental
+
+
+
+* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A new function with the signature
+ `(fn: (...args) : R, ...args) : R`.
+
+Captures the current execution context and returns a function that accepts a
+function as an argument. Whenever the returned function is called, it
+calls the function passed to it within the captured context.
-The `onPropagate` is called during creation of an async resource. Throwing at
-this time will print the stack trace and exit. See
-[`async_hooks` Error handling][] for details.
+```js
+const asyncLocalStorage = new AsyncLocalStorage();
+const runInAsyncScope = asyncLocalStorage.run(123, () => asyncLocalStorage.snapshot());
+const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
+console.log(result); // returns 123
+```
+
+AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
+async context tracking purposes, for example:
+
+```js
+class Foo {
+ #runInAsyncScope = AsyncLocalStorage.snapshot();
+
+ get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
+}
-Creating an async resource within the `onPropagate` callback will result in
-a recursive call to `onPropagate`.
+const foo = asyncLocalStorage.run(123, () => new Foo());
+console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
+```
#### `asyncLocalStorage.disable()`
@@ -349,7 +381,7 @@ The `init` hook will trigger when an `AsyncResource` is instantiated.
The following is an overview of the `AsyncResource` API.
-```mjs
+```mjs|cjs
import { AsyncResource, executionAsyncId } from 'node:async_hooks';
// AsyncResource() is meant to be extended. Instantiating a
@@ -375,9 +407,7 @@ 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
@@ -510,14 +540,12 @@ 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
+```mjs|cjs
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);
@@ -526,7 +554,7 @@ parentPort.on('message', (task) => {
a Worker pool around it could use the following structure:
-```mjs
+```mjs|cjs
import { AsyncResource } from 'node:async_hooks';
import { EventEmitter } from 'node:events';
import path from 'node:path';
@@ -612,9 +640,7 @@ export default class WorkerPool extends EventEmitter {
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');
@@ -712,7 +738,7 @@ were scheduled.
This pool could be used as follows:
-```mjs
+```mjs|cjs
import WorkerPool from './worker_pool.js';
import os from 'node:os';
@@ -726,9 +752,7 @@ for (let i = 0; i < 10; i++) {
pool.close();
});
}
-```
-
-```cjs
+--------------
const WorkerPool = require('./worker_pool.js');
const os = require('node:os');
@@ -754,7 +778,7 @@ 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
+```mjs|cjs
import { createServer } from 'node:http';
import { AsyncResource, executionAsyncId } from 'node:async_hooks';
@@ -767,9 +791,7 @@ const server = createServer((req, res) => {
});
res.end();
}).listen(3000);
-```
-
-```cjs
+--------------
const { createServer } = require('node:http');
const { AsyncResource, executionAsyncId } = require('node:async_hooks');
@@ -788,5 +810,4 @@ const server = createServer((req, res) => {
[`EventEmitter`]: /api/v18/events#class-eventemitter
[`Stream`]: /api/v18/stream#stream
[`Worker`]: worker_threads.md#class-worker
-[`async_hooks` Error handling]: async_hooks.md#error-handling
[`util.promisify()`]: /api/v18/util#utilpromisifyoriginal
diff --git a/content/api/v18/async_hooks.en.md b/content/api/v18/async_hooks.en.md
index 948e3ca37f..fe81a3504d 100644
--- a/content/api/v18/async_hooks.en.md
+++ b/content/api/v18/async_hooks.en.md
@@ -13,7 +13,7 @@ Experimental. Please migrate away from this API, if you can. We do not recommend
-
+
We strongly discourage the use of the `async_hooks` API.
Other APIs that can cover most of its use cases include:
@@ -24,11 +24,9 @@ Other APIs that can cover most of its use cases include:
The `node:async_hooks` module provides an API to track asynchronous resources.
It can be accessed using:
-```mjs
+```mjs|cjs
import async_hooks from 'node:async_hooks';
-```
-
-```cjs
+--------------
const async_hooks = require('node:async_hooks');
```
@@ -48,7 +46,7 @@ interface, and each thread will use a new set of async IDs.
Following is a simple overview of the public API.
-```mjs
+```mjs|cjs
import async_hooks from 'node:async_hooks';
// Return the ID of the current execution context.
@@ -94,9 +92,7 @@ function destroy(asyncId) { }
// 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.
@@ -167,16 +163,14 @@ 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
+```mjs|cjs
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({
@@ -232,7 +226,7 @@ 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
+```mjs|cjs
import { writeFileSync } from 'node:fs';
import { format } from 'node:util';
@@ -240,9 +234,7 @@ 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');
@@ -273,13 +265,11 @@ 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
+```mjs|cjs
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();
@@ -319,15 +309,13 @@ 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
+```mjs|cjs
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));
@@ -369,10 +357,11 @@ created, while `triggerAsyncId` shows _why_ a resource was created.
The following is a simple demonstration of `triggerAsyncId`:
-```mjs
+```mjs|cjs
import { createHook, executionAsyncId } from 'node:async_hooks';
import { stdout } from 'node:process';
import net from 'node:net';
+import fs from 'node:fs';
createHook({
init(asyncId, type, triggerAsyncId) {
@@ -384,12 +373,11 @@ createHook({
}).enable();
net.createServer((conn) => {}).listen(8080);
-```
-
-```cjs
+--------------
const { createHook, executionAsyncId } = require('node:async_hooks');
const { stdout } = require('node:process');
const net = require('node:net');
+const fs = require('node:fs');
createHook({
init(asyncId, type, triggerAsyncId) {
@@ -624,7 +612,7 @@ 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
+```mjs|cjs
import { open } from 'node:fs';
import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
@@ -632,9 +620,7 @@ 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');
@@ -647,7 +633,7 @@ open(__filename, 'r', (err, fd) => {
This can be used to implement continuation local storage without the
use of a tracking `Map` to store the metadata:
-```mjs
+```mjs|cjs
import { createServer } from 'node:http';
import {
executionAsyncId,
@@ -671,9 +657,7 @@ const server = createServer((req, res) => {
res.end(JSON.stringify(executionAsyncResource()[sym]));
}, 100);
}).listen(3000);
-```
-
-```cjs
+--------------
const { createServer } = require('node:http');
const {
executionAsyncId,
@@ -706,17 +690,17 @@ const server = createServer((req, res) => {
* 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
+```mjs|cjs
import { executionAsyncId } from 'node:async_hooks';
+import fs from 'node:fs';
console.log(executionAsyncId()); // 1 - bootstrap
fs.open(path, 'r', (err, fd) => {
console.log(executionAsyncId()); // 6 - open()
});
-```
-
-```cjs
+--------------
const async_hooks = require('node:async_hooks');
+const fs = require('node:fs');
console.log(async_hooks.executionAsyncId()); // 1 - bootstrap
fs.open(path, 'r', (err, fd) => {
@@ -783,7 +767,7 @@ 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
+```mjs|cjs
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
Promise.resolve(1729).then(() => {
@@ -791,9 +775,7 @@ Promise.resolve(1729).then(() => {
});
// produces:
// eid 1 tid 0
-```
-
-```cjs
+--------------
const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');
Promise.resolve(1729).then(() => {
@@ -811,7 +793,7 @@ the resource that caused (triggered) the `then()` callback to be executed.
Installing async hooks via `async_hooks.createHook` enables promise execution
tracking:
-```mjs
+```mjs|cjs
import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
Promise.resolve(1729).then(() => {
@@ -819,9 +801,7 @@ Promise.resolve(1729).then(() => {
});
// produces:
// eid 7 tid 6
-```
-
-```cjs
+--------------
const { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
diff --git a/content/api/v18/buffer.en.md b/content/api/v18/buffer.en.md
index cf5010499c..c17b131ae9 100644
--- a/content/api/v18/buffer.en.md
+++ b/content/api/v18/buffer.en.md
@@ -13,7 +13,7 @@ Stable
-
+
`Buffer` objects are used to represent a fixed-length sequence of bytes. Many
Node.js APIs support `Buffer`s.
@@ -25,7 +25,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Creates a zero-filled Buffer of length 10.
@@ -56,9 +56,7 @@ 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.
@@ -99,7 +97,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello world', 'utf8');
@@ -113,9 +111,7 @@ 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');
@@ -194,7 +190,7 @@ The following legacy character encodings are also supported:
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
Buffer.from('1ag123', 'hex');
@@ -206,9 +202,7 @@ Buffer.from('1a7', 'hex');
Buffer.from('1634', 'hex');
// Prints , all data represented.
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
Buffer.from('1ag123', 'hex');
@@ -255,7 +249,7 @@ There are two ways to create new [`TypedArray`][] instances from a `Buffer`:
contents, interpreted as an array of integers, and not as a byte sequence
of the target type.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
@@ -264,9 +258,7 @@ 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]);
@@ -280,7 +272,7 @@ console.log(uint32array);
* Passing the `Buffer`s underlying [`ArrayBuffer`][] will create a
[`TypedArray`][] that shares its memory with the `Buffer`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello', 'utf16le');
@@ -292,9 +284,7 @@ const uint16array = new Uint16Array(
console.log(uint16array);
// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('hello', 'utf16le');
@@ -313,7 +303,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
@@ -338,9 +328,7 @@ console.log(buf1);
// Prints:
console.log(buf2);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
@@ -371,7 +359,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(20);
@@ -379,9 +367,7 @@ 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);
@@ -410,7 +396,7 @@ function:
`Buffer` instances can be iterated over using `for..of` syntax:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3]);
@@ -422,9 +408,7 @@ for (const b of buf) {
// 1
// 2
// 3
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3]);
@@ -530,7 +514,7 @@ 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
+```mjs|cjs
import { Blob, Buffer } from 'node:buffer';
import { setTimeout as delay } from 'node:timers/promises';
@@ -555,9 +539,7 @@ 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');
@@ -602,16 +584,14 @@ It can be constructed in a variety of ways.
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
`Buffer` will be zero-filled.
-```mjs
+```mjs|cjs
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);
@@ -627,16 +607,14 @@ is thrown.
If `fill` is specified, the allocated `Buffer` will be initialized by calling
[`buf.fill(fill)`][`buf.fill()`].
-```mjs
+```mjs|cjs
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');
@@ -648,16 +626,14 @@ console.log(buf);
If both `fill` and `encoding` are specified, the allocated `Buffer` will be
initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`].
-```mjs
+```mjs|cjs
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');
@@ -688,7 +664,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(10);
@@ -700,9 +676,7 @@ buf.fill(0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(10);
@@ -760,7 +734,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Need to keep around a few small chunks of memory.
@@ -778,9 +752,7 @@ socket.on('readable', () => {
store.push(sb);
}
});
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Need to keep around a few small chunks of memory.
@@ -821,7 +793,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const str = '\u00bd + \u00bc = \u00be';
@@ -829,9 +801,7 @@ 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';
@@ -858,7 +828,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('1234');
@@ -868,9 +838,7 @@ 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');
@@ -905,7 +873,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a single `Buffer` from a list of three `Buffer` instances.
@@ -924,9 +892,7 @@ 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.
@@ -950,6 +916,26 @@ console.log(bufA.length);
`Buffer.concat()` may also use the internal `Buffer` pool like
[`Buffer.allocUnsafe()`][] does.
+#### Static method: `Buffer.copyBytesFrom(view[, offset[, length]])`
+
+
+
+* `view` [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) The [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) to copy.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The starting offset within `view`. **Default:**: `0`.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of elements from `view` to copy.
+ **Default:** `view.length - offset`.
+
+Copies the underlying memory of `view` into a new `Buffer`.
+
+```js
+const u16 = new Uint16Array([0, 0xffff]);
+const buf = Buffer.copyBytesFrom(u16, 0, 1);
+u16[1] = 0;
+console.log(buf.length); // 2
+console.log(buf[0]); // 255
+console.log(buf[1]); // 255
+```
+
#### Static method: `Buffer.from(array)`
@@ -959,14 +945,12 @@ console.log(bufA.length);
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
@@ -995,7 +979,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
@@ -1014,9 +998,7 @@ arr[1] = 6000;
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
@@ -1040,7 +1022,7 @@ console.log(buf);
The optional `byteOffset` and `length` arguments specify a memory range within
the `arrayBuffer` that will be shared by the `Buffer`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const ab = new ArrayBuffer(10);
@@ -1048,9 +1030,7 @@ const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const ab = new ArrayBuffer(10);
@@ -1069,7 +1049,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
@@ -1079,9 +1059,7 @@ 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
@@ -1102,7 +1080,7 @@ console.log(buf);
Copies the passed `buffer` data onto a new `Buffer` instance.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('buffer');
@@ -1114,9 +1092,7 @@ console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: buffer
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf1 = Buffer.from('buffer');
@@ -1144,14 +1120,12 @@ appropriate for `Buffer.from()` variants.
For objects whose `valueOf()` function returns a value not strictly equal to
`object`, returns `Buffer.from(object.valueOf(), offsetOrEncoding, length)`.
-```mjs
+```mjs|cjs
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'));
@@ -1161,7 +1135,7 @@ const buf = Buffer.from(new String('this is a test'));
For objects that support `Symbol.toPrimitive`, returns
`Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
class Foo {
@@ -1172,9 +1146,7 @@ class Foo {
const buf = Buffer.from(new Foo(), 'utf8');
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
class Foo {
@@ -1200,7 +1172,7 @@ is not of another type appropriate for `Buffer.from()` variants.
Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
the character encoding to be used when converting `string` into bytes.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('this is a tést');
@@ -1212,9 +1184,7 @@ 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');
@@ -1240,7 +1210,7 @@ appropriate for `Buffer.from()` variants.
Returns `true` if `obj` is a `Buffer`, `false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
Buffer.isBuffer(Buffer.alloc(10)); // true
@@ -1248,9 +1218,7 @@ 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
@@ -1270,7 +1238,7 @@ Buffer.isBuffer(new Uint8Array(1024)); // false
Returns `true` if `encoding` is the name of a supported character encoding,
or `false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
console.log(Buffer.isEncoding('utf8'));
@@ -1284,9 +1252,7 @@ console.log(Buffer.isEncoding('utf/8'));
console.log(Buffer.isEncoding(''));
// Prints: false
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
console.log(Buffer.isEncoding('utf8'));
@@ -1325,7 +1291,7 @@ access is the same as `Uint8Array`. In other words, `buf[index]` returns
`buf[index] = value` does not modify the buffer if `index` is negative or
`>= buf.length`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Copy an ASCII string into a `Buffer` one byte at a time.
@@ -1341,9 +1307,7 @@ for (let i = 0; i < str.length; 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.
@@ -1369,7 +1333,7 @@ console.log(buf.toString('utf8'));
This `ArrayBuffer` is not guaranteed to correspond exactly to the original
`Buffer`. See the notes on `buf.byteOffset` for details.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arrayBuffer = new ArrayBuffer(16);
@@ -1377,9 +1341,7 @@ const buffer = Buffer.from(arrayBuffer);
console.log(buffer.buffer === arrayBuffer);
// Prints: true
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const arrayBuffer = new ArrayBuffer(16);
@@ -1404,7 +1366,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a buffer smaller than `Buffer.poolSize`.
@@ -1414,9 +1376,7 @@ const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// 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`.
@@ -1452,7 +1412,7 @@ Comparison is based on the actual sequence of bytes in each `Buffer`.
* `1` is returned if `target` should come _before_ `buf` when sorted.
* `-1` is returned if `target` should come _after_ `buf` when sorted.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('ABC');
@@ -1472,9 +1432,7 @@ console.log(buf2.compare(buf3));
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');
@@ -1500,7 +1458,7 @@ The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`
arguments can be used to limit the comparison to specific ranges within `target`
and `buf` respectively.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
@@ -1512,9 +1470,7 @@ 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]);
@@ -1551,7 +1507,7 @@ memory region overlaps with `buf`.
for all TypedArrays, including Node.js `Buffer`s, although it takes
different function arguments.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create two `Buffer` instances.
@@ -1570,9 +1526,7 @@ buf1.copy(buf2, 8, 16, 20);
console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Create two `Buffer` instances.
@@ -1593,7 +1547,7 @@ console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
```
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a `Buffer` and copy data from one region to an overlapping region
@@ -1610,9 +1564,7 @@ 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
@@ -1640,7 +1592,7 @@ console.log(buf.toString());
Creates and returns an [iterator][] of `[index, byte]` pairs from the contents
of `buf`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Log the entire contents of a `Buffer`.
@@ -1657,9 +1609,7 @@ for (const pair of buf.entries()) {
// [3, 102]
// [4, 101]
// [5, 114]
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Log the entire contents of a `Buffer`.
@@ -1690,7 +1640,7 @@ Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,
`false` otherwise. Equivalent to
[`buf.compare(otherBuffer) === 0`][`buf.compare()`].
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('ABC');
@@ -1701,9 +1651,7 @@ 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');
@@ -1733,7 +1681,7 @@ console.log(buf1.equals(buf3));
Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
the entire `buf` will be filled:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with the ASCII character 'h'.
@@ -1748,9 +1696,7 @@ const c = Buffer.allocUnsafe(5).fill('');
console.log(c.fill(''));
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Fill a `Buffer` with the ASCII character 'h'.
@@ -1774,16 +1720,14 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
@@ -1795,7 +1739,7 @@ console.log(Buffer.allocUnsafe(5).fill('\u0222'));
If `value` contains invalid characters, it is truncated; if no valid
fill data remains, an exception is thrown:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(5);
@@ -1806,9 +1750,7 @@ 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);
@@ -1834,7 +1776,7 @@ console.log(buf.fill('zz', 'hex'));
Equivalent to [`buf.indexOf() !== -1`][`buf.indexOf()`].
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this is a buffer');
@@ -1853,9 +1795,7 @@ 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');
@@ -1898,7 +1838,7 @@ If `value` is:
* a number, `value` will be interpreted as an unsigned 8-bit integer
value between `0` and `255`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this is a buffer');
@@ -1922,9 +1862,7 @@ 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');
@@ -1958,7 +1896,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
@@ -1974,9 +1912,7 @@ 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');
@@ -2006,7 +1942,7 @@ than `buf.length`, `byteOffset` will be returned. If `value` is empty and
Creates and returns an [iterator][] of `buf` keys (indices).
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -2021,9 +1957,7 @@ for (const key of buf.keys()) {
// 3
// 4
// 5
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
@@ -2057,7 +1991,7 @@ for (const key of buf.keys()) {
Identical to [`buf.indexOf()`][], except the last occurrence of `value` is found
rather than the first occurrence.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this buffer is a buffer');
@@ -2083,9 +2017,7 @@ 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');
@@ -2121,7 +2053,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
@@ -2140,9 +2072,7 @@ console.log(b.lastIndexOf('b', {}));
// 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');
@@ -2173,7 +2103,7 @@ If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned.
Returns the number of bytes in `buf`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a `Buffer` and write a shorter string to it using UTF-8.
@@ -2187,9 +2117,7 @@ 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.
@@ -2257,16 +2185,14 @@ Reads an unsigned, big-endian 64-bit integer from `buf` at the specified
This function is also available under the `readBigUint64BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64BE(0));
// Prints: 4294967295n
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
@@ -2288,16 +2214,14 @@ Reads an unsigned, little-endian 64-bit integer from `buf` at the specified
This function is also available under the `readBigUint64LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64LE(0));
// Prints: 18446744069414584320n
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
@@ -2316,16 +2240,14 @@ console.log(buf.readBigUInt64LE(0));
Reads a 64-bit, big-endian double from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleBE(0));
// Prints: 8.20788039913184e-304
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
@@ -2344,7 +2266,7 @@ console.log(buf.readDoubleBE(0));
Reads a 64-bit, little-endian double from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
@@ -2353,9 +2275,7 @@ 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]);
@@ -2376,16 +2296,14 @@ console.log(buf.readDoubleLE(1));
Reads a 32-bit, big-endian float from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
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]);
@@ -2404,7 +2322,7 @@ console.log(buf.readFloatBE(0));
Reads a 32-bit, little-endian float from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
@@ -2413,9 +2331,7 @@ 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]);
@@ -2438,7 +2354,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([-1, 5]);
@@ -2449,9 +2365,7 @@ 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]);
@@ -2476,16 +2390,14 @@ 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
+```mjs|cjs
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]);
@@ -2507,7 +2419,7 @@ Reads a signed, little-endian 16-bit integer from `buf` at the specified
Integers read from a `Buffer` are interpreted as two's complement signed values.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 5]);
@@ -2516,9 +2428,7 @@ 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]);
@@ -2541,16 +2451,14 @@ 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
+```mjs|cjs
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]);
@@ -2572,7 +2480,7 @@ Reads a signed, little-endian 32-bit integer from `buf` at the specified
Integers read from a `Buffer` are interpreted as two's complement signed values.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 0, 0, 5]);
@@ -2581,9 +2489,7 @@ 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]);
@@ -2608,7 +2514,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2619,9 +2525,7 @@ 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]);
@@ -2648,16 +2552,14 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntLE(0, 6).toString(16));
// Prints: -546f87a9cbee
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2678,7 +2580,7 @@ Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
This function is also available under the `readUint8` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, -2]);
@@ -2689,9 +2591,7 @@ 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]);
@@ -2717,7 +2617,7 @@ Reads an unsigned, big-endian 16-bit integer from `buf` at the specified
This function is also available under the `readUint16BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56]);
@@ -2726,9 +2626,7 @@ 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]);
@@ -2752,7 +2650,7 @@ Reads an unsigned, little-endian 16-bit integer from `buf` at the specified
This function is also available under the `readUint16LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56]);
@@ -2763,9 +2661,7 @@ 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]);
@@ -2791,16 +2687,14 @@ Reads an unsigned, big-endian 32-bit integer from `buf` at the specified
This function is also available under the `readUint32BE` alias.
-```mjs
+```mjs|cjs
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]);
@@ -2822,7 +2716,7 @@ Reads an unsigned, little-endian 32-bit integer from `buf` at the specified
This function is also available under the `readUint32LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
@@ -2831,9 +2725,7 @@ 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]);
@@ -2860,7 +2752,7 @@ up to 48 bits of accuracy.
This function is also available under the `readUintBE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2869,9 +2761,7 @@ 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]);
@@ -2898,16 +2788,14 @@ up to 48 bits of accuracy.
This function is also available under the `readUintLE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntLE(0, 6).toString(16));
// Prints: ab9078563412
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2936,7 +2824,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
@@ -2958,9 +2846,7 @@ 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
@@ -2987,7 +2873,7 @@ console.log(buf2.toString('ascii', 0, buf2.length));
Specifying negative indexes causes the slice to be generated relative to the
end of `buf` rather than the beginning.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -3003,9 +2889,7 @@ console.log(buf.subarray(-6, -2).toString());
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');
@@ -3045,7 +2929,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -3065,9 +2949,7 @@ console.log(notReallyCopiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Also prints: cuffer (!)
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
@@ -3099,7 +2981,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
@@ -3116,9 +2998,7 @@ 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]);
@@ -3140,14 +3020,12 @@ buf2.swap16();
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
@@ -3164,7 +3042,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
@@ -3181,9 +3059,7 @@ 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]);
@@ -3211,7 +3087,7 @@ buf2.swap32();
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
@@ -3228,9 +3104,7 @@ 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]);
@@ -3261,7 +3135,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
@@ -3278,9 +3152,7 @@ const copy = JSON.parse(json, (key, value) => {
console.log(copy);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
@@ -3318,7 +3190,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.allocUnsafe(26);
@@ -3341,9 +3213,7 @@ 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);
@@ -3377,7 +3247,7 @@ console.log(buf2.toString(undefined, 0, 3));
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -3403,9 +3273,7 @@ for (const value of buf) {
// 102
// 101
// 114
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
@@ -3450,7 +3318,7 @@ Writes `string` to `buf` at `offset` according to the character encoding in
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(256);
@@ -3466,9 +3334,7 @@ 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);
@@ -3499,7 +3365,7 @@ Writes `value` to `buf` at the specified `offset` as big-endian.
`value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3508,9 +3374,7 @@ buf.writeBigInt64BE(0x0102030405060708n, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3534,7 +3398,7 @@ Writes `value` to `buf` at the specified `offset` as little-endian.
`value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3543,9 +3407,7 @@ buf.writeBigInt64LE(0x0102030405060708n, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3569,7 +3431,7 @@ Writes `value` to `buf` at the specified `offset` as big-endian.
This function is also available under the `writeBigUint64BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3578,9 +3440,7 @@ buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3602,7 +3462,7 @@ console.log(buf);
Writes `value` to `buf` at the specified `offset` as little-endian
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3611,9 +3471,7 @@ buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3639,7 +3497,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3648,9 +3506,7 @@ buf.writeDoubleBE(123.456, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3674,7 +3530,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3683,9 +3539,7 @@ buf.writeDoubleLE(123.456, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3708,7 +3562,7 @@ console.log(buf);
Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is
undefined when `value` is anything other than a JavaScript number.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3717,9 +3571,7 @@ buf.writeFloatBE(0xcafebabe, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3742,7 +3594,7 @@ console.log(buf);
Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is
undefined when `value` is anything other than a JavaScript number.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3751,9 +3603,7 @@ buf.writeFloatLE(0xcafebabe, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3779,7 +3629,7 @@ a signed 8-bit integer.
`value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
@@ -3789,9 +3639,7 @@ buf.writeInt8(-2, 1);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
@@ -3818,7 +3666,7 @@ anything other than a signed 16-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
@@ -3827,9 +3675,7 @@ buf.writeInt16BE(0x0102, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
@@ -3855,7 +3701,7 @@ anything other than a signed 16-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
@@ -3864,9 +3710,7 @@ buf.writeInt16LE(0x0304, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
@@ -3892,7 +3736,7 @@ anything other than a signed 32-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3901,9 +3745,7 @@ buf.writeInt32BE(0x01020304, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3929,7 +3771,7 @@ anything other than a signed 32-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3938,9 +3780,7 @@ buf.writeInt32LE(0x05060708, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3966,7 +3806,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -3975,9 +3815,7 @@ buf.writeIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4003,7 +3841,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -4012,9 +3850,7 @@ buf.writeIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4040,7 +3876,7 @@ other than an unsigned 8-bit integer.
This function is also available under the `writeUint8` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4052,9 +3888,7 @@ buf.writeUInt8(0x42, 3);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4083,7 +3917,7 @@ is anything other than an unsigned 16-bit integer.
This function is also available under the `writeUint16BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4093,9 +3927,7 @@ buf.writeUInt16BE(0xbeef, 2);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4122,7 +3954,7 @@ anything other than an unsigned 16-bit integer.
This function is also available under the `writeUint16LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4132,9 +3964,7 @@ buf.writeUInt16LE(0xbeef, 2);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4161,7 +3991,7 @@ is anything other than an unsigned 32-bit integer.
This function is also available under the `writeUint32BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4170,9 +4000,7 @@ buf.writeUInt32BE(0xfeedface, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4198,7 +4026,7 @@ anything other than an unsigned 32-bit integer.
This function is also available under the `writeUint32LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4207,9 +4035,7 @@ buf.writeUInt32LE(0xfeedface, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4237,7 +4063,7 @@ when `value` is anything other than an unsigned integer.
This function is also available under the `writeUintBE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -4246,9 +4072,7 @@ buf.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4276,7 +4100,7 @@ when `value` is anything other than an unsigned integer.
This function is also available under the `writeUintLE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -4285,9 +4109,7 @@ buf.writeUIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4476,6 +4298,18 @@ For code running using Node.js APIs, converting between base64-encoded strings
and binary data should be performed using `Buffer.from(str, 'base64')` and
`buf.toString('base64')`.**
+#### `buffer.isAscii(input)`
+
+
+
+* input [`Buffer`](/api/v18/buffer#buffer) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) The input to validate.
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+This function returns `true` if `input` contains only valid ASCII-encoded data,
+including the case in which `input` is empty.
+
+Throws if the `input` is a detached array buffer.
+
#### `buffer.isUtf8(input)`
@@ -4552,15 +4386,13 @@ Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,
The transcoding process will use substitution characters if a given byte
sequence cannot be adequately represented in the target encoding. For instance:
-```mjs
+```mjs|cjs
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');
diff --git a/content/api/v18/child_process.en.md b/content/api/v18/child_process.en.md
index 5b8e06b4ee..a041774de9 100644
--- a/content/api/v18/child_process.en.md
+++ b/content/api/v18/child_process.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:child_process` module provides the ability to spawn subprocesses in
a manner that is similar, but not identical, to popen(3). This capability
@@ -117,7 +117,7 @@ When running on Windows, `.bat` and `.cmd` files can be invoked using
[`child_process.exec()`][] do). In any case, if the script filename contains
spaces it needs to be quoted.
-```js
+```js|js
// On Windows Only...
const { spawn } = require('node:child_process');
const bat = spawn('cmd.exe', ['/c', 'my.bat']);
@@ -133,9 +133,7 @@ bat.stderr.on('data', (data) => {
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) => {
diff --git a/content/api/v18/cli.en.md b/content/api/v18/cli.en.md
index c0f0e3daf9..7cc470aa45 100644
--- a/content/api/v18/cli.en.md
+++ b/content/api/v18/cli.en.md
@@ -162,7 +162,7 @@ $ node --completion-bash > node_bash_completion
$ source node_bash_completion
```
-#### `-C=condition`, `--conditions=condition`
+#### `-C condition`, `--conditions=condition`
@@ -183,7 +183,7 @@ The default Node.js conditions of `"node"`, `"default"`, `"import"`, and
For example, to run a module with "development" resolutions:
```console
-$ node -C=development app.js
+$ node -C development app.js
```
#### `--cpu-prof`
@@ -392,6 +392,15 @@ the ability to import a directory that has an index file.
See [customizing ESM specifier resolution][] for example usage.
+#### `--experimental-test-coverage`
+
+
+
+When used in conjunction with the `node:test` module, a code coverage report is
+generated as part of the test runner output. If no tests are run, a coverage
+report is not generated. See the documentation on
+[collecting code coverage from tests][] for more details.
+
#### `--experimental-vm-modules`
@@ -1007,6 +1016,20 @@ A regular expression that configures the test runner to only execute tests
whose name matches the provided pattern. See the documentation on
[filtering tests by name][] for more details.
+#### `--test-reporter`
+
+
+
+A test reporter to use when running tests. See the documentation on
+[test reporters][] for more details.
+
+#### `--test-reporter-destination`
+
+
+
+The destination for the corresponding test reporter. See the documentation on
+[test reporters][] for more details.
+
#### `--test-only`
@@ -1590,6 +1613,7 @@ V8 options that are allowed are:
* `--abort-on-uncaught-exception`
* `--disallow-code-generation-from-strings`
+* `--enable-etw-stack-walking`
* `--huge-max-old-generation-size`
* `--interpreted-frames-native-stack`
* `--jitless`
@@ -1604,6 +1628,8 @@ V8 options that are allowed are:
`--perf-basic-prof-only-functions`, `--perf-basic-prof`,
`--perf-prof-unwinding-info`, and `--perf-prof` are only available on Linux.
+`--enable-etw-stack-walking` is only available on Windows.
+
#### `NODE_PATH=path[:…]`
@@ -1924,6 +1950,7 @@ done
[`unhandledRejection`]: /api/v18/process#event-unhandledrejection
[`v8.startupSnapshot` API]: v8.md#startup-snapshot-api
[`worker_threads.threadId`]: worker_threads.md#workerthreadid
+[collecting code coverage from tests]: /api/v18/test#collecting-code-coverage
[conditional exports]: /api/v18/packages#conditional-exports
[context-aware]: /api/v18/addons#context-aware-addons
[customizing ESM specifier resolution]: /api/v18/esm#customizing-esm-specifier-resolution-algorithm
@@ -1938,6 +1965,7 @@ done
[scavenge garbage collector]: https://v8.dev/blog/orinoco-parallel-scavenger
[security warning]: #warning-binding-inspector-to-a-public-ipport-combination-is-insecure
[semi-space]: https://www.memorymanagement.org/glossary/s.html#semi.space
+[test reporters]: /api/v18/test#test-reporters
[timezone IDs]: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
[tracking issue for user-land snapshots]: https://github.com/nodejs/node/issues/44014
[ways that `TZ` is handled in other environments]: https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
diff --git a/content/api/v18/cluster.en.md b/content/api/v18/cluster.en.md
index f20ec8557d..276a98a457 100644
--- a/content/api/v18/cluster.en.md
+++ b/content/api/v18/cluster.en.md
@@ -13,7 +13,7 @@ Stable
-
+
Clusters of Node.js processes can be used to run multiple instances of Node.js
that can distribute workloads among their application threads. When process
@@ -23,7 +23,7 @@ allows running multiple application threads within a single Node.js instance.
The cluster module allows easy creation of child processes that all share
server ports.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';
@@ -52,9 +52,7 @@ if (cluster.isPrimary) {
console.log(`Worker ${process.pid} started`);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const http = require('node:http');
const numCPUs = require('node:os').availableParallelism();
@@ -195,7 +193,7 @@ Within a worker, `process.on('error')` may also be used.
Similar to the `cluster.on('exit')` event, but specific to this worker.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
if (cluster.isPrimary) {
@@ -210,9 +208,7 @@ if (cluster.isPrimary) {
}
});
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
if (cluster.isPrimary) {
@@ -237,13 +233,11 @@ if (cluster.isPrimary) {
Similar to the `cluster.on('listening')` event, but specific to this worker.
-```mjs
+```mjs|cjs
cluster.fork().on('listening', (address) => {
// Worker is listening
});
-```
-
-```cjs
+--------------
cluster.fork().on('listening', (address) => {
// Worker is listening
});
@@ -267,7 +261,7 @@ See [`process` event: `'message'`][].
Here is an example using the message system. It keeps a count in the primary
process of the number of HTTP requests received by the workers:
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';
@@ -309,9 +303,7 @@ if (cluster.isPrimary) {
process.send({ cmd: 'notifyRequest' });
}).listen(8000);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const http = require('node:http');
const process = require('node:process');
@@ -485,7 +477,7 @@ has been created. It is disconnected after the `'disconnect'` event is emitted.
This function returns `true` if the worker's process has terminated (either
because of exiting or being signaled). Otherwise, it returns `false`.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';
@@ -516,9 +508,7 @@ if (cluster.isPrimary) {
process.kill(process.pid);
}).listen(8000);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const http = require('node:http');
const numCPUs = require('node:os').availableParallelism();
@@ -892,7 +882,7 @@ the `env` passed to [`.fork()`][].
The defaults above apply to the first call only; the defaults for later
calls are the current values at the time of `cluster.setupPrimary()` is called.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
cluster.setupPrimary({
@@ -906,9 +896,7 @@ cluster.setupPrimary({
args: ['--use', 'http'],
});
cluster.fork(); // http worker
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
cluster.setupPrimary({
@@ -934,7 +922,7 @@ This can only be called from the primary process.
A reference to the current worker object. Not available in the primary process.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
if (cluster.isPrimary) {
@@ -944,9 +932,7 @@ if (cluster.isPrimary) {
} else if (cluster.isWorker) {
console.log(`I am worker #${cluster.worker.id}`);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
if (cluster.isPrimary) {
@@ -973,15 +959,13 @@ _and_ exited. The order between these two events cannot be determined in
advance. However, it is guaranteed that the removal from the `cluster.workers`
list happens before the last `'disconnect'` or `'exit'` event is emitted.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
for (const worker of Object.values(cluster.workers)) {
worker.send('big announcement to all workers');
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
for (const worker of Object.values(cluster.workers)) {
diff --git a/content/api/v18/console.en.md b/content/api/v18/console.en.md
index 5d030297ae..7e22858e13 100644
--- a/content/api/v18/console.en.md
+++ b/content/api/v18/console.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:console` module provides a simple debugging console that is similar to
the JavaScript console mechanism provided by web browsers.
@@ -83,11 +83,9 @@ The `Console` class can be used to create a simple logger with configurable
output streams and can be accessed using either `require('node:console').Console`
or `console.Console` (or their destructured counterparts):
-```js
+```js|js
const { Console } = require('node:console');
-```
-
-```js
+--------------
const { Console } = console;
```
diff --git a/content/api/v18/crypto.en.md b/content/api/v18/crypto.en.md
index 543de669b1..a5ebb570bb 100644
--- a/content/api/v18/crypto.en.md
+++ b/content/api/v18/crypto.en.md
@@ -13,13 +13,13 @@ Stable
-
+
The `node:crypto` module provides cryptographic functionality that includes a
set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
functions.
-```mjs
+```mjs|cjs
const { createHmac } = await import('node:crypto');
const secret = 'abcdefg';
@@ -29,15 +29,13 @@ const hash = createHmac('sha256', secret)
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
-```
-
-```cjs
-const crypto = require('node:crypto');
+--------------
+const { createHmac } = require('node:crypto');
const secret = 'abcdefg';
-const hash = crypto.createHmac('sha256', secret)
- .update('I love cupcakes')
- .digest('hex');
+const hash = createHmac('sha256', secret)
+ .update('I love cupcakes')
+ .digest('hex');
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
@@ -101,15 +99,13 @@ data. The most common usage is handling output generated by the HTML5
* Returns: [`Buffer`](/api/v18/buffer#buffer) The challenge component of the `spkac` data structure, which
includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
@@ -126,15 +122,13 @@ console.log(challenge.toString('utf8'));
* Returns: [`Buffer`](/api/v18/buffer#buffer) The public key component of the `spkac` data structure,
which includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
@@ -151,18 +145,16 @@ console.log(publicKey);
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the given `spkac` data structure is valid,
`false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
-```
-
-```cjs
-const { Certificate } = require('node:crypto');
+--------------
const { Buffer } = require('node:buffer');
+const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
@@ -185,14 +177,12 @@ the `crypto.Certificate` class as illustrated in the examples below.
Instances of the `Certificate` class can be created using the `new` keyword
or by calling `crypto.Certificate()` as a function:
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const cert1 = new Certificate();
const cert2 = Certificate();
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const cert1 = new Certificate();
@@ -208,16 +198,14 @@ const cert2 = Certificate();
* Returns: [`Buffer`](/api/v18/buffer#buffer) The challenge component of the `spkac` data structure, which
includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
@@ -235,16 +223,14 @@ console.log(challenge.toString('utf8'));
* Returns: [`Buffer`](/api/v18/buffer#buffer) The public key component of the `spkac` data structure,
which includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
@@ -262,7 +248,7 @@ console.log(publicKey);
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the given `spkac` data structure is valid,
`false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { Certificate } = await import('node:crypto');
@@ -270,11 +256,9 @@ const cert = Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
-```
-
-```cjs
-const { Certificate } = require('node:crypto');
+--------------
const { Buffer } = require('node:buffer');
+const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
@@ -302,7 +286,7 @@ directly using the `new` keyword.
Example: Using `Cipher` objects as streams:
-```mjs
+```mjs|cjs
const {
scrypt,
randomFill,
@@ -333,9 +317,7 @@ scrypt(password, 'salt', 24, (err, key) => {
cipher.end();
});
});
-```
-
-```cjs
+--------------
const {
scrypt,
randomFill,
@@ -370,7 +352,7 @@ scrypt(password, 'salt', 24, (err, key) => {
Example: Using `Cipher` and piped streams:
-```mjs
+```mjs|cjs
import {
createReadStream,
createWriteStream,
@@ -407,9 +389,7 @@ scrypt(password, 'salt', 24, (err, key) => {
});
});
});
-```
-
-```cjs
+--------------
const {
createReadStream,
createWriteStream,
@@ -450,7 +430,7 @@ scrypt(password, 'salt', 24, (err, key) => {
Example: Using the [`cipher.update()`][] and [`cipher.final()`][] methods:
-```mjs
+```mjs|cjs
const {
scrypt,
randomFill,
@@ -475,9 +455,7 @@ scrypt(password, 'salt', 24, (err, key) => {
console.log(encrypted);
});
});
-```
-
-```cjs
+--------------
const {
scrypt,
randomFill,
@@ -618,7 +596,7 @@ directly using the `new` keyword.
Example: Using `Decipher` objects as streams:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
scryptSync,
@@ -653,9 +631,7 @@ const encrypted =
'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
decipher.write(encrypted, 'hex');
decipher.end();
-```
-
-```cjs
+--------------
const {
scryptSync,
createDecipheriv,
@@ -694,7 +670,7 @@ decipher.end();
Example: Using `Decipher` and piped streams:
-```mjs
+```mjs|cjs
import {
createReadStream,
createWriteStream,
@@ -718,9 +694,7 @@ const input = createReadStream('test.enc');
const output = createWriteStream('test.js');
input.pipe(decipher).pipe(output);
-```
-
-```cjs
+--------------
const {
createReadStream,
createWriteStream,
@@ -748,7 +722,7 @@ input.pipe(decipher).pipe(output);
Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
scryptSync,
@@ -771,9 +745,7 @@ let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
// Prints: some clear text data
-```
-
-```cjs
+--------------
const {
scryptSync,
createDecipheriv,
@@ -911,7 +883,7 @@ exchanges.
Instances of the `DiffieHellman` class can be created using the
[`crypto.createDiffieHellman()`][] function.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const {
@@ -932,9 +904,7 @@ const bobSecret = bob.computeSecret(aliceKey);
// OK
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const {
@@ -984,12 +954,17 @@ If `outputEncoding` is given a string is returned; otherwise, a
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The [encoding][] of the return value.
* Returns: [`Buffer`](/api/v18/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-Generates private and public Diffie-Hellman key values, and returns
+Generates private and public Diffie-Hellman key values unless they have been
+generated or computed already, and returns
the public key in the specified `encoding`. This key should be
transferred to the other party.
If `encoding` is provided a string is returned; otherwise a
[`Buffer`][] is returned.
+This function is a thin wrapper around [`DH_generate_key()`][]. In particular,
+once a private key has been generated or set, calling this function only updates
+the public key but does not generate a new private key.
+
#### `diffieHellman.getGenerator([encoding])`
@@ -1046,6 +1021,10 @@ Sets the Diffie-Hellman private key. If the `encoding` argument is provided,
to be a string. If no `encoding` is provided, `privateKey` is expected
to be a [`Buffer`][], `TypedArray`, or `DataView`.
+This function does not automatically compute the associated public key. Either
+[`diffieHellman.setPublicKey()`][] or [`diffieHellman.generateKeys()`][] can be
+used to manually provide the public key or to automatically derive it.
+
#### `diffieHellman.setPublicKey(publicKey[, encoding])`
@@ -1081,12 +1060,10 @@ It works the same as `DiffieHellman`, except that it does not allow changing
its keys after creation. In other words, it does not implement `setPublicKey()`
or `setPrivateKey()` methods.
-```mjs
+```mjs|cjs
const { createDiffieHellmanGroup } = await import('node:crypto');
const dh = createDiffieHellmanGroup('modp16');
-```
-
-```cjs
+--------------
const { createDiffieHellmanGroup } = require('node:crypto');
const dh = createDiffieHellmanGroup('modp16');
```
@@ -1117,7 +1094,7 @@ key exchanges.
Instances of the `ECDH` class can be created using the
[`crypto.createECDH()`][] function.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const {
@@ -1138,9 +1115,7 @@ const bobSecret = bob.computeSecret(aliceKey);
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const {
@@ -1192,7 +1167,7 @@ If the `inputEncoding` is not provided, `key` is expected to be a [`Buffer`][],
Example (uncompressing a key):
-```mjs
+```mjs|cjs
const {
createECDH,
ECDH,
@@ -1211,9 +1186,7 @@ const uncompressedKey = ECDH.convertKey(compressedKey,
// The converted key and the uncompressed public key should be the same
console.log(uncompressedKey === ecdh.getPublicKey('hex'));
-```
-
-```cjs
+--------------
const {
createECDH,
ECDH,
@@ -1347,7 +1320,7 @@ set.
Example (obtaining a shared secret):
-```mjs
+```mjs|cjs
const {
createECDH,
createHash,
@@ -1372,9 +1345,7 @@ const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
// aliceSecret and bobSecret should be the same shared secret value
console.log(aliceSecret === bobSecret);
-```
-
-```cjs
+--------------
const {
createECDH,
createHash,
@@ -1420,7 +1391,7 @@ objects are not to be created directly using the `new` keyword.
Example: Using `Hash` objects as streams:
-```mjs
+```mjs|cjs
const {
createHash,
} = await import('node:crypto');
@@ -1440,9 +1411,7 @@ hash.on('readable', () => {
hash.write('some data to hash');
hash.end();
-```
-
-```cjs
+--------------
const {
createHash,
} = require('node:crypto');
@@ -1466,7 +1435,7 @@ hash.end();
Example: Using `Hash` and piped streams:
-```mjs
+```mjs|cjs
import { createReadStream } from 'node:fs';
import { stdout } from 'node:process';
const { createHash } = await import('node:crypto');
@@ -1475,9 +1444,7 @@ const hash = createHash('sha256');
const input = createReadStream('test.js');
input.pipe(hash).setEncoding('hex').pipe(stdout);
-```
-
-```cjs
+--------------
const { createReadStream } = require('node:fs');
const { createHash } = require('node:crypto');
const { stdout } = require('node:process');
@@ -1490,7 +1457,7 @@ input.pipe(hash).setEncoding('hex').pipe(stdout);
Example: Using the [`hash.update()`][] and [`hash.digest()`][] methods:
-```mjs
+```mjs|cjs
const {
createHash,
} = await import('node:crypto');
@@ -1501,9 +1468,7 @@ hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
-```
-
-```cjs
+--------------
const {
createHash,
} = require('node:crypto');
@@ -1533,7 +1498,7 @@ specify the desired output length in bytes.
An error is thrown when an attempt is made to copy the `Hash` object after
its [`hash.digest()`][] method has been called.
-```mjs
+```mjs|cjs
// Calculate a rolling hash.
const {
createHash,
@@ -1551,9 +1516,7 @@ hash.update('three');
console.log(hash.copy().digest('hex'));
// Etc.
-```
-
-```cjs
+--------------
// Calculate a rolling hash.
const {
createHash,
@@ -1622,7 +1585,7 @@ objects are not to be created directly using the `new` keyword.
Example: Using `Hmac` objects as streams:
-```mjs
+```mjs|cjs
const {
createHmac,
} = await import('node:crypto');
@@ -1642,9 +1605,7 @@ hmac.on('readable', () => {
hmac.write('some data to hash');
hmac.end();
-```
-
-```cjs
+--------------
const {
createHmac,
} = require('node:crypto');
@@ -1668,7 +1629,7 @@ hmac.end();
Example: Using `Hmac` and piped streams:
-```mjs
+```mjs|cjs
import { createReadStream } from 'node:fs';
import { stdout } from 'node:process';
const {
@@ -1679,9 +1640,7 @@ const hmac = createHmac('sha256', 'a secret');
const input = createReadStream('test.js');
input.pipe(hmac).pipe(stdout);
-```
-
-```cjs
+--------------
const {
createReadStream,
} = require('node:fs');
@@ -1698,7 +1657,7 @@ input.pipe(hmac).pipe(stdout);
Example: Using the [`hmac.update()`][] and [`hmac.digest()`][] methods:
-```mjs
+```mjs|cjs
const {
createHmac,
} = await import('node:crypto');
@@ -1709,9 +1668,7 @@ hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
-```
-
-```cjs
+--------------
const {
createHmac,
} = require('node:crypto');
@@ -1780,7 +1737,7 @@ be listed in the `transferList` argument.
Example: Converting a `CryptoKey` instance to a `KeyObject`:
-```mjs
+```mjs|cjs
const { webcrypto, KeyObject } = await import('node:crypto');
const { subtle } = webcrypto;
@@ -1793,9 +1750,7 @@ const key = await subtle.generateKey({
const keyObject = KeyObject.from(key);
console.log(keyObject.symmetricKeySize);
// Prints: 32 (symmetric key size in bytes)
-```
-
-```cjs
+--------------
const {
webcrypto: {
subtle,
@@ -1958,7 +1913,7 @@ to be created directly using the `new` keyword.
Example: Using `Sign` and [`Verify`][] objects as streams:
-```mjs
+```mjs|cjs
const {
generateKeyPairSync,
createSign,
@@ -1979,9 +1934,7 @@ verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature, 'hex'));
// Prints: true
-```
-
-```cjs
+--------------
const {
generateKeyPairSync,
createSign,
@@ -2006,7 +1959,7 @@ console.log(verify.verify(publicKey, signature, 'hex'));
Example: Using the [`sign.update()`][] and [`verify.update()`][] methods:
-```mjs
+```mjs|cjs
const {
generateKeyPairSync,
createSign,
@@ -2027,9 +1980,7 @@ verify.update('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature));
// Prints: true
-```
-
-```cjs
+--------------
const {
generateKeyPairSync,
createSign,
@@ -2202,15 +2153,13 @@ be passed instead of a public key.
Encapsulates an X509 certificate and provides read-only access to
its information.
-```mjs
+```mjs|cjs
const { X509Certificate } = await import('node:crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
console.log(x509.subject);
-```
-
-```cjs
+--------------
const { X509Certificate } = require('node:crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
@@ -2856,7 +2805,7 @@ display the available digest algorithms.
Example: generating the sha256 sum of a file
-```mjs
+```mjs|cjs
import {
createReadStream,
} from 'node:fs';
@@ -2880,9 +2829,7 @@ input.on('readable', () => {
console.log(`${hash.digest('hex')} ${filename}`);
}
});
-```
-
-```cjs
+--------------
const {
createReadStream,
} = require('node:fs');
@@ -2931,7 +2878,7 @@ a [`KeyObject`][], its type must be `secret`.
Example: generating the sha256 HMAC of a file
-```mjs
+```mjs|cjs
import {
createReadStream,
} from 'node:fs';
@@ -2955,9 +2902,7 @@ input.on('readable', () => {
console.log(`${hmac.digest('hex')} ${filename}`);
}
});
-```
-
-```cjs
+--------------
const {
createReadStream,
} = require('node:fs');
@@ -3115,7 +3060,7 @@ Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`
Asynchronously generates a new random secret key of the given `length`. The
`type` will determine which validations will be performed on the `length`.
-```mjs
+```mjs|cjs
const {
generateKey,
} = await import('node:crypto');
@@ -3124,9 +3069,7 @@ generateKey('hmac', { length: 64 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});
-```
-
-```cjs
+--------------
const {
generateKey,
} = require('node:crypto');
@@ -3176,7 +3119,7 @@ the respective part of the key is returned as a [`KeyObject`][].
It is recommended to encode public keys as `'spki'` and private keys as
`'pkcs8'` with encryption for long-term storage:
-```mjs
+```mjs|cjs
const {
generateKeyPair,
} = await import('node:crypto');
@@ -3196,9 +3139,7 @@ generateKeyPair('rsa', {
}, (err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
});
-```
-
-```cjs
+--------------
const {
generateKeyPair,
} = require('node:crypto');
@@ -3265,7 +3206,7 @@ When encoding public keys, it is recommended to use `'spki'`. When encoding
private keys, it is recommended to use `'pkcs8'` with a strong passphrase,
and to keep the passphrase confidential.
-```mjs
+```mjs|cjs
const {
generateKeyPairSync,
} = await import('node:crypto');
@@ -3286,9 +3227,7 @@ const {
passphrase: 'top secret',
},
});
-```
-
-```cjs
+--------------
const {
generateKeyPairSync,
} = require('node:crypto');
@@ -3332,16 +3271,14 @@ it will be a buffer containing the data encoded as DER.
Synchronously generates a new random secret key of the given `length`. The
`type` will determine which validations will be performed on the `length`.
-```mjs
+```mjs|cjs
const {
generateKeySync,
} = await import('node:crypto');
const key = generateKeySync('hmac', { length: 64 });
console.log(key.export().toString('hex')); // e89..........41e
-```
-
-```cjs
+--------------
const {
generateKeySync,
} = require('node:crypto');
@@ -3465,15 +3402,13 @@ unacceptable, `undefined` will be returned.
* Returns: string\[] An array with the names of the supported cipher
algorithms.
-```mjs
+```mjs|cjs
const {
getCiphers,
} = await import('node:crypto');
console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
-```
-
-```cjs
+--------------
const {
getCiphers,
} = require('node:crypto');
@@ -3487,15 +3422,13 @@ console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
* Returns: string\[] An array with the names of the supported elliptic curves.
-```mjs
+```mjs|cjs
const {
getCurves,
} = await import('node:crypto');
console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
-```
-
-```cjs
+--------------
const {
getCurves,
} = require('node:crypto');
@@ -3522,7 +3455,7 @@ and communication time.
Example (obtaining a shared secret):
-```mjs
+```mjs|cjs
const {
getDiffieHellman,
} = await import('node:crypto');
@@ -3537,9 +3470,7 @@ const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);
-```
-
-```cjs
+--------------
const {
getDiffieHellman,
} = require('node:crypto');
@@ -3572,15 +3503,13 @@ console.log(aliceSecret === bobSecret);
* Returns: string\[] An array of the names of the supported hash algorithms,
such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms.
-```mjs
+```mjs|cjs
const {
getHashes,
} = await import('node:crypto');
console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
-```
-
-```cjs
+--------------
const {
getHashes,
} = require('node:crypto');
@@ -3627,7 +3556,7 @@ otherwise `err` will be `null`. The successfully generated `derivedKey` will
be passed to the callback as an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any
of the input arguments specify invalid values or types.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
hkdf,
@@ -3637,9 +3566,7 @@ hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
if (err) throw err;
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
});
-```
-
-```cjs
+--------------
const {
hkdf,
} = require('node:crypto');
@@ -3677,7 +3604,7 @@ The successfully generated `derivedKey` will be returned as an [`ArrayBuffer`](h
An error will be thrown if any of the input arguments specify invalid values or
types, or if the derived key cannot be generated.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
hkdfSync,
@@ -3685,9 +3612,7 @@ const {
const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
-```
-
-```cjs
+--------------
const {
hkdfSync,
} = require('node:crypto');
@@ -3731,7 +3656,7 @@ random and at least 16 bytes long. See [NIST SP 800-132][] for details.
When passing strings for `password` or `salt`, please consider
[caveats when using strings as inputs to cryptographic APIs][].
-```mjs
+```mjs|cjs
const {
pbkdf2,
} = await import('node:crypto');
@@ -3740,9 +3665,7 @@ pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
-```
-
-```cjs
+--------------
const {
pbkdf2,
} = require('node:crypto');
@@ -3757,16 +3680,14 @@ The `crypto.DEFAULT_ENCODING` property can be used to change the way the
`derivedKey` is passed to the callback. This property, however, has been
deprecated and use should be avoided.
-```mjs
+```mjs|cjs
import crypto from 'node:crypto';
crypto.DEFAULT_ENCODING = 'hex';
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey); // '3745e48...aa39b34'
});
-```
-
-```cjs
+--------------
const crypto = require('node:crypto');
crypto.DEFAULT_ENCODING = 'hex';
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
@@ -3811,16 +3732,14 @@ random and at least 16 bytes long. See [NIST SP 800-132][] for details.
When passing strings for `password` or `salt`, please consider
[caveats when using strings as inputs to cryptographic APIs][].
-```mjs
+```mjs|cjs
const {
pbkdf2Sync,
} = await import('node:crypto');
const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex')); // '3745e48...08d59ae'
-```
-
-```cjs
+--------------
const {
pbkdf2Sync,
} = require('node:crypto');
@@ -3833,14 +3752,12 @@ The `crypto.DEFAULT_ENCODING` property may be used to change the way the
`derivedKey` is returned. This property, however, is deprecated and use
should be avoided.
-```mjs
+```mjs|cjs
import crypto from 'node:crypto';
crypto.DEFAULT_ENCODING = 'hex';
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
console.log(key); // '3745e48...aa39b34'
-```
-
-```cjs
+--------------
const crypto = require('node:crypto');
crypto.DEFAULT_ENCODING = 'hex';
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
@@ -3978,7 +3895,7 @@ and the `callback` function is invoked with two arguments: `err` and `buf`.
If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The
`buf` argument is a [`Buffer`][] containing the generated bytes.
-```mjs
+```mjs|cjs
// Asynchronous
const {
randomBytes,
@@ -3988,9 +3905,7 @@ randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});
-```
-
-```cjs
+--------------
// Asynchronous
const {
randomBytes,
@@ -4006,7 +3921,7 @@ If the `callback` function is not provided, the random bytes are generated
synchronously and returned as a [`Buffer`][]. An error will be thrown if
there is a problem generating the bytes.
-```mjs
+```mjs|cjs
// Synchronous
const {
randomBytes,
@@ -4015,9 +3930,7 @@ const {
const buf = randomBytes(256);
console.log(
`${buf.length} bytes of random data: ${buf.toString('hex')}`);
-```
-
-```cjs
+--------------
// Synchronous
const {
randomBytes,
@@ -4057,7 +3970,7 @@ request.
Synchronous version of [`crypto.randomFill()`][].
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');
@@ -4070,9 +3983,7 @@ console.log(buf.toString('hex'));
// The above is equivalent to the following:
randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));
-```
-
-```cjs
+--------------
const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4090,7 +4001,7 @@ console.log(buf.toString('hex'));
Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as
`buffer`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');
@@ -4104,9 +4015,7 @@ console.log(Buffer.from(randomFillSync(b).buffer,
const c = new ArrayBuffer(10);
console.log(Buffer.from(randomFillSync(c)).toString('hex'));
-```
-
-```cjs
+--------------
const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4139,7 +4048,7 @@ requires that a callback is passed in.
If the `callback` function is not provided, an error will be thrown.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');
@@ -4159,9 +4068,7 @@ randomFill(buf, 5, 5, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
-```
-
-```cjs
+--------------
const { randomFill } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4192,7 +4099,7 @@ result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array
contains finite numbers only, they are not drawn from a uniform random
distribution and have no meaningful lower or upper bounds.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');
@@ -4215,9 +4122,7 @@ randomFill(c, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf).toString('hex'));
});
-```
-
-```cjs
+--------------
const { randomFill } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4268,7 +4173,7 @@ be [safe integers][].
If the `callback` function is not provided, the random integer is
generated synchronously.
-```mjs
+```mjs|cjs
// Asynchronous
const {
randomInt,
@@ -4278,9 +4183,7 @@ randomInt(3, (err, n) => {
if (err) throw err;
console.log(`Random number chosen from (0, 1, 2): ${n}`);
});
-```
-
-```cjs
+--------------
// Asynchronous
const {
randomInt,
@@ -4292,7 +4195,7 @@ randomInt(3, (err, n) => {
});
```
-```mjs
+```mjs|cjs
// Synchronous
const {
randomInt,
@@ -4300,9 +4203,7 @@ const {
const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
-```
-
-```cjs
+--------------
// Synchronous
const {
randomInt,
@@ -4312,7 +4213,7 @@ const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
```
-```mjs
+```mjs|cjs
// With `min` argument
const {
randomInt,
@@ -4320,9 +4221,7 @@ const {
const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);
-```
-
-```cjs
+--------------
// With `min` argument
const {
randomInt,
@@ -4385,7 +4284,7 @@ The `callback` function is called with two arguments: `err` and `derivedKey`.
An exception is thrown when any of the input arguments specify invalid values
or types.
-```mjs
+```mjs|cjs
const {
scrypt,
} = await import('node:crypto');
@@ -4400,9 +4299,7 @@ scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
});
-```
-
-```cjs
+--------------
const {
scrypt,
} = require('node:crypto');
@@ -4454,7 +4351,7 @@ returned as a [`Buffer`][].
An exception is thrown when any of the input arguments specify invalid values
or types.
-```mjs
+```mjs|cjs
const {
scryptSync,
} = await import('node:crypto');
@@ -4465,9 +4362,7 @@ console.log(key1.toString('hex')); // '3745e48...08d59ae'
// Using a custom N parameter. Must be a power of two.
const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
console.log(key2.toString('hex')); // '3745e48...aa39b34'
-```
-
-```cjs
+--------------
const {
scryptSync,
} = require('node:crypto');
@@ -4778,7 +4673,7 @@ mode must adhere to certain restrictions when using the cipher API:
applications _must_ call `final()` to compute or verify the
authentication tag.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
createCipheriv,
@@ -4820,9 +4715,7 @@ try {
}
console.log(receivedPlaintext);
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const {
createCipheriv,
@@ -4884,7 +4777,7 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_ALL
Applies multiple bug workarounds within OpenSSL. See
- https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html
+ https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html
for detail.
@@ -4896,13 +4789,13 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
Allows legacy insecure renegotiation between OpenSSL and unpatched
clients or servers. See
- https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html .
+ https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html .
SSL_OP_CIPHER_SERVER_PREFERENCE
Attempts to use the server's preferences instead of the client's when
selecting a cipher. Behavior depends on protocol version. See
- https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html .
+ https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html .
SSL_OP_CISCO_ANYCONNECT
@@ -4922,44 +4815,10 @@ See the [list of SSL OP Flags][] for details.
Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability
workaround added in OpenSSL 0.9.6d.
-
- SSL_OP_EPHEMERAL_RSA
- Instructs OpenSSL to always use the tmp_rsa key when performing RSA
- operations.
-
SSL_OP_LEGACY_SERVER_CONNECT
Allows initial connection to servers that do not support RI.
-
- SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
-
-
-
- SSL_OP_MICROSOFT_SESS_ID_BUG
-
-
-
- SSL_OP_MSIE_SSLV2_RSA_PADDING
- Instructs OpenSSL to disable the workaround for a man-in-the-middle
- protocol-version vulnerability in the SSL 2.0 server implementation.
-
-
- SSL_OP_NETSCAPE_CA_DN_BUG
-
-
-
- SSL_OP_NETSCAPE_CHALLENGE_BUG
-
-
-
- SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
-
-
-
- SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
-
-
SSL_OP_NO_COMPRESSION
Instructs OpenSSL to disable support for SSL/TLS compression.
@@ -5009,14 +4868,6 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_NO_TLSv1_3
Instructs OpenSSL to turn off TLS v1.3
-
- SSL_OP_PKCS1_CHECK_1
-
-
-
- SSL_OP_PKCS1_CHECK_2
-
-
SSL_OP_PRIORITIZE_CHACHA
Instructs OpenSSL server to prioritize ChaCha20-Poly1305
@@ -5025,32 +4876,6 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_CIPHER_SERVER_PREFERENCE
is not enabled.
-
- SSL_OP_SINGLE_DH_USE
- Instructs OpenSSL to always create a new key when using
- temporary/ephemeral DH parameters.
-
-
- SSL_OP_SINGLE_ECDH_USE
- Instructs OpenSSL to always create a new key when using
- temporary/ephemeral ECDH parameters.
-
-
- SSL_OP_SSLEAY_080_CLIENT_DH_BUG
-
-
-
- SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
-
-
-
- SSL_OP_TLS_BLOCK_PADDING_BUG
-
-
-
- SSL_OP_TLS_D5_BUG
-
-
SSL_OP_TLS_ROLLBACK_BUG
Instructs OpenSSL to disable version rollback attack detection.
@@ -5233,6 +5058,7 @@ See the [list of SSL OP Flags][] for details.
[Web Crypto API documentation]: /api/v18/webcrypto
[`BN_is_prime_ex`]: https://www.openssl.org/docs/man1.1.1/man3/BN_is_prime_ex.html
[`Buffer`]: /api/v18/buffer
+[`DH_generate_key()`]: https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html
[`DiffieHellmanGroup`]: #class-diffiehellmangroup
[`EVP_BytesToKey`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html
[`KeyObject`]: #class-keyobject
@@ -5269,6 +5095,7 @@ See the [list of SSL OP Flags][] for details.
[`crypto.webcrypto.subtle`]: /api/v18/webcrypto#class-subtlecrypto
[`decipher.final()`]: #decipherfinaloutputencoding
[`decipher.update()`]: #decipherupdatedata-inputencoding-outputencoding
+[`diffieHellman.generateKeys()`]: #diffiehellmangeneratekeysencoding
[`diffieHellman.setPublicKey()`]: #diffiehellmansetpublickeypublickey-encoding
[`ecdh.generateKeys()`]: #ecdhgeneratekeysencoding-format
[`ecdh.setPrivateKey()`]: #ecdhsetprivatekeyprivatekey-encoding
diff --git a/content/api/v18/debugger.en.md b/content/api/v18/debugger.en.md
index 13b63ea36d..5c0a921404 100644
--- a/content/api/v18/debugger.en.md
+++ b/content/api/v18/debugger.en.md
@@ -206,11 +206,19 @@ debug>
after)
* `watch(expr)`: Add expression to watch list
* `unwatch(expr)`: Remove expression from watch list
+* `unwatch(index)`: Remove expression at specific index from watch list
* `watchers`: List all watchers and their values (automatically listed on each
breakpoint)
* `repl`: Open debugger's repl for evaluation in debugging script's context
* `exec expr`, `p expr`: Execute an expression in debugging script's context and
print its value
+* `profile`: Start CPU profiling session
+* `profileEnd`: Stop current CPU profiling session
+* `profiles`: List all completed CPU profiling sessions
+* `profiles[n].save(filepath = 'node.cpuprofile')`: Save CPU profiling session
+ to disk as JSON
+* `takeHeapSnapshot(filepath = 'node.heapsnapshot')`: Take a heap snapshot
+ and save to disk as JSON
#### Execution control
diff --git a/content/api/v18/deprecations.en.md b/content/api/v18/deprecations.en.md
index 4f2022ebcb..2b677f8310 100644
--- a/content/api/v18/deprecations.en.md
+++ b/content/api/v18/deprecations.en.md
@@ -1864,7 +1864,7 @@ In a future version of Node.js, [`message.headers`][],
[`dnsPromises.lookup()`]: /api/v18/dns#dnspromiseslookuphostname-options
[`domain`]: /api/v18/domain
[`ecdh.setPublicKey()`]: /api/v18/crypto#ecdhsetpublickeypublickey-encoding
-[`emitter.listenerCount(eventName)`]: /api/v18/events#emitterlistenercounteventname
+[`emitter.listenerCount(eventName)`]: /api/v18/events#emitterlistenercounteventname-listener
[`events.listenerCount(emitter, eventName)`]: /api/v18/events#eventslistenercountemitter-eventname
[`fs.FileHandle`]: /api/v18/fs#class-filehandle
[`fs.access()`]: /api/v18/fs#fsaccesspath-mode-callback
diff --git a/content/api/v18/dgram.en.md b/content/api/v18/dgram.en.md
index 512812357b..ff64e61bd1 100644
--- a/content/api/v18/dgram.en.md
+++ b/content/api/v18/dgram.en.md
@@ -15,11 +15,11 @@ Stable
-
+
The `node:dgram` module provides an implementation of UDP datagram sockets.
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
const server = dgram.createSocket('udp4');
@@ -40,9 +40,7 @@ server.on('listening', () => {
server.bind(41234);
// Prints: server listening 0.0.0.0:41234
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const server = dgram.createSocket('udp4');
@@ -148,7 +146,7 @@ When sharing a UDP socket across multiple `cluster` workers, the
`socket.addMembership()` function must be called only once or an
`EADDRINUSE` error will occur:
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import dgram from 'node:dgram';
@@ -161,9 +159,7 @@ if (cluster.isPrimary) {
s.addMembership('224.0.0.114');
});
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const dgram = require('node:dgram');
@@ -236,7 +232,7 @@ attempting to bind with a closed socket), an [`Error`][] may be thrown.
Example of a UDP server listening on port 41234:
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
const server = dgram.createSocket('udp4');
@@ -257,9 +253,7 @@ server.on('listening', () => {
server.bind(41234);
// Prints: server listening 0.0.0.0:41234
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const server = dgram.createSocket('udp4');
@@ -511,7 +505,7 @@ This method throws [`ERR_SOCKET_BAD_PORT`][] if called on an unbound socket.
Example of sending a UDP packet to a port on `localhost`;
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';
@@ -520,9 +514,7 @@ const client = dgram.createSocket('udp4');
client.send(message, 41234, 'localhost', (err) => {
client.close();
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
@@ -536,7 +528,7 @@ client.send(message, 41234, 'localhost', (err) => {
Example of sending a UDP packet composed of multiple buffers to a port on
`127.0.0.1`;
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';
@@ -546,9 +538,7 @@ const client = dgram.createSocket('udp4');
client.send([buf1, buf2], 41234, (err) => {
client.close();
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
@@ -568,7 +558,7 @@ however, sending multiple buffers is faster.
Example of sending a UDP packet using a socket connected to a port on
`localhost`:
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';
@@ -579,9 +569,7 @@ client.connect(41234, 'localhost', (err) => {
client.close();
});
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
diff --git a/content/api/v18/diagnostics_channel.en.md b/content/api/v18/diagnostics_channel.en.md
index cdd5eb68d5..1267e6f41c 100644
--- a/content/api/v18/diagnostics_channel.en.md
+++ b/content/api/v18/diagnostics_channel.en.md
@@ -5,7 +5,7 @@ category: 'api'
version: 'v18'
---
-
+
@@ -15,18 +15,16 @@ Stable
-
+
The `node:diagnostics_channel` module provides an API to create named channels
to report arbitrary message data for diagnostics purposes.
It can be accessed using:
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
```
@@ -48,7 +46,7 @@ other modules.
Following is a simple overview of the public API.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
// Get a reusable channel object
@@ -71,9 +69,7 @@ if (channel.hasSubscribers) {
// Unsubscribe from the channel
diagnostics_channel.unsubscribe('my-channel', onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
// Get a reusable channel object
@@ -111,15 +107,13 @@ the message you want to send might be expensive to prepare.
This API is optional but helpful when trying to publish messages from very
performance-sensitive code.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
if (diagnostics_channel.hasSubscribers('my-channel')) {
// There are subscribers, prepare and publish message
}
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
if (diagnostics_channel.hasSubscribers('my-channel')) {
@@ -138,13 +132,11 @@ This is the primary entry-point for anyone wanting to publish to a named
channel. It produces a channel object which is optimized to reduce overhead at
publish time as much as possible.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -163,15 +155,13 @@ Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an [`'uncaughtException'`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
diagnostics_channel.subscribe('my-channel', (message, name) => {
// Received data
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
diagnostics_channel.subscribe('my-channel', (message, name) => {
@@ -190,7 +180,7 @@ diagnostics_channel.subscribe('my-channel', (message, name) => {
Remove a message handler previously registered to this channel with
[`diagnostics_channel.subscribe(name, onMessage)`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
function onMessage(message, name) {
@@ -200,9 +190,7 @@ function onMessage(message, name) {
diagnostics_channel.subscribe('my-channel', onMessage);
diagnostics_channel.unsubscribe('my-channel', onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
function onMessage(message, name) {
@@ -238,7 +226,7 @@ the message you want to send might be expensive to prepare.
This API is optional but helpful when trying to publish messages from very
performance-sensitive code.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -246,9 +234,7 @@ const channel = diagnostics_channel.channel('my-channel');
if (channel.hasSubscribers) {
// There are subscribers, prepare and publish message
}
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -267,7 +253,7 @@ if (channel.hasSubscribers) {
Publish a message to any subscribers to the channel. This will trigger
message handlers synchronously so they will execute within the same context.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -275,9 +261,7 @@ const channel = diagnostics_channel.channel('my-channel');
channel.publish({
some: 'message',
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -305,7 +289,7 @@ Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an [`'uncaughtException'`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -313,9 +297,7 @@ const channel = diagnostics_channel.channel('my-channel');
channel.subscribe((message, name) => {
// Received data
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -341,7 +323,7 @@ Deprecated: Use [`diagnostics_channel.unsubscribe(name, onMessage)`][]
Remove a message handler previously registered to this channel with
[`channel.subscribe(onMessage)`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -353,9 +335,7 @@ function onMessage(message, name) {
channel.subscribe(onMessage);
channel.unsubscribe(onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
diff --git a/content/api/v18/dns.en.md b/content/api/v18/dns.en.md
index 88a3cd63d1..4f0ab40d10 100644
--- a/content/api/v18/dns.en.md
+++ b/content/api/v18/dns.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:dns` module enables name resolution. For example, use it to look up IP
addresses of host names.
diff --git a/content/api/v18/domain.en.md b/content/api/v18/domain.en.md
index 3d570665c0..622b8036e2 100644
--- a/content/api/v18/domain.en.md
+++ b/content/api/v18/domain.en.md
@@ -15,7 +15,7 @@ Deprecated
-
+
**This module is pending deprecation.** Once a replacement API has been
finalized, this module will be fully deprecated. Most developers should
diff --git a/content/api/v18/esm.en.md b/content/api/v18/esm.en.md
index dc571a41f0..733d4776d6 100644
--- a/content/api/v18/esm.en.md
+++ b/content/api/v18/esm.en.md
@@ -206,12 +206,10 @@ The default export can be used for, among other things, modifying the named
exports. Named exports of builtin modules are updated only by calling
[`module.syncBuiltinESMExports()`][].
-```js
+```js|js
import EventEmitter from 'node:events';
const e = new EventEmitter();
-```
-
-```js
+--------------
import { readFile } from 'node:fs';
readFile('./foo.txt', (err, source) => {
if (err) {
@@ -513,13 +511,11 @@ export const five = await Promise.resolve(5);
And a `b.mjs` with
-```js
+```js|bash
import { five } from './a.mjs';
console.log(five); // Logs `5`
-```
-
-```bash
+--------------
node b.mjs # works
```
@@ -583,14 +579,12 @@ These modules cannot access other modules that are not over `http:` or `https:`.
To still access local modules while avoiding the security concern, pass in
references to the local dependencies:
-```mjs
+```mjs|mjs
// file.mjs
import worker_threads from 'node:worker_threads';
import { configure, resize } from 'https://example.com/imagelib.mjs';
configure({ worker_threads });
-```
-
-```mjs
+--------------
// https://example.com/imagelib.mjs
let worker_threads;
export function configure(opts) {
@@ -908,7 +902,7 @@ functionality, there are substantial downsides to actually using this loader:
performance is much slower than loading files from disk, there is no caching,
and there is no security.
-```js
+```js|js
// https-loader.mjs
import { get } from 'node:https';
@@ -956,9 +950,7 @@ export function load(url, context, nextLoad) {
// Let Node.js handle all other URLs.
return nextLoad(url);
}
-```
-
-```js
+--------------
// main.mjs
import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';
@@ -981,7 +973,7 @@ This is less performant than transpiling source files before running
Node.js; a transpiler loader should only be used for development and testing
purposes.
-```js
+```js|coffee
// coffeescript-loader.mjs
import { readFile } from 'node:fs/promises';
import { dirname, extname, resolve as resolvePath } from 'node:path';
@@ -1023,7 +1015,7 @@ export async function load(url, context, nextLoad) {
// file, search up the file system for the nearest parent package.json file
// and read its "type" field.
const format = await getPackageType(url);
- // When a hook returns a format of 'commonjs', `source` is be ignored.
+ // When a hook returns a format of 'commonjs', `source` is ignored.
// To handle CommonJS files, a handler needs to be registered with
// `require.extensions` in order to process the files with the CommonJS
// loader. Avoiding the need for a separate CommonJS handler is a future
@@ -1079,9 +1071,7 @@ async function getPackageType(url) {
// If at the root, stop and return false
return dir.length > 1 && getPackageType(resolvePath(dir, '..'));
}
-```
-
-```coffee
+--------------
# main.coffee
import { scream } from './scream.coffee'
console.log scream 'hello, world'
diff --git a/content/api/v18/events.en.md b/content/api/v18/events.en.md
index c26a3ba23a..4b53b06bd4 100644
--- a/content/api/v18/events.en.md
+++ b/content/api/v18/events.en.md
@@ -15,7 +15,7 @@ Stable
-
+
Much of the Node.js core API is built around an idiomatic asynchronous
event-driven architecture in which certain kinds of objects (called "emitters")
@@ -39,7 +39,7 @@ The following example shows a simple `EventEmitter` instance with a single
listener. The `eventEmitter.on()` method is used to register listeners, while
the `eventEmitter.emit()` method is used to trigger the event.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
@@ -49,9 +49,7 @@ myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
@@ -71,7 +69,7 @@ an ordinary listener function is called, the standard `this` keyword
is intentionally set to reference the `EventEmitter` instance to which the
listener is attached.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -86,9 +84,7 @@ myEmitter.on('event', function(a, b) {
// } true
});
myEmitter.emit('event', 'a', 'b');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -108,7 +104,7 @@ myEmitter.emit('event', 'a', 'b');
It is possible to use ES6 Arrow Functions as listeners, however, when doing so,
the `this` keyword will no longer reference the `EventEmitter` instance:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -117,9 +113,7 @@ myEmitter.on('event', (a, b) => {
// Prints: a b {}
});
myEmitter.emit('event', 'a', 'b');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -138,7 +132,7 @@ events and helps avoid race conditions and logic errors. When appropriate,
listener functions can switch to an asynchronous mode of operation using
the `setImmediate()` or `process.nextTick()` methods:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -148,9 +142,7 @@ myEmitter.on('event', (a, b) => {
});
});
myEmitter.emit('event', 'a', 'b');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -167,7 +159,7 @@ myEmitter.emit('event', 'a', 'b');
When a listener is registered using the `eventEmitter.on()` method, that
listener is invoked _every time_ the named event is emitted.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -179,9 +171,7 @@ myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Prints: 2
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -199,7 +189,7 @@ Using the `eventEmitter.once()` method, it is possible to register a listener
that is called at most once for a particular event. Once the event is emitted,
the listener is unregistered and _then_ called.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -211,9 +201,7 @@ myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Ignored
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -237,15 +225,13 @@ If an `EventEmitter` does _not_ have at least one listener registered for the
`'error'` event, and an `'error'` event is emitted, the error is thrown, a
stack trace is printed, and the Node.js process exits.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// Throws and crashes Node.js
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -258,7 +244,7 @@ used. (Note, however, that the `node:domain` module is deprecated.)
As a best practice, listeners should always be added for the `'error'` events.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -267,9 +253,7 @@ myEmitter.on('error', (err) => {
});
myEmitter.emit('error', new Error('whoops!'));
// Prints: whoops! there was an error
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -283,7 +267,7 @@ myEmitter.emit('error', new Error('whoops!'));
It is possible to monitor `'error'` events without consuming the emitted error
by installing a listener using the symbol `events.errorMonitor`.
-```mjs
+```mjs|cjs
import { EventEmitter, errorMonitor } from 'node:events';
const myEmitter = new EventEmitter();
@@ -292,9 +276,7 @@ myEmitter.on(errorMonitor, (err) => {
});
myEmitter.emit('error', new Error('whoops!'));
// Still throws and crashes Node.js
-```
-
-```cjs
+--------------
const { EventEmitter, errorMonitor } = require('node:events');
const myEmitter = new EventEmitter();
@@ -310,15 +292,13 @@ myEmitter.emit('error', new Error('whoops!'));
Using `async` functions with event handlers is problematic, because it
can lead to an unhandled rejection in case of a thrown exception:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
ee.on('something', async (value) => {
throw new Error('kaboom');
});
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const ee = new EventEmitter();
ee.on('something', async (value) => {
@@ -332,7 +312,7 @@ handler on the `Promise`. This handler routes the exception
asynchronously to the [`Symbol.for('nodejs.rejection')`][rejection] method
if there is one, or to [`'error'`][error] event handler if there is none.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const ee1 = new EventEmitter({ captureRejections: true });
ee1.on('something', async (value) => {
@@ -347,9 +327,7 @@ ee2.on('something', async (value) => {
});
ee2[Symbol.for('nodejs.rejection')] = console.log;
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const ee1 = new EventEmitter({ captureRejections: true });
ee1.on('something', async (value) => {
@@ -369,7 +347,7 @@ ee2[Symbol.for('nodejs.rejection')] = console.log;
Setting `events.captureRejections = true` will change the default for all
new instances of `EventEmitter`.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
EventEmitter.captureRejections = true;
@@ -379,9 +357,7 @@ ee1.on('something', async (value) => {
});
ee1.on('error', console.log);
-```
-
-```cjs
+--------------
const events = require('node:events');
events.captureRejections = true;
const ee1 = new events.EventEmitter();
@@ -402,11 +378,9 @@ recommendation is to **not use `async` functions as `'error'` event handlers**.
The `EventEmitter` class is defined and exposed by the `node:events` module:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
```
@@ -437,7 +411,7 @@ but important side effect: any _additional_ listeners registered to the same
`name` _within_ the `'newListener'` callback are inserted _before_ the
listener that is in the process of being added.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
@@ -458,9 +432,7 @@ myEmitter.emit('event');
// Prints:
// B
// A
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
@@ -515,7 +487,7 @@ to each.
Returns `true` if the event had listeners, `false` otherwise.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
@@ -546,9 +518,7 @@ myEmitter.emit('event', 1, 2, 3, 4, 5);
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const myEmitter = new EventEmitter();
@@ -590,7 +560,7 @@ myEmitter.emit('event', 1, 2, 3, 4, 5);
Returns an array listing the events for which the emitter has registered
listeners. The values in the array are strings or `Symbol`s.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
@@ -602,9 +572,7 @@ myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const myEE = new EventEmitter();
@@ -628,14 +596,17 @@ Returns the current max listener value for the `EventEmitter` which is either
set by [`emitter.setMaxListeners(n)`][] or defaults to
[`events.defaultMaxListeners`][].
-#### `emitter.listenerCount(eventName)`
+#### `emitter.listenerCount(eventName[, listener])`
-
+
* `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The name of the event being listened for
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The event handler function
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-Returns the number of listeners listening to the event named `eventName`.
+Returns the number of listeners listening for the event named `eventName`.
+If `listener` is provided, it will return how many times the listener is found
+in the list of the listeners of the event.
#### `emitter.listeners(eventName)`
@@ -690,7 +661,7 @@ By default, event listeners are invoked in the order they are added. The
`emitter.prependListener()` method can be used as an alternative to add the
event listener to the beginning of the listeners array.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
@@ -699,9 +670,7 @@ myEE.emit('foo');
// Prints:
// b
// a
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
@@ -735,7 +704,7 @@ By default, event listeners are invoked in the order they are added. The
`emitter.prependOnceListener()` method can be used as an alternative to add the
event listener to the beginning of the listeners array.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
@@ -744,9 +713,7 @@ myEE.emit('foo');
// Prints:
// b
// a
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
@@ -845,7 +812,7 @@ time of emitting are called in order. This implies that any
_before_ the last listener finishes execution will not remove them from
`emit()` in progress. Subsequent events behave as expected.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -875,9 +842,7 @@ myEmitter.emit('event');
myEmitter.emit('event');
// Prints:
// A
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -920,7 +885,7 @@ event (as in the example below), `removeListener()` will remove the most
recently added instance. In the example the `once('ping')`
listener is removed:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
@@ -934,9 +899,7 @@ ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const ee = new EventEmitter();
@@ -979,7 +942,7 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
Returns a copy of the array of listeners for the event named `eventName`,
including any wrappers (such as those created by `.once()`).
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
@@ -1002,9 +965,7 @@ const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
@@ -1043,7 +1004,7 @@ promise rejection happens when emitting an event and
It is possible to use [`events.captureRejectionSymbol`][rejectionsymbol] in
place of `Symbol.for('nodejs.rejection')`.
-```mjs
+```mjs|cjs
import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter {
@@ -1060,9 +1021,7 @@ class MyClass extends EventEmitter {
// Tear the resource down here.
}
}
-```
-
-```cjs
+--------------
const { EventEmitter, captureRejectionSymbol } = require('node:events');
class MyClass extends EventEmitter {
@@ -1103,7 +1062,7 @@ that a "possible EventEmitter memory leak" has been detected. For any single
`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`
methods can be used to temporarily avoid this warning:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
@@ -1111,9 +1070,7 @@ emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
@@ -1160,37 +1117,35 @@ the emitter.
For `EventTarget`s this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.
-```mjs
+```mjs|cjs
import { getEventListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
- getEventListeners(ee, 'foo'); // [listener]
+ console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
- getEventListeners(et, 'foo'); // [listener]
+ console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
-```
-
-```cjs
+--------------
const { getEventListeners, EventEmitter } = require('node:events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
- getEventListeners(ee, 'foo'); // [listener]
+ console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
- getEventListeners(et, 'foo'); // [listener]
+ console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
```
@@ -1213,7 +1168,7 @@ This method is intentionally generic and works with the web platform
[EventTarget][WHATWG-EventTarget] interface, which has no special
`'error'` event semantics and does not listen to the `'error'` event.
-```mjs
+```mjs|cjs
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
@@ -1236,9 +1191,7 @@ try {
} catch (err) {
console.error('error happened', err);
}
-```
-
-```cjs
+--------------
const { once, EventEmitter } = require('node:events');
async function run() {
@@ -1271,7 +1224,7 @@ is used to wait for another event. If `events.once()` is used to wait for the
'`error'` event itself, then it is treated as any other kind of event without
special handling:
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
@@ -1283,9 +1236,7 @@ once(ee, 'error')
ee.emit('error', new Error('boom'));
// Prints: ok boom
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const ee = new EventEmitter();
@@ -1301,7 +1252,7 @@ ee.emit('error', new Error('boom'));
An [`AbortSignal`](/api/v18/globals#abortsignal) can be used to cancel waiting for the event:
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
@@ -1323,9 +1274,7 @@ async function foo(emitter, event, signal) {
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const ee = new EventEmitter();
@@ -1358,7 +1307,7 @@ because the `process.nextTick()` queue is drained before the `Promise` microtask
queue, and because `EventEmitter` emits all events synchronously, it is possible
for `events.once()` to miss an event.
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
import process from 'node:process';
@@ -1380,9 +1329,7 @@ process.nextTick(() => {
});
foo().then(() => console.log('done'));
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const myEE = new EventEmitter();
@@ -1409,7 +1356,7 @@ To catch both events, create each of the Promises _before_ awaiting either
of them, then it becomes possible to use `Promise.all()`, `Promise.race()`,
or `Promise.allSettled()`:
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
import process from 'node:process';
@@ -1426,9 +1373,7 @@ process.nextTick(() => {
});
foo().then(() => console.log('done'));
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const myEE = new EventEmitter();
@@ -1478,7 +1423,7 @@ Deprecated: Use [`emitter.listenerCount()`][] instead.
A class method that returns the number of listeners for the given `eventName`
registered on the given `emitter`.
-```mjs
+```mjs|cjs
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
@@ -1486,9 +1431,7 @@ myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
-```
-
-```cjs
+--------------
const { EventEmitter, listenerCount } = require('node:events');
const myEmitter = new EventEmitter();
@@ -1508,7 +1451,7 @@ console.log(listenerCount(myEmitter, 'event'));
* `signal` [`AbortSignal`](/api/v18/globals#abortsignal) Can be used to cancel awaiting events.
* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) that iterates `eventName` events emitted by the `emitter`
-```mjs
+```mjs|cjs
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
@@ -1527,9 +1470,7 @@ for await (const event of on(ee, 'foo')) {
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
-```
-
-```cjs
+--------------
const { on, EventEmitter } = require('node:events');
(async () => {
@@ -1558,7 +1499,7 @@ composed of the emitted event arguments.
An [`AbortSignal`](/api/v18/globals#abortsignal) can be used to cancel waiting on events:
-```mjs
+```mjs|cjs
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
@@ -1583,9 +1524,7 @@ const ac = new AbortController();
})();
process.nextTick(() => ac.abort());
-```
-
-```cjs
+--------------
const { on, EventEmitter } = require('node:events');
const ac = new AbortController();
@@ -1621,16 +1560,14 @@ process.nextTick(() => ac.abort());
or [`EventEmitter`](/api/v18/events#eventemitter) instances. If none are specified, `n` is set as the default
max for all newly created [`EventTarget`](/api/v18/events#eventtarget) and [`EventEmitter`](/api/v18/events#eventemitter) objects.
-```mjs
+```mjs|cjs
import { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
-```
-
-```cjs
+--------------
const {
setMaxListeners,
EventEmitter,
@@ -1650,7 +1587,7 @@ Integrates `EventEmitter` with [`AsyncResource`](/api/v18/async_hooks#asyncresou
require manual async tracking. Specifically, all events emitted by instances
of `events.EventEmitterAsyncResource` will run within its [async context][].
-```mjs
+```mjs|cjs
import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
import { notStrictEqual, strictEqual } from 'node:assert';
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
@@ -1677,9 +1614,7 @@ Promise.resolve().then(() => {
ee1.emit('foo');
ee2.emit('foo');
});
-```
-
-```cjs
+--------------
const { EventEmitterAsyncResource, EventEmitter } = require('node:events');
const { notStrictEqual, strictEqual } = require('node:assert');
const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');
@@ -2154,6 +2089,18 @@ equivalent `EventEmitter` API. The only difference between `addListener()` and
`addEventListener()` is that `addListener()` will return a reference to the
`EventTarget`.
+##### `nodeEventTarget.emit(type, arg)`
+
+
+
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `arg` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if event listeners registered for the `type` exist,
+ otherwise `false`.
+
+Node.js-specific extension to the `EventTarget` class that dispatches the
+`arg` to the list of handlers for `type`.
+
##### `nodeEventTarget.eventNames()`
@@ -2205,7 +2152,7 @@ of max event listeners.
* Returns: [`EventTarget`](/api/v18/events#eventtarget) this
-Node.js-specific alias for `eventTarget.removeListener()`.
+Node.js-specific alias for `eventTarget.removeEventListener()`.
##### `nodeEventTarget.on(type, listener)`
@@ -2217,7 +2164,7 @@ Node.js-specific alias for `eventTarget.removeListener()`.
* Returns: [`EventTarget`](/api/v18/events#eventtarget) this
-Node.js-specific alias for `eventTarget.addListener()`.
+Node.js-specific alias for `eventTarget.addEventListener()`.
##### `nodeEventTarget.once(type, listener)`
@@ -2270,7 +2217,7 @@ to the `EventTarget`.
[`EventTarget` error handling]: #eventtarget-error-handling
[`Event` Web API]: https://dom.spec.whatwg.org/#event
[`domain`]: /api/v18/domain
-[`emitter.listenerCount()`]: #emitterlistenercounteventname
+[`emitter.listenerCount()`]: #emitterlistenercounteventname-listener
[`emitter.removeListener()`]: #emitterremovelistenereventname-listener
[`emitter.setMaxListeners(n)`]: #emittersetmaxlistenersn
[`event.defaultPrevented`]: #eventdefaultprevented
diff --git a/content/api/v18/fs.en.md b/content/api/v18/fs.en.md
index c01ac4d39d..ae2aacd81e 100644
--- a/content/api/v18/fs.en.md
+++ b/content/api/v18/fs.en.md
@@ -15,28 +15,24 @@ Stable
-
+
The `node:fs` module enables interacting with the file system in a
way modeled on standard POSIX functions.
To use the promise-based APIs:
-```mjs
+```mjs|cjs
import * as fs from 'node:fs/promises';
-```
-
-```cjs
+--------------
const fs = require('node:fs/promises');
```
To use the callback and sync APIs:
-```mjs
+```mjs|cjs
import * as fs from 'node:fs';
-```
-
-```cjs
+--------------
const fs = require('node:fs');
```
@@ -48,7 +44,7 @@ forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).
Promise-based operations return a promise that is fulfilled when the
asynchronous operation is complete.
-```mjs
+```mjs|cjs
import { unlink } from 'node:fs/promises';
try {
@@ -57,9 +53,7 @@ try {
} catch (error) {
console.error('there was an error:', error.message);
}
-```
-
-```cjs
+--------------
const { unlink } = require('node:fs/promises');
(async function(path) {
@@ -80,16 +74,14 @@ the completion callback depend on the method, but the first argument is always
reserved for an exception. If the operation is completed successfully, then
the first argument is `null` or `undefined`.
-```mjs
+```mjs|cjs
import { unlink } from 'node:fs';
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
-```
-
-```cjs
+--------------
const { unlink } = require('node:fs');
unlink('/tmp/hello', (err) => {
@@ -108,7 +100,7 @@ The synchronous APIs block the Node.js event loop and further JavaScript
execution until the operation is complete. Exceptions are thrown immediately
and can be handled using `try…catch`, or can be allowed to bubble up.
-```mjs
+```mjs|cjs
import { unlinkSync } from 'node:fs';
try {
@@ -117,9 +109,7 @@ try {
} catch (err) {
// handle the error
}
-```
-
-```cjs
+--------------
const { unlinkSync } = require('node:fs');
try {
@@ -418,7 +408,7 @@ Returns a `ReadableStream` that may be used to read the files data.
An error will be thrown if this method is called more than once or is called
after the `FileHandle` is closed or closing.
-```mjs
+```mjs|cjs
import {
open,
} from 'node:fs/promises';
@@ -429,9 +419,7 @@ for await (const chunk of file.readableWebStream())
console.log(chunk);
await file.close();
-```
-
-```cjs
+--------------
const {
open,
} = require('node:fs/promises');
@@ -488,7 +476,7 @@ of the file.
Convenience method to create a `readline` interface and stream over the file.
See [`filehandle.createReadStream()`][] for the options.
-```mjs
+```mjs|cjs
import { open } from 'node:fs/promises';
const file = await open('./some/file/to/read');
@@ -496,9 +484,7 @@ const file = await open('./some/file/to/read');
for await (const line of file.readLines()) {
console.log(line);
}
-```
-
-```cjs
+--------------
const { open } = require('node:fs/promises');
(async () => {
@@ -963,7 +949,7 @@ property indicating whether parent directories should be created. Calling
`fsPromises.mkdir()` when `path` is a directory that exists results in a
rejection only when `recursive` is false.
-```mjs
+```mjs|cjs
import { mkdir } from 'node:fs/promises';
try {
@@ -974,11 +960,9 @@ try {
} catch (err) {
console.error(err.message);
}
-```
-
-```cjs
+--------------
const { mkdir } = require('node:fs/promises');
-const { resolve, join } = require('node:path');
+const { join } = require('node:path');
async function makeDirectory() {
const projectFolder = join(__dirname, 'test', 'project');
@@ -1012,9 +996,11 @@ object with an `encoding` property specifying the character encoding to use.
```mjs
import { mkdtemp } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
try {
- await mkdtemp(path.join(os.tmpdir(), 'foo-'));
+ await mkdtemp(join(tmpdir(), 'foo-'));
} catch (err) {
console.error(err);
}
@@ -1143,7 +1129,7 @@ returned.
An example of reading a `package.json` file located in the same directory of the
running code:
-```mjs
+```mjs|cjs
import { readFile } from 'node:fs/promises';
try {
const filePath = new URL('./package.json', import.meta.url);
@@ -1152,9 +1138,7 @@ try {
} catch (err) {
console.error(err.message);
}
-```
-
-```cjs
+--------------
const { readFile } = require('node:fs/promises');
const { resolve } = require('node:path');
async function logFile() {
@@ -1307,6 +1291,17 @@ Removes files and directories (modeled on the standard POSIX `rm` utility).
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the [`fs.Stats`](/api/v18/fs#fsstats) object for the
given `path`.
+#### `fsPromises.statfs(path[, options])`
+
+
+
+* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`URL`](/api/v18/url#the-whatwg-url-api)
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the numeric values in the returned
+ fs.StatFs object should be `bigint`. **Default:** `false`.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the fs.StatFs object for the
+ given `path`.
+
#### `fsPromises.symlink(target, path[, type])`
@@ -2476,8 +2471,10 @@ object with an `encoding` property specifying the character encoding to use.
```mjs
import { mkdtemp } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
-mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
+mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
if (err) throw err;
console.log(directory);
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
@@ -3054,6 +3051,24 @@ Stats {
}
```
+#### `fs.statfs(path[, options], callback)`
+
+
+
+* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`URL`](/api/v18/url#the-whatwg-url-api)
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the numeric values in the returned
+ fs.StatFs object should be `bigint`. **Default:** `false`.
+* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+ * `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
+ * `stats` fs.StatFs
+
+Asynchronous statfs(2). Returns information about the mounted file system which
+contains `path`. The callback gets two arguments `(err, stats)` where `stats`
+is an fs.StatFs object.
+
+In case of an error, the `err.code` will be one of [Common System Errors][].
+
#### `fs.symlink(target, path[, type], callback)`
@@ -3107,16 +3122,14 @@ Truncates the file. No arguments other than a possible exception are
given to the completion callback. A file descriptor can also be passed as the
first argument. In this case, `fs.ftruncate()` is called.
-```mjs
+```mjs|cjs
import { truncate } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was truncated');
});
-```
-
-```cjs
+--------------
const { truncate } = require('node:fs');
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
@@ -4270,6 +4283,21 @@ utility). Returns `undefined`.
Retrieves the [`fs.Stats`](/api/v18/fs#fsstats) for the path.
+#### `fs.statfsSync(path[, options])`
+
+
+
+* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`URL`](/api/v18/url#the-whatwg-url-api)
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the numeric values in the returned
+ fs.StatFs object should be `bigint`. **Default:** `false`.
+* Returns: fs.StatFs
+
+Synchronous statfs(2). Returns information about the mounted file system which
+contains `path`.
+
+In case of an error, the `err.code` will be one of [Common System Errors][].
+
#### `fs.symlinkSync(target, path[, type])`
@@ -5132,6 +5160,98 @@ The times in the stat object have the following semantics:
Prior to Node.js 0.12, the `ctime` held the `birthtime` on Windows systems. As
of 0.12, `ctime` is not "creation time", and on Unix systems, it never was.
+#### `fs.StatFs`
+
+
+
+Provides information about a mounted file system.
+
+Objects returned from [`fs.statfs()`][] and its synchronous counterpart are of
+this type. If `bigint` in the `options` passed to those methods is `true`, the
+numeric values will be `bigint` instead of `number`.
+
+```console
+StatFs {
+ type: 1397114950,
+ bsize: 4096,
+ blocks: 121938943,
+ bfree: 61058895,
+ bavail: 61058895,
+ files: 999,
+ ffree: 1000000
+}
+```
+
+`bigint` version:
+
+```console
+StatFs {
+ type: 1397114950n,
+ bsize: 4096n,
+ blocks: 121938943n,
+ bfree: 61058895n,
+ bavail: 61058895n,
+ files: 999n,
+ ffree: 1000000n
+}
+```
+
+##### `statfs.bavail`
+
+
+
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Free blocks available to unprivileged users.
+
+##### `statfs.bfree`
+
+
+
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Free blocks in file system.
+
+##### `statfs.blocks`
+
+
+
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Total data blocks in file system.
+
+##### `statfs.bsize`
+
+
+
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Optimal transfer block size.
+
+##### `statfs.ffree`
+
+
+
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Free file nodes in file system.
+
+##### `statfs.files`
+
+
+
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Total file nodes in file system.
+
+##### `statfs.type`
+
+
+
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
+
+Type of file system.
+
#### `fs.WriteStream`
@@ -5517,6 +5637,8 @@ For example, the following is prone to error because the `fs.stat()`
operation might complete before the `fs.rename()` operation:
```js
+const fs = require('node:fs');
+
fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
console.log('renamed complete');
@@ -5530,28 +5652,26 @@ fs.stat('/tmp/world', (err, stats) => {
It is important to correctly order the operations by awaiting the results
of one before invoking the other:
-```mjs
+```mjs|cjs
import { rename, stat } from 'node:fs/promises';
-const from = '/tmp/hello';
-const to = '/tmp/world';
+const oldPath = '/tmp/hello';
+const newPath = '/tmp/world';
try {
- await rename(from, to);
- const stats = await stat(to);
+ await rename(oldPath, newPath);
+ const stats = await stat(newPath);
console.log(`stats: ${JSON.stringify(stats)}`);
} catch (error) {
console.error('there was an error:', error.message);
}
-```
-
-```cjs
+--------------
const { rename, stat } = require('node:fs/promises');
-(async function(from, to) {
+(async function(oldPath, newPath) {
try {
- await rename(from, to);
- const stats = await stat(to);
+ await rename(oldPath, newPath);
+ const stats = await stat(newPath);
console.log(`stats: ${JSON.stringify(stats)}`);
} catch (error) {
console.error('there was an error:', error.message);
@@ -5562,7 +5682,7 @@ const { rename, stat } = require('node:fs/promises');
Or, when using the callback APIs, move the `fs.stat()` call into the callback
of the `fs.rename()` operation:
-```mjs
+```mjs|cjs
import { rename, stat } from 'node:fs';
rename('/tmp/hello', '/tmp/world', (err) => {
@@ -5572,9 +5692,7 @@ rename('/tmp/hello', '/tmp/world', (err) => {
console.log(`stats: ${JSON.stringify(stats)}`);
});
});
-```
-
-```cjs
+--------------
const { rename, stat } = require('node:fs/promises');
rename('/tmp/hello', '/tmp/world', (err) => {
@@ -5607,7 +5725,7 @@ try {
fd = await open('/open/some/file.txt', 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
@@ -5621,7 +5739,7 @@ try {
fd = await open('file.txt', 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
@@ -5734,7 +5852,7 @@ try {
fd = await open(Buffer.from('/open/some/file.txt'), 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
@@ -5957,6 +6075,7 @@ the file contents.
[`fs.rmSync()`]: #fsrmsyncpath-options
[`fs.rmdir()`]: #fsrmdirpath-options-callback
[`fs.stat()`]: #fsstatpath-options-callback
+[`fs.statfs()`]: #fsstatfspath-options-callback
[`fs.symlink()`]: #fssymlinktarget-path-type-callback
[`fs.utimes()`]: #fsutimespath-atime-mtime-callback
[`fs.watch()`]: #fswatchfilename-options-listener
diff --git a/content/api/v18/http.en.md b/content/api/v18/http.en.md
index 31da8a07b7..6b1fcbe35f 100644
--- a/content/api/v18/http.en.md
+++ b/content/api/v18/http.en.md
@@ -13,7 +13,7 @@ Stable
-
+
To use the HTTP server and client one must `require('node:http')`.
@@ -363,8 +363,9 @@ the data is read it will consume memory that can eventually lead to a
For backward compatibility, `res` will only emit `'error'` if there is an
`'error'` listener registered.
-Set `Content-Length` header to limit the response body size. Mismatching the
-`Content-Length` header value will result in an \[`Error`]\[] being thrown,
+Set `Content-Length` header to limit the response body size.
+If [`response.strictContentLength`][] is set to `true`, mismatching the
+`Content-Length` header value will result in an `Error` being thrown,
identified by `code:` [`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`][].
`Content-Length` value should be in bytes, not characters. Use
@@ -1118,7 +1119,8 @@ not be emitted.
If a client connection emits an `'error'` event, it will be forwarded here.
Listener of this event is responsible for closing/destroying the underlying
socket. For example, one may wish to more gracefully close the socket with a
-custom HTTP response instead of abruptly severing the connection.
+custom HTTP response instead of abruptly severing the connection. The socket
+**must be closed or destroyed** before the listener ends.
This event is guaranteed to be passed an instance of the [`net.Socket`](/api/v18/net#netsocket) class,
a subclass of [`stream.Duplex`](/api/v18/stream#streamduplex), unless the user specifies a socket
@@ -1761,6 +1763,17 @@ response.statusMessage = 'Not found';
After response header was sent to the client, this property indicates the
status message which was sent out.
+#### `response.strictContentLength`
+
+
+
+* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
+
+If set to `true`, Node.js will check whether the `Content-Length`
+header value and the size of the body, in bytes, are equal.
+Mismatching the `Content-Length` header value will result
+in an `Error` being thrown, identified by `code:` [`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`][].
+
#### `response.uncork()`
@@ -2496,6 +2509,46 @@ Sets a single header value. If the header already exists in the to-be-sent
headers, its value will be replaced. Use an array of strings to send multiple
headers with the same name.
+#### `outgoingMessage.setHeaders(headers)`
+
+
+
+* `headers` [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) | [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
+* Returns: [`http.ServerResponse`](/api/v18/http#httpserverresponse)
+
+Returns the response object.
+
+Sets multiple header values for implicit headers.
+`headers` must be an instance of [`Headers`][] or `Map`,
+if a header already exists in the to-be-sent headers,
+its value will be replaced.
+
+```js
+const headers = new Headers({ foo: 'bar' });
+response.setHeaders(headers);
+```
+
+or
+
+```js
+const headers = new Map([['foo', 'bar']]);
+res.setHeaders(headers);
+```
+
+When headers have been set with [`outgoingMessage.setHeaders()`][],
+they will be merged with any headers passed to [`response.writeHead()`][],
+with the headers passed to [`response.writeHead()`][] given precedence.
+
+```js
+// Returns content-type = text/plain
+const server = http.createServer((req, res) => {
+ const headers = new Headers({ 'Content-Type': 'text/html' });
+ res.setHeaders(headers);
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('ok');
+});
+```
+
#### `outgoingMessage.setTimeout(msesc[, callback])`
@@ -2644,6 +2697,7 @@ Found'`.
* `requestTimeout`: Sets the timeout value in milliseconds for receiving
the entire request from the client.
See [`server.requestTimeout`][] for more information.
+ **Default:** `300000`.
* `joinDuplicateHeaders` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) It joins the field line values of multiple
headers in a request with `, ` instead of discarding the duplicates.
See [`message.headers`][] for more information.
@@ -2651,7 +2705,6 @@ Found'`.
* `ServerResponse` [`http.ServerResponse`](/api/v18/http#httpserverresponse) Specifies the `ServerResponse` class
to be used. Useful for extending the original `ServerResponse`. **Default:**
`ServerResponse`.
- **Default:** `300000`.
* `uniqueHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) A list of response headers that should be sent only
once. If the header's value is an array, the items will be joined
using `; `.
@@ -2665,7 +2718,7 @@ Returns a new instance of [`http.Server`][].
The `requestListener` is a function which is automatically
added to the [`'request'`][] event.
-```cjs
+```cjs|cjs
const http = require('node:http');
// Create a local server to receive data from
@@ -2677,9 +2730,7 @@ const server = http.createServer((req, res) => {
});
server.listen(8000);
-```
-
-```cjs
+--------------
const http = require('node:http');
// Create a local server to receive data from
@@ -3149,6 +3200,7 @@ Set the maximum number of idle HTTP parsers.
[`Buffer.byteLength()`]: /api/v18/buffer#static-method-bufferbytelengthstring-encoding
[`Duplex`]: /api/v18/stream#class-streamduplex
[`HPE_HEADER_OVERFLOW`]: /api/v18/errors#hpe_header_overflow
+[`Headers`]: /api/v18/globals#class-headers
[`TypeError`]: /api/v18/errors#class-typeerror
[`URL`]: /api/v18/url#the-whatwg-url-api
[`agent.createConnection()`]: #agentcreateconnectionoptions-callback
@@ -3175,6 +3227,7 @@ Set the maximum number of idle HTTP parsers.
[`net.createConnection()`]: /api/v18/net#netcreateconnectionoptions-connectlistener
[`new URL()`]: /api/v18/url#new-urlinput-base
[`outgoingMessage.setHeader(name, value)`]: #outgoingmessagesetheadername-value
+[`outgoingMessage.setHeaders()`]: #outgoingmessagesetheadersheaders
[`outgoingMessage.socket`]: #outgoingmessagesocket
[`removeHeader(name)`]: #requestremoveheadername
[`request.destroy()`]: #requestdestroyerror
@@ -3193,6 +3246,7 @@ Set the maximum number of idle HTTP parsers.
[`response.getHeader()`]: #responsegetheadername
[`response.setHeader()`]: #responsesetheadername-value
[`response.socket`]: #responsesocket
+[`response.strictContentLength`]: #responsestrictcontentlength
[`response.writableEnded`]: #responsewritableended
[`response.writableFinished`]: #responsewritablefinished
[`response.write()`]: #responsewritechunk-encoding-callback
diff --git a/content/api/v18/http2.en.md b/content/api/v18/http2.en.md
index 1afc6c9249..5b73f08905 100644
--- a/content/api/v18/http2.en.md
+++ b/content/api/v18/http2.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:http2` module provides an implementation of the [HTTP/2][] protocol.
It can be accessed using:
@@ -328,7 +328,7 @@ server.on('stream', (stream, headers) => {
stream.end('Hello World ');
});
-server.listen(80);
+server.listen(8000);
```
Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence,
@@ -2158,7 +2158,7 @@ server.on('stream', (stream, headers) => {
stream.end('Hello World ');
});
-server.listen(80);
+server.listen(8000);
```
#### `http2.createSecureServer(options[, onRequestHandler])`
@@ -2255,7 +2255,7 @@ server.on('stream', (stream, headers) => {
stream.end('Hello World ');
});
-server.listen(80);
+server.listen(8443);
```
#### `http2.connect(authority[, options][, listener])`
@@ -2657,7 +2657,7 @@ const client = http2.connect('http://localhost:8001');
// for CONNECT requests or an error will be thrown.
const req = client.request({
':method': 'CONNECT',
- ':authority': `localhost:${port}`,
+ ':authority': 'localhost:8000',
});
req.on('response', (headers) => {
diff --git a/content/api/v18/https.en.md b/content/api/v18/https.en.md
index 8eb1ed13f0..f0047688f5 100644
--- a/content/api/v18/https.en.md
+++ b/content/api/v18/https.en.md
@@ -13,7 +13,7 @@ Stable
-
+
HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.
diff --git a/content/api/v18/inspector.en.md b/content/api/v18/inspector.en.md
index 747cc94515..27f5adae4a 100644
--- a/content/api/v18/inspector.en.md
+++ b/content/api/v18/inspector.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:inspector` module provides an API for interacting with the V8
inspector.
@@ -189,7 +189,11 @@ by V8. Chrome DevTools Protocol domain provides an interface for interacting
with one of the runtime agents used to inspect the application state and listen
to the run-time events.
-### Example usage
+You can not set `reportProgress` to `true` when sending a
+`HeapProfiler.takeHeapSnapshot` or `HeapProfiler.stopTrackingHeapObjects`
+command to V8.
+
+##### Example usage
Apart from the debugger, various V8 Profilers are available through the DevTools
protocol.
diff --git a/content/api/v18/module.en.md b/content/api/v18/module.en.md
index a1e9b7252e..1562650a4b 100644
--- a/content/api/v18/module.en.md
+++ b/content/api/v18/module.en.md
@@ -29,13 +29,11 @@ if a module is maintained by a third party or not.
`module` in this context isn't the same object that's provided
by the [module wrapper][]. To access it, require the `Module` module:
-```mjs
+```mjs|cjs
// module.mjs
// In an ECMAScript module
import { builtinModules as builtin } from 'node:module';
-```
-
-```cjs
+--------------
// module.cjs
// In a CommonJS module
const builtin = require('node:module').builtinModules;
@@ -127,13 +125,11 @@ To enable source map parsing, Node.js must be run with the flag
[`--enable-source-maps`][], or with code coverage enabled by setting
[`NODE_V8_COVERAGE=dir`][].
-```mjs
+```mjs|cjs
// module.mjs
// In an ECMAScript module
import { findSourceMap, SourceMap } from 'node:module';
-```
-
-```cjs
+--------------
// module.cjs
// In a CommonJS module
const { findSourceMap, SourceMap } = require('node:module');
diff --git a/content/api/v18/modules.en.md b/content/api/v18/modules.en.md
index f85b4a6a93..986d4bb219 100644
--- a/content/api/v18/modules.en.md
+++ b/content/api/v18/modules.en.md
@@ -752,11 +752,9 @@ See ["Accessing the main module"](#accessing-the-main-module).
In `entry.js` script:
-```js
+```js|bash
console.log(require.main);
-```
-
-```bash
+--------------
node entry.js
```
diff --git a/content/api/v18/n-api.en.md b/content/api/v18/n-api.en.md
index c1e843e231..ccc72755c4 100644
--- a/content/api/v18/n-api.en.md
+++ b/content/api/v18/n-api.en.md
@@ -54,12 +54,10 @@ following `node-addon-api` code. The first section shows the
`node-addon-api` code and the second section shows what actually gets
used in the addon.
-```cpp
+```cpp|cpp
Object obj = Object::New(env);
obj["foo"] = String::New(env, "bar");
-```
-
-```cpp
+--------------
napi_status status;
napi_value object, string;
status = napi_create_object(env, &object);
@@ -391,16 +389,14 @@ implementation of Node-API or any implementation of Node-API outside of Node.js.
to the addon and which instantiates the addon by calling into `addon.c` when the
addon is loaded into a Node.js environment.
-```c
+```c|c
// addon.h
#ifndef _ADDON_H_
#define _ADDON_H_
#include
napi_value create_addon(napi_env env);
#endif // _ADDON_H_
-```
-
-```c
+--------------
// addon.c
#include "addon.h"
@@ -5727,12 +5723,10 @@ Experimental
-```c
+```c|text
NAPI_EXTERN napi_status
node_api_get_module_file_name(napi_env env, const char** result);
-```
-
* `[in] env`: The environment that the API is invoked under.
* `[out] result`: A URL containing the absolute path of the
location from which the add-on was loaded. For a file on the local
diff --git a/content/api/v18/navigation.json b/content/api/v18/navigation.json
index 9c3a0efd67..d231687cf6 100644
--- a/content/api/v18/navigation.json
+++ b/content/api/v18/navigation.json
@@ -1,4 +1,1775 @@
{
"version": "v18",
- "items": []
+ "items": [
+ {
+ "slug": "/api/v18/addons/",
+ "title": "C addons",
+ "type": "module",
+ "name": "addons"
+ },
+ {
+ "slug": "/api/v18/assert/",
+ "title": "Assert",
+ "type": "module",
+ "name": "assert"
+ },
+ {
+ "slug": "/api/v18/assert/#assertassertionerror",
+ "title": "assertAssertionError",
+ "type": "class",
+ "name": "assert"
+ },
+ {
+ "slug": "/api/v18/assert/#assertcalltracker",
+ "title": "assertCallTracker",
+ "type": "class",
+ "name": "assert"
+ },
+ {
+ "slug": "/api/v18/async_context/",
+ "title": "Asynchronous context tracking",
+ "type": "module",
+ "name": "async_context"
+ },
+ {
+ "slug": "/api/v18/async_context/#asynclocalstorage",
+ "title": "AsyncLocalStorage",
+ "type": "class",
+ "name": "async_context"
+ },
+ {
+ "slug": "/api/v18/async_context/#asyncresource",
+ "title": "AsyncResource",
+ "type": "class",
+ "name": "async_context"
+ },
+ {
+ "slug": "/api/v18/async_hooks/",
+ "title": "Async hooks",
+ "type": "module",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v18/async_hooks/#asynchook",
+ "title": "AsyncHook",
+ "type": "class",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v18/async_hooks/#asynclocalstorage",
+ "title": "AsyncLocalStorage",
+ "type": "class",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v18/async_hooks/#asyncresource",
+ "title": "AsyncResource",
+ "type": "class",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v18/buffer/",
+ "title": "Buffer",
+ "type": "module",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v18/buffer/#blob",
+ "title": "Blob",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v18/buffer/#buffer",
+ "title": "Buffer",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v18/buffer/#file",
+ "title": "File",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v18/buffer/#slowbuffer",
+ "title": "SlowBuffer",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v18/child_process/",
+ "title": "Child process",
+ "type": "module",
+ "name": "child_process"
+ },
+ {
+ "slug": "/api/v18/child_process/#childprocess",
+ "title": "ChildProcess",
+ "type": "class",
+ "name": "child_process"
+ },
+ {
+ "slug": "/api/v18/cli/",
+ "title": "Command-line API",
+ "type": "module",
+ "name": "cli"
+ },
+ {
+ "slug": "/api/v18/cluster/",
+ "title": "Cluster",
+ "type": "module",
+ "name": "cluster"
+ },
+ {
+ "slug": "/api/v18/cluster/#worker",
+ "title": "Worker",
+ "type": "class",
+ "name": "cluster"
+ },
+ {
+ "slug": "/api/v18/console/",
+ "title": "Console",
+ "type": "module",
+ "name": "console"
+ },
+ {
+ "slug": "/api/v18/console/#console",
+ "title": "Console",
+ "type": "class",
+ "name": "console"
+ },
+ {
+ "slug": "/api/v18/console/#console",
+ "title": "Console",
+ "type": "class",
+ "name": "console"
+ },
+ {
+ "slug": "/api/v18/corepack/",
+ "title": "Corepack",
+ "type": "module",
+ "name": "corepack"
+ },
+ {
+ "slug": "/api/v18/crypto/",
+ "title": "Crypto",
+ "type": "module",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#certificate",
+ "title": "Certificate",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#cipher",
+ "title": "Cipher",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#decipher",
+ "title": "Decipher",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#diffiehellman",
+ "title": "DiffieHellman",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#diffiehellmangroup",
+ "title": "DiffieHellmanGroup",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#ecdh",
+ "title": "ECDH",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#hash",
+ "title": "Hash",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#hmac",
+ "title": "Hmac",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#keyobject",
+ "title": "KeyObject",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#sign",
+ "title": "Sign",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#verify",
+ "title": "Verify",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/crypto/#x509certificate",
+ "title": "X509Certificate",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v18/debugger/",
+ "title": "Debugger",
+ "type": "module",
+ "name": "debugger"
+ },
+ {
+ "slug": "/api/v18/deprecations/",
+ "title": "Deprecated APIs",
+ "type": "module",
+ "name": "deprecations"
+ },
+ {
+ "slug": "/api/v18/dgram/",
+ "title": "UDPdatagram sockets",
+ "type": "module",
+ "name": "dgram"
+ },
+ {
+ "slug": "/api/v18/dgram/#dgramsocket",
+ "title": "dgramSocket",
+ "type": "class",
+ "name": "dgram"
+ },
+ {
+ "slug": "/api/v18/diagnostics_channel/",
+ "title": "Diagnostics Channel",
+ "type": "module",
+ "name": "diagnostics_channel"
+ },
+ {
+ "slug": "/api/v18/diagnostics_channel/#channel",
+ "title": "Channel",
+ "type": "class",
+ "name": "diagnostics_channel"
+ },
+ {
+ "slug": "/api/v18/dns/",
+ "title": "DNS",
+ "type": "module",
+ "name": "dns"
+ },
+ {
+ "slug": "/api/v18/dns/#dnspromisesresolver",
+ "title": "dnsPromisesResolver",
+ "type": "class",
+ "name": "dns"
+ },
+ {
+ "slug": "/api/v18/dns/#dnsresolver",
+ "title": "dnsResolver",
+ "type": "class",
+ "name": "dns"
+ },
+ {
+ "slug": "/api/v18/documentation/",
+ "title": "About this documentation",
+ "type": "module",
+ "name": "documentation"
+ },
+ {
+ "slug": "/api/v18/domain/",
+ "title": "Domain",
+ "type": "module",
+ "name": "domain"
+ },
+ {
+ "slug": "/api/v18/domain/#domain",
+ "title": "Domain",
+ "type": "class",
+ "name": "domain"
+ },
+ {
+ "slug": "/api/v18/embedding/",
+ "title": "C embedder API",
+ "type": "module",
+ "name": "embedding"
+ },
+ {
+ "slug": "/api/v18/errors/",
+ "title": "Errors",
+ "type": "module",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v18/errors/#assertionerror",
+ "title": "AssertionError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v18/errors/#error",
+ "title": "Error",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v18/errors/#rangeerror",
+ "title": "RangeError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v18/errors/#referenceerror",
+ "title": "ReferenceError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v18/errors/#syntaxerror",
+ "title": "SyntaxError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v18/errors/#systemerror",
+ "title": "SystemError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v18/errors/#typeerror",
+ "title": "TypeError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v18/esm/",
+ "title": "ECMAScript modules",
+ "type": "module",
+ "name": "esm"
+ },
+ {
+ "slug": "/api/v18/events/",
+ "title": "Events",
+ "type": "module",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v18/events/#customevent",
+ "title": "CustomEvent",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v18/events/#event",
+ "title": "Event",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v18/events/#eventemitter",
+ "title": "EventEmitter",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v18/events/#eventseventemitterasyncresource-extends-eventemitter",
+ "title": "eventsEventEmitterAsyncResource extends EventEmitter",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v18/events/#eventtarget",
+ "title": "EventTarget",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v18/events/#nodeeventtarget",
+ "title": "NodeEventTarget",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v18/fs/",
+ "title": "File system",
+ "type": "module",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v18/fs/#filehandle",
+ "title": "FileHandle",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v18/fs/#fsdir",
+ "title": "fsDir",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v18/fs/#fsdirent",
+ "title": "fsDirent",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v18/fs/#fsfswatcher",
+ "title": "fsFSWatcher",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v18/fs/#fsreadstream",
+ "title": "fsReadStream",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v18/fs/#fsstatfs",
+ "title": "fsStatFs",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v18/fs/#fsstats",
+ "title": "fsStats",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v18/fs/#fsstatwatcher",
+ "title": "fsStatWatcher",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v18/fs/#fswritestream",
+ "title": "fsWriteStream",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v18/globals/",
+ "title": "Global objects",
+ "type": "module",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#abortcontroller",
+ "title": "AbortController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#abortcontroller",
+ "title": "AbortController",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#abortsignal",
+ "title": "AbortSignal",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#blob",
+ "title": "Blob",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#blob",
+ "title": "Blob",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#buffer",
+ "title": "Buffer",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#buffer",
+ "title": "Buffer",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#bytelengthqueuingstrategy",
+ "title": "ByteLengthQueuingStrategy",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#clearimmediateimmediateobject",
+ "title": "clearImmediate",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#clearintervalintervalobject",
+ "title": "clearInterval",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#cleartimeouttimeoutobject",
+ "title": "clearTimeout",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#compressionstream",
+ "title": "CompressionStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#console",
+ "title": "console",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#countqueuingstrategy",
+ "title": "CountQueuingStrategy",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#customevent",
+ "title": "CustomEvent",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#decompressionstream",
+ "title": "DecompressionStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#domexception",
+ "title": "DOMException",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#event",
+ "title": "Event",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#eventtarget",
+ "title": "EventTarget",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#global",
+ "title": "global",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#messagechannel",
+ "title": "MessageChannel",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#messageevent",
+ "title": "MessageEvent",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#messageport",
+ "title": "MessagePort",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#process",
+ "title": "process",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#queuemicrotaskcallback",
+ "title": "queueMicrotask",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#readablebytestreamcontroller",
+ "title": "ReadableByteStreamController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#readablestream",
+ "title": "ReadableStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#readablestreambyobreader",
+ "title": "ReadableStreamBYOBReader",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#readablestreambyobrequest",
+ "title": "ReadableStreamBYOBRequest",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#readablestreamdefaultcontroller",
+ "title": "ReadableStreamDefaultController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#readablestreamdefaultreader",
+ "title": "ReadableStreamDefaultReader",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#setimmediatecallback-args",
+ "title": "setImmediate",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#setintervalcallback-delay-args",
+ "title": "setInterval",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#settimeoutcallback-delay-args",
+ "title": "setTimeout",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#structuredclonevalue-options",
+ "title": "structuredClone",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#textdecoder",
+ "title": "TextDecoder",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#textdecoderstream",
+ "title": "TextDecoderStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#textencoder",
+ "title": "TextEncoder",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#textencoderstream",
+ "title": "TextEncoderStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#transformstream",
+ "title": "TransformStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#transformstreamdefaultcontroller",
+ "title": "TransformStreamDefaultController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#url",
+ "title": "URL",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#urlsearchparams",
+ "title": "URLSearchParams",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#webassembly",
+ "title": "WebAssembly",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#writablestream",
+ "title": "WritableStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#writablestreamdefaultcontroller",
+ "title": "WritableStreamDefaultController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/globals/#writablestreamdefaultwriter",
+ "title": "WritableStreamDefaultWriter",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v18/http/",
+ "title": "HTTP",
+ "type": "module",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v18/http/#httpagent",
+ "title": "httpAgent",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v18/http/#httpclientrequest",
+ "title": "httpClientRequest",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v18/http/#httpincomingmessage",
+ "title": "httpIncomingMessage",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v18/http/#httpoutgoingmessage",
+ "title": "httpOutgoingMessage",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v18/http/#httpserver",
+ "title": "httpServer",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v18/http/#httpserverresponse",
+ "title": "httpServerResponse",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v18/http2/",
+ "title": "HTTP2",
+ "type": "module",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/http2/#clienthttp2session",
+ "title": "ClientHttp2Session",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/http2/#clienthttp2stream",
+ "title": "ClientHttp2Stream",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/http2/#http2http2serverrequest",
+ "title": "http2Http2ServerRequest",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/http2/#http2http2serverresponse",
+ "title": "http2Http2ServerResponse",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/http2/#http2secureserver",
+ "title": "Http2SecureServer",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/http2/#http2server",
+ "title": "Http2Server",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/http2/#http2session",
+ "title": "Http2Session",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/http2/#http2stream",
+ "title": "Http2Stream",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/http2/#serverhttp2session",
+ "title": "ServerHttp2Session",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/http2/#serverhttp2stream",
+ "title": "ServerHttp2Stream",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v18/https/",
+ "title": "HTTPS",
+ "type": "module",
+ "name": "https"
+ },
+ {
+ "slug": "/api/v18/https/#httpsagent",
+ "title": "httpsAgent",
+ "type": "class",
+ "name": "https"
+ },
+ {
+ "slug": "/api/v18/https/#httpsserver",
+ "title": "httpsServer",
+ "type": "class",
+ "name": "https"
+ },
+ {
+ "slug": "/api/v18/inspector/",
+ "title": "Inspector",
+ "type": "module",
+ "name": "inspector"
+ },
+ {
+ "slug": "/api/v18/inspector/#inspectorsession",
+ "title": "inspectorSession",
+ "type": "class",
+ "name": "inspector"
+ },
+ {
+ "slug": "/api/v18/intl/",
+ "title": "Internationalization support",
+ "type": "module",
+ "name": "intl"
+ },
+ {
+ "slug": "/api/v18/module/",
+ "title": "nodemodule API",
+ "type": "module",
+ "name": "module"
+ },
+ {
+ "slug": "/api/v18/module/#modulesourcemap",
+ "title": "moduleSourceMap",
+ "type": "class",
+ "name": "module"
+ },
+ {
+ "slug": "/api/v18/modules/",
+ "title": "CommonJS modules",
+ "type": "module",
+ "name": "modules"
+ },
+ {
+ "slug": "/api/v18/n-api/",
+ "title": "Node-API",
+ "type": "module",
+ "name": "n-api"
+ },
+ {
+ "slug": "/api/v18/net/",
+ "title": "Net",
+ "type": "module",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v18/net/#netblocklist",
+ "title": "netBlockList",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v18/net/#netserver",
+ "title": "netServer",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v18/net/#netsocket",
+ "title": "netSocket",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v18/net/#netsocketaddress",
+ "title": "netSocketAddress",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v18/os/",
+ "title": "OS",
+ "type": "module",
+ "name": "os"
+ },
+ {
+ "slug": "/api/v18/packages/",
+ "title": "Packages",
+ "type": "module",
+ "name": "packages"
+ },
+ {
+ "slug": "/api/v18/path/",
+ "title": "Path",
+ "type": "module",
+ "name": "path"
+ },
+ {
+ "slug": "/api/v18/perf_hooks/",
+ "title": "Performance measurement APIs",
+ "type": "module",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v18/perf_hooks/#histogram",
+ "title": "Histogram",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v18/perf_hooks/#intervalhistogram-extends-histogram",
+ "title": "IntervalHistogram extends Histogram",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v18/perf_hooks/#perf-hooksperformanceobserver",
+ "title": "perf_hooksPerformanceObserver",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v18/perf_hooks/#performanceentry",
+ "title": "PerformanceEntry",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v18/perf_hooks/#performancenodetiming",
+ "title": "PerformanceNodeTiming",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v18/perf_hooks/#performanceobserverentrylist",
+ "title": "PerformanceObserverEntryList",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v18/perf_hooks/#performanceresourcetiming",
+ "title": "PerformanceResourceTiming",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v18/perf_hooks/#recordablehistogram-extends-histogram",
+ "title": "RecordableHistogram extends Histogram",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v18/permissions/",
+ "title": "Permissions",
+ "type": "module",
+ "name": "permissions"
+ },
+ {
+ "slug": "/api/v18/policy/",
+ "title": "Policies",
+ "type": "module",
+ "name": "policy"
+ },
+ {
+ "slug": "/api/v18/process/",
+ "title": "Process",
+ "type": "module",
+ "name": "process"
+ },
+ {
+ "slug": "/api/v18/punycode/",
+ "title": "Punycode",
+ "type": "module",
+ "name": "punycode"
+ },
+ {
+ "slug": "/api/v18/querystring/",
+ "title": "Query string",
+ "type": "module",
+ "name": "querystring"
+ },
+ {
+ "slug": "/api/v18/readline/",
+ "title": "Readline",
+ "type": "module",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v18/readline/#interfaceconstructor",
+ "title": "InterfaceConstructor",
+ "type": "class",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v18/readline/#readlineinterface",
+ "title": "readlineInterface",
+ "type": "class",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v18/readline/#readlinepromisesinterface",
+ "title": "readlinePromisesInterface",
+ "type": "class",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v18/readline/#readlinepromisesreadline",
+ "title": "readlinePromisesReadline",
+ "type": "class",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v18/repl/",
+ "title": "REPL",
+ "type": "module",
+ "name": "repl"
+ },
+ {
+ "slug": "/api/v18/repl/#replserver",
+ "title": "REPLServer",
+ "type": "class",
+ "name": "repl"
+ },
+ {
+ "slug": "/api/v18/report/",
+ "title": "Diagnostic report",
+ "type": "module",
+ "name": "report"
+ },
+ {
+ "slug": "/api/v18/single-executable-applications/",
+ "title": "Single executable applications",
+ "type": "module",
+ "name": "single-executable-applications"
+ },
+ {
+ "slug": "/api/v18/stream/",
+ "title": "Stream",
+ "type": "module",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v18/stream/#streamduplex",
+ "title": "streamDuplex",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v18/stream/#streamduplex",
+ "title": "streamDuplex",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v18/stream/#streampassthrough",
+ "title": "streamPassThrough",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v18/stream/#streamreadable",
+ "title": "streamReadable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v18/stream/#streamreadable",
+ "title": "streamReadable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v18/stream/#streamtransform",
+ "title": "streamTransform",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v18/stream/#streamtransform",
+ "title": "streamTransform",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v18/stream/#streamwritable",
+ "title": "streamWritable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v18/stream/#streamwritable",
+ "title": "streamWritable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v18/string_decoder/",
+ "title": "String decoder",
+ "type": "module",
+ "name": "string_decoder"
+ },
+ {
+ "slug": "/api/v18/string_decoder/#stringdecoder",
+ "title": "StringDecoder",
+ "type": "class",
+ "name": "string_decoder"
+ },
+ {
+ "slug": "/api/v18/synopsis/",
+ "title": "Usage and example",
+ "type": "module",
+ "name": "synopsis"
+ },
+ {
+ "slug": "/api/v18/test/",
+ "title": "Test runner",
+ "type": "module",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v18/test/#mockfunctioncontext",
+ "title": "MockFunctionContext",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v18/test/#mocktracker",
+ "title": "MockTracker",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v18/test/#suitecontext",
+ "title": "SuiteContext",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v18/test/#testcontext",
+ "title": "TestContext",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v18/test/#testsstream",
+ "title": "TestsStream",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v18/timers/",
+ "title": "Timers",
+ "type": "module",
+ "name": "timers"
+ },
+ {
+ "slug": "/api/v18/timers/#immediate",
+ "title": "Immediate",
+ "type": "class",
+ "name": "timers"
+ },
+ {
+ "slug": "/api/v18/timers/#timeout",
+ "title": "Timeout",
+ "type": "class",
+ "name": "timers"
+ },
+ {
+ "slug": "/api/v18/tls/",
+ "title": "TLS ",
+ "type": "module",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v18/tls/#tlscryptostream",
+ "title": "tlsCryptoStream",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v18/tls/#tlssecurepair",
+ "title": "tlsSecurePair",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v18/tls/#tlsserver",
+ "title": "tlsServer",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v18/tls/#tlstlssocket",
+ "title": "tlsTLSSocket",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v18/tracing/",
+ "title": "Trace events",
+ "type": "module",
+ "name": "tracing"
+ },
+ {
+ "slug": "/api/v18/tty/",
+ "title": "TTY",
+ "type": "module",
+ "name": "tty"
+ },
+ {
+ "slug": "/api/v18/tty/#ttyreadstream",
+ "title": "ttyReadStream",
+ "type": "class",
+ "name": "tty"
+ },
+ {
+ "slug": "/api/v18/tty/#ttywritestream",
+ "title": "ttyWriteStream",
+ "type": "class",
+ "name": "tty"
+ },
+ {
+ "slug": "/api/v18/url/",
+ "title": "URL",
+ "type": "module",
+ "name": "url"
+ },
+ {
+ "slug": "/api/v18/url/#url",
+ "title": "URL",
+ "type": "class",
+ "name": "url"
+ },
+ {
+ "slug": "/api/v18/url/#urlsearchparams",
+ "title": "URLSearchParams",
+ "type": "class",
+ "name": "url"
+ },
+ {
+ "slug": "/api/v18/util/",
+ "title": "Util",
+ "type": "module",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v18/util/#utilmimeparams",
+ "title": "utilMIMEParams",
+ "type": "class",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v18/util/#utilmimetype",
+ "title": "utilMIMEType",
+ "type": "class",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v18/util/#utiltextdecoder",
+ "title": "utilTextDecoder",
+ "type": "class",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v18/util/#utiltextencoder",
+ "title": "utilTextEncoder",
+ "type": "class",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v18/v8/",
+ "title": "V8",
+ "type": "module",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v18/v8/#v8defaultdeserializer",
+ "title": "v8DefaultDeserializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v18/v8/#v8defaultserializer",
+ "title": "v8DefaultSerializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v18/v8/#v8deserializer",
+ "title": "v8Deserializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v18/v8/#v8gcprofiler",
+ "title": "v8GCProfiler",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v18/v8/#v8serializer",
+ "title": "v8Serializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v18/vm/",
+ "title": "VM ",
+ "type": "module",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v18/vm/#vmmodule",
+ "title": "vmModule",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v18/vm/#vmscript",
+ "title": "vmScript",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v18/vm/#vmsourcetextmodule",
+ "title": "vmSourceTextModule",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v18/vm/#vmsyntheticmodule",
+ "title": "vmSyntheticModule",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v18/wasi/",
+ "title": "WebAssembly System Interface ",
+ "type": "module",
+ "name": "wasi"
+ },
+ {
+ "slug": "/api/v18/wasi/#wasi",
+ "title": "WASI",
+ "type": "class",
+ "name": "wasi"
+ },
+ {
+ "slug": "/api/v18/webcrypto/",
+ "title": "Web Crypto API",
+ "type": "module",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#aescbcparams",
+ "title": "AesCbcParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#aesctrparams",
+ "title": "AesCtrParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#aesgcmparams",
+ "title": "AesGcmParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#aeskeygenparams",
+ "title": "AesKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#algorithmidentifier",
+ "title": "AlgorithmIdentifier",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#crypto",
+ "title": "Crypto",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#cryptokey",
+ "title": "CryptoKey",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#cryptokeypair",
+ "title": "CryptoKeyPair",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#ecdhkeyderiveparams",
+ "title": "EcdhKeyDeriveParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#ecdsaparams",
+ "title": "EcdsaParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#eckeygenparams",
+ "title": "EcKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#eckeyimportparams",
+ "title": "EcKeyImportParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#ed448params",
+ "title": "Ed448Params",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#hkdfparams",
+ "title": "HkdfParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#hmacimportparams",
+ "title": "HmacImportParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#hmackeygenparams",
+ "title": "HmacKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#pbkdf2params",
+ "title": "Pbkdf2Params",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#rsahashedimportparams",
+ "title": "RsaHashedImportParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#rsahashedkeygenparams",
+ "title": "RsaHashedKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#rsaoaepparams",
+ "title": "RsaOaepParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#rsapssparams",
+ "title": "RsaPssParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webcrypto/#subtlecrypto",
+ "title": "SubtleCrypto",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v18/webstreams/",
+ "title": "Web Streams API",
+ "type": "module",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#bytelengthqueuingstrategy",
+ "title": "ByteLengthQueuingStrategy",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#compressionstream",
+ "title": "CompressionStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#countqueuingstrategy",
+ "title": "CountQueuingStrategy",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#decompressionstream",
+ "title": "DecompressionStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#readablebytestreamcontroller",
+ "title": "ReadableByteStreamController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#readablestream",
+ "title": "ReadableStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#readablestreambyobreader",
+ "title": "ReadableStreamBYOBReader",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#readablestreambyobrequest",
+ "title": "ReadableStreamBYOBRequest",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#readablestreamdefaultcontroller",
+ "title": "ReadableStreamDefaultController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#readablestreamdefaultreader",
+ "title": "ReadableStreamDefaultReader",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#textdecoderstream",
+ "title": "TextDecoderStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#textencoderstream",
+ "title": "TextEncoderStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#transformstream",
+ "title": "TransformStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#transformstreamdefaultcontroller",
+ "title": "TransformStreamDefaultController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#writablestream",
+ "title": "WritableStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#writablestreamdefaultcontroller",
+ "title": "WritableStreamDefaultController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/webstreams/#writablestreamdefaultwriter",
+ "title": "WritableStreamDefaultWriter",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v18/worker_threads/",
+ "title": "Worker threads",
+ "type": "module",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v18/worker_threads/#broadcastchannel-extends-eventtarget",
+ "title": "BroadcastChannel extends EventTarget",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v18/worker_threads/#messagechannel",
+ "title": "MessageChannel",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v18/worker_threads/#messageport",
+ "title": "MessagePort",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v18/worker_threads/#worker",
+ "title": "Worker",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v18/zlib/",
+ "title": "Zlib",
+ "type": "module",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#brotlioptions",
+ "title": "BrotliOptions",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#options",
+ "title": "Options",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#zlibbrotlicompress",
+ "title": "zlibBrotliCompress",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#zlibbrotlidecompress",
+ "title": "zlibBrotliDecompress",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#zlibdeflate",
+ "title": "zlibDeflate",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#zlibdeflateraw",
+ "title": "zlibDeflateRaw",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#zlibgunzip",
+ "title": "zlibGunzip",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#zlibgzip",
+ "title": "zlibGzip",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#zlibinflate",
+ "title": "zlibInflate",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#zlibinflateraw",
+ "title": "zlibInflateRaw",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#zlibunzip",
+ "title": "zlibUnzip",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v18/zlib/#zlibzlibbase",
+ "title": "zlibZlibBase",
+ "type": "class",
+ "name": "zlib"
+ }
+ ]
}
\ No newline at end of file
diff --git a/content/api/v18/net.en.md b/content/api/v18/net.en.md
index cecc42979c..e4c94566b9 100644
--- a/content/api/v18/net.en.md
+++ b/content/api/v18/net.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:net` module provides an asynchronous network API for creating stream-based
TCP or [IPC][] servers ([`net.createServer()`][]) and clients
@@ -865,6 +865,14 @@ See [`writable.destroy()`][] for further details.
See [`writable.destroyed`][] for further details.
+#### `socket.destroySoon()`
+
+
+
+Destroys the socket after all data is written. If the `'finish'` event was
+already emitted the socket is destroyed immediately. If the socket is still
+writable it implicitly calls `socket.end()`.
+
#### `socket.end([data[, encoding]][, callback])`
diff --git a/content/api/v18/os.en.md b/content/api/v18/os.en.md
index 8bed8ab276..d5c1dcfff8 100644
--- a/content/api/v18/os.en.md
+++ b/content/api/v18/os.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:os` module provides operating system-related utility methods and
properties. It can be accessed using:
diff --git a/content/api/v18/packages.en.md b/content/api/v18/packages.en.md
index 238807f9c1..aecfbbf287 100644
--- a/content/api/v18/packages.en.md
+++ b/content/api/v18/packages.en.md
@@ -478,7 +478,7 @@ targets, this expansion is dependent on only the files of the package itself.
To exclude private subfolders from patterns, `null` targets can be used:
-```json
+```json|js
// ./node_modules/es-module-package/package.json
{
"exports": {
@@ -486,9 +486,7 @@ To exclude private subfolders from patterns, `null` targets can be used:
"./features/private-internal/*": null
}
}
-```
-
-```js
+--------------
import featureInternal from 'es-module-package/features/private-internal/m.js';
// Throws: ERR_PACKAGE_PATH_NOT_EXPORTED
@@ -717,25 +715,21 @@ const { something } = require('a-package/foo.js'); // Loads from ./foo.js.
Finally, self-referencing also works with scoped packages. For example, this
code will also work:
-```json
+```json|cjs
// package.json
{
"name": "@my/package",
"exports": "./index.js"
}
-```
-
-```cjs
+--------------
// ./index.js
module.exports = 42;
```
-```cjs
+```cjs|console
// ./other.js
console.log(require('@my/package'));
-```
-
-```console
+--------------
$ node other.js
42
```
@@ -837,12 +831,10 @@ to be treated as ES modules, just as `"type": "commonjs"` would cause them
to be treated as CommonJS.
See [Enabling](esm.md#enabling).
-```cjs
+```cjs|js
// ./node_modules/pkg/index.cjs
exports.name = 'value';
-```
-
-```js
+--------------
// ./node_modules/pkg/wrapper.mjs
import cjsModule from './index.cjs';
export const name = cjsModule.name;
@@ -1109,14 +1101,12 @@ The nearest parent `package.json` is defined as the first `package.json` found
when searching in the current folder, that folder's parent, and so on up
until a node\_modules folder or the volume root is reached.
-```json
+```json|bash
// package.json
{
"type": "module"
}
-```
-
-```bash
+--------------
# In same folder as preceding package.json
node my-app.js # Runs as ES module
```
diff --git a/content/api/v18/path.en.md b/content/api/v18/path.en.md
index 5590439541..3bdb8da1f1 100644
--- a/content/api/v18/path.en.md
+++ b/content/api/v18/path.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:path` module provides utilities for working with file and directory
paths. It can be accessed using:
@@ -375,7 +375,7 @@ The returned object will have the following properties:
For example, on POSIX:
-```js
+```js|text
path.parse('/home/user/dir/file.txt');
// Returns:
// { root: '/',
@@ -383,9 +383,7 @@ path.parse('/home/user/dir/file.txt');
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
-```
-
-```text
+--------------
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
@@ -397,7 +395,7 @@ path.parse('/home/user/dir/file.txt');
On Windows:
-```js
+```js|text
path.parse('C:\\path\\dir\\file.txt');
// Returns:
// { root: 'C:\\',
@@ -405,9 +403,7 @@ path.parse('C:\\path\\dir\\file.txt');
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
-```
-
-```text
+--------------
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
diff --git a/content/api/v18/perf_hooks.en.md b/content/api/v18/perf_hooks.en.md
index f0049ad070..fadebc5fb3 100644
--- a/content/api/v18/perf_hooks.en.md
+++ b/content/api/v18/perf_hooks.en.md
@@ -13,7 +13,7 @@ Stable
-
+
This module provides an implementation of a subset of the W3C
[Web Performance APIs][] as well as additional APIs for
diff --git a/content/api/v18/permissions.en.md b/content/api/v18/permissions.en.md
index 0d889f31eb..63dd223973 100644
--- a/content/api/v18/permissions.en.md
+++ b/content/api/v18/permissions.en.md
@@ -395,7 +395,7 @@ The following example, would allow access to `fs` for all `data:` resources:
Given an import map:
-```json
+```json|json
{
"imports": {
"react": "./app/node_modules/react/index.js"
@@ -406,9 +406,7 @@ Given an import map:
}
}
}
-```
-
-```json
+--------------
{
"dependencies": true,
"scopes": {
diff --git a/content/api/v18/process.en.md b/content/api/v18/process.en.md
index 9c7165ffff..c30b24bfdb 100644
--- a/content/api/v18/process.en.md
+++ b/content/api/v18/process.en.md
@@ -9,16 +9,14 @@ version: 'v18'
-
+
The `process` object provides information about, and control over, the current
Node.js process.
-```mjs
+```mjs|cjs
import process from 'node:process';
-```
-
-```cjs
+--------------
const process = require('node:process');
```
@@ -45,7 +43,7 @@ termination, such as calling [`process.exit()`][] or uncaught exceptions.
The `'beforeExit'` should _not_ be used as an alternative to the `'exit'` event
unless the intention is to schedule additional work.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('beforeExit', (code) => {
@@ -62,9 +60,7 @@ console.log('This message is displayed first.');
// This message is displayed first.
// Process beforeExit event with code: 0
// Process exit event with code: 0
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('beforeExit', (code) => {
@@ -110,15 +106,13 @@ The listener callback function is invoked with the exit code specified either
by the [`process.exitCode`][] property, or the `exitCode` argument passed to the
[`process.exit()`][] method.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('exit', (code) => {
console.log(`About to exit with code: ${code}`);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('exit', (code) => {
@@ -131,7 +125,7 @@ process will exit immediately after calling the `'exit'` event listeners
causing any additional work still queued in the event loop to be abandoned.
In the following example, for instance, the timeout will never occur:
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('exit', (code) => {
@@ -139,9 +133,7 @@ process.on('exit', (code) => {
console.log('This will not run');
}, 0);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('exit', (code) => {
@@ -203,7 +195,7 @@ example, [`Promise.race()`][] can trigger a `'multipleResolves'` event.
Because of the unreliability of the event in cases like the
[`Promise.race()`][] example above it has been deprecated.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('multipleResolves', (type, promise, reason) => {
@@ -230,9 +222,7 @@ main().then(console.log);
// at new Promise ()
// at main (*)
// First call
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('multipleResolves', (type, promise, reason) => {
@@ -291,7 +281,7 @@ In asynchronous code, the `'unhandledRejection'` event is emitted when the list
of unhandled rejections grows, and the `'rejectionHandled'` event is emitted
when the list of unhandled rejections shrinks.
-```mjs
+```mjs|cjs
import process from 'node:process';
const unhandledRejections = new Map();
@@ -301,9 +291,7 @@ process.on('unhandledRejection', (reason, promise) => {
process.on('rejectionHandled', (promise) => {
unhandledRejections.delete(promise);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
const unhandledRejections = new Map();
@@ -344,7 +332,7 @@ behavior. Alternatively, change the [`process.exitCode`][] in the
provided exit code. Otherwise, in the presence of such handler the process will
exit with 0.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('uncaughtException', (err, origin) => {
@@ -362,9 +350,7 @@ setTimeout(() => {
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('uncaughtException', (err, origin) => {
@@ -436,7 +422,7 @@ Installing an `'uncaughtExceptionMonitor'` listener does not change the behavior
once an `'uncaughtException'` event is emitted. The process will
still crash if no `'uncaughtException'` listener is installed.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('uncaughtExceptionMonitor', (err, origin) => {
@@ -446,9 +432,7 @@ process.on('uncaughtExceptionMonitor', (err, origin) => {
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
// Still crashes Node.js
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('uncaughtExceptionMonitor', (err, origin) => {
@@ -476,7 +460,7 @@ are propagated through a `Promise` chain. The `'unhandledRejection'` event is
useful for detecting and keeping track of promises that were rejected whose
rejections have not yet been handled.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('unhandledRejection', (reason, promise) => {
@@ -487,9 +471,7 @@ process.on('unhandledRejection', (reason, promise) => {
somePromise.then((res) => {
return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)
}); // No `.catch()` or `.then()`
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('unhandledRejection', (reason, promise) => {
@@ -505,7 +487,7 @@ somePromise.then((res) => {
The following will also trigger the `'unhandledRejection'` event to be
emitted:
-```mjs
+```mjs|cjs
import process from 'node:process';
function SomeResource() {
@@ -515,9 +497,7 @@ function SomeResource() {
const resource = new SomeResource();
// no .catch or .then on resource.loaded for at least a turn
-```
-
-```cjs
+--------------
const process = require('node:process');
function SomeResource() {
@@ -554,7 +534,7 @@ are not part of the normal Node.js and JavaScript error handling flow.
Node.js can emit warnings whenever it detects bad coding practices that could
lead to sub-optimal application performance, bugs, or security vulnerabilities.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('warning', (warning) => {
@@ -562,9 +542,7 @@ process.on('warning', (warning) => {
console.warn(warning.message); // Print the warning message
console.warn(warning.stack); // Print the stack trace
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('warning', (warning) => {
@@ -671,7 +649,7 @@ The signal handler will receive the signal's name (`'SIGINT'`,
The name of each event will be the uppercase common name for the signal (e.g.
`'SIGINT'` for `SIGINT` signals).
-```mjs
+```mjs|cjs
import process from 'node:process';
// Begin reading from stdin so the process does not exit.
@@ -688,9 +666,7 @@ function handle(signal) {
process.on('SIGINT', handle);
process.on('SIGTERM', handle);
-```
-
-```cjs
+--------------
const process = require('node:process');
// Begin reading from stdin so the process does not exit.
@@ -793,7 +769,7 @@ appear only _once_; each will begin with one or more dashes. Flags
passed through to V8 will contain underscores instead of non-leading
dashes:
-```mjs
+```mjs|cjs
import { allowedNodeEnvironmentFlags } from 'node:process';
allowedNodeEnvironmentFlags.forEach((flag) => {
@@ -802,9 +778,7 @@ allowedNodeEnvironmentFlags.forEach((flag) => {
// --abort_on_uncaught_exception
// ...
});
-```
-
-```cjs
+--------------
const { allowedNodeEnvironmentFlags } = require('node:process');
allowedNodeEnvironmentFlags.forEach((flag) => {
@@ -833,13 +807,11 @@ The operating system CPU architecture for which the Node.js binary was compiled.
Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,
`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`.
-```mjs
+```mjs|cjs
import { arch } from 'node:process';
console.log(`This processor architecture is ${arch}`);
-```
-
-```cjs
+--------------
const { arch } = require('node:process');
console.log(`This processor architecture is ${arch}`);
@@ -860,16 +832,14 @@ arguments.
For example, assuming the following script for `process-args.js`:
-```mjs
+```mjs|cjs
import { argv } from 'node:process';
// print process.argv
argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
-```
-
-```cjs
+--------------
const { argv } = require('node:process');
// print process.argv
@@ -954,7 +924,7 @@ The `process.chdir()` method changes the current working directory of the
Node.js process or throws an exception if doing so fails (for instance, if
the specified `directory` does not exist).
-```mjs
+```mjs|cjs
import { chdir, cwd } from 'node:process';
console.log(`Starting directory: ${cwd()}`);
@@ -964,9 +934,7 @@ try {
} catch (err) {
console.error(`chdir: ${err}`);
}
-```
-
-```cjs
+--------------
const { chdir, cwd } = require('node:process');
console.log(`Starting directory: ${cwd()}`);
@@ -1043,6 +1011,25 @@ and [Cluster][] documentation), the `process.connected` property will return
Once `process.connected` is `false`, it is no longer possible to send messages
over the IPC channel using `process.send()`.
+### `process.constrainedMemory()`
+
+
+
+
+
+Experimental
+
+
+
+* [`number`](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)
+
+Gets the amount of memory available to the process (in bytes) based on
+limits imposed by the OS. If there is no such constraint, or the constraint
+is unknown, `undefined` is returned.
+
+See [`uv_get_constrained_memory`][uv_get_constrained_memory] for more
+information.
+
### `process.cpuUsage([previousValue])`
@@ -1062,7 +1049,7 @@ actual elapsed time if multiple CPU cores are performing work for this process.
The result of a previous call to `process.cpuUsage()` can be passed as the
argument to the function, to get a diff reading.
-```mjs
+```mjs|cjs
import { cpuUsage } from 'node:process';
const startUsage = cpuUsage();
@@ -1074,9 +1061,7 @@ while (Date.now() - now < 500);
console.log(cpuUsage(startUsage));
// { user: 514883, system: 11226 }
-```
-
-```cjs
+--------------
const { cpuUsage } = require('node:process');
const startUsage = cpuUsage();
@@ -1099,13 +1084,11 @@ console.log(cpuUsage(startUsage));
The `process.cwd()` method returns the current working directory of the Node.js
process.
-```mjs
+```mjs|cjs
import { cwd } from 'node:process';
console.log(`Current directory: ${cwd()}`);
-```
-
-```cjs
+--------------
const { cwd } = require('node:process');
console.log(`Current directory: ${cwd()}`);
@@ -1119,13 +1102,11 @@ console.log(`Current directory: ${cwd()}`);
The port used by the Node.js debugger when enabled.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.debugPort = 5858;
-```
-
-```cjs
+--------------
const process = require('node:process');
process.debugPort = 5858;
@@ -1172,7 +1153,7 @@ that exports a `foo` function. All the symbols are loaded before
the call returns, by passing the `RTLD_NOW` constant. In this example
the constant is assumed to be available.
-```mjs
+```mjs|cjs
import { dlopen } from 'node:process';
import { constants } from 'node:os';
import { fileURLToPath } from 'node:url';
@@ -1181,9 +1162,7 @@ const module = { exports: {} };
dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)),
constants.dlopen.RTLD_NOW);
module.exports.foo();
-```
-
-```cjs
+--------------
const { dlopen } = require('node:process');
const { constants } = require('node:os');
const { join } = require('node:path');
@@ -1211,7 +1190,7 @@ The `process.emitWarning()` method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
[`'warning'`][process_warning] event.
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning with a code and additional detail.
@@ -1222,9 +1201,7 @@ emitWarning('Something happened!', {
// Emits:
// (node:56338) [MY_WARNING] Warning: Something happened!
// This is some additional information
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning with a code and additional detail.
@@ -1241,7 +1218,7 @@ In this example, an `Error` object is generated internally by
`process.emitWarning()` and passed through to the
[`'warning'`][process_warning] handler.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('warning', (warning) => {
@@ -1251,9 +1228,7 @@ process.on('warning', (warning) => {
console.warn(warning.stack); // Stack trace
console.warn(warning.detail); // 'This is some additional information'
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('warning', (warning) => {
@@ -1283,15 +1258,13 @@ The `process.emitWarning()` method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
[`'warning'`][process_warning] event.
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning using a string.
emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning using a string.
@@ -1299,15 +1272,13 @@ emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
```
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning using a string and a type.
emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning using a string and a type.
@@ -1315,14 +1286,12 @@ emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!
```
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
emitWarning('Something happened!', 'CustomWarning', 'WARN001');
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');
@@ -1333,7 +1302,7 @@ In each of the previous examples, an `Error` object is generated internally by
`process.emitWarning()` and passed through to the [`'warning'`][process_warning]
handler.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('warning', (warning) => {
@@ -1342,9 +1311,7 @@ process.on('warning', (warning) => {
console.warn(warning.code);
console.warn(warning.stack);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('warning', (warning) => {
@@ -1359,7 +1326,7 @@ If `warning` is passed as an `Error` object, it will be passed through to the
`'warning'` event handler unmodified (and the optional `type`,
`code` and `ctor` arguments will be ignored):
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning using an Error object.
@@ -1370,9 +1337,7 @@ myWarning.code = 'WARN001';
emitWarning(myWarning);
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning using an Error object.
@@ -1406,7 +1371,7 @@ The following additional handling is implemented if the warning `type` is
As a best practice, warnings should be emitted only once per process. To do
so, place the `emitWarning()` behind a boolean.
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
function emitMyWarning() {
@@ -1419,9 +1384,7 @@ emitMyWarning();
// Emits: (node: 56339) Warning: Only warn once!
emitMyWarning();
// Emits nothing
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
function emitMyWarning() {
@@ -1473,14 +1436,12 @@ $ node -e 'process.env.foo = "bar"' && echo $foo
While the following will:
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.foo = 'bar';
@@ -1491,7 +1452,7 @@ Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.test = null;
@@ -1500,9 +1461,7 @@ console.log(env.test);
env.test = undefined;
console.log(env.test);
// => 'undefined'
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.test = null;
@@ -1515,16 +1474,14 @@ console.log(env.test);
Use `delete` to delete a property from `process.env`.
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.TEST = 1;
@@ -1535,15 +1492,13 @@ console.log(env.TEST);
On Windows operating systems, environment variables are case-insensitive.
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.TEST = 1;
@@ -1617,13 +1572,11 @@ called.
To exit with a 'failure' code:
-```mjs
+```mjs|cjs
import { exit } from 'node:process';
exit(1);
-```
-
-```cjs
+--------------
const { exit } = require('node:process');
exit(1);
@@ -1645,7 +1598,7 @@ For instance, the following example illustrates a _misuse_ of the
`process.exit()` method that could lead to data printed to stdout being
truncated and lost:
-```mjs
+```mjs|cjs
import { exit } from 'node:process';
// This is an example of what *not* to do:
@@ -1653,9 +1606,7 @@ if (someConditionNotMet()) {
printUsageToStdout();
exit(1);
}
-```
-
-```cjs
+--------------
const { exit } = require('node:process');
// This is an example of what *not* to do:
@@ -1674,7 +1625,7 @@ Rather than calling `process.exit()` directly, the code _should_ set the
`process.exitCode` and allow the process to exit naturally by avoiding
scheduling any additional work for the event loop:
-```mjs
+```mjs|cjs
import process from 'node:process';
// How to properly set the exit code while letting
@@ -1683,9 +1634,7 @@ if (someConditionNotMet()) {
printUsageToStdout();
process.exitCode = 1;
}
-```
-
-```cjs
+--------------
const process = require('node:process');
// How to properly set the exit code while letting
@@ -1732,7 +1681,7 @@ The `process.getActiveResourcesInfo()` method returns an array of strings
containing the types of the active resources that are currently keeping the
event loop alive.
-```mjs
+```mjs|cjs
import { getActiveResourcesInfo } from 'node:process';
import { setTimeout } from 'node:timers';
@@ -1742,9 +1691,7 @@ console.log('After:', getActiveResourcesInfo());
// Prints:
// Before: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap' ]
// After: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]
-```
-
-```cjs
+--------------
const { getActiveResourcesInfo } = require('node:process');
const { setTimeout } = require('node:timers');
@@ -1763,15 +1710,13 @@ console.log('After:', getActiveResourcesInfo());
The `process.getegid()` method returns the numerical effective group identity
of the Node.js process. (See getegid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getegid) {
console.log(`Current gid: ${process.getegid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getegid) {
@@ -1791,15 +1736,13 @@ Android).
The `process.geteuid()` method returns the numerical effective user identity of
the process. (See geteuid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.geteuid) {
console.log(`Current uid: ${process.geteuid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.geteuid) {
@@ -1819,15 +1762,13 @@ Android).
The `process.getgid()` method returns the numerical group identity of the
process. (See getgid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgid) {
console.log(`Current gid: ${process.getgid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgid) {
@@ -1848,15 +1789,13 @@ The `process.getgroups()` method returns an array with the supplementary group
IDs. POSIX leaves it unspecified if the effective group ID is included but
Node.js ensures it always is.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgroups) {
console.log(process.getgroups()); // [ 16, 21, 297 ]
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgroups) {
@@ -1876,15 +1815,13 @@ Android).
The `process.getuid()` method returns the numeric user identity of the process.
(See getuid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getuid) {
console.log(`Current uid: ${process.getuid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getuid) {
@@ -1934,7 +1871,7 @@ These times are relative to an arbitrary time in the
past, and not related to the time of day and therefore not subject to clock
drift. The primary use is for measuring performance between intervals:
-```mjs
+```mjs|cjs
import { hrtime } from 'node:process';
const NS_PER_SEC = 1e9;
@@ -1948,9 +1885,7 @@ setTimeout(() => {
console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
// Benchmark took 1000000552 nanoseconds
}, 1000);
-```
-
-```cjs
+--------------
const { hrtime } = require('node:process');
const NS_PER_SEC = 1e9;
@@ -1979,7 +1914,7 @@ Unlike [`process.hrtime()`][], it does not support an additional `time`
argument since the difference can just be computed directly
by subtraction of the two `bigint`s.
-```mjs
+```mjs|cjs
import { hrtime } from 'node:process';
const start = hrtime.bigint();
@@ -1992,9 +1927,7 @@ setTimeout(() => {
console.log(`Benchmark took ${end - start} nanoseconds`);
// Benchmark took 1154389282 nanoseconds
}, 1000);
-```
-
-```cjs
+--------------
const { hrtime } = require('node:process');
const start = hrtime.bigint();
@@ -2023,7 +1956,7 @@ access or the `CAP_SETGID` capability.
Use care when dropping privileges:
-```mjs
+```mjs|cjs
import { getgroups, initgroups, setgid } from 'node:process';
console.log(getgroups()); // [ 0 ]
@@ -2031,9 +1964,7 @@ initgroups('nodeuser', 1000); // switch user
console.log(getgroups()); // [ 27, 30, 46, 1000, 0 ]
setgid(1000); // drop root gid
console.log(getgroups()); // [ 27, 30, 46, 1000 ]
-```
-
-```cjs
+--------------
const { getgroups, initgroups, setgid } = require('node:process');
console.log(getgroups()); // [ 0 ]
@@ -2070,7 +2001,7 @@ Even though the name of this function is `process.kill()`, it is really just a
signal sender, like the `kill` system call. The signal sent may do something
other than kill the target process.
-```mjs
+```mjs|cjs
import process, { kill } from 'node:process';
process.on('SIGHUP', () => {
@@ -2083,9 +2014,7 @@ setTimeout(() => {
}, 100);
kill(process.pid, 'SIGHUP');
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('SIGHUP', () => {
@@ -2138,7 +2067,7 @@ is no entry script.
Returns an object describing the memory usage of the Node.js process measured in
bytes.
-```mjs
+```mjs|cjs
import { memoryUsage } from 'node:process';
console.log(memoryUsage());
@@ -2150,9 +2079,7 @@ console.log(memoryUsage());
// external: 49879,
// arrayBuffers: 9386
// }
-```
-
-```cjs
+--------------
const { memoryUsage } = require('node:process');
console.log(memoryUsage());
@@ -2201,14 +2128,12 @@ process, including all C++ and JavaScript objects and code.
This is the same value as the `rss` property provided by `process.memoryUsage()`
but `process.memoryUsage.rss()` is faster.
-```mjs
+```mjs|cjs
import { memoryUsage } from 'node:process';
console.log(memoryUsage.rss());
// 35655680
-```
-
-```cjs
+--------------
const { rss } = require('node:process');
console.log(memoryUsage.rss());
@@ -2228,7 +2153,7 @@ completion and before the event loop is allowed to continue. It's possible to
create an infinite loop if one were to recursively call `process.nextTick()`.
See the [Event Loop][] guide for more background.
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
console.log('start');
@@ -2240,9 +2165,7 @@ console.log('scheduled');
// start
// scheduled
// nextTick callback
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
console.log('start');
@@ -2260,7 +2183,7 @@ This is important when developing APIs in order to give users the opportunity
to assign event handlers _after_ an object has been constructed but before any
I/O has occurred:
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
function MyThing(options) {
@@ -2275,9 +2198,7 @@ const thing = new MyThing();
thing.getReadyForStuff();
// thing.startDoingStuff() gets called now, not before.
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
function MyThing(options) {
@@ -2325,7 +2246,7 @@ It is not clear whether `foo()` or `bar()` will be called first.
The following approach is much better:
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
function definitelyAsync(arg, cb) {
@@ -2336,9 +2257,7 @@ function definitelyAsync(arg, cb) {
fs.stat('file', cb);
}
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
function definitelyAsync(arg, cb) {
@@ -2359,7 +2278,7 @@ execute the then, catch, and finally handlers of resolved promises. Within
Node.js, every time the "next tick queue" is drained, the microtask queue
is drained immediately after.
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
Promise.resolve().then(() => console.log(2));
@@ -2369,9 +2288,7 @@ nextTick(() => console.log(1));
// 1
// 2
// 3
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
Promise.resolve().then(() => console.log(2));
@@ -2449,13 +2366,11 @@ flag's behavior.
The `process.pid` property returns the PID of the process.
-```mjs
+```mjs|cjs
import { pid } from 'node:process';
console.log(`This process is pid ${pid}`);
-```
-
-```cjs
+--------------
const { pid } = require('node:process');
console.log(`This process is pid ${pid}`);
@@ -2480,13 +2395,11 @@ Currently possible values are:
* `'sunos'`
* `'win32'`
-```mjs
+```mjs|cjs
import { platform } from 'node:process';
console.log(`This platform is ${platform}`);
-```
-
-```cjs
+--------------
const { platform } = require('node:process');
console.log(`This platform is ${platform}`);
@@ -2505,13 +2418,11 @@ Android operating system. However, Android support in Node.js
The `process.ppid` property returns the PID of the parent of the
current process.
-```mjs
+```mjs|cjs
import { ppid } from 'node:process';
console.log(`The parent process is pid ${ppid}`);
-```
-
-```cjs
+--------------
const { ppid } = require('node:process');
console.log(`The parent process is pid ${ppid}`);
@@ -2583,13 +2494,11 @@ Write reports in a compact format, single-line JSON, more easily consumable
by log processing systems than the default multi-line format designed for
human consumption.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Reports are compact? ${report.compact}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Reports are compact? ${report.compact}`);
@@ -2605,13 +2514,11 @@ Directory where the report is written. The default value is the empty string,
indicating that reports are written to the current working directory of the
Node.js process.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report directory is ${report.directory}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report directory is ${report.directory}`);
@@ -2630,13 +2537,11 @@ value is the empty string.
If the value of `process.report.filename` is set to `'stdout'` or `'stderr'`,
the report is written to the stdout or stderr of the process respectively.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report filename is ${report.filename}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report filename is ${report.filename}`);
@@ -2653,7 +2558,7 @@ Returns a JavaScript Object representation of a diagnostic report for the
running process. The report's JavaScript stack trace is taken from `err`, if
present.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
const data = report.getReport();
@@ -2662,9 +2567,7 @@ console.log(data.header.nodejsVersion);
// Similar to process.report.writeReport()
import fs from 'node:fs';
fs.writeFileSync('my-report.log', util.inspect(data), 'utf8');
-```
-
-```cjs
+--------------
const { report } = require('node:process');
const data = report.getReport();
@@ -2686,13 +2589,11 @@ Additional documentation is available in the [report documentation][].
If `true`, a diagnostic report is generated on fatal errors, such as out of
memory errors or failed C++ assertions.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report on fatal error: ${report.reportOnFatalError}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report on fatal error: ${report.reportOnFatalError}`);
@@ -2707,13 +2608,11 @@ console.log(`Report on fatal error: ${report.reportOnFatalError}`);
If `true`, a diagnostic report is generated when the process receives the
signal specified by `process.report.signal`.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report on signal: ${report.reportOnSignal}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report on signal: ${report.reportOnSignal}`);
@@ -2727,13 +2626,11 @@ console.log(`Report on signal: ${report.reportOnSignal}`);
If `true`, a diagnostic report is generated on uncaught exception.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report on exception: ${report.reportOnUncaughtException}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report on exception: ${report.reportOnUncaughtException}`);
@@ -2748,13 +2645,11 @@ console.log(`Report on exception: ${report.reportOnUncaughtException}`);
The signal used to trigger the creation of a diagnostic report. Defaults to
`'SIGUSR2'`.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report signal: ${report.signal}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report signal: ${report.signal}`);
@@ -2780,13 +2675,11 @@ JavaScript stack trace is taken from `err`, if present.
If the value of `filename` is set to `'stdout'` or `'stderr'`, the report is
written to the stdout or stderr of the process respectively.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
report.writeReport();
-```
-
-```cjs
+--------------
const { report } = require('node:process');
report.writeReport();
@@ -2841,7 +2734,7 @@ Additional documentation is available in the [report documentation][].
process becoming runnable or because the current process exceeded its
time slice. This field is not supported on Windows.
-```mjs
+```mjs|cjs
import { resourceUsage } from 'node:process';
console.log(resourceUsage());
@@ -2866,9 +2759,7 @@ console.log(resourceUsage());
involuntaryContextSwitches: 1
}
*/
-```
-
-```cjs
+--------------
const { resourceUsage } = require('node:process');
console.log(resourceUsage());
@@ -2930,7 +2821,7 @@ The `process.setegid()` method sets the effective group identity of the process.
name string. If a group name is specified, this method blocks while resolving
the associated a numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getegid && process.setegid) {
@@ -2942,9 +2833,7 @@ if (process.getegid && process.setegid) {
console.error(`Failed to set gid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getegid && process.setegid) {
@@ -2973,7 +2862,7 @@ The `process.seteuid()` method sets the effective user identity of the process.
string. If a username is specified, the method blocks while resolving the
associated numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.geteuid && process.seteuid) {
@@ -2985,9 +2874,7 @@ if (process.geteuid && process.seteuid) {
console.error(`Failed to set uid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.geteuid && process.seteuid) {
@@ -3016,7 +2903,7 @@ setgid(2).) The `id` can be passed as either a numeric ID or a group name
string. If a group name is specified, this method blocks while resolving the
associated numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgid && process.setgid) {
@@ -3028,9 +2915,7 @@ if (process.getgid && process.setgid) {
console.error(`Failed to set gid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgid && process.setgid) {
@@ -3060,7 +2945,7 @@ process to have `root` or the `CAP_SETGID` capability.
The `groups` array can contain numeric group IDs, group names, or both.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgroups && process.setgroups) {
@@ -3071,9 +2956,7 @@ if (process.getgroups && process.setgroups) {
console.error(`Failed to set groups: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgroups && process.setgroups) {
@@ -3101,7 +2984,7 @@ setuid(2).) The `id` can be passed as either a numeric ID or a username string.
If a username is specified, the method blocks while resolving the associated
numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getuid && process.setuid) {
@@ -3113,9 +2996,7 @@ if (process.getuid && process.setuid) {
console.error(`Failed to set uid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getuid && process.setuid) {
@@ -3236,13 +3117,11 @@ a [Writable][] stream.
For example, to copy `process.stdin` to `process.stdout`:
-```mjs
+```mjs|cjs
import { stdin, stdout } from 'node:process';
stdin.pipe(stdout);
-```
-
-```cjs
+--------------
const { stdin, stdout } = require('node:process');
stdin.pipe(stdout);
@@ -3393,7 +3272,7 @@ processes inherit the mask from the parent process.
`process.umask(mask)` sets the Node.js process's file mode creation mask. Child
processes inherit the mask from the parent process. Returns the previous mask.
-```mjs
+```mjs|cjs
import { umask } from 'node:process';
const newmask = 0o022;
@@ -3401,9 +3280,7 @@ const oldmask = umask(newmask);
console.log(
`Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`,
);
-```
-
-```cjs
+--------------
const { umask } = require('node:process');
const newmask = 0o022;
@@ -3435,14 +3312,12 @@ seconds.
The `process.version` property contains the Node.js version string.
-```mjs
+```mjs|cjs
import { version } from 'node:process';
console.log(`Version: ${version}`);
// Version: v14.8.0
-```
-
-```cjs
+--------------
const { version } = require('node:process');
console.log(`Version: ${version}`);
@@ -3463,13 +3338,11 @@ Node.js and its dependencies. `process.versions.modules` indicates the current
ABI version, which is increased whenever a C++ API changes. Node.js will refuse
to load modules that were compiled against a different module ABI version.
-```mjs
+```mjs|cjs
import { versions } from 'node:process';
console.log(versions);
-```
-
-```cjs
+--------------
const { versions } = require('node:process');
console.log(versions);
@@ -3604,6 +3477,7 @@ cases:
[process_warning]: #event-warning
[report documentation]: /api/v18/report
[terminal raw mode]: /api/v18/tty#readstreamsetrawmodemode
+[uv_get_constrained_memory]: https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory
[uv_rusage_t]: https://docs.libuv.org/en/v1.x/misc.html#c.uv_rusage_t
[wikipedia_major_fault]: https://en.wikipedia.org/wiki/Page_fault#Major
[wikipedia_minor_fault]: https://en.wikipedia.org/wiki/Page_fault#Minor
diff --git a/content/api/v18/punycode.en.md b/content/api/v18/punycode.en.md
index 1ffb0d286f..24b3dbf4d7 100644
--- a/content/api/v18/punycode.en.md
+++ b/content/api/v18/punycode.en.md
@@ -15,7 +15,7 @@ Deprecated
-
+
**The version of the punycode module bundled in Node.js is being deprecated.**
In a future major version of Node.js this module will be removed. Users
diff --git a/content/api/v18/querystring.en.md b/content/api/v18/querystring.en.md
index 9c25b78c80..384eedf006 100644
--- a/content/api/v18/querystring.en.md
+++ b/content/api/v18/querystring.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:querystring` module provides utilities for parsing and formatting URL
query strings. It can be accessed using:
diff --git a/content/api/v18/readline.en.md b/content/api/v18/readline.en.md
index 911f1f04f6..c419f72bbd 100644
--- a/content/api/v18/readline.en.md
+++ b/content/api/v18/readline.en.md
@@ -13,35 +13,31 @@ Stable
-
+
The `node:readline` module provides an interface for reading data from a
[Readable][] stream (such as [`process.stdin`][]) one line at a time.
To use the promise-based APIs:
-```mjs
+```mjs|cjs
import * as readline from 'node:readline/promises';
-```
-
-```cjs
+--------------
const readline = require('node:readline/promises');
```
To use the callback and sync APIs:
-```mjs
+```mjs|cjs
import * as readline from 'node:readline';
-```
-
-```cjs
+--------------
const readline = require('node:readline');
```
The following simple example illustrates the basic use of the `node:readline`
module.
-```mjs
+```mjs|cjs
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
@@ -52,9 +48,7 @@ const answer = await rl.question('What do you think of Node.js? ');
console.log(`Thank you for your valuable feedback: ${answer}`);
rl.close();
-```
-
-```cjs
+--------------
const readline = require('node:readline');
const { stdin: input, stdout: output } = require('node:process');
diff --git a/content/api/v18/repl.en.md b/content/api/v18/repl.en.md
index d888739755..8ec70db9d6 100644
--- a/content/api/v18/repl.en.md
+++ b/content/api/v18/repl.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation
that is available both as a standalone program or includible in other
diff --git a/content/api/v18/single-executable-applications.en.md b/content/api/v18/single-executable-applications.en.md
new file mode 100644
index 0000000000..6d2b86767d
--- /dev/null
+++ b/content/api/v18/single-executable-applications.en.md
@@ -0,0 +1,149 @@
+---
+title: 'single-executable-applications'
+displayTitle: 'Single executable applications'
+category: 'api'
+version: 'v18'
+---
+
+
+
+
+
+Experimental: This feature is being designed and will change.
+
+
+
+
+
+This feature allows the distribution of a Node.js application conveniently to a
+system that does not have Node.js installed.
+
+Node.js supports the creation of [single executable applications][] by allowing
+the injection of a JavaScript file into the `node` binary. During start up, the
+program checks if anything has been injected. If the script is found, it
+executes its contents. Otherwise Node.js operates as it normally does.
+
+The single executable application feature only supports running a single
+embedded [CommonJS][] file.
+
+A bundled JavaScript file can be turned into a single executable application
+with any tool which can inject resources into the `node` binary.
+
+Here are the steps for creating a single executable application using one such
+tool, [postject][]:
+
+1. Create a JavaScript file:
+ ```console
+ $ echo 'console.log(`Hello, $process.argv[2]!`);' > hello.js
+ ```
+
+2. Create a copy of the `node` executable and name it according to your needs:
+ ```console
+ $ cp $(command -v node) hello
+ ```
+
+3. Inject the JavaScript file into the copied binary by running `postject` with
+ the following options:
+
+ * `hello` - The name of the copy of the `node` executable created in step 2.
+ * `NODE_JS_CODE` - The name of the resource / note / section in the binary
+ where the contents of the JavaScript file will be stored.
+ * `hello.js` - The name of the JavaScript file created in step 1.
+ * `--sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2` - The
+ [fuse][] used by the Node.js project to detect if a file has been injected.
+ * `--macho-segment-name NODE_JS` (only needed on macOS) - The name of the
+ segment in the binary where the contents of the JavaScript file will be
+ stored.
+
+ To summarize, here is the required command for each platform:
+
+ * On systems other than macOS:
+ ```console
+ $ npx postject hello NODE_JS_CODE hello.js \
+ --sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2
+ ```
+
+ * On macOS:
+ ```console
+ $ npx postject hello NODE_JS_CODE hello.js \
+ --sentinel-fuse NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \
+ --macho-segment-name NODE_JS
+ ```
+
+4. Run the binary:
+ ```console
+ $ ./hello world
+ Hello, world!
+ ```
+
+### Notes
+
+#### `require(id)` in the injected module is not file based
+
+`require()` in the injected module is not the same as the [`require()`][]
+available to modules that are not injected. It also does not have any of the
+properties that non-injected [`require()`][] has except [`require.main`][]. It
+can only be used to load built-in modules. Attempting to load a module that can
+only be found in the file system will throw an error.
+
+Instead of relying on a file based `require()`, users can bundle their
+application into a standalone JavaScript file to inject into the executable.
+This also ensures a more deterministic dependency graph.
+
+However, if a file based `require()` is still needed, that can also be achieved:
+
+```js
+const { createRequire } = require('node:module');
+require = createRequire(__filename);
+```
+
+#### `__filename` and `module.filename` in the injected module
+
+The values of `__filename` and `module.filename` in the injected module are
+equal to [`process.execPath`][].
+
+#### `__dirname` in the injected module
+
+The value of `__dirname` in the injected module is equal to the directory name
+of [`process.execPath`][].
+
+#### Single executable application creation process
+
+A tool aiming to create a single executable Node.js application must
+inject the contents of a JavaScript file into:
+
+* a resource named `NODE_JS_CODE` if the `node` binary is a [PE][] file
+* a section named `NODE_JS_CODE` in the `NODE_JS` segment if the `node` binary
+ is a [Mach-O][] file
+* a note named `NODE_JS_CODE` if the `node` binary is an [ELF][] file
+
+Search the binary for the
+`NODE_JS_FUSE_fce680ab2cc467b6e072b8b5df1996b2:0` [fuse][] string and flip the
+last character to `1` to indicate that a resource has been injected.
+
+#### Platform support
+
+Single-executable support is tested regularly on CI only on the following
+platforms:
+
+* Windows
+* macOS
+* Linux (AMD64 only)
+
+This is due to a lack of better tools to generate single-executables that can be
+used to test this feature on other platforms.
+
+Suggestions for other resource injection tools/workflows are welcomed. Please
+start a discussion at [https://github.com/nodejs/single-executable/discussions](https://github.com/nodejs/single-executable/discussions)
+to help us document them.
+
+[CommonJS]: /api/v18/modules#modules-commonjs-modules
+[ELF]: https://en.wikipedia.org/wiki/Executable_and_Linkable_Format
+[Mach-O]: https://en.wikipedia.org/wiki/Mach-O
+[PE]: https://en.wikipedia.org/wiki/Portable_Executable
+[`process.execPath`]: /api/v18/process#processexecpath
+[`require()`]: /api/v18/modules#requireid
+[`require.main`]: /api/v18/modules#accessing-the-main-module
+[fuse]: https://www.electronjs.org/docs/latest/tutorial/fuses
+[postject]: https://github.com/nodejs/postject
+[single executable applications]: https://github.com/nodejs/single-executable
diff --git a/content/api/v18/stream.en.md b/content/api/v18/stream.en.md
index a912c9e300..ded99be493 100644
--- a/content/api/v18/stream.en.md
+++ b/content/api/v18/stream.en.md
@@ -13,7 +13,7 @@ Stable
-
+
A stream is an abstract interface for working with streaming data in Node.js.
The `node:stream` module provides an API for implementing the stream interface.
@@ -86,7 +86,7 @@ or `require('node:stream').promises`.
* `end` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills when the pipeline is complete.
-```cjs
+```cjs|mjs
const { pipeline } = require('node:stream/promises');
const fs = require('node:fs');
const zlib = require('node:zlib');
@@ -101,9 +101,7 @@ async function run() {
}
run().catch(console.error);
-```
-
-```mjs
+--------------
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
@@ -120,7 +118,7 @@ To use an `AbortSignal`, pass it inside an options object, as the last argument.
When the signal is aborted, `destroy` will be called on the underlying pipeline,
with an `AbortError`.
-```cjs
+```cjs|mjs
const { pipeline } = require('node:stream/promises');
const fs = require('node:fs');
const zlib = require('node:zlib');
@@ -139,9 +137,7 @@ async function run() {
}
run().catch(console.error); // AbortError
-```
-
-```mjs
+--------------
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
@@ -163,7 +159,7 @@ try {
The `pipeline` API also supports async generators:
-```cjs
+```cjs|mjs
const { pipeline } = require('node:stream/promises');
const fs = require('node:fs');
@@ -182,9 +178,7 @@ async function run() {
}
run().catch(console.error);
-```
-
-```mjs
+--------------
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
@@ -205,7 +199,7 @@ Remember to handle the `signal` argument passed into the async generator.
Especially in the case where the async generator is the source for the
pipeline (i.e. first argument) or the pipeline will never complete.
-```cjs
+```cjs|mjs
const { pipeline } = require('node:stream/promises');
const fs = require('node:fs');
@@ -221,9 +215,7 @@ async function run() {
}
run().catch(console.error);
-```
-
-```mjs
+--------------
import { pipeline } from 'node:stream/promises';
import fs from 'node:fs';
await pipeline(
@@ -251,7 +243,7 @@ The `pipeline` API provides [callback version][stream-pipeline]:
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills when the stream is no
longer readable or writable.
-```cjs
+```cjs|mjs
const { finished } = require('node:stream/promises');
const fs = require('node:fs');
@@ -264,9 +256,7 @@ async function run() {
run().catch(console.error);
rs.resume(); // Drain the stream.
-```
-
-```mjs
+--------------
import { finished } from 'node:stream/promises';
import { createReadStream } from 'node:fs';
@@ -618,7 +608,7 @@ This is a destructive and immediate way to destroy a stream. Previous calls to
Use `end()` instead of destroy if data should flush before close, or wait for
the `'drain'` event before destroying the stream.
-```cjs
+```cjs|cjs
const { Writable } = require('node:stream');
const myStream = new Writable();
@@ -626,9 +616,7 @@ const myStream = new Writable();
const fooErr = new Error('foo error');
myStream.destroy(fooErr);
myStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error
-```
-
-```cjs
+--------------
const { Writable } = require('node:stream');
const myStream = new Writable();
@@ -2070,7 +2058,7 @@ const anyBigFile = await Readable.from([
'file3',
]).some(async (fileName) => {
const stats = await stat(fileName);
- return stat.size > 1024 * 1024;
+ return stats.size > 1024 * 1024;
}, { concurrency: 2 });
console.log(anyBigFile); // `true` if any file in the list is bigger than 1MB
console.log('done'); // Stream has finished
@@ -2122,7 +2110,7 @@ const foundBigFile = await Readable.from([
'file3',
]).find(async (fileName) => {
const stats = await stat(fileName);
- return stat.size > 1024 * 1024;
+ return stats.size > 1024 * 1024;
}, { concurrency: 2 });
console.log(foundBigFile); // File name of large file, if any file in the list is bigger than 1MB
console.log('done'); // Stream has finished
@@ -2172,7 +2160,7 @@ const allBigFiles = await Readable.from([
'file3',
]).every(async (fileName) => {
const stats = await stat(fileName);
- return stat.size > 1024 * 1024;
+ return stats.size > 1024 * 1024;
}, { concurrency: 2 });
// `true` if all files in the list are bigger than 1MiB
console.log(allBigFiles);
@@ -2484,15 +2472,16 @@ const cleanup = finished(rs, (err) => {
#### `stream.pipeline(streams, callback)`
-
+
-* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]
-* `source` [`Stream`](/api/v18/stream#stream) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]|
+ ReadableStream\[]|WritableStream\[]|TransformStream\[]
+* `source` [`Stream`](/api/v18/stream#stream) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`ReadableStream`](/api/v18/webstreams#readablestream)
* Returns: [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
-* `...transforms` [`Stream`](/api/v18/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `...transforms` [`Stream`](/api/v18/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`TransformStream`](/api/v18/webstreams#transformstream)
* `source` [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
* Returns: [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
-* `destination` [`Stream`](/api/v18/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `destination` [`Stream`](/api/v18/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`WritableStream`](/api/v18/webstreams#writablestream)
* `source` [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
* Returns: [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called when the pipeline is fully done.
@@ -2564,7 +2553,7 @@ const server = http.createServer((req, res) => {
#### `stream.compose(...streams)`
-
+
@@ -2572,7 +2561,8 @@ const server = http.createServer((req, res) => {
-* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]
+* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]|
+ ReadableStream\[]|WritableStream\[]|TransformStream\[]
* Returns: [`stream.Duplex`](/api/v18/stream#streamduplex)
Combines two or more streams into a `Duplex` stream that writes to the
@@ -2777,8 +2767,14 @@ Experimental
* `streamReadable` [`stream.Readable`](/api/v18/stream#streamreadable)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `strategy` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `size` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+ * `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The maximum internal queue size (of the created
+ `ReadableStream`) before backpressure is applied in reading from the given
+ `stream.Readable`. If no value is provided, it will be taken from the
+ given `stream.Readable`.
+ * `size` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A function that size of the given chunk of data.
+ If no value is provided, the size will be `1` for all the chunks.
+ * `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+ * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`ReadableStream`](/api/v18/webstreams#readablestream)
#### `stream.Writable.fromWeb(writableStream[, options])`
@@ -2872,7 +2868,7 @@ Experimental
* `signal` [`AbortSignal`](/api/v18/globals#abortsignal)
* Returns: [`stream.Duplex`](/api/v18/stream#streamduplex)
-```mjs
+```mjs|cjs
import { Duplex } from 'node:stream';
import {
ReadableStream,
@@ -2902,9 +2898,7 @@ duplex.write('hello');
for await (const chunk of duplex) {
console.log('readable', chunk);
}
-```
-
-```cjs
+--------------
const { Duplex } = require('node:stream');
const {
ReadableStream,
@@ -2948,7 +2942,7 @@ Experimental
* `readable` [`ReadableStream`](/api/v18/webstreams#readablestream)
* `writable` [`WritableStream`](/api/v18/webstreams#writablestream)
-```mjs
+```mjs|cjs
import { Duplex } from 'node:stream';
const duplex = Duplex({
@@ -2968,9 +2962,7 @@ writable.getWriter().write('hello');
const { value } = await readable.getReader().read();
console.log('readable', value);
-```
-
-```cjs
+--------------
const { Duplex } = require('node:stream');
const duplex = Duplex({
@@ -2995,17 +2987,19 @@ readable.getReader().read().then((result) => {
#### `stream.addAbortSignal(signal, stream)`
-
+
* `signal` [`AbortSignal`](/api/v18/globals#abortsignal) A signal representing possible cancellation
-* `stream` [`Stream`](/api/v18/stream#stream) a stream to attach a signal to
+* `stream` [`Stream`](/api/v18/stream#stream) | [`ReadableStream`](/api/v18/webstreams#readablestream) | [`WritableStream`](/api/v18/webstreams#writablestream)
+
+A stream to attach a signal to.
Attaches an AbortSignal to a readable or writeable stream. This lets code
control stream destruction using an `AbortController`.
Calling `abort` on the `AbortController` corresponding to the passed
`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`
-on the stream.
+on the stream, and `controller.error(new AbortError())` for webstreams.
```js
const fs = require('node:fs');
@@ -3043,6 +3037,37 @@ const stream = addAbortSignal(
})();
```
+Or using an `AbortSignal` with a ReadableStream:
+
+```js
+const controller = new AbortController();
+const rs = new ReadableStream({
+ start(controller) {
+ controller.enqueue('hello');
+ controller.enqueue('world');
+ controller.close();
+ },
+});
+
+addAbortSignal(controller.signal, rs);
+
+finished(rs, (err) => {
+ if (err) {
+ if (err.name === 'AbortError') {
+ // The operation was cancelled
+ }
+ }
+});
+
+const reader = rs.getReader();
+
+reader.read().then(({ value, done }) => {
+ console.log(value); // hello
+ console.log(done); // false
+ controller.abort();
+});
+```
+
### API for stream implementers
diff --git a/content/api/v18/string_decoder.en.md b/content/api/v18/string_decoder.en.md
index 068a2591f8..c87baec081 100644
--- a/content/api/v18/string_decoder.en.md
+++ b/content/api/v18/string_decoder.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:string_decoder` module provides an API for decoding `Buffer` objects
into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
diff --git a/content/api/v18/test.en.md b/content/api/v18/test.en.md
index 88f2e10960..728780a3db 100644
--- a/content/api/v18/test.en.md
+++ b/content/api/v18/test.en.md
@@ -7,33 +7,31 @@ version: 'v18'
+
+
Experimental
-
+
-The `node:test` module facilitates the creation of JavaScript tests that
-report results in [TAP][] format. To access it:
+The `node:test` module facilitates the creation of JavaScript tests.
+To access it:
-```mjs
+```mjs|cjs
import test from 'node:test';
-```
-
-```cjs
+--------------
const test = require('node:test');
```
This module is only available under the `node:` scheme. The following will not
work:
-```mjs
+```mjs|cjs
import test from 'test';
-```
-
-```cjs
+--------------
const test = require('test');
```
@@ -100,9 +98,7 @@ test('callback failing test', (t, done) => {
});
```
-As a test file executes, TAP is written to the standard output of the Node.js
-process. This output can be interpreted by any test harness that understands
-the TAP format. If any tests fail, the process exit code is set to `1`.
+If any tests fail, the process exit code is set to `1`.
### Subtests
@@ -131,8 +127,7 @@ test to fail.
### Skipping tests
Individual tests can be skipped by passing the `skip` option to the test, or by
-calling the test context's `skip()` method. Both of these options support
-including a message that is displayed in the TAP output as shown in the
+calling the test context's `skip()` method as shown in the
following example.
```js
@@ -162,8 +157,7 @@ test('skip() method with message', (t) => {
Running tests can also be done using `describe` to declare a suite
and `it` to declare a test.
A suite is used to organize and group related tests together.
-`it` is an alias for `test`, except there is no test context passed,
-since nesting is done using suites.
+`it` is a shorthand for [`test()`][].
```js
describe('A thing', () => {
@@ -185,11 +179,9 @@ describe('A thing', () => {
`describe` and `it` are imported from the `node:test` module.
-```mjs
+```mjs|cjs
import { describe, it } from 'node:test';
-```
-
-```cjs
+--------------
const { describe, it } = require('node:test');
```
@@ -267,7 +259,7 @@ Test name patterns do not change the set of files that the test runner executes.
### Extraneous asynchronous activity
-Once a test function finishes executing, the TAP results are output as quickly
+Once a test function finishes executing, the results are reported as quickly
as possible while maintaining the order of the tests. However, it is possible
for the test function to generate asynchronous activity that outlives the test
itself. The test runner handles this type of activity, but does not delay the
@@ -276,13 +268,13 @@ reporting of test results in order to accommodate it.
In the following example, a test completes with two `setImmediate()`
operations still outstanding. The first `setImmediate()` attempts to create a
new subtest. Because the parent test has already finished and output its
-results, the new subtest is immediately marked as failed, and reported in the
-top level of the file's TAP output.
+results, the new subtest is immediately marked as failed, and reported later
+to the TestsStream.
The second `setImmediate()` creates an `uncaughtException` event.
`uncaughtException` and `unhandledRejection` events originating from a completed
-test are handled by the `test` module and reported as diagnostic warnings in
-the top level of the file's TAP output.
+test are marked as failed by the `test` module and reported as diagnostic
+warnings at the top level by the TestsStream.
```js
test('a test that creates asynchronous activity', (t) => {
@@ -382,6 +374,56 @@ Otherwise, the test is considered to be a failure. Test files must be
executable by Node.js, but are not required to use the `node:test` module
internally.
+### Collecting code coverage
+
+When Node.js is started with the [`--experimental-test-coverage`][]
+command-line flag, code coverage is collected and statistics are reported once
+all tests have completed. If the [`NODE_V8_COVERAGE`][] environment variable is
+used to specify a code coverage directory, the generated V8 coverage files are
+written to that directory. Node.js core modules and files within
+`node_modules/` directories are not included in the coverage report. If
+coverage is enabled, the coverage report is sent to any [test reporters][] via
+the `'test:coverage'` event.
+
+Coverage can be disabled on a series of lines using the following
+comment syntax:
+
+```js
+/* node:coverage disable */
+if (anAlwaysFalseCondition) {
+ // Code in this branch will never be executed, but the lines are ignored for
+ // coverage purposes. All lines following the 'disable' comment are ignored
+ // until a corresponding 'enable' comment is encountered.
+ console.log('this is never executed');
+}
+/* node:coverage enable */
+```
+
+Coverage can also be disabled for a specified number of lines. After the
+specified number of lines, coverage will be automatically reenabled. If the
+number of lines is not explicitly provided, a single line is ignored.
+
+```js
+/* node:coverage ignore next */
+if (anAlwaysFalseCondition) { console.log('this is never executed'); }
+
+/* node:coverage ignore next 3 */
+if (anAlwaysFalseCondition) {
+ console.log('this is never executed');
+}
+```
+
+The test runner's code coverage functionality has the following limitations,
+which will be addressed in a future Node.js release:
+
+* Although coverage data is collected for child processes, this information is
+ not included in the coverage report. Because the command line test runner uses
+ child processes to execute test files, it cannot be used with
+ `--experimental-test-coverage`.
+* Source maps are not supported.
+* Excluding specific files or directories from the coverage report is not
+ supported.
+
### Mocking
The `node:test` module supports mocking during testing via a top-level `mock`
@@ -389,7 +431,7 @@ object. The following example creates a spy on a function that adds two numbers
together. The spy is then used to assert that the function was called as
expected.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
import { mock, test } from 'node:test';
@@ -410,9 +452,7 @@ test('spies on a function', () => {
// Reset the globally tracked mocks.
mock.reset();
});
-```
-
-```cjs
+--------------
'use strict';
const assert = require('node:assert');
const { mock, test } = require('node:test');
@@ -465,6 +505,185 @@ test('spies on an object method', (t) => {
});
```
+### Test reporters
+
+
+
+The `node:test` module supports passing [`--test-reporter`][]
+flags for the test runner to use a specific reporter.
+
+The following built-reporters are supported:
+
+* `tap`
+ The `tap` reporter outputs the test results in the [TAP][] format.
+
+* `spec`
+ The `spec` reporter outputs the test results in a human-readable format.
+
+* `dot`
+ The `dot` reporter outputs the test results in a compact format,
+ where each passing test is represented by a `.`,
+ and each failing test is represented by a `X`.
+
+When `stdout` is a [TTY][], the `spec` reporter is used by default.
+Otherwise, the `tap` reporter is used by default.
+
+#### Custom reporters
+
+[`--test-reporter`][] can be used to specify a path to custom reporter.
+A custom reporter is a module that exports a value
+accepted by [stream.compose][].
+Reporters should transform events emitted by a TestsStream
+
+Example of a custom reporter using [`stream.Transform`](/api/v18/stream#streamtransform):
+
+```mjs|cjs
+import { Transform } from 'node:stream';
+
+const customReporter = new Transform({
+ writableObjectMode: true,
+ transform(event, encoding, callback) {
+ switch (event.type) {
+ case 'test:start':
+ callback(null, `test ${event.data.name} started`);
+ break;
+ case 'test:pass':
+ callback(null, `test ${event.data.name} passed`);
+ break;
+ case 'test:fail':
+ callback(null, `test ${event.data.name} failed`);
+ break;
+ case 'test:plan':
+ callback(null, 'test plan');
+ break;
+ case 'test:diagnostic':
+ callback(null, event.data.message);
+ break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ callback(null, `total line count: ${totalLineCount}\n`);
+ break;
+ }
+ }
+ },
+});
+
+export default customReporter;
+--------------
+const { Transform } = require('node:stream');
+
+const customReporter = new Transform({
+ writableObjectMode: true,
+ transform(event, encoding, callback) {
+ switch (event.type) {
+ case 'test:start':
+ callback(null, `test ${event.data.name} started`);
+ break;
+ case 'test:pass':
+ callback(null, `test ${event.data.name} passed`);
+ break;
+ case 'test:fail':
+ callback(null, `test ${event.data.name} failed`);
+ break;
+ case 'test:plan':
+ callback(null, 'test plan');
+ break;
+ case 'test:diagnostic':
+ callback(null, event.data.message);
+ break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ callback(null, `total line count: ${totalLineCount}\n`);
+ break;
+ }
+ }
+ },
+});
+
+module.exports = customReporter;
+```
+
+Example of a custom reporter using a generator function:
+
+```mjs|cjs
+export default async function * customReporter(source) {
+ for await (const event of source) {
+ switch (event.type) {
+ case 'test:start':
+ yield `test ${event.data.name} started\n`;
+ break;
+ case 'test:pass':
+ yield `test ${event.data.name} passed\n`;
+ break;
+ case 'test:fail':
+ yield `test ${event.data.name} failed\n`;
+ break;
+ case 'test:plan':
+ yield 'test plan';
+ break;
+ case 'test:diagnostic':
+ yield `${event.data.message}\n`;
+ break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ yield `total line count: ${totalLineCount}\n`;
+ break;
+ }
+ }
+ }
+}
+--------------
+module.exports = async function * customReporter(source) {
+ for await (const event of source) {
+ switch (event.type) {
+ case 'test:start':
+ yield `test ${event.data.name} started\n`;
+ break;
+ case 'test:pass':
+ yield `test ${event.data.name} passed\n`;
+ break;
+ case 'test:fail':
+ yield `test ${event.data.name} failed\n`;
+ break;
+ case 'test:plan':
+ yield 'test plan\n';
+ break;
+ case 'test:diagnostic':
+ yield `${event.data.message}\n`;
+ break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ yield `total line count: ${totalLineCount}\n`;
+ break;
+ }
+ }
+ }
+};
+```
+
+The value provided to `--test-reporter` should be a string like one used in an
+`import()` in JavaScript code.
+
+#### Multiple reporters
+
+The [`--test-reporter`][] flag can be specified multiple times to report test
+results in several formats. In this situation
+it is required to specify a destination for each reporter
+using [`--test-reporter-destination`][].
+Destination can be `stdout`, `stderr`, or a file path.
+Reporters and destinations are paired according
+to the order they were specified.
+
+In the following example, the `spec` reporter will output to `stdout`,
+and the `dot` reporter will output to `file.txt`:
+
+```bash
+node --test-reporter=spec --test-reporter=dot --test-reporter-destination=stdout --test-reporter-destination=file.txt
+```
+
+When a single reporter is specified, the destination will default to `stdout`,
+unless a destination is explicitly provided.
+
### `run([options])`
@@ -473,13 +692,15 @@ test('spies on an object method', (t) => {
properties are supported:
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If a number is provided,
then that many files would run in parallel.
- If truthy, it would run (number of cpu cores - 1)
- files in parallel.
- If falsy, it would only run one file at a time.
- If unspecified, subtests inherit this value from their parent.
- **Default:** `true`.
+ If `true`, it would run `os.availableParallelism() - 1` test files in
+ parallel.
+ If `false`, it would only run one test file at a time.
+ **Default:** `false`.
* `files`: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the list of files to run.
**Default** matching files from [test runner execution model][].
+ * `setup` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A function that accepts the `TestsStream` instance
+ and can be used to setup listeners before any tests are run.
+ **Default:** `undefined`.
* `signal` [`AbortSignal`](/api/v18/globals#abortsignal) Allows aborting an in-progress test execution.
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number of milliseconds the test execution will
fail after.
@@ -490,7 +711,7 @@ test('spies on an object method', (t) => {
number. If a nullish value is provided, each process gets its own port,
incremented from the primary's `process.debugPort`.
**Default:** `undefined`.
-* Returns: [`TapStream`](/api/v18/test#tapstream)
+* Returns: TestsStream
```js
run({ files: [path.resolve('./tests/test.js')] })
@@ -508,10 +729,9 @@ run({ files: [path.resolve('./tests/test.js')] })
properties are supported:
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If a number is provided,
then that many tests would run in parallel.
- If truthy, it would run (number of cpu cores - 1)
- tests in parallel.
+ If `true`, it would run `os.availableParallelism() - 1` tests in parallel.
For subtests, it will be `Infinity` tests in parallel.
- If falsy, it would only run one test at a time.
+ If `false`, it would only run one test at a time.
If unspecified, subtests inherit this value from their parent.
**Default:** `false`.
* `only` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If truthy, and the test context is configured to run
@@ -531,20 +751,22 @@ run({ files: [path.resolve('./tests/test.js')] })
to this function is a [`TestContext`][] object. If the test uses callbacks,
the callback function is passed as the second argument. **Default:** A no-op
function.
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Resolved with `undefined` once the test completes.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Resolved with `undefined` once
+ the test completes, or immediately if the test runs within [`describe()`][].
The `test()` function is the value imported from the `test` module. Each
-invocation of this function results in the creation of a test point in the TAP
-output.
+invocation of this function results in reporting the test to the TestsStream.
The `TestContext` object passed to the `fn` argument can be used to perform
actions related to the current test. Examples include skipping the test, adding
-additional TAP diagnostic information, or creating subtests.
+additional diagnostic information, or creating subtests.
-`test()` returns a `Promise` that resolves once the test completes. The return
-value can usually be discarded for top level tests. However, the return value
-from subtests should be used to prevent the parent test from finishing first
-and cancelling the subtest as shown in the following example.
+`test()` returns a `Promise` that resolves once the test completes.
+if `test()` is called within a `describe()` block, it resolve immediately.
+The return value can usually be discarded for top level tests.
+However, the return value from subtests should be used to prevent the parent
+test from finishing first and cancelling the subtest
+as shown in the following example.
```js
test('top level test', async (t) => {
@@ -578,8 +800,7 @@ thus prevent the scheduled cancellation.
* Returns: `undefined`.
The `describe()` function imported from the `node:test` module. Each
-invocation of this function results in the creation of a Subtest
-and a test point in the TAP output.
+invocation of this function results in the creation of a Subtest.
After invocation of top level `describe` functions,
all top level tests and suites will execute.
@@ -592,21 +813,20 @@ Shorthand for skipping a suite, same as [`describe([name], { skip: true }[, fn])
Shorthand for marking a suite as `TODO`, same as
[`describe([name], { todo: true }[, fn])`][describe options].
+### `describe.only([name][, options][, fn])`
+
+
+
+Shorthand for marking a suite as `only`, same as
+[`describe([name], { only: true }[, fn])`][describe options].
+
### `it([name][, options][, fn])`
-* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the test, which is displayed when reporting test
- results. **Default:** The `name` property of `fn`, or `''` if `fn`
- does not have a name.
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the suite.
- supports the same options as `test([name][, options][, fn])`.
-* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) The function under test.
- If the test uses callbacks, the callback function is passed as an argument.
- **Default:** A no-op function.
-* Returns: `undefined`.
+
-The `it()` function is the value imported from the `node:test` module.
-Each invocation of this function results in the creation of a test point in the
-TAP output.
+Shorthand for [`test()`][].
+
+The `it()` function is imported from the `node:test` module.
### `it.skip([name][, options][, fn])`
@@ -618,6 +838,13 @@ same as [`it([name], { skip: true }[, fn])`][it options].
Shorthand for marking a test as `TODO`,
same as [`it([name], { todo: true }[, fn])`][it options].
+### `it.only([name][, options][, fn])`
+
+
+
+Shorthand for marking a test as `only`,
+same as [`it([name], { only: true }[, fn])`][it options].
+
### `before([fn][, options])`
@@ -690,7 +917,7 @@ before each subtest of the current suite.
```js
describe('tests', async () => {
- beforeEach(() => t.diagnostic('about to run a test'));
+ beforeEach(() => console.log('about to run a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
@@ -717,7 +944,7 @@ after each subtest of the current test.
```js
describe('tests', async () => {
- afterEach(() => t.diagnostic('about to run a test'));
+ afterEach(() => console.log('finished running a test'));
it('is a subtest', () => {
assert.ok('some relevant assertion here');
});
@@ -997,19 +1224,59 @@ not disassociate the mocks from the `MockTracker` instance.
This function is syntax sugar for [`MockTracker.method`][] with `options.setter`
set to `true`.
-### `TapStream`
+### `TestsStream`
* Extends [`ReadableStream`](/api/v18/webstreams#readablestream)
-A successful call to [`run()`][] method will return a new [`TapStream`](/api/v18/test#tapstream)
-object, streaming a [TAP][] output
-`TapStream` will emit events, in the order of the tests definition
+A successful call to [`run()`][] method will return a new TestsStream
+object, streaming a series of events representing the execution of the tests.
+`TestsStream` will emit events, in the order of the tests definition
+
+#### `'test:coverage'`
+
+* `data` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `summary` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object containing the coverage report.
+ * `files` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array of coverage reports for individual files. Each
+ report is an object with the following schema:
+ * `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The absolute path of the file.
+ * `totalLineCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The total number of lines.
+ * `totalBranchCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The total number of branches.
+ * `totalFunctionCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The total number of functions.
+ * `coveredLineCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of covered lines.
+ * `coveredBranchCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of covered branches.
+ * `coveredFunctionCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of covered functions.
+ * `coveredLinePercent` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The percentage of lines covered.
+ * `coveredBranchPercent` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The percentage of branches covered.
+ * `coveredFunctionPercent` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The percentage of functions covered.
+ * `uncoveredLineNumbers` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array of integers representing line
+ numbers that are uncovered.
+ * `totals` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object containing a summary of coverage for all
+ files.
+ * `totalLineCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The total number of lines.
+ * `totalBranchCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The total number of branches.
+ * `totalFunctionCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The total number of functions.
+ * `coveredLineCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of covered lines.
+ * `coveredBranchCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of covered branches.
+ * `coveredFunctionCount` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of covered functions.
+ * `coveredLinePercent` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The percentage of lines covered.
+ * `coveredBranchPercent` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The percentage of branches covered.
+ * `coveredFunctionPercent` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The percentage of functions covered.
+ * `workingDirectory` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The working directory when code coverage
+ began. This is useful for displaying relative path names in case the tests
+ changed the working directory of the Node.js process.
+ * `nesting` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The nesting level of the test.
+
+Emitted when code coverage is enabled and all tests have completed.
#### `'test:diagnostic'`
-* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The diagnostic message.
+* `data` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The path of the test file,
+ undefined if test is not ran through a file.
+ * `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The diagnostic message.
+ * `nesting` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The nesting level of the test.
Emitted when [`context.diagnostic`][] is called.
@@ -1017,10 +1284,15 @@ Emitted when [`context.diagnostic`][] is called.
* `data` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `details` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Additional execution metadata.
+ * `duration` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The duration of the test in milliseconds.
+ * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The error thrown by the test.
+ * `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The path of the test file,
+ undefined if test is not ran through a file.
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The test name.
+ * `nesting` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The nesting level of the test.
* `testNumber` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ordinal number of the test.
- * `todo` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.todo`][] is called
- * `skip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.skip`][] is called
+ * `todo` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.todo`][] is called
+ * `skip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.skip`][] is called
Emitted when a test fails.
@@ -1028,13 +1300,37 @@ Emitted when a test fails.
* `data` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `details` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Additional execution metadata.
+ * `duration` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The duration of the test in milliseconds.
+ * `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The path of the test file,
+ undefined if test is not ran through a file.
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The test name.
+ * `nesting` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The nesting level of the test.
* `testNumber` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ordinal number of the test.
- * `todo` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.todo`][] is called
- * `skip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.skip`][] is called
+ * `todo` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.todo`][] is called
+ * `skip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Present if [`context.skip`][] is called
Emitted when a test passes.
+#### `'test:plan'`
+
+* `data` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The path of the test file,
+ undefined if test is not ran through a file.
+ * `nesting` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The nesting level of the test.
+ * `count` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of subtests that have ran.
+
+Emitted when all subtests have completed for a given test.
+
+#### `'test:start'`
+
+* `data` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The path of the test file,
+ undefined if test is not ran through a file.
+ * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The test name.
+ * `nesting` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The nesting level of the test.
+
+Emitted when a test starts.
+
### `TestContext`
@@ -1132,9 +1428,9 @@ test('top level test', async (t) => {
-* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Message to be displayed as a TAP diagnostic.
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Message to be reported.
-This function is used to write TAP diagnostics to the output. Any diagnostic
+This function is used to write diagnostics to the output. Any diagnostic
information is included at the end of the test's results. This function does
not return a value.
@@ -1189,10 +1485,10 @@ test('top level test', async (t) => {
-* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Optional skip message to be displayed in TAP output.
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Optional skip message.
This function causes the test's output to indicate the test as skipped. If
-`message` is provided, it is included in the TAP output. Calling `skip()` does
+`message` is provided, it is included in the output. Calling `skip()` does
not terminate execution of the test function. This function does not return a
value.
@@ -1207,10 +1503,10 @@ test('top level test', (t) => {
-* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Optional `TODO` message to be displayed in TAP output.
+* `message` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Optional `TODO` message.
This function adds a `TODO` directive to the test's output. If `message` is
-provided, it is included in the TAP output. Calling `todo()` does not terminate
+provided, it is included in the output. Calling `todo()` does not terminate
execution of the test function. This function does not return a value.
```js
@@ -1229,9 +1525,12 @@ test('top level test', (t) => {
`fn` does not have a name.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the subtest. The following
properties are supported:
- * `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of tests that can be run at the same time.
+ * `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) If a number is provided,
+ then that many tests would run in parallel.
+ If `true`, it would run all subtests in parallel.
+ If `false`, it would only run one test at a time.
If unspecified, subtests inherit this value from their parent.
- **Default:** `1`.
+ **Default:** `null`.
* `only` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If truthy, and the test context is configured to run
`only` tests, then this test will be run. Otherwise, the test is skipped.
**Default:** `false`.
@@ -1288,19 +1587,27 @@ The name of the suite.
aborted.
[TAP]: https://testanything.org/
+[TTY]: /api/v18/tty
+[`--experimental-test-coverage`]: /api/v18/cli#--experimental-test-coverage
[`--test-name-pattern`]: /api/v18/cli#--test-name-pattern
[`--test-only`]: /api/v18/cli#--test-only
+[`--test-reporter-destination`]: /api/v18/cli#--test-reporter-destination
+[`--test-reporter`]: /api/v18/cli#--test-reporter
[`--test`]: /api/v18/cli#--test
[`MockFunctionContext`]: #class-mockfunctioncontext
[`MockTracker.method`]: #mockmethodobject-methodname-implementation-options
[`MockTracker`]: #class-mocktracker
+[`NODE_V8_COVERAGE`]: /api/v18/cli#node_v8_coveragedir
[`SuiteContext`]: #class-suitecontext
[`TestContext`]: #class-testcontext
[`context.diagnostic`]: #contextdiagnosticmessage
[`context.skip`]: #contextskipmessage
[`context.todo`]: #contexttodomessage
+[`describe()`]: #describename-options-fn
[`run()`]: #runoptions
[`test()`]: #testname-options-fn
[describe options]: #describename-options-fn
[it options]: #testname-options-fn
+[stream.compose]: /api/v18/stream#streamcomposestreams
+[test reporters]: #test-reporters
[test runner execution model]: #test-runner-execution-model
diff --git a/content/api/v18/timers.en.md b/content/api/v18/timers.en.md
index 02e0c297c2..e96b7246e9 100644
--- a/content/api/v18/timers.en.md
+++ b/content/api/v18/timers.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `timer` module exposes a global API for scheduling functions to
be called at some future period of time. Because the timer functions are
@@ -306,15 +306,13 @@ The `timers/promises` API provides an alternative set of timer functions
that return `Promise` objects. The API is accessible via
`require('node:timers/promises')`.
-```mjs
+```mjs|cjs
import {
setTimeout,
setImmediate,
setInterval,
} from 'timers/promises';
-```
-
-```cjs
+--------------
const {
setTimeout,
setImmediate,
@@ -336,7 +334,7 @@ const {
* `signal` [`AbortSignal`](/api/v18/globals#abortsignal) An optional `AbortSignal` that can be used to
cancel the scheduled `Timeout`.
-```mjs
+```mjs|cjs
import {
setTimeout,
} from 'timers/promises';
@@ -344,9 +342,7 @@ import {
const res = await setTimeout(100, 'result');
console.log(res); // Prints 'result'
-```
-
-```cjs
+--------------
const {
setTimeout,
} = require('node:timers/promises');
@@ -368,7 +364,7 @@ setTimeout(100, 'result').then((res) => {
* `signal` [`AbortSignal`](/api/v18/globals#abortsignal) An optional `AbortSignal` that can be used to
cancel the scheduled `Immediate`.
-```mjs
+```mjs|cjs
import {
setImmediate,
} from 'timers/promises';
@@ -376,9 +372,7 @@ import {
const res = await setImmediate('result');
console.log(res); // Prints 'result'
-```
-
-```cjs
+--------------
const {
setImmediate,
} = require('node:timers/promises');
@@ -407,7 +401,7 @@ or implicitly to keep the event loop alive.
* `signal` [`AbortSignal`](/api/v18/globals#abortsignal) An optional `AbortSignal` that can be used to
cancel the scheduled `Timeout` between operations.
-```mjs
+```mjs|cjs
import {
setInterval,
} from 'timers/promises';
@@ -420,9 +414,7 @@ for await (const startTime of setInterval(interval, Date.now())) {
break;
}
console.log(Date.now());
-```
-
-```cjs
+--------------
const {
setInterval,
} = require('node:timers/promises');
diff --git a/content/api/v18/tls.en.md b/content/api/v18/tls.en.md
index 77fac828d7..aa2027b0be 100644
--- a/content/api/v18/tls.en.md
+++ b/content/api/v18/tls.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:tls` module provides an implementation of the Transport Layer Security
(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
@@ -130,23 +130,17 @@ all sessions). Methods implementing this technique are called "ephemeral".
Currently two methods are commonly used to achieve perfect forward secrecy (note
the character "E" appended to the traditional abbreviations):
-* [DHE][]: An ephemeral version of the Diffie-Hellman key-agreement protocol.
* [ECDHE][]: An ephemeral version of the Elliptic Curve Diffie-Hellman
key-agreement protocol.
+* [DHE][]: An ephemeral version of the Diffie-Hellman key-agreement protocol.
-To use perfect forward secrecy using `DHE` with the `node:tls` module, it is
-required to generate Diffie-Hellman parameters and specify them with the
-`dhparam` option to [`tls.createSecureContext()`][]. The following illustrates
-the use of the OpenSSL command-line interface to generate such parameters:
-
-```bash
-openssl dhparam -outform PEM -out dhparam.pem 2048
-```
+Perfect forward secrecy using ECDHE is enabled by default. The `ecdhCurve`
+option can be used when creating a TLS server to customize the list of supported
+ECDH curves to use. See [`tls.createServer()`][] for more info.
-If using perfect forward secrecy using `ECDHE`, Diffie-Hellman parameters are
-not required and a default ECDHE curve will be used. The `ecdhCurve` property
-can be used when creating a TLS Server to specify the list of names of supported
-curves to use, see [`tls.createServer()`][] for more info.
+DHE is disabled by default but can be enabled alongside ECDHE by setting the
+`dhparam` option to `'auto'`. Custom DHE parameters are also supported but
+discouraged in favor of automatically selected, well-known parameters.
Perfect forward secrecy was optional up to TLSv1.2. As of TLSv1.3, (EC)DHE is
always used (with the exception of PSK-only connections).
@@ -363,6 +357,30 @@ export NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'
node server.js
```
+To verify, use the following command to show the set cipher list, note the
+difference between `defaultCoreCipherList` and `defaultCipherList`:
+
+```bash
+node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' -p crypto.constants.defaultCipherList | tr ':' '\n'
+ECDHE-RSA-AES128-GCM-SHA256
+!RC4
+```
+
+i.e. the `defaultCoreCipherList` list is set at compilation time and the
+`defaultCipherList` is set at runtime.
+
+To modify the default cipher suites from within the runtime, modify the
+`tls.DEFAULT_CIPHERS` variable, this must be performed before listening on any
+sockets, it will not affect sockets already opened. For example:
+
+```js
+// Remove Obsolete CBC Ciphers and RSA Key Exchange based Ciphers as they don't provide Forward Secrecy
+tls.DEFAULT_CIPHERS +=
+ ':!ECDHE-RSA-AES128-SHA:!ECDHE-RSA-AES128-SHA256:!ECDHE-RSA-AES256-SHA:!ECDHE-RSA-AES256-SHA384' +
+ ':!ECDHE-ECDSA-AES128-SHA:!ECDHE-ECDSA-AES128-SHA256:!ECDHE-ECDSA-AES256-SHA:!ECDHE-ECDSA-AES256-SHA384' +
+ ':!kRSA';
+```
+
The default can also be replaced on a per client or server basis using the
`ciphers` option from [`tls.createSecureContext()`][], which is also available
in [`tls.createServer()`][], [`tls.connect()`][], and when creating new
@@ -1555,7 +1573,7 @@ argument.
### `tls.createSecureContext([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `ca` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) Optionally override the trusted CA
@@ -1599,12 +1617,10 @@ argument.
client certificate.
* `crl` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) PEM formatted CRLs (Certificate
Revocation Lists).
- * `dhparam` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) Diffie-Hellman parameters, required for
- [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters.
- The key length must be greater than or equal to 1024 bits or else an error
- will be thrown. Although 1024 bits is permissible, use 2048 bits or larger
- for stronger security. If omitted or invalid, the parameters are silently
- discarded and DHE ciphers will not be available.
+ * `dhparam` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) `'auto'` or custom Diffie-Hellman parameters,
+ required for non-ECDHE [perfect forward secrecy][]. If omitted or invalid,
+ the parameters are silently discarded and DHE ciphers will not be available.
+ [ECDHE][]-based [perfect forward secrecy][] will still be available.
* `ecdhCurve` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string describing a named curve or a colon separated
list of curve NIDs or names, for example `P-521:P-384:P-256`, to use for
ECDH key agreement. Set to `auto` to select the
@@ -1691,6 +1707,13 @@ A key is _required_ for ciphers that use certificates. Either `key` or
If the `ca` option is not given, then Node.js will default to using
[Mozilla's publicly trusted list of CAs][].
+Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`
+option. When set to `'auto'`, well-known DHE parameters of sufficient strength
+will be selected automatically. Otherwise, if necessary, `openssl dhparam` can
+be used to create custom parameters. The key length must be greater than or
+equal to 1024 bits or else an error will be thrown. Although 1024 bits is
+permissible, use 2048 bits or larger for stronger security.
+
### `tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])`
@@ -1927,6 +1950,16 @@ information.
`'TLSv1.3'`. If multiple of the options are provided, the lowest minimum is
used.
+### `tls.DEFAULT_CIPHERS`
+
+
+
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The default value of the `ciphers` option of
+ [`tls.createSecureContext()`][]. It can be assigned any of the supported
+ OpenSSL ciphers. Defaults to the content of
+ `crypto.constants.defaultCoreCipherList`, unless changed using CLI options
+ using `--tls-default-ciphers`.
+
[CVE-2021-44531]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531
[Chrome's 'modern cryptography' setting]: https://www.chromium.org/Home/chromium-security/education/tls#TOC-Cipher-Suites
[DHE]: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
diff --git a/content/api/v18/tracing.en.md b/content/api/v18/tracing.en.md
index 77dc3779d7..4eab9a5ba0 100644
--- a/content/api/v18/tracing.en.md
+++ b/content/api/v18/tracing.en.md
@@ -13,7 +13,7 @@ Experimental
-
+
The `node:trace_events` module provides a mechanism to centralize tracing
information generated by V8, Node.js core, and userspace code.
diff --git a/content/api/v18/tty.en.md b/content/api/v18/tty.en.md
index 6b82ad74b4..3133bda05c 100644
--- a/content/api/v18/tty.en.md
+++ b/content/api/v18/tty.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`
classes. In most cases, it will not be necessary or possible to use this module
diff --git a/content/api/v18/url.en.md b/content/api/v18/url.en.md
index 50a1181a65..b409d66480 100644
--- a/content/api/v18/url.en.md
+++ b/content/api/v18/url.en.md
@@ -13,16 +13,14 @@ Stable
-
+
The `node:url` module provides utilities for URL resolution and parsing. It can
be accessed using:
-```mjs
+```mjs|cjs
import url from 'node:url';
-```
-
-```cjs
+--------------
const url = require('node:url');
```
@@ -74,13 +72,11 @@ const myURL =
Parsing the URL string using the legacy API:
-```mjs
+```mjs|cjs
import url from 'node:url';
const myURL =
url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
-```
-
-```cjs
+--------------
const url = require('node:url');
const myURL =
url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
@@ -91,14 +87,12 @@ const myURL =
It is possible to construct a WHATWG URL from component parts using either the
property setters or a template literal string:
-```js
+```js|js
const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';
-```
-
-```js
+--------------
const pathname = '/a/b/c';
const search = '?d=e';
const hash = '#fgh';
@@ -147,12 +141,10 @@ const myURL = new URL('/foo', 'https://example.org/');
The URL constructor is accessible as a property on the global object.
It can also be imported from the built-in url module:
-```mjs
+```mjs|cjs
import { URL } from 'node:url';
console.log(URL === globalThis.URL); // Prints 'true'.
-```
-
-```cjs
+--------------
console.log(URL === require('node:url').URL); // Prints 'true'.
```
@@ -299,13 +291,11 @@ will be thrown.
Gets the read-only serialization of the URL's origin.
-```js
+```js|js
const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);
// Prints https://example.org
-```
-
-```js
+--------------
const idnURL = new URL('https://測試');
console.log(idnURL.origin);
// Prints https://xn--g6w251d
@@ -539,14 +529,14 @@ instance, the `URL` object will not percent encode the ASCII tilde (`~`)
character, while `URLSearchParams` will always encode it:
```js
-const myUrl = new URL('https://example.org/abc?foo=~bar');
+const myURL = new URL('https://example.org/abc?foo=~bar');
-console.log(myUrl.search); // prints ?foo=~bar
+console.log(myURL.search); // prints ?foo=~bar
// Modify the URL via searchParams...
-myUrl.searchParams.sort();
+myURL.searchParams.sort();
-console.log(myUrl.search); // prints ?foo=%7Ebar
+console.log(myURL.search); // prints ?foo=%7Ebar
```
##### `url.username`
@@ -906,6 +896,12 @@ console.log(params.toString());
// Prints foo=def&abc=def&xyz=opq
```
+##### `urlSearchParams.size`
+
+
+
+The total number of parameter entries.
+
##### `urlSearchParams.sort()`
@@ -971,7 +967,7 @@ It performs the inverse operation to [`url.domainToUnicode()`][].
This feature is only available if the `node` executable was compiled with
[ICU][] enabled. If not, the domain names are passed through unchanged.
-```mjs
+```mjs|cjs
import url from 'node:url';
console.log(url.domainToASCII('español.com'));
@@ -980,9 +976,7 @@ console.log(url.domainToASCII('中文.com'));
// Prints xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
// Prints an empty string
-```
-
-```cjs
+--------------
const url = require('node:url');
console.log(url.domainToASCII('español.com'));
@@ -1008,7 +1002,7 @@ It performs the inverse operation to [`url.domainToASCII()`][].
This feature is only available if the `node` executable was compiled with
[ICU][] enabled. If not, the domain names are passed through unchanged.
-```mjs
+```mjs|cjs
import url from 'node:url';
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
@@ -1017,9 +1011,7 @@ console.log(url.domainToUnicode('xn--fiq228c.com'));
// Prints 中文.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
// Prints an empty string
-```
-
-```cjs
+--------------
const url = require('node:url');
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
@@ -1040,7 +1032,7 @@ console.log(url.domainToUnicode('xn--iñvalid.com'));
This function ensures the correct decodings of percent-encoded characters as
well as ensuring a cross-platform valid absolute path string.
-```mjs
+```mjs|cjs
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
@@ -1056,9 +1048,7 @@ fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX)
new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
-```
-
-```cjs
+--------------
const { fileURLToPath } = require('node:url');
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows)
@@ -1098,7 +1088,7 @@ string serializations of the URL. These are not, however, customizable in
any way. The `url.format(URL[, options])` method allows for basic customization
of the output.
-```mjs
+```mjs|cjs
import url from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');
@@ -1110,9 +1100,7 @@ console.log(myURL.toString());
console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://測試/?abc'
-```
-
-```cjs
+--------------
const url = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');
@@ -1136,7 +1124,7 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
This function ensures that `path` is resolved absolutely, and that the URL
control characters are correctly encoded when converting into a File URL.
-```mjs
+```mjs|cjs
import { pathToFileURL } from 'node:url';
new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1
@@ -1144,9 +1132,7 @@ pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)
new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX)
-```
-
-```cjs
+--------------
const { pathToFileURL } = require('node:url');
new URL(__filename); // Incorrect: throws (POSIX)
new URL(__filename); // Incorrect: C:\... (Windows)
@@ -1184,7 +1170,7 @@ pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSI
This utility function converts a URL object into an ordinary options object as
expected by the [`http.request()`][] and [`https.request()`][] APIs.
-```mjs
+```mjs|cjs
import { urlToHttpOptions } from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');
@@ -1201,13 +1187,11 @@ console.log(urlToHttpOptions(myURL));
auth: 'a:b'
}
*/
-```
-
-```cjs
+--------------
const { urlToHttpOptions } = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');
-console.log(urlToHttpOptions(myUrl));
+console.log(urlToHttpOptions(myURL));
/*
{
protocol: 'https:',
diff --git a/content/api/v18/util.en.md b/content/api/v18/util.en.md
index 3a0cbae077..c6cbfd1634 100644
--- a/content/api/v18/util.en.md
+++ b/content/api/v18/util.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:util` module supports the needs of Node.js internal APIs. Many of the
utilities are useful for application and module developers as well. To access
@@ -896,13 +896,11 @@ properties for each of these components.
Creates a new `MIMEType` object by parsing the `input`.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/plain');
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/plain');
@@ -912,14 +910,12 @@ A `TypeError` will be thrown if the `input` is not a valid MIME. Note
that an effort will be made to coerce the given values into strings. For
instance:
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIME = new MIMEType({ toString: () => 'text/plain' });
console.log(String(myMIME));
// Prints: text/plain
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIME = new MIMEType({ toString: () => 'text/plain' });
console.log(String(myMIME));
@@ -932,7 +928,7 @@ console.log(String(myMIME));
Gets and sets the type portion of the MIME.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/javascript');
@@ -943,9 +939,7 @@ console.log(myMIME.type);
// Prints: application
console.log(String(myMIME));
// Prints: application/javascript
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/javascript');
@@ -964,7 +958,7 @@ console.log(String(myMIME));
Gets and sets the subtype portion of the MIME.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/ecmascript');
@@ -975,9 +969,7 @@ console.log(myMIME.subtype);
// Prints: javascript
console.log(String(myMIME));
// Prints: text/javascript
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/ecmascript');
@@ -997,7 +989,7 @@ console.log(String(myMIME));
Gets the essence of the MIME. This property is read only.
Use `mime.type` or `mime.subtype` to alter the MIME.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/javascript;key=value');
@@ -1008,9 +1000,7 @@ console.log(myMIME.essence);
// Prints: application/javascript
console.log(String(myMIME));
// Prints: application/javascript;key=value
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/javascript;key=value');
@@ -1049,7 +1039,7 @@ Alias for [`mime.toString()`][].
This method is automatically called when an `MIMEType` object is serialized
with [`JSON.stringify()`][].
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIMES = [
@@ -1058,9 +1048,7 @@ const myMIMES = [
];
console.log(JSON.stringify(myMIMES));
// Prints: ["image/png", "image/gif"]
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIMES = [
@@ -1082,13 +1070,11 @@ The `MIMEParams` API provides read and write access to the parameters of a
Creates a new `MIMEParams` object by with empty parameters
-```mjs
+```mjs|cjs
import { MIMEParams } from 'node:util';
const myParams = new MIMEParams();
-```
-
-```cjs
+--------------
const { MIMEParams } = require('node:util');
const myParams = new MIMEParams();
@@ -1130,7 +1116,7 @@ Returns `true` if there is at least one name-value pair whose name is `name`.
Returns an iterator over the names of each name-value pair.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=0;bar=1');
@@ -1140,9 +1126,7 @@ for (const name of params.keys()) {
// Prints:
// foo
// bar
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const { params } = new MIMEType('text/plain;foo=0;bar=1');
@@ -1163,7 +1147,7 @@ Sets the value in the `MIMEParams` object associated with `name` to
`value`. If there are any pre-existing name-value pairs whose names are `name`,
set the first such pair's value to `value`.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=0;bar=1');
@@ -1171,9 +1155,7 @@ params.set('foo', 'def');
params.set('baz', 'xyz');
console.log(params.toString());
// Prints: foo=def&bar=1&baz=xyz
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const { params } = new MIMEType('text/plain;foo=0;bar=1');
@@ -1195,7 +1177,7 @@ Returns an iterator over the values of each name-value pair.
Alias for [`mimeParams.entries()`][].
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=bar;xyz=baz');
@@ -1205,9 +1187,7 @@ for (const [name, value] of params) {
// Prints:
// foo bar
// xyz baz
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const { params } = new MIMEType('text/plain;foo=bar;xyz=baz');
@@ -1267,7 +1247,7 @@ Provides a higher level API for command-line argument parsing than interacting
with `process.argv` directly. Takes a specification for the expected arguments
and returns a structured object with the parsed options and positionals.
-```mjs
+```mjs|cjs
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
@@ -1285,9 +1265,7 @@ const {
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
-```
-
-```cjs
+--------------
const { parseArgs } = require('node:util');
const args = ['-f', '--bar', 'b'];
const options = {
@@ -1340,7 +1318,7 @@ For example to use the returned tokens to add support for a negated option
like `--no-color`, the tokens can be reprocessed to change the value stored
for the negated option.
-```mjs
+```mjs|cjs
import { parseArgs } from 'node:util';
const options = {
@@ -1370,9 +1348,7 @@ const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
-```
-
-```cjs
+--------------
const { parseArgs } = require('node:util');
const options = {
@@ -1793,6 +1769,51 @@ const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);
```
+### `util.aborted(signal, resource)`
+
+
+
+
+
+Experimental
+
+
+
+* `signal` [`AbortSignal`](/api/v18/globals#abortsignal)
+* `resource` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Any non-null entity, reference to which is held weakly.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+
+Listens to abort event on the provided `signal` and
+returns a promise that is fulfilled when the `signal` is
+aborted. If the passed `resource` is garbage collected before the `signal` is
+aborted, the returned promise shall remain pending indefinitely.
+
+```cjs|mjs
+const { aborted } = require('node:util');
+
+const dependent = obtainSomethingAbortable();
+
+aborted(dependent.signal, dependent).then(() => {
+ // Do something when dependent is aborted.
+});
+
+dependent.on('event', () => {
+ dependent.abort();
+});
+--------------
+import { aborted } from 'node:util';
+
+const dependent = obtainSomethingAbortable();
+
+aborted(dependent.signal, dependent).then(() => {
+ // Do something when dependent is aborted.
+});
+
+dependent.on('event', () => {
+ dependent.abort();
+});
+```
+
### `util.types`
@@ -2013,7 +2034,7 @@ properties. Such objects are created either by Node.js internals or native
addons. In JavaScript, they are [frozen][`Object.freeze()`] objects with a
`null` prototype.
-```c
+```c|js
#include
#include
napi_value result;
@@ -2029,9 +2050,7 @@ static napi_value MyNapi(napi_env env, napi_callback_info info) {
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...
-```
-
-```js
+--------------
const native = require('napi_addon.node');
const data = native.myNapi();
util.types.isExternal(data); // returns true
diff --git a/content/api/v18/v8.en.md b/content/api/v18/v8.en.md
index f1f94d420d..65a2ad69e1 100644
--- a/content/api/v18/v8.en.md
+++ b/content/api/v18/v8.en.md
@@ -7,7 +7,7 @@ version: 'v18'
-
+
The `node:v8` module exposes APIs that are specific to the version of [V8][]
built into the Node.js binary. It can be accessed using:
@@ -638,13 +638,11 @@ stopHookSet();
**The `init` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onInit((promise, parent) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onInit((promise, parent) => {});
@@ -661,13 +659,11 @@ const stop = promiseHooks.onInit((promise, parent) => {});
**The `settled` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onSettled((promise) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onSettled((promise) => {});
@@ -684,13 +680,11 @@ const stop = promiseHooks.onSettled((promise) => {});
**The `before` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onBefore((promise) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onBefore((promise) => {});
@@ -707,13 +701,11 @@ const stop = promiseHooks.onBefore((promise) => {});
**The `after` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onAfter((promise) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onAfter((promise) => {});
@@ -743,15 +735,13 @@ be tracked, then only the `init` callback needs to be passed. The
specifics of all functions that can be passed to `callbacks` is in the
[Hook Callbacks][] section.
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stopAll = promiseHooks.createHook({
init(promise, parent) {},
});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stopAll = promiseHooks.createHook({
@@ -943,6 +933,104 @@ needs to be provided to the deserialized application.
Returns true if the Node.js instance is run to build a snapshot.
+### `v8.GCProfiler`
+
+
+
+This API collects GC data in current thread.
+
+#### `new v8.GCProfiler()`
+
+
+
+Create a new instance of the `v8.GCProfiler` class.
+
+#### `profiler.start()`
+
+
+
+Start collecting GC data.
+
+#### `profiler.stop()`
+
+
+
+Stop collecting GC data and return an object.The content of object
+is as follows.
+
+```json
+{
+ "version": 1,
+ "startTime": 1674059033862,
+ "statistics": [
+ {
+ "gcType": "Scavenge",
+ "beforeGC": {
+ "heapStatistics": {
+ "totalHeapSize": 5005312,
+ "totalHeapSizeExecutable": 524288,
+ "totalPhysicalSize": 5226496,
+ "totalAvailableSize": 4341325216,
+ "totalGlobalHandlesSize": 8192,
+ "usedGlobalHandlesSize": 2112,
+ "usedHeapSize": 4883840,
+ "heapSizeLimit": 4345298944,
+ "mallocedMemory": 254128,
+ "externalMemory": 225138,
+ "peakMallocedMemory": 181760
+ },
+ "heapSpaceStatistics": [
+ {
+ "spaceName": "read_only_space",
+ "spaceSize": 0,
+ "spaceUsedSize": 0,
+ "spaceAvailableSize": 0,
+ "physicalSpaceSize": 0
+ }
+ ]
+ },
+ "cost": 1574.14,
+ "afterGC": {
+ "heapStatistics": {
+ "totalHeapSize": 6053888,
+ "totalHeapSizeExecutable": 524288,
+ "totalPhysicalSize": 5500928,
+ "totalAvailableSize": 4341101384,
+ "totalGlobalHandlesSize": 8192,
+ "usedGlobalHandlesSize": 2112,
+ "usedHeapSize": 4059096,
+ "heapSizeLimit": 4345298944,
+ "mallocedMemory": 254128,
+ "externalMemory": 225138,
+ "peakMallocedMemory": 181760
+ },
+ "heapSpaceStatistics": [
+ {
+ "spaceName": "read_only_space",
+ "spaceSize": 0,
+ "spaceUsedSize": 0,
+ "spaceAvailableSize": 0,
+ "physicalSpaceSize": 0
+ }
+ ]
+ }
+ }
+ ],
+ "endTime": 1674059036865
+}
+```
+
+Here's an example.
+
+```js
+const { GCProfiler } = require('v8');
+const profiler = new GCProfiler();
+profiler.start();
+setTimeout(() => {
+ console.log(profiler.stop());
+}, 1000);
+```
+
[HTML structured clone algorithm]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
[Hook Callbacks]: #hook-callbacks
[V8]: https://developers.google.com/v8/
diff --git a/content/api/v18/vm.en.md b/content/api/v18/vm.en.md
index ee3b16b72f..8b1dec6aea 100644
--- a/content/api/v18/vm.en.md
+++ b/content/api/v18/vm.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:vm` module enables compiling and running code within V8 Virtual
Machine contexts.
@@ -315,7 +315,7 @@ console.log(globalVar);
When the script is compiled from a source that contains a source map magic
comment, this property will be set to the URL of the source map.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const script = new vm.Script(`
@@ -325,9 +325,7 @@ function myFunc() {}
console.log(script.sourceMapURL);
// Prints: sourcemap.json
-```
-
-```cjs
+--------------
const vm = require('node:vm');
const script = new vm.Script(`
@@ -370,7 +368,7 @@ This implementation lies at a lower level than the [ECMAScript Module
loader][]. There is also no way to interact with the Loader yet, though
support is planned.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const contextifiedObject = vm.createContext({
@@ -439,9 +437,7 @@ await bar.link(linker);
// Prints 42.
await bar.evaluate();
-```
-
-```cjs
+--------------
const vm = require('node:vm');
const contextifiedObject = vm.createContext({
@@ -725,7 +721,7 @@ Properties assigned to the `import.meta` object that are objects may
allow the module to access information outside the specified `context`. Use
`vm.runInContext()` to create objects in a specific context.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const contextifiedObject = vm.createContext({ secret: 42 });
@@ -751,9 +747,7 @@ await module.evaluate();
// meta.prop = {};
// above with
// meta.prop = vm.runInContext('{}', contextifiedObject);
-```
-
-```cjs
+--------------
const vm = require('node:vm');
const contextifiedObject = vm.createContext({ secret: 42 });
(async () => {
@@ -874,7 +868,7 @@ This method is used after the module is linked to set the values of exports. If
it is called before the module is linked, an [`ERR_VM_MODULE_STATUS`][] error
will be thrown.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const m = new vm.SyntheticModule(['x'], () => {
@@ -885,9 +879,7 @@ await m.link(() => {});
await m.evaluate();
assert.strictEqual(m.namespace.x, 1);
-```
-
-```cjs
+--------------
const vm = require('node:vm');
(async () => {
const m = new vm.SyntheticModule(['x'], () => {
@@ -901,7 +893,7 @@ const vm = require('node:vm');
### `vm.compileFunction(code[, params[, options]])`
-
+
* `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The body of the function to compile.
* `params` string\[] An array of strings containing all parameters for the
diff --git a/content/api/v18/wasi.en.md b/content/api/v18/wasi.en.md
index 152ee80eff..60dbeb81a2 100644
--- a/content/api/v18/wasi.en.md
+++ b/content/api/v18/wasi.en.md
@@ -13,13 +13,13 @@ Experimental
-
+
The WASI API provides an implementation of the [WebAssembly System Interface][]
specification. WASI gives sandboxed WebAssembly applications access to the
underlying operating system via a collection of POSIX-like functions.
-```mjs
+```mjs|cjs
import { readFile } from 'node:fs/promises';
import { WASI } from 'wasi';
import { argv, env } from 'node:process';
@@ -42,9 +42,7 @@ const wasm = await WebAssembly.compile(
const instance = await WebAssembly.instantiate(wasm, importObject);
wasi.start(instance);
-```
-
-```cjs
+--------------
'use strict';
const { readFile } = require('node:fs/promises');
const { WASI } = require('wasi');
diff --git a/content/api/v18/webstreams.en.md b/content/api/v18/webstreams.en.md
index 9f7a43d1ec..74bcb14da8 100644
--- a/content/api/v18/webstreams.en.md
+++ b/content/api/v18/webstreams.en.md
@@ -36,7 +36,7 @@ This example creates a simple `ReadableStream` that pushes the current
`performance.now()` timestamp once every second forever. An async iterable
is used to read the data from the stream.
-```mjs
+```mjs|cjs
import {
ReadableStream,
} from 'node:stream/web';
@@ -60,9 +60,7 @@ const stream = new ReadableStream({
for await (const value of stream)
console.log(value);
-```
-
-```cjs
+--------------
const {
ReadableStream,
} = require('node:stream/web');
@@ -153,7 +151,7 @@ stream's data.
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) `'byob'` or `undefined`
* Returns: [`ReadableStreamDefaultReader`](/api/v18/webstreams#readablestreamdefaultreader) | [`ReadableStreamBYOBReader`](/api/v18/webstreams#readablestreambyobreader)
-```mjs
+```mjs|cjs
import { ReadableStream } from 'node:stream/web';
const stream = new ReadableStream();
@@ -161,9 +159,7 @@ const stream = new ReadableStream();
const reader = stream.getReader();
console.log(await reader.read());
-```
-
-```cjs
+--------------
const { ReadableStream } = require('node:stream/web');
const stream = new ReadableStream();
@@ -206,7 +202,7 @@ pipeline is configured, `transform.readable` is returned.
Causes the `readableStream.locked` to be `true` while the pipe operation
is active.
-```mjs
+```mjs|cjs
import {
ReadableStream,
TransformStream,
@@ -228,9 +224,7 @@ const transformedStream = stream.pipeThrough(transform);
for await (const chunk of transformedStream)
console.log(chunk);
-```
-
-```cjs
+--------------
const {
ReadableStream,
TransformStream,
@@ -562,7 +556,7 @@ Closes the [`ReadableStream`](/api/v18/webstreams#readablestream) to which this
Returns the amount of data remaining to fill the [`ReadableStream`](/api/v18/webstreams#readablestream)'s
queue.
-##### `readableStreamDefaultController.enqueue(chunk)`
+##### `readableStreamDefaultController.enqueue([chunk])`
@@ -570,7 +564,7 @@ queue.
Appends a new chunk of data to the [`ReadableStream`](/api/v18/webstreams#readablestream)'s queue.
-##### `readableStreamDefaultController.error(error)`
+##### `readableStreamDefaultController.error([error])`
@@ -615,7 +609,7 @@ queue.
Appends a new chunk of data to the [`ReadableStream`](/api/v18/webstreams#readablestream)'s queue.
-##### `readableByteStreamController.error(error)`
+##### `readableByteStreamController.error([error])`
@@ -841,7 +835,7 @@ Appends a new chunk of data to the [`WritableStream`](/api/v18/webstreams#writab
The `WritableStreamDefaultController` manage's the [`WritableStream`](/api/v18/webstreams#writablestream)'s
internal state.
-##### `writableStreamDefaultController.error(error)`
+##### `writableStreamDefaultController.error([error])`
@@ -1180,7 +1174,7 @@ streams.
They are accessed using:
-```mjs
+```mjs|cjs
import {
arrayBuffer,
blob,
@@ -1188,9 +1182,7 @@ import {
json,
text,
} from 'node:stream/consumers';
-```
-
-```cjs
+--------------
const {
arrayBuffer,
blob,
@@ -1208,7 +1200,7 @@ const {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an `ArrayBuffer` containing the full
contents of the stream.
-```mjs
+```mjs|cjs
import { buffer as arrayBuffer } from 'node:stream/consumers';
import { Readable } from 'node:stream';
import { TextEncoder } from 'node:util';
@@ -1219,15 +1211,13 @@ const dataArray = encoder.encode('hello world from consumers!');
const readable = Readable.from(dataArray);
const data = await arrayBuffer(readable);
console.log(`from readable: ${data.byteLength}`);
-```
-
-```cjs
+--------------
const { arrayBuffer } = require('node:stream/consumers');
const { Readable } = require('node:stream');
const { TextEncoder } = require('node:util');
const encoder = new TextEncoder();
-const dataArray = encoder.encode(['hello world from consumers!']);
+const dataArray = encoder.encode('hello world from consumers!');
const readable = Readable.from(dataArray);
arrayBuffer(readable).then((data) => {
console.log(`from readable: ${data.byteLength}`);
@@ -1242,7 +1232,7 @@ arrayBuffer(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`Blob`](/api/v18/buffer#blob) containing the full contents
of the stream.
-```mjs
+```mjs|cjs
import { blob } from 'node:stream/consumers';
const dataBlob = new Blob(['hello world from consumers!']);
@@ -1250,9 +1240,7 @@ const dataBlob = new Blob(['hello world from consumers!']);
const readable = dataBlob.stream();
const data = await blob(readable);
console.log(`from readable: ${data.size}`);
-```
-
-```cjs
+--------------
const { blob } = require('node:stream/consumers');
const dataBlob = new Blob(['hello world from consumers!']);
@@ -1271,7 +1259,7 @@ blob(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`Buffer`](/api/v18/buffer#buffer) containing the full
contents of the stream.
-```mjs
+```mjs|cjs
import { buffer } from 'node:stream/consumers';
import { Readable } from 'node:stream';
import { Buffer } from 'node:buffer';
@@ -1281,9 +1269,7 @@ const dataBuffer = Buffer.from('hello world from consumers!');
const readable = Readable.from(dataBuffer);
const data = await buffer(readable);
console.log(`from readable: ${data.length}`);
-```
-
-```cjs
+--------------
const { buffer } = require('node:stream/consumers');
const { Readable } = require('node:stream');
const { Buffer } = require('node:buffer');
@@ -1304,7 +1290,7 @@ buffer(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the contents of the stream parsed as a
UTF-8 encoded string that is then passed through `JSON.parse()`.
-```mjs
+```mjs|cjs
import { json } from 'node:stream/consumers';
import { Readable } from 'node:stream';
@@ -1320,9 +1306,7 @@ const items = Array.from(
const readable = Readable.from(JSON.stringify(items));
const data = await json(readable);
console.log(`from readable: ${data.length}`);
-```
-
-```cjs
+--------------
const { json } = require('node:stream/consumers');
const { Readable } = require('node:stream');
@@ -1349,16 +1333,14 @@ json(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the contents of the stream parsed as a
UTF-8 encoded string.
-```mjs
-import { json, text, blob, buffer } from 'node:stream/consumers';
+```mjs|cjs
+import { text } from 'node:stream/consumers';
import { Readable } from 'node:stream';
const readable = Readable.from('Hello world from consumers!');
const data = await text(readable);
console.log(`from readable: ${data.length}`);
-```
-
-```cjs
+--------------
const { text } = require('node:stream/consumers');
const { Readable } = require('node:stream');
diff --git a/content/api/v18/worker_threads.en.md b/content/api/v18/worker_threads.en.md
index dd32ebb1e0..797df05bb2 100644
--- a/content/api/v18/worker_threads.en.md
+++ b/content/api/v18/worker_threads.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:worker_threads` module enables the use of threads that execute
JavaScript in parallel. To access it:
@@ -789,7 +789,7 @@ if (isMainThread) {
#### `new Worker(filename[, options])`
-
+
* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api) The path to the Worker's main script or module. Must
be either an absolute path or a relative path (i.e. relative to the
@@ -854,6 +854,9 @@ if (isMainThread) {
used for generated code.
* `stackSizeMb` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The default maximum stack size for the thread.
Small values may lead to unusable Worker instances. **Default:** `4`.
+ * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) An optional `name` to be appended to the worker title
+ for debuggin/identification purposes, making the final title as
+ `[worker $id] $name`. **Default:** `''`.
#### `'error'`
@@ -1081,7 +1084,7 @@ with `stdio`. This means that `stdio` output originating from a `Worker` can
get blocked by synchronous code on the receiving end that is blocking the
Node.js event loop.
-```mjs
+```mjs|cjs
import {
Worker,
isMainThread,
@@ -1096,9 +1099,7 @@ if (isMainThread) {
// This output will be blocked by the for loop in the main thread.
console.log('foo');
}
-```
-
-```cjs
+--------------
'use strict';
const {
diff --git a/content/api/v18/zlib.en.md b/content/api/v18/zlib.en.md
index b8747f593e..30ca5ff110 100644
--- a/content/api/v18/zlib.en.md
+++ b/content/api/v18/zlib.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:zlib` module provides compression functionality implemented using
Gzip, Deflate/Inflate, and Brotli.
@@ -147,7 +147,7 @@ Using `zlib` encoding can be expensive, and the results ought to be cached.
See [Memory usage tuning][] for more information on the speed/memory/compression
tradeoffs involved in `zlib` usage.
-```js
+```js|js
// Client request example
const zlib = require('node:zlib');
const http = require('node:http');
@@ -184,9 +184,7 @@ request.on('response', (response) => {
break;
}
});
-```
-
-```js
+--------------
// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
diff --git a/content/api/v19/assert.en.md b/content/api/v19/assert.en.md
index 19f6dc8c72..cbdca11748 100644
--- a/content/api/v19/assert.en.md
+++ b/content/api/v19/assert.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:assert` module provides a set of assertion functions for verifying
invariants.
@@ -31,25 +31,21 @@ assertion mode, error messages for objects display the objects, often truncated.
To use strict assertion mode:
-```mjs
+```mjs|cjs
import { strict as assert } from 'node:assert';
-```
-
-```cjs
+--------------
const assert = require('node:assert').strict;
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
```
Example error diff:
-```mjs
+```mjs|cjs
import { strict as assert } from 'node:assert';
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
@@ -66,9 +62,7 @@ assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// ...
// 5
// ]
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
@@ -103,11 +97,9 @@ Legacy assertion mode uses the [`==` operator][] in:
To use legacy assertion mode:
-```mjs
+```mjs|cjs
import assert from 'node:assert';
-```
-
-```cjs
+--------------
const assert = require('node:assert');
```
@@ -153,7 +145,7 @@ and:
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
+```mjs|cjs
import assert from 'node:assert';
// Generate an AssertionError to compare the error message later:
@@ -176,9 +168,7 @@ try {
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:
@@ -224,7 +214,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
import process from 'node:process';
@@ -242,9 +232,7 @@ callsfunc();
process.on('exit', () => {
tracker.verify();
});
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const tracker = new assert.CallTracker();
@@ -276,7 +264,7 @@ function has not been called exactly `exact` times when
[`tracker.verify()`][] is called, then [`tracker.verify()`][] will throw an
error.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
// Creates call tracker.
@@ -287,9 +275,7 @@ 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.
@@ -314,7 +300,7 @@ const callsfunc = tracker.calls(func);
* `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
+```mjs|cjs
import assert from 'node:assert';
const tracker = new assert.CallTracker();
@@ -325,9 +311,7 @@ callsfunc(1, 2, 3);
assert.deepStrictEqual(tracker.getCalls(callsfunc),
[{ thisArg: this, arguments: [1, 2, 3 ] }]);
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Creates call tracker.
@@ -358,7 +342,7 @@ assert.deepStrictEqual(tracker.getCalls(callsfunc),
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
+```mjs|cjs
import assert from 'node:assert';
// Creates call tracker.
@@ -382,9 +366,7 @@ tracker.report();
// stack: stack trace
// }
// ]
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Creates call tracker.
@@ -420,7 +402,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
const tracker = new assert.CallTracker();
@@ -434,9 +416,7 @@ tracker.getCalls(callsfunc).length === 1;
tracker.reset(callsfunc);
tracker.getCalls(callsfunc).length === 0;
-```
-
-```cjs
+--------------
const assert = require('node:assert');
function func() {}
@@ -458,7 +438,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
// Creates call tracker.
@@ -474,9 +454,7 @@ callsfunc();
// Will throw an error since callsfunc() was only called once.
tracker.verify();
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Creates call tracker.
@@ -554,14 +532,12 @@ are also recursively evaluated by the following rules.
The following example does not throw an [`AssertionError`][] because the
primitives are compared using the [`==` operator][].
-```mjs
+```mjs|cjs
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!
@@ -571,7 +547,7 @@ assert.deepEqual('+00000000', false);
"Deep" equality means that the enumerable "own" properties of child objects
are evaluated also:
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const obj1 = {
@@ -604,9 +580,7 @@ assert.deepEqual(obj1, obj3);
// Prototypes are ignored:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const obj1 = {
@@ -679,7 +653,7 @@ are recursively evaluated also by the following rules.
* [`RegExp`][] lastIndex, flags, and source are always compared, even if these
are not enumerable properties.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
// This fails because 1 !== '1'.
@@ -769,9 +743,7 @@ assert.deepStrictEqual(weakMap1, weakMap3);
// - [items unknown],
// - unequal: true
// }
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
// This fails because 1 !== '1'.
@@ -879,7 +851,7 @@ parameter is an instance of an [`Error`][] then it will be thrown instead of the
Expects the `string` input not to match the regular expression.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotMatch('I will fail', /fail/);
@@ -890,9 +862,7 @@ assert.doesNotMatch(123, /pass/);
assert.doesNotMatch('I will pass', /different/);
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotMatch('I will fail', /fail/);
@@ -941,7 +911,7 @@ function. See [`assert.throws()`][] for more details.
Besides the async nature to await the completion behaves identically to
[`assert.doesNotThrow()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
await assert.doesNotReject(
@@ -950,9 +920,7 @@ await assert.doesNotReject(
},
SyntaxError,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
(async () => {
@@ -965,16 +933,14 @@ const assert = require('node:assert/strict');
})();
```
-```mjs
+```mjs|cjs
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')))
@@ -1012,7 +978,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotThrow(
@@ -1021,9 +987,7 @@ assert.doesNotThrow(
},
SyntaxError,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotThrow(
@@ -1037,7 +1001,7 @@ assert.doesNotThrow(
However, the following will result in an [`AssertionError`][] with the message
'Got unwanted exception...':
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotThrow(
@@ -1046,9 +1010,7 @@ assert.doesNotThrow(
},
TypeError,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotThrow(
@@ -1063,7 +1025,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.doesNotThrow(
@@ -1074,9 +1036,7 @@ assert.doesNotThrow(
'Whoops',
);
// Throws: AssertionError: Got unwanted exception: Whoops
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.doesNotThrow(
@@ -1113,7 +1073,7 @@ 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
+```mjs|cjs
import assert from 'node:assert';
assert.equal(1, 1);
@@ -1127,9 +1087,7 @@ 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);
@@ -1161,7 +1119,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.fail();
@@ -1172,9 +1130,7 @@ assert.fail('boom');
assert.fail(new TypeError('need array'));
// TypeError: need array
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.fail();
@@ -1215,7 +1171,7 @@ the other arguments will be stored as properties on the thrown object. If
removed from stacktrace (see [`Error.captureStackTrace`][]). If no arguments are
given, the default message `Failed` will be used.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.fail('a', 'b');
@@ -1232,9 +1188,7 @@ assert.fail(1, 2, 'whoops', '>');
assert.fail(1, 2, new TypeError('need array'));
// TypeError: need array
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.fail('a', 'b');
@@ -1258,7 +1212,7 @@ influence on the error message.
Example use of `stackStartFn` for truncating the exception's stacktrace:
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
function suppressFrame() {
@@ -1269,9 +1223,7 @@ suppressFrame();
// at repl:1:1
// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
// ...
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
function suppressFrame() {
@@ -1295,7 +1247,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.ifError(null);
@@ -1319,9 +1271,7 @@ let err;
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
// at ifErrorFrame
// at errorFrame
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.ifError(null);
@@ -1357,7 +1307,7 @@ let err;
Expects the `string` input to match the regular expression.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.match('I will fail', /pass/);
@@ -1368,9 +1318,7 @@ assert.match(123, /pass/);
assert.match('I will pass', /pass/);
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.match('I will fail', /pass/);
@@ -1412,7 +1360,7 @@ Legacy: Use [`assert.notDeepStrictEqual()`][] instead.
Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const obj1 = {
@@ -1443,9 +1391,7 @@ assert.notDeepEqual(obj1, obj3);
assert.notDeepEqual(obj1, obj4);
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const obj1 = {
@@ -1494,14 +1440,12 @@ instead of the `AssertionError`.
Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
-```mjs
+```mjs|cjs
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' });
@@ -1537,7 +1481,7 @@ Legacy: Use [`assert.notStrictEqual()`][] instead.
Tests shallow, coercive inequality with the [`!=` operator][]. `NaN` is
specially handled and treated as being identical if both sides are `NaN`.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
assert.notEqual(1, 2);
@@ -1548,9 +1492,7 @@ assert.notEqual(1, 1);
assert.notEqual(1, '1');
// AssertionError: 1 != '1'
-```
-
-```cjs
+--------------
const assert = require('node:assert');
assert.notEqual(1, 2);
@@ -1580,7 +1522,7 @@ parameter is an instance of an [`Error`][] then it will be thrown instead of the
Tests strict inequality between the `actual` and `expected` parameters as
determined by [`Object.is()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.notStrictEqual(1, 2);
@@ -1593,9 +1535,7 @@ assert.notStrictEqual(1, 1);
assert.notStrictEqual(1, '1');
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.notStrictEqual(1, 2);
@@ -1637,7 +1577,7 @@ If no arguments are passed in at all `message` will be set to the string:
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
+```mjs|cjs
import assert from 'node:assert/strict';
assert.ok(true);
@@ -1670,9 +1610,7 @@ assert.ok(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert.ok(0)
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.ok(true);
@@ -1707,7 +1645,7 @@ assert.ok(0);
// assert.ok(0)
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
// Using `assert()` works the same:
@@ -1715,9 +1653,7 @@ assert(0);
// AssertionError: The expression evaluated to a falsy value:
//
// assert(0)
-```
-
-```cjs
+--------------
const assert = require('node:assert');
// Using `assert()` works the same:
@@ -1756,7 +1692,7 @@ each property will be tested for including the non-enumerable `message` and
If specified, `message` will be the message provided by the [`AssertionError`][]
if the `asyncFn` fails to reject.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
await assert.rejects(
@@ -1768,9 +1704,7 @@ await assert.rejects(
message: 'Wrong value',
},
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
(async () => {
@@ -1786,7 +1720,7 @@ const assert = require('node:assert/strict');
})();
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
await assert.rejects(
@@ -1799,9 +1733,7 @@ await assert.rejects(
return true;
},
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
(async () => {
@@ -1818,7 +1750,7 @@ const assert = require('node:assert/strict');
})();
```
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.rejects(
@@ -1827,9 +1759,7 @@ assert.rejects(
).then(() => {
// ...
});
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.rejects(
@@ -1857,7 +1787,7 @@ argument gets considered.
Tests strict equality between the `actual` and `expected` parameters as
determined by [`Object.is()`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.strictEqual(1, 2);
@@ -1883,9 +1813,7 @@ assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
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);
@@ -1942,7 +1870,7 @@ fails.
Custom validation object/error instance:
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
const err = new TypeError('Wrong value');
@@ -2009,9 +1937,7 @@ assert.throws(
// an error as validation object.
err,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
const err = new TypeError('Wrong value');
@@ -2082,7 +2008,7 @@ assert.throws(
Validate instanceof using constructor:
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.throws(
@@ -2091,9 +2017,7 @@ assert.throws(
},
Error,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.throws(
@@ -2109,7 +2033,7 @@ Validate error message using [`RegExp`][]:
Using a regular expression runs `.toString` on the error object, and will
therefore also include the error name.
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.throws(
@@ -2118,9 +2042,7 @@ assert.throws(
},
/^Error: Wrong value$/,
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.throws(
@@ -2136,7 +2058,7 @@ Custom error validation:
The function must return `true` to indicate all internal validations passed.
It will otherwise fail with an [`AssertionError`][].
-```mjs
+```mjs|cjs
import assert from 'node:assert/strict';
assert.throws(
@@ -2155,9 +2077,7 @@ assert.throws(
},
'unexpected error',
);
-```
-
-```cjs
+--------------
const assert = require('node:assert/strict');
assert.throws(
@@ -2185,7 +2105,7 @@ 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
+```mjs|cjs
import assert from 'node:assert/strict';
function throwingFirst() {
@@ -2219,9 +2139,7 @@ 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() {
diff --git a/content/api/v19/async_context.en.md b/content/api/v19/async_context.en.md
index 96fdad2605..b5aeede3fa 100644
--- a/content/api/v19/async_context.en.md
+++ b/content/api/v19/async_context.en.md
@@ -13,7 +13,7 @@ Stable
-
+
### Introduction
@@ -26,11 +26,9 @@ in other languages.
The `AsyncLocalStorage` and `AsyncResource` classes are part of the
`node:async_hooks` module:
-```mjs
+```mjs|cjs
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
-```
-
-```cjs
+--------------
const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');
```
@@ -49,7 +47,7 @@ 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
+```mjs|cjs
import http from 'node:http';
import { AsyncLocalStorage } from 'node:async_hooks';
@@ -79,9 +77,7 @@ http.get('http://localhost:8080');
// 1: start
// 0: finish
// 1: finish
-```
-
-```cjs
+--------------
const http = require('node:http');
const { AsyncLocalStorage } = require('node:async_hooks');
@@ -124,6 +120,60 @@ with each other's data.
Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
`run()` call or after an `enterWith()` call.
+#### Static method: `AsyncLocalStorage.bind(fn)`
+
+
+
+
+
+Experimental
+
+
+
+* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to bind to the current execution context.
+* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A new function that calls `fn` within the captured
+ execution context.
+
+Binds the given function to the current execution context.
+
+#### Static method: `AsyncLocalStorage.snapshot()`
+
+
+
+
+
+Experimental
+
+
+
+* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A new function with the signature
+ `(fn: (...args) : R, ...args) : R`.
+
+Captures the current execution context and returns a function that accepts a
+function as an argument. Whenever the returned function is called, it
+calls the function passed to it within the captured context.
+
+```js
+const asyncLocalStorage = new AsyncLocalStorage();
+const runInAsyncScope = asyncLocalStorage.run(123, () => asyncLocalStorage.snapshot());
+const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
+console.log(result); // returns 123
+```
+
+AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
+async context tracking purposes, for example:
+
+```js
+class Foo {
+ #runInAsyncScope = AsyncLocalStorage.snapshot();
+
+ get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
+}
+
+const foo = asyncLocalStorage.run(123, () => new Foo());
+console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
+```
+
#### `asyncLocalStorage.disable()`
@@ -331,7 +381,7 @@ The `init` hook will trigger when an `AsyncResource` is instantiated.
The following is an overview of the `AsyncResource` API.
-```mjs
+```mjs|cjs
import { AsyncResource, executionAsyncId } from 'node:async_hooks';
// AsyncResource() is meant to be extended. Instantiating a
@@ -357,9 +407,7 @@ 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
@@ -492,14 +540,12 @@ 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
+```mjs|cjs
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);
@@ -508,7 +554,7 @@ parentPort.on('message', (task) => {
a Worker pool around it could use the following structure:
-```mjs
+```mjs|cjs
import { AsyncResource } from 'node:async_hooks';
import { EventEmitter } from 'node:events';
import path from 'node:path';
@@ -594,9 +640,7 @@ export default class WorkerPool extends EventEmitter {
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');
@@ -694,7 +738,7 @@ were scheduled.
This pool could be used as follows:
-```mjs
+```mjs|cjs
import WorkerPool from './worker_pool.js';
import os from 'node:os';
@@ -708,9 +752,7 @@ for (let i = 0; i < 10; i++) {
pool.close();
});
}
-```
-
-```cjs
+--------------
const WorkerPool = require('./worker_pool.js');
const os = require('node:os');
@@ -736,7 +778,7 @@ 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
+```mjs|cjs
import { createServer } from 'node:http';
import { AsyncResource, executionAsyncId } from 'node:async_hooks';
@@ -749,9 +791,7 @@ const server = createServer((req, res) => {
});
res.end();
}).listen(3000);
-```
-
-```cjs
+--------------
const { createServer } = require('node:http');
const { AsyncResource, executionAsyncId } = require('node:async_hooks');
diff --git a/content/api/v19/async_hooks.en.md b/content/api/v19/async_hooks.en.md
index 6a05103e2c..1ede29a321 100644
--- a/content/api/v19/async_hooks.en.md
+++ b/content/api/v19/async_hooks.en.md
@@ -13,7 +13,7 @@ Experimental. Please migrate away from this API, if you can. We do not recommend
-
+
We strongly discourage the use of the `async_hooks` API.
Other APIs that can cover most of its use cases include:
@@ -24,11 +24,9 @@ Other APIs that can cover most of its use cases include:
The `node:async_hooks` module provides an API to track asynchronous resources.
It can be accessed using:
-```mjs
+```mjs|cjs
import async_hooks from 'node:async_hooks';
-```
-
-```cjs
+--------------
const async_hooks = require('node:async_hooks');
```
@@ -48,7 +46,7 @@ interface, and each thread will use a new set of async IDs.
Following is a simple overview of the public API.
-```mjs
+```mjs|cjs
import async_hooks from 'node:async_hooks';
// Return the ID of the current execution context.
@@ -94,9 +92,7 @@ function destroy(asyncId) { }
// 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.
@@ -167,16 +163,14 @@ 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
+```mjs|cjs
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({
@@ -232,7 +226,7 @@ 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
+```mjs|cjs
import { writeFileSync } from 'node:fs';
import { format } from 'node:util';
@@ -240,9 +234,7 @@ 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');
@@ -273,13 +265,11 @@ 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
+```mjs|cjs
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();
@@ -319,15 +309,13 @@ 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
+```mjs|cjs
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));
@@ -369,10 +357,11 @@ created, while `triggerAsyncId` shows _why_ a resource was created.
The following is a simple demonstration of `triggerAsyncId`:
-```mjs
+```mjs|cjs
import { createHook, executionAsyncId } from 'node:async_hooks';
import { stdout } from 'node:process';
import net from 'node:net';
+import fs from 'node:fs';
createHook({
init(asyncId, type, triggerAsyncId) {
@@ -384,12 +373,11 @@ createHook({
}).enable();
net.createServer((conn) => {}).listen(8080);
-```
-
-```cjs
+--------------
const { createHook, executionAsyncId } = require('node:async_hooks');
const { stdout } = require('node:process');
const net = require('node:net');
+const fs = require('node:fs');
createHook({
init(asyncId, type, triggerAsyncId) {
@@ -624,7 +612,7 @@ 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
+```mjs|cjs
import { open } from 'node:fs';
import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
@@ -632,9 +620,7 @@ 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');
@@ -647,7 +633,7 @@ open(__filename, 'r', (err, fd) => {
This can be used to implement continuation local storage without the
use of a tracking `Map` to store the metadata:
-```mjs
+```mjs|cjs
import { createServer } from 'node:http';
import {
executionAsyncId,
@@ -671,9 +657,7 @@ const server = createServer((req, res) => {
res.end(JSON.stringify(executionAsyncResource()[sym]));
}, 100);
}).listen(3000);
-```
-
-```cjs
+--------------
const { createServer } = require('node:http');
const {
executionAsyncId,
@@ -706,17 +690,17 @@ const server = createServer((req, res) => {
* 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
+```mjs|cjs
import { executionAsyncId } from 'node:async_hooks';
+import fs from 'node:fs';
console.log(executionAsyncId()); // 1 - bootstrap
fs.open(path, 'r', (err, fd) => {
console.log(executionAsyncId()); // 6 - open()
});
-```
-
-```cjs
+--------------
const async_hooks = require('node:async_hooks');
+const fs = require('node:fs');
console.log(async_hooks.executionAsyncId()); // 1 - bootstrap
fs.open(path, 'r', (err, fd) => {
@@ -783,7 +767,7 @@ 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
+```mjs|cjs
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
Promise.resolve(1729).then(() => {
@@ -791,9 +775,7 @@ Promise.resolve(1729).then(() => {
});
// produces:
// eid 1 tid 0
-```
-
-```cjs
+--------------
const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');
Promise.resolve(1729).then(() => {
@@ -811,7 +793,7 @@ the resource that caused (triggered) the `then()` callback to be executed.
Installing async hooks via `async_hooks.createHook` enables promise execution
tracking:
-```mjs
+```mjs|cjs
import { createHook, executionAsyncId, triggerAsyncId } from 'node:async_hooks';
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
Promise.resolve(1729).then(() => {
@@ -819,9 +801,7 @@ Promise.resolve(1729).then(() => {
});
// produces:
// eid 7 tid 6
-```
-
-```cjs
+--------------
const { createHook, executionAsyncId, triggerAsyncId } = require('node:async_hooks');
createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
diff --git a/content/api/v19/buffer.en.md b/content/api/v19/buffer.en.md
index ae21e9d909..c0410518e4 100644
--- a/content/api/v19/buffer.en.md
+++ b/content/api/v19/buffer.en.md
@@ -13,7 +13,7 @@ Stable
-
+
`Buffer` objects are used to represent a fixed-length sequence of bytes. Many
Node.js APIs support `Buffer`s.
@@ -25,7 +25,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Creates a zero-filled Buffer of length 10.
@@ -56,9 +56,7 @@ 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.
@@ -99,7 +97,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello world', 'utf8');
@@ -113,9 +111,7 @@ 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');
@@ -194,7 +190,7 @@ The following legacy character encodings are also supported:
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
Buffer.from('1ag123', 'hex');
@@ -206,9 +202,7 @@ Buffer.from('1a7', 'hex');
Buffer.from('1634', 'hex');
// Prints , all data represented.
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
Buffer.from('1ag123', 'hex');
@@ -255,7 +249,7 @@ There are two ways to create new [`TypedArray`][] instances from a `Buffer`:
contents, interpreted as an array of integers, and not as a byte sequence
of the target type.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
@@ -264,9 +258,7 @@ 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]);
@@ -280,7 +272,7 @@ console.log(uint32array);
* Passing the `Buffer`s underlying [`ArrayBuffer`][] will create a
[`TypedArray`][] that shares its memory with the `Buffer`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('hello', 'utf16le');
@@ -292,9 +284,7 @@ const uint16array = new Uint16Array(
console.log(uint16array);
// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('hello', 'utf16le');
@@ -313,7 +303,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
@@ -338,9 +328,7 @@ console.log(buf1);
// Prints:
console.log(buf2);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
@@ -371,7 +359,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(20);
@@ -379,9 +367,7 @@ 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);
@@ -410,7 +396,7 @@ function:
`Buffer` instances can be iterated over using `for..of` syntax:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3]);
@@ -422,9 +408,7 @@ for (const b of buf) {
// 1
// 2
// 3
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3]);
@@ -530,7 +514,7 @@ 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
+```mjs|cjs
import { Blob, Buffer } from 'node:buffer';
import { setTimeout as delay } from 'node:timers/promises';
@@ -555,9 +539,7 @@ 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');
@@ -602,16 +584,14 @@ It can be constructed in a variety of ways.
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
`Buffer` will be zero-filled.
-```mjs
+```mjs|cjs
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);
@@ -627,16 +607,14 @@ is thrown.
If `fill` is specified, the allocated `Buffer` will be initialized by calling
[`buf.fill(fill)`][`buf.fill()`].
-```mjs
+```mjs|cjs
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');
@@ -648,16 +626,14 @@ console.log(buf);
If both `fill` and `encoding` are specified, the allocated `Buffer` will be
initialized by calling [`buf.fill(fill, encoding)`][`buf.fill()`].
-```mjs
+```mjs|cjs
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');
@@ -688,7 +664,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(10);
@@ -700,9 +676,7 @@ buf.fill(0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(10);
@@ -760,7 +734,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Need to keep around a few small chunks of memory.
@@ -778,9 +752,7 @@ socket.on('readable', () => {
store.push(sb);
}
});
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Need to keep around a few small chunks of memory.
@@ -821,7 +793,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const str = '\u00bd + \u00bc = \u00be';
@@ -829,9 +801,7 @@ 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';
@@ -858,7 +828,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('1234');
@@ -868,9 +838,7 @@ 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');
@@ -905,7 +873,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a single `Buffer` from a list of three `Buffer` instances.
@@ -924,9 +892,7 @@ 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.
@@ -950,6 +916,26 @@ console.log(bufA.length);
`Buffer.concat()` may also use the internal `Buffer` pool like
[`Buffer.allocUnsafe()`][] does.
+#### Static method: `Buffer.copyBytesFrom(view[, offset[, length]])`
+
+
+
+* `view` [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) The [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) to copy.
+* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The starting offset within `view`. **Default:**: `0`.
+* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of elements from `view` to copy.
+ **Default:** `view.length - offset`.
+
+Copies the underlying memory of `view` into a new `Buffer`.
+
+```js
+const u16 = new Uint16Array([0, 0xffff]);
+const buf = Buffer.copyBytesFrom(u16, 0, 1);
+u16[1] = 0;
+console.log(buf.length); // 2
+console.log(buf[0]); // 255
+console.log(buf[1]); // 255
+```
+
#### Static method: `Buffer.from(array)`
@@ -959,14 +945,12 @@ console.log(bufA.length);
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
@@ -995,7 +979,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arr = new Uint16Array(2);
@@ -1014,9 +998,7 @@ arr[1] = 6000;
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const arr = new Uint16Array(2);
@@ -1040,7 +1022,7 @@ console.log(buf);
The optional `byteOffset` and `length` arguments specify a memory range within
the `arrayBuffer` that will be shared by the `Buffer`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const ab = new ArrayBuffer(10);
@@ -1048,9 +1030,7 @@ const buf = Buffer.from(ab, 0, 2);
console.log(buf.length);
// Prints: 2
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const ab = new ArrayBuffer(10);
@@ -1069,7 +1049,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
@@ -1079,9 +1059,7 @@ 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
@@ -1102,7 +1080,7 @@ console.log(buf);
Copies the passed `buffer` data onto a new `Buffer` instance.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('buffer');
@@ -1114,9 +1092,7 @@ console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: buffer
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf1 = Buffer.from('buffer');
@@ -1144,14 +1120,12 @@ appropriate for `Buffer.from()` variants.
For objects whose `valueOf()` function returns a value not strictly equal to
`object`, returns `Buffer.from(object.valueOf(), offsetOrEncoding, length)`.
-```mjs
+```mjs|cjs
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'));
@@ -1161,7 +1135,7 @@ const buf = Buffer.from(new String('this is a test'));
For objects that support `Symbol.toPrimitive`, returns
`Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
class Foo {
@@ -1172,9 +1146,7 @@ class Foo {
const buf = Buffer.from(new Foo(), 'utf8');
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
class Foo {
@@ -1200,7 +1172,7 @@ is not of another type appropriate for `Buffer.from()` variants.
Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
the character encoding to be used when converting `string` into bytes.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('this is a tést');
@@ -1212,9 +1184,7 @@ 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');
@@ -1240,7 +1210,7 @@ appropriate for `Buffer.from()` variants.
Returns `true` if `obj` is a `Buffer`, `false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
Buffer.isBuffer(Buffer.alloc(10)); // true
@@ -1248,9 +1218,7 @@ 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
@@ -1270,7 +1238,7 @@ Buffer.isBuffer(new Uint8Array(1024)); // false
Returns `true` if `encoding` is the name of a supported character encoding,
or `false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
console.log(Buffer.isEncoding('utf8'));
@@ -1284,9 +1252,7 @@ console.log(Buffer.isEncoding('utf/8'));
console.log(Buffer.isEncoding(''));
// Prints: false
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
console.log(Buffer.isEncoding('utf8'));
@@ -1325,7 +1291,7 @@ access is the same as `Uint8Array`. In other words, `buf[index]` returns
`buf[index] = value` does not modify the buffer if `index` is negative or
`>= buf.length`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Copy an ASCII string into a `Buffer` one byte at a time.
@@ -1341,9 +1307,7 @@ for (let i = 0; i < str.length; 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.
@@ -1369,7 +1333,7 @@ console.log(buf.toString('utf8'));
This `ArrayBuffer` is not guaranteed to correspond exactly to the original
`Buffer`. See the notes on `buf.byteOffset` for details.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const arrayBuffer = new ArrayBuffer(16);
@@ -1377,9 +1341,7 @@ const buffer = Buffer.from(arrayBuffer);
console.log(buffer.buffer === arrayBuffer);
// Prints: true
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const arrayBuffer = new ArrayBuffer(16);
@@ -1404,7 +1366,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a buffer smaller than `Buffer.poolSize`.
@@ -1414,9 +1376,7 @@ const nodeBuffer = Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// 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`.
@@ -1452,7 +1412,7 @@ Comparison is based on the actual sequence of bytes in each `Buffer`.
* `1` is returned if `target` should come _before_ `buf` when sorted.
* `-1` is returned if `target` should come _after_ `buf` when sorted.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('ABC');
@@ -1472,9 +1432,7 @@ console.log(buf2.compare(buf3));
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');
@@ -1500,7 +1458,7 @@ The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`
arguments can be used to limit the comparison to specific ranges within `target`
and `buf` respectively.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
@@ -1512,9 +1470,7 @@ 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]);
@@ -1551,7 +1507,7 @@ memory region overlaps with `buf`.
for all TypedArrays, including Node.js `Buffer`s, although it takes
different function arguments.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create two `Buffer` instances.
@@ -1570,9 +1526,7 @@ buf1.copy(buf2, 8, 16, 20);
console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Create two `Buffer` instances.
@@ -1593,7 +1547,7 @@ console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
```
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a `Buffer` and copy data from one region to an overlapping region
@@ -1610,9 +1564,7 @@ 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
@@ -1640,7 +1592,7 @@ console.log(buf.toString());
Creates and returns an [iterator][] of `[index, byte]` pairs from the contents
of `buf`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Log the entire contents of a `Buffer`.
@@ -1657,9 +1609,7 @@ for (const pair of buf.entries()) {
// [3, 102]
// [4, 101]
// [5, 114]
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Log the entire contents of a `Buffer`.
@@ -1690,7 +1640,7 @@ Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,
`false` otherwise. Equivalent to
[`buf.compare(otherBuffer) === 0`][`buf.compare()`].
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from('ABC');
@@ -1701,9 +1651,7 @@ 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');
@@ -1733,7 +1681,7 @@ console.log(buf1.equals(buf3));
Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
the entire `buf` will be filled:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with the ASCII character 'h'.
@@ -1748,9 +1696,7 @@ const c = Buffer.allocUnsafe(5).fill('');
console.log(c.fill(''));
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Fill a `Buffer` with the ASCII character 'h'.
@@ -1774,16 +1720,14 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
// Fill a `Buffer` with character that takes up two bytes in UTF-8.
@@ -1795,7 +1739,7 @@ console.log(Buffer.allocUnsafe(5).fill('\u0222'));
If `value` contains invalid characters, it is truncated; if no valid
fill data remains, an exception is thrown:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(5);
@@ -1806,9 +1750,7 @@ 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);
@@ -1834,7 +1776,7 @@ console.log(buf.fill('zz', 'hex'));
Equivalent to [`buf.indexOf() !== -1`][`buf.indexOf()`].
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this is a buffer');
@@ -1853,9 +1795,7 @@ 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');
@@ -1898,7 +1838,7 @@ If `value` is:
* a number, `value` will be interpreted as an unsigned 8-bit integer
value between `0` and `255`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this is a buffer');
@@ -1922,9 +1862,7 @@ 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');
@@ -1958,7 +1896,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
@@ -1974,9 +1912,7 @@ 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');
@@ -2006,7 +1942,7 @@ than `buf.length`, `byteOffset` will be returned. If `value` is empty and
Creates and returns an [iterator][] of `buf` keys (indices).
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -2021,9 +1957,7 @@ for (const key of buf.keys()) {
// 3
// 4
// 5
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
@@ -2057,7 +1991,7 @@ for (const key of buf.keys()) {
Identical to [`buf.indexOf()`][], except the last occurrence of `value` is found
rather than the first occurrence.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('this buffer is a buffer');
@@ -2083,9 +2017,7 @@ 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');
@@ -2121,7 +2053,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const b = Buffer.from('abcdef');
@@ -2140,9 +2072,7 @@ console.log(b.lastIndexOf('b', {}));
// 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');
@@ -2173,7 +2103,7 @@ If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned.
Returns the number of bytes in `buf`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a `Buffer` and write a shorter string to it using UTF-8.
@@ -2187,9 +2117,7 @@ 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.
@@ -2257,16 +2185,14 @@ Reads an unsigned, big-endian 64-bit integer from `buf` at the specified
This function is also available under the `readBigUint64BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64BE(0));
// Prints: 4294967295n
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
@@ -2288,16 +2214,14 @@ Reads an unsigned, little-endian 64-bit integer from `buf` at the specified
This function is also available under the `readBigUint64LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
console.log(buf.readBigUInt64LE(0));
// Prints: 18446744069414584320n
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
@@ -2316,16 +2240,14 @@ console.log(buf.readBigUInt64LE(0));
Reads a 64-bit, big-endian double from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleBE(0));
// Prints: 8.20788039913184e-304
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
@@ -2344,7 +2266,7 @@ console.log(buf.readDoubleBE(0));
Reads a 64-bit, little-endian double from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
@@ -2353,9 +2275,7 @@ 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]);
@@ -2376,16 +2296,14 @@ console.log(buf.readDoubleLE(1));
Reads a 32-bit, big-endian float from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
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]);
@@ -2404,7 +2322,7 @@ console.log(buf.readFloatBE(0));
Reads a 32-bit, little-endian float from `buf` at the specified `offset`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, 2, 3, 4]);
@@ -2413,9 +2331,7 @@ 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]);
@@ -2438,7 +2354,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([-1, 5]);
@@ -2449,9 +2365,7 @@ 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]);
@@ -2476,16 +2390,14 @@ 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
+```mjs|cjs
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]);
@@ -2507,7 +2419,7 @@ Reads a signed, little-endian 16-bit integer from `buf` at the specified
Integers read from a `Buffer` are interpreted as two's complement signed values.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 5]);
@@ -2516,9 +2428,7 @@ 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]);
@@ -2541,16 +2451,14 @@ 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
+```mjs|cjs
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]);
@@ -2572,7 +2480,7 @@ Reads a signed, little-endian 32-bit integer from `buf` at the specified
Integers read from a `Buffer` are interpreted as two's complement signed values.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0, 0, 0, 5]);
@@ -2581,9 +2489,7 @@ 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]);
@@ -2608,7 +2514,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2619,9 +2525,7 @@ 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]);
@@ -2648,16 +2552,14 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readIntLE(0, 6).toString(16));
// Prints: -546f87a9cbee
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2678,7 +2580,7 @@ Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
This function is also available under the `readUint8` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([1, -2]);
@@ -2689,9 +2591,7 @@ 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]);
@@ -2717,7 +2617,7 @@ Reads an unsigned, big-endian 16-bit integer from `buf` at the specified
This function is also available under the `readUint16BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56]);
@@ -2726,9 +2626,7 @@ 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]);
@@ -2752,7 +2650,7 @@ Reads an unsigned, little-endian 16-bit integer from `buf` at the specified
This function is also available under the `readUint16LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56]);
@@ -2763,9 +2661,7 @@ 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]);
@@ -2791,16 +2687,14 @@ Reads an unsigned, big-endian 32-bit integer from `buf` at the specified
This function is also available under the `readUint32BE` alias.
-```mjs
+```mjs|cjs
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]);
@@ -2822,7 +2716,7 @@ Reads an unsigned, little-endian 32-bit integer from `buf` at the specified
This function is also available under the `readUint32LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
@@ -2831,9 +2725,7 @@ 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]);
@@ -2860,7 +2752,7 @@ up to 48 bits of accuracy.
This function is also available under the `readUintBE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2869,9 +2761,7 @@ 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]);
@@ -2898,16 +2788,14 @@ up to 48 bits of accuracy.
This function is also available under the `readUintLE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
console.log(buf.readUIntLE(0, 6).toString(16));
// Prints: ab9078563412
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
@@ -2936,7 +2824,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
@@ -2958,9 +2846,7 @@ 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
@@ -2987,7 +2873,7 @@ console.log(buf2.toString('ascii', 0, buf2.length));
Specifying negative indexes causes the slice to be generated relative to the
end of `buf` rather than the beginning.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -3003,9 +2889,7 @@ console.log(buf.subarray(-6, -2).toString());
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');
@@ -3045,7 +2929,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -3065,9 +2949,7 @@ console.log(notReallyCopiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Also prints: cuffer (!)
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
@@ -3099,7 +2981,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
@@ -3116,9 +2998,7 @@ 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]);
@@ -3140,14 +3020,12 @@ buf2.swap16();
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
@@ -3164,7 +3042,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
@@ -3181,9 +3059,7 @@ 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]);
@@ -3211,7 +3087,7 @@ buf2.swap32();
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
@@ -3228,9 +3104,7 @@ 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]);
@@ -3261,7 +3135,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
@@ -3278,9 +3152,7 @@ const copy = JSON.parse(json, (key, value) => {
console.log(copy);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
@@ -3318,7 +3190,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf1 = Buffer.allocUnsafe(26);
@@ -3341,9 +3213,7 @@ 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);
@@ -3377,7 +3247,7 @@ console.log(buf2.toString(undefined, 0, 3));
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
@@ -3403,9 +3273,7 @@ for (const value of buf) {
// 102
// 101
// 114
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
@@ -3450,7 +3318,7 @@ Writes `string` to `buf` at `offset` according to the character encoding in
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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.alloc(256);
@@ -3466,9 +3334,7 @@ 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);
@@ -3499,7 +3365,7 @@ Writes `value` to `buf` at the specified `offset` as big-endian.
`value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3508,9 +3374,7 @@ buf.writeBigInt64BE(0x0102030405060708n, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3534,7 +3398,7 @@ Writes `value` to `buf` at the specified `offset` as little-endian.
`value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3543,9 +3407,7 @@ buf.writeBigInt64LE(0x0102030405060708n, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3569,7 +3431,7 @@ Writes `value` to `buf` at the specified `offset` as big-endian.
This function is also available under the `writeBigUint64BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3578,9 +3440,7 @@ buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3602,7 +3462,7 @@ console.log(buf);
Writes `value` to `buf` at the specified `offset` as little-endian
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3611,9 +3471,7 @@ buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3639,7 +3497,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3648,9 +3506,7 @@ buf.writeDoubleBE(123.456, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3674,7 +3530,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(8);
@@ -3683,9 +3539,7 @@ buf.writeDoubleLE(123.456, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(8);
@@ -3708,7 +3562,7 @@ console.log(buf);
Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is
undefined when `value` is anything other than a JavaScript number.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3717,9 +3571,7 @@ buf.writeFloatBE(0xcafebabe, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3742,7 +3594,7 @@ console.log(buf);
Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is
undefined when `value` is anything other than a JavaScript number.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3751,9 +3603,7 @@ buf.writeFloatLE(0xcafebabe, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3779,7 +3629,7 @@ a signed 8-bit integer.
`value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
@@ -3789,9 +3639,7 @@ buf.writeInt8(-2, 1);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
@@ -3818,7 +3666,7 @@ anything other than a signed 16-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
@@ -3827,9 +3675,7 @@ buf.writeInt16BE(0x0102, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
@@ -3855,7 +3701,7 @@ anything other than a signed 16-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(2);
@@ -3864,9 +3710,7 @@ buf.writeInt16LE(0x0304, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(2);
@@ -3892,7 +3736,7 @@ anything other than a signed 32-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3901,9 +3745,7 @@ buf.writeInt32BE(0x01020304, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3929,7 +3771,7 @@ anything other than a signed 32-bit integer.
The `value` is interpreted and written as a two's complement signed integer.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -3938,9 +3780,7 @@ buf.writeInt32LE(0x05060708, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -3966,7 +3806,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -3975,9 +3815,7 @@ buf.writeIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4003,7 +3841,7 @@ 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
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -4012,9 +3850,7 @@ buf.writeIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4040,7 +3876,7 @@ other than an unsigned 8-bit integer.
This function is also available under the `writeUint8` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4052,9 +3888,7 @@ buf.writeUInt8(0x42, 3);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4083,7 +3917,7 @@ is anything other than an unsigned 16-bit integer.
This function is also available under the `writeUint16BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4093,9 +3927,7 @@ buf.writeUInt16BE(0xbeef, 2);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4122,7 +3954,7 @@ anything other than an unsigned 16-bit integer.
This function is also available under the `writeUint16LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4132,9 +3964,7 @@ buf.writeUInt16LE(0xbeef, 2);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4161,7 +3991,7 @@ is anything other than an unsigned 32-bit integer.
This function is also available under the `writeUint32BE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4170,9 +4000,7 @@ buf.writeUInt32BE(0xfeedface, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4198,7 +4026,7 @@ anything other than an unsigned 32-bit integer.
This function is also available under the `writeUint32LE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(4);
@@ -4207,9 +4035,7 @@ buf.writeUInt32LE(0xfeedface, 0);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(4);
@@ -4237,7 +4063,7 @@ when `value` is anything other than an unsigned integer.
This function is also available under the `writeUintBE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -4246,9 +4072,7 @@ buf.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4276,7 +4100,7 @@ when `value` is anything other than an unsigned integer.
This function is also available under the `writeUintLE` alias.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const buf = Buffer.allocUnsafe(6);
@@ -4285,9 +4109,7 @@ buf.writeUIntLE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints:
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const buf = Buffer.allocUnsafe(6);
@@ -4564,15 +4386,13 @@ Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,
The transcoding process will use substitution characters if a given byte
sequence cannot be adequately represented in the target encoding. For instance:
-```mjs
+```mjs|cjs
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');
diff --git a/content/api/v19/child_process.en.md b/content/api/v19/child_process.en.md
index cff9fb0e4d..e26a4b845d 100644
--- a/content/api/v19/child_process.en.md
+++ b/content/api/v19/child_process.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:child_process` module provides the ability to spawn subprocesses in
a manner that is similar, but not identical, to popen(3). This capability
@@ -117,7 +117,7 @@ When running on Windows, `.bat` and `.cmd` files can be invoked using
[`child_process.exec()`][] do). In any case, if the script filename contains
spaces it needs to be quoted.
-```js
+```js|js
// On Windows Only...
const { spawn } = require('node:child_process');
const bat = spawn('cmd.exe', ['/c', 'my.bat']);
@@ -133,9 +133,7 @@ bat.stderr.on('data', (data) => {
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) => {
diff --git a/content/api/v19/cluster.en.md b/content/api/v19/cluster.en.md
index b0d444d108..5d9f4073b0 100644
--- a/content/api/v19/cluster.en.md
+++ b/content/api/v19/cluster.en.md
@@ -13,7 +13,7 @@ Stable
-
+
Clusters of Node.js processes can be used to run multiple instances of Node.js
that can distribute workloads among their application threads. When process
@@ -23,7 +23,7 @@ allows running multiple application threads within a single Node.js instance.
The cluster module allows easy creation of child processes that all share
server ports.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';
@@ -52,9 +52,7 @@ if (cluster.isPrimary) {
console.log(`Worker ${process.pid} started`);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const http = require('node:http');
const numCPUs = require('node:os').availableParallelism();
@@ -195,7 +193,7 @@ Within a worker, `process.on('error')` may also be used.
Similar to the `cluster.on('exit')` event, but specific to this worker.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
if (cluster.isPrimary) {
@@ -210,9 +208,7 @@ if (cluster.isPrimary) {
}
});
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
if (cluster.isPrimary) {
@@ -237,13 +233,11 @@ if (cluster.isPrimary) {
Similar to the `cluster.on('listening')` event, but specific to this worker.
-```mjs
+```mjs|cjs
cluster.fork().on('listening', (address) => {
// Worker is listening
});
-```
-
-```cjs
+--------------
cluster.fork().on('listening', (address) => {
// Worker is listening
});
@@ -267,7 +261,7 @@ See [`process` event: `'message'`][].
Here is an example using the message system. It keeps a count in the primary
process of the number of HTTP requests received by the workers:
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';
@@ -309,9 +303,7 @@ if (cluster.isPrimary) {
process.send({ cmd: 'notifyRequest' });
}).listen(8000);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const http = require('node:http');
const process = require('node:process');
@@ -485,7 +477,7 @@ has been created. It is disconnected after the `'disconnect'` event is emitted.
This function returns `true` if the worker's process has terminated (either
because of exiting or being signaled). Otherwise, it returns `false`.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import http from 'node:http';
import { availableParallelism } from 'node:os';
@@ -516,9 +508,7 @@ if (cluster.isPrimary) {
process.kill(process.pid);
}).listen(8000);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const http = require('node:http');
const numCPUs = require('node:os').availableParallelism();
@@ -892,7 +882,7 @@ the `env` passed to [`.fork()`][].
The defaults above apply to the first call only; the defaults for later
calls are the current values at the time of `cluster.setupPrimary()` is called.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
cluster.setupPrimary({
@@ -906,9 +896,7 @@ cluster.setupPrimary({
args: ['--use', 'http'],
});
cluster.fork(); // http worker
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
cluster.setupPrimary({
@@ -934,7 +922,7 @@ This can only be called from the primary process.
A reference to the current worker object. Not available in the primary process.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
if (cluster.isPrimary) {
@@ -944,9 +932,7 @@ if (cluster.isPrimary) {
} else if (cluster.isWorker) {
console.log(`I am worker #${cluster.worker.id}`);
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
if (cluster.isPrimary) {
@@ -973,15 +959,13 @@ _and_ exited. The order between these two events cannot be determined in
advance. However, it is guaranteed that the removal from the `cluster.workers`
list happens before the last `'disconnect'` or `'exit'` event is emitted.
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
for (const worker of Object.values(cluster.workers)) {
worker.send('big announcement to all workers');
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
for (const worker of Object.values(cluster.workers)) {
diff --git a/content/api/v19/console.en.md b/content/api/v19/console.en.md
index 5568871963..8048b9f311 100644
--- a/content/api/v19/console.en.md
+++ b/content/api/v19/console.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:console` module provides a simple debugging console that is similar to
the JavaScript console mechanism provided by web browsers.
@@ -83,11 +83,9 @@ The `Console` class can be used to create a simple logger with configurable
output streams and can be accessed using either `require('node:console').Console`
or `console.Console` (or their destructured counterparts):
-```js
+```js|js
const { Console } = require('node:console');
-```
-
-```js
+--------------
const { Console } = console;
```
diff --git a/content/api/v19/crypto.en.md b/content/api/v19/crypto.en.md
index 82de53f86f..fda3a676f0 100644
--- a/content/api/v19/crypto.en.md
+++ b/content/api/v19/crypto.en.md
@@ -13,13 +13,13 @@ Stable
-
+
The `node:crypto` module provides cryptographic functionality that includes a
set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
functions.
-```mjs
+```mjs|cjs
const { createHmac } = await import('node:crypto');
const secret = 'abcdefg';
@@ -29,15 +29,13 @@ const hash = createHmac('sha256', secret)
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
-```
-
-```cjs
-const crypto = require('node:crypto');
+--------------
+const { createHmac } = require('node:crypto');
const secret = 'abcdefg';
-const hash = crypto.createHmac('sha256', secret)
- .update('I love cupcakes')
- .digest('hex');
+const hash = createHmac('sha256', secret)
+ .update('I love cupcakes')
+ .digest('hex');
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
@@ -101,15 +99,13 @@ data. The most common usage is handling output generated by the HTML5
* Returns: [`Buffer`](/api/v19/buffer#buffer) The challenge component of the `spkac` data structure, which
includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
@@ -126,15 +122,13 @@ console.log(challenge.toString('utf8'));
* Returns: [`Buffer`](/api/v19/buffer#buffer) The public key component of the `spkac` data structure,
which includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
@@ -151,18 +145,16 @@ console.log(publicKey);
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the given `spkac` data structure is valid,
`false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
-```
-
-```cjs
-const { Certificate } = require('node:crypto');
+--------------
const { Buffer } = require('node:buffer');
+const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
@@ -185,14 +177,12 @@ the `crypto.Certificate` class as illustrated in the examples below.
Instances of the `Certificate` class can be created using the `new` keyword
or by calling `crypto.Certificate()` as a function:
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const cert1 = new Certificate();
const cert2 = Certificate();
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const cert1 = new Certificate();
@@ -208,16 +198,14 @@ const cert2 = Certificate();
* Returns: [`Buffer`](/api/v19/buffer#buffer) The challenge component of the `spkac` data structure, which
includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
@@ -235,16 +223,14 @@ console.log(challenge.toString('utf8'));
* Returns: [`Buffer`](/api/v19/buffer#buffer) The public key component of the `spkac` data structure,
which includes a public key and a challenge.
-```mjs
+```mjs|cjs
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as
-```
-
-```cjs
+--------------
const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
@@ -262,7 +248,7 @@ console.log(publicKey);
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the given `spkac` data structure is valid,
`false` otherwise.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { Certificate } = await import('node:crypto');
@@ -270,11 +256,9 @@ const cert = Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
-```
-
-```cjs
-const { Certificate } = require('node:crypto');
+--------------
const { Buffer } = require('node:buffer');
+const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
@@ -302,7 +286,7 @@ directly using the `new` keyword.
Example: Using `Cipher` objects as streams:
-```mjs
+```mjs|cjs
const {
scrypt,
randomFill,
@@ -333,9 +317,7 @@ scrypt(password, 'salt', 24, (err, key) => {
cipher.end();
});
});
-```
-
-```cjs
+--------------
const {
scrypt,
randomFill,
@@ -370,7 +352,7 @@ scrypt(password, 'salt', 24, (err, key) => {
Example: Using `Cipher` and piped streams:
-```mjs
+```mjs|cjs
import {
createReadStream,
createWriteStream,
@@ -407,9 +389,7 @@ scrypt(password, 'salt', 24, (err, key) => {
});
});
});
-```
-
-```cjs
+--------------
const {
createReadStream,
createWriteStream,
@@ -450,7 +430,7 @@ scrypt(password, 'salt', 24, (err, key) => {
Example: Using the [`cipher.update()`][] and [`cipher.final()`][] methods:
-```mjs
+```mjs|cjs
const {
scrypt,
randomFill,
@@ -475,9 +455,7 @@ scrypt(password, 'salt', 24, (err, key) => {
console.log(encrypted);
});
});
-```
-
-```cjs
+--------------
const {
scrypt,
randomFill,
@@ -618,7 +596,7 @@ directly using the `new` keyword.
Example: Using `Decipher` objects as streams:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
scryptSync,
@@ -653,9 +631,7 @@ const encrypted =
'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
decipher.write(encrypted, 'hex');
decipher.end();
-```
-
-```cjs
+--------------
const {
scryptSync,
createDecipheriv,
@@ -694,7 +670,7 @@ decipher.end();
Example: Using `Decipher` and piped streams:
-```mjs
+```mjs|cjs
import {
createReadStream,
createWriteStream,
@@ -718,9 +694,7 @@ const input = createReadStream('test.enc');
const output = createWriteStream('test.js');
input.pipe(decipher).pipe(output);
-```
-
-```cjs
+--------------
const {
createReadStream,
createWriteStream,
@@ -748,7 +722,7 @@ input.pipe(decipher).pipe(output);
Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods:
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
scryptSync,
@@ -771,9 +745,7 @@ let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
// Prints: some clear text data
-```
-
-```cjs
+--------------
const {
scryptSync,
createDecipheriv,
@@ -911,7 +883,7 @@ exchanges.
Instances of the `DiffieHellman` class can be created using the
[`crypto.createDiffieHellman()`][] function.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const {
@@ -932,9 +904,7 @@ const bobSecret = bob.computeSecret(aliceKey);
// OK
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const {
@@ -1081,12 +1051,10 @@ It works the same as `DiffieHellman`, except that it does not allow changing
its keys after creation. In other words, it does not implement `setPublicKey()`
or `setPrivateKey()` methods.
-```mjs
+```mjs|cjs
const { createDiffieHellmanGroup } = await import('node:crypto');
const dh = createDiffieHellmanGroup('modp16');
-```
-
-```cjs
+--------------
const { createDiffieHellmanGroup } = require('node:crypto');
const dh = createDiffieHellmanGroup('modp16');
```
@@ -1117,7 +1085,7 @@ key exchanges.
Instances of the `ECDH` class can be created using the
[`crypto.createECDH()`][] function.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
const {
@@ -1138,9 +1106,7 @@ const bobSecret = bob.computeSecret(aliceKey);
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
// OK
-```
-
-```cjs
+--------------
const assert = require('node:assert');
const {
@@ -1192,7 +1158,7 @@ If the `inputEncoding` is not provided, `key` is expected to be a [`Buffer`][],
Example (uncompressing a key):
-```mjs
+```mjs|cjs
const {
createECDH,
ECDH,
@@ -1211,9 +1177,7 @@ const uncompressedKey = ECDH.convertKey(compressedKey,
// The converted key and the uncompressed public key should be the same
console.log(uncompressedKey === ecdh.getPublicKey('hex'));
-```
-
-```cjs
+--------------
const {
createECDH,
ECDH,
@@ -1347,7 +1311,7 @@ set.
Example (obtaining a shared secret):
-```mjs
+```mjs|cjs
const {
createECDH,
createHash,
@@ -1372,9 +1336,7 @@ const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
// aliceSecret and bobSecret should be the same shared secret value
console.log(aliceSecret === bobSecret);
-```
-
-```cjs
+--------------
const {
createECDH,
createHash,
@@ -1420,7 +1382,7 @@ objects are not to be created directly using the `new` keyword.
Example: Using `Hash` objects as streams:
-```mjs
+```mjs|cjs
const {
createHash,
} = await import('node:crypto');
@@ -1440,9 +1402,7 @@ hash.on('readable', () => {
hash.write('some data to hash');
hash.end();
-```
-
-```cjs
+--------------
const {
createHash,
} = require('node:crypto');
@@ -1466,7 +1426,7 @@ hash.end();
Example: Using `Hash` and piped streams:
-```mjs
+```mjs|cjs
import { createReadStream } from 'node:fs';
import { stdout } from 'node:process';
const { createHash } = await import('node:crypto');
@@ -1475,9 +1435,7 @@ const hash = createHash('sha256');
const input = createReadStream('test.js');
input.pipe(hash).setEncoding('hex').pipe(stdout);
-```
-
-```cjs
+--------------
const { createReadStream } = require('node:fs');
const { createHash } = require('node:crypto');
const { stdout } = require('node:process');
@@ -1490,7 +1448,7 @@ input.pipe(hash).setEncoding('hex').pipe(stdout);
Example: Using the [`hash.update()`][] and [`hash.digest()`][] methods:
-```mjs
+```mjs|cjs
const {
createHash,
} = await import('node:crypto');
@@ -1501,9 +1459,7 @@ hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
-```
-
-```cjs
+--------------
const {
createHash,
} = require('node:crypto');
@@ -1533,7 +1489,7 @@ specify the desired output length in bytes.
An error is thrown when an attempt is made to copy the `Hash` object after
its [`hash.digest()`][] method has been called.
-```mjs
+```mjs|cjs
// Calculate a rolling hash.
const {
createHash,
@@ -1551,9 +1507,7 @@ hash.update('three');
console.log(hash.copy().digest('hex'));
// Etc.
-```
-
-```cjs
+--------------
// Calculate a rolling hash.
const {
createHash,
@@ -1622,7 +1576,7 @@ objects are not to be created directly using the `new` keyword.
Example: Using `Hmac` objects as streams:
-```mjs
+```mjs|cjs
const {
createHmac,
} = await import('node:crypto');
@@ -1642,9 +1596,7 @@ hmac.on('readable', () => {
hmac.write('some data to hash');
hmac.end();
-```
-
-```cjs
+--------------
const {
createHmac,
} = require('node:crypto');
@@ -1668,7 +1620,7 @@ hmac.end();
Example: Using `Hmac` and piped streams:
-```mjs
+```mjs|cjs
import { createReadStream } from 'node:fs';
import { stdout } from 'node:process';
const {
@@ -1679,9 +1631,7 @@ const hmac = createHmac('sha256', 'a secret');
const input = createReadStream('test.js');
input.pipe(hmac).pipe(stdout);
-```
-
-```cjs
+--------------
const {
createReadStream,
} = require('node:fs');
@@ -1698,7 +1648,7 @@ input.pipe(hmac).pipe(stdout);
Example: Using the [`hmac.update()`][] and [`hmac.digest()`][] methods:
-```mjs
+```mjs|cjs
const {
createHmac,
} = await import('node:crypto');
@@ -1709,9 +1659,7 @@ hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
-```
-
-```cjs
+--------------
const {
createHmac,
} = require('node:crypto');
@@ -1780,7 +1728,7 @@ be listed in the `transferList` argument.
Example: Converting a `CryptoKey` instance to a `KeyObject`:
-```mjs
+```mjs|cjs
const { KeyObject } = await import('node:crypto');
const { subtle } = globalThis.crypto;
@@ -1793,9 +1741,7 @@ const key = await subtle.generateKey({
const keyObject = KeyObject.from(key);
console.log(keyObject.symmetricKeySize);
// Prints: 32 (symmetric key size in bytes)
-```
-
-```cjs
+--------------
const { KeyObject } = require('node:crypto');
const { subtle } = globalThis.crypto;
@@ -1954,7 +1900,7 @@ to be created directly using the `new` keyword.
Example: Using `Sign` and [`Verify`][] objects as streams:
-```mjs
+```mjs|cjs
const {
generateKeyPairSync,
createSign,
@@ -1975,9 +1921,7 @@ verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature, 'hex'));
// Prints: true
-```
-
-```cjs
+--------------
const {
generateKeyPairSync,
createSign,
@@ -2002,7 +1946,7 @@ console.log(verify.verify(publicKey, signature, 'hex'));
Example: Using the [`sign.update()`][] and [`verify.update()`][] methods:
-```mjs
+```mjs|cjs
const {
generateKeyPairSync,
createSign,
@@ -2023,9 +1967,7 @@ verify.update('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature));
// Prints: true
-```
-
-```cjs
+--------------
const {
generateKeyPairSync,
createSign,
@@ -2198,15 +2140,13 @@ be passed instead of a public key.
Encapsulates an X509 certificate and provides read-only access to
its information.
-```mjs
+```mjs|cjs
const { X509Certificate } = await import('node:crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
console.log(x509.subject);
-```
-
-```cjs
+--------------
const { X509Certificate } = require('node:crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
@@ -2852,7 +2792,7 @@ display the available digest algorithms.
Example: generating the sha256 sum of a file
-```mjs
+```mjs|cjs
import {
createReadStream,
} from 'node:fs';
@@ -2876,9 +2816,7 @@ input.on('readable', () => {
console.log(`${hash.digest('hex')} ${filename}`);
}
});
-```
-
-```cjs
+--------------
const {
createReadStream,
} = require('node:fs');
@@ -2927,7 +2865,7 @@ a [`KeyObject`][], its type must be `secret`.
Example: generating the sha256 HMAC of a file
-```mjs
+```mjs|cjs
import {
createReadStream,
} from 'node:fs';
@@ -2951,9 +2889,7 @@ input.on('readable', () => {
console.log(`${hmac.digest('hex')} ${filename}`);
}
});
-```
-
-```cjs
+--------------
const {
createReadStream,
} = require('node:fs');
@@ -3111,7 +3047,7 @@ Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`
Asynchronously generates a new random secret key of the given `length`. The
`type` will determine which validations will be performed on the `length`.
-```mjs
+```mjs|cjs
const {
generateKey,
} = await import('node:crypto');
@@ -3120,9 +3056,7 @@ generateKey('hmac', { length: 64 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});
-```
-
-```cjs
+--------------
const {
generateKey,
} = require('node:crypto');
@@ -3172,7 +3106,7 @@ the respective part of the key is returned as a [`KeyObject`][].
It is recommended to encode public keys as `'spki'` and private keys as
`'pkcs8'` with encryption for long-term storage:
-```mjs
+```mjs|cjs
const {
generateKeyPair,
} = await import('node:crypto');
@@ -3192,9 +3126,7 @@ generateKeyPair('rsa', {
}, (err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
});
-```
-
-```cjs
+--------------
const {
generateKeyPair,
} = require('node:crypto');
@@ -3261,7 +3193,7 @@ When encoding public keys, it is recommended to use `'spki'`. When encoding
private keys, it is recommended to use `'pkcs8'` with a strong passphrase,
and to keep the passphrase confidential.
-```mjs
+```mjs|cjs
const {
generateKeyPairSync,
} = await import('node:crypto');
@@ -3282,9 +3214,7 @@ const {
passphrase: 'top secret',
},
});
-```
-
-```cjs
+--------------
const {
generateKeyPairSync,
} = require('node:crypto');
@@ -3328,16 +3258,14 @@ it will be a buffer containing the data encoded as DER.
Synchronously generates a new random secret key of the given `length`. The
`type` will determine which validations will be performed on the `length`.
-```mjs
+```mjs|cjs
const {
generateKeySync,
} = await import('node:crypto');
const key = generateKeySync('hmac', { length: 64 });
console.log(key.export().toString('hex')); // e89..........41e
-```
-
-```cjs
+--------------
const {
generateKeySync,
} = require('node:crypto');
@@ -3461,15 +3389,13 @@ unacceptable, `undefined` will be returned.
* Returns: string\[] An array with the names of the supported cipher
algorithms.
-```mjs
+```mjs|cjs
const {
getCiphers,
} = await import('node:crypto');
console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
-```
-
-```cjs
+--------------
const {
getCiphers,
} = require('node:crypto');
@@ -3483,15 +3409,13 @@ console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
* Returns: string\[] An array with the names of the supported elliptic curves.
-```mjs
+```mjs|cjs
const {
getCurves,
} = await import('node:crypto');
console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
-```
-
-```cjs
+--------------
const {
getCurves,
} = require('node:crypto');
@@ -3518,7 +3442,7 @@ and communication time.
Example (obtaining a shared secret):
-```mjs
+```mjs|cjs
const {
getDiffieHellman,
} = await import('node:crypto');
@@ -3533,9 +3457,7 @@ const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);
-```
-
-```cjs
+--------------
const {
getDiffieHellman,
} = require('node:crypto');
@@ -3568,15 +3490,13 @@ console.log(aliceSecret === bobSecret);
* Returns: string\[] An array of the names of the supported hash algorithms,
such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms.
-```mjs
+```mjs|cjs
const {
getHashes,
} = await import('node:crypto');
console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
-```
-
-```cjs
+--------------
const {
getHashes,
} = require('node:crypto');
@@ -3623,7 +3543,7 @@ otherwise `err` will be `null`. The successfully generated `derivedKey` will
be passed to the callback as an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any
of the input arguments specify invalid values or types.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
hkdf,
@@ -3633,9 +3553,7 @@ hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
if (err) throw err;
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
});
-```
-
-```cjs
+--------------
const {
hkdf,
} = require('node:crypto');
@@ -3673,7 +3591,7 @@ The successfully generated `derivedKey` will be returned as an [`ArrayBuffer`](h
An error will be thrown if any of the input arguments specify invalid values or
types, or if the derived key cannot be generated.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
hkdfSync,
@@ -3681,9 +3599,7 @@ const {
const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
-```
-
-```cjs
+--------------
const {
hkdfSync,
} = require('node:crypto');
@@ -3727,7 +3643,7 @@ random and at least 16 bytes long. See [NIST SP 800-132][] for details.
When passing strings for `password` or `salt`, please consider
[caveats when using strings as inputs to cryptographic APIs][].
-```mjs
+```mjs|cjs
const {
pbkdf2,
} = await import('node:crypto');
@@ -3736,9 +3652,7 @@ pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
-```
-
-```cjs
+--------------
const {
pbkdf2,
} = require('node:crypto');
@@ -3753,16 +3667,14 @@ The `crypto.DEFAULT_ENCODING` property can be used to change the way the
`derivedKey` is passed to the callback. This property, however, has been
deprecated and use should be avoided.
-```mjs
+```mjs|cjs
import crypto from 'node:crypto';
crypto.DEFAULT_ENCODING = 'hex';
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey); // '3745e48...aa39b34'
});
-```
-
-```cjs
+--------------
const crypto = require('node:crypto');
crypto.DEFAULT_ENCODING = 'hex';
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
@@ -3807,16 +3719,14 @@ random and at least 16 bytes long. See [NIST SP 800-132][] for details.
When passing strings for `password` or `salt`, please consider
[caveats when using strings as inputs to cryptographic APIs][].
-```mjs
+```mjs|cjs
const {
pbkdf2Sync,
} = await import('node:crypto');
const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex')); // '3745e48...08d59ae'
-```
-
-```cjs
+--------------
const {
pbkdf2Sync,
} = require('node:crypto');
@@ -3829,14 +3739,12 @@ The `crypto.DEFAULT_ENCODING` property may be used to change the way the
`derivedKey` is returned. This property, however, is deprecated and use
should be avoided.
-```mjs
+```mjs|cjs
import crypto from 'node:crypto';
crypto.DEFAULT_ENCODING = 'hex';
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
console.log(key); // '3745e48...aa39b34'
-```
-
-```cjs
+--------------
const crypto = require('node:crypto');
crypto.DEFAULT_ENCODING = 'hex';
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
@@ -3974,7 +3882,7 @@ and the `callback` function is invoked with two arguments: `err` and `buf`.
If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The
`buf` argument is a [`Buffer`][] containing the generated bytes.
-```mjs
+```mjs|cjs
// Asynchronous
const {
randomBytes,
@@ -3984,9 +3892,7 @@ randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});
-```
-
-```cjs
+--------------
// Asynchronous
const {
randomBytes,
@@ -4002,7 +3908,7 @@ If the `callback` function is not provided, the random bytes are generated
synchronously and returned as a [`Buffer`][]. An error will be thrown if
there is a problem generating the bytes.
-```mjs
+```mjs|cjs
// Synchronous
const {
randomBytes,
@@ -4011,9 +3917,7 @@ const {
const buf = randomBytes(256);
console.log(
`${buf.length} bytes of random data: ${buf.toString('hex')}`);
-```
-
-```cjs
+--------------
// Synchronous
const {
randomBytes,
@@ -4053,7 +3957,7 @@ request.
Synchronous version of [`crypto.randomFill()`][].
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');
@@ -4066,9 +3970,7 @@ console.log(buf.toString('hex'));
// The above is equivalent to the following:
randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));
-```
-
-```cjs
+--------------
const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4086,7 +3988,7 @@ console.log(buf.toString('hex'));
Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as
`buffer`.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');
@@ -4100,9 +4002,7 @@ console.log(Buffer.from(randomFillSync(b).buffer,
const c = new ArrayBuffer(10);
console.log(Buffer.from(randomFillSync(c)).toString('hex'));
-```
-
-```cjs
+--------------
const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4135,7 +4035,7 @@ requires that a callback is passed in.
If the `callback` function is not provided, an error will be thrown.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');
@@ -4155,9 +4055,7 @@ randomFill(buf, 5, 5, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
-```
-
-```cjs
+--------------
const { randomFill } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4188,7 +4086,7 @@ result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array
contains finite numbers only, they are not drawn from a uniform random
distribution and have no meaningful lower or upper bounds.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');
@@ -4211,9 +4109,7 @@ randomFill(c, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf).toString('hex'));
});
-```
-
-```cjs
+--------------
const { randomFill } = require('node:crypto');
const { Buffer } = require('node:buffer');
@@ -4264,7 +4160,7 @@ be [safe integers][].
If the `callback` function is not provided, the random integer is
generated synchronously.
-```mjs
+```mjs|cjs
// Asynchronous
const {
randomInt,
@@ -4274,9 +4170,7 @@ randomInt(3, (err, n) => {
if (err) throw err;
console.log(`Random number chosen from (0, 1, 2): ${n}`);
});
-```
-
-```cjs
+--------------
// Asynchronous
const {
randomInt,
@@ -4288,7 +4182,7 @@ randomInt(3, (err, n) => {
});
```
-```mjs
+```mjs|cjs
// Synchronous
const {
randomInt,
@@ -4296,9 +4190,7 @@ const {
const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
-```
-
-```cjs
+--------------
// Synchronous
const {
randomInt,
@@ -4308,7 +4200,7 @@ const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
```
-```mjs
+```mjs|cjs
// With `min` argument
const {
randomInt,
@@ -4316,9 +4208,7 @@ const {
const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);
-```
-
-```cjs
+--------------
// With `min` argument
const {
randomInt,
@@ -4381,7 +4271,7 @@ The `callback` function is called with two arguments: `err` and `derivedKey`.
An exception is thrown when any of the input arguments specify invalid values
or types.
-```mjs
+```mjs|cjs
const {
scrypt,
} = await import('node:crypto');
@@ -4396,9 +4286,7 @@ scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
});
-```
-
-```cjs
+--------------
const {
scrypt,
} = require('node:crypto');
@@ -4450,7 +4338,7 @@ returned as a [`Buffer`][].
An exception is thrown when any of the input arguments specify invalid values
or types.
-```mjs
+```mjs|cjs
const {
scryptSync,
} = await import('node:crypto');
@@ -4461,9 +4349,7 @@ console.log(key1.toString('hex')); // '3745e48...08d59ae'
// Using a custom N parameter. Must be a power of two.
const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
console.log(key2.toString('hex')); // '3745e48...aa39b34'
-```
-
-```cjs
+--------------
const {
scryptSync,
} = require('node:crypto');
@@ -4774,7 +4660,7 @@ mode must adhere to certain restrictions when using the cipher API:
applications _must_ call `final()` to compute or verify the
authentication tag.
-```mjs
+```mjs|cjs
import { Buffer } from 'node:buffer';
const {
createCipheriv,
@@ -4816,9 +4702,7 @@ try {
}
console.log(receivedPlaintext);
-```
-
-```cjs
+--------------
const { Buffer } = require('node:buffer');
const {
createCipheriv,
@@ -4880,7 +4764,7 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_ALL
Applies multiple bug workarounds within OpenSSL. See
- https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html
+ https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html
for detail.
@@ -4892,13 +4776,13 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
Allows legacy insecure renegotiation between OpenSSL and unpatched
clients or servers. See
- https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html .
+ https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html .
SSL_OP_CIPHER_SERVER_PREFERENCE
Attempts to use the server's preferences instead of the client's when
selecting a cipher. Behavior depends on protocol version. See
- https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html .
+ https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html .
SSL_OP_CISCO_ANYCONNECT
@@ -4918,44 +4802,10 @@ See the [list of SSL OP Flags][] for details.
Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability
workaround added in OpenSSL 0.9.6d.
-
- SSL_OP_EPHEMERAL_RSA
- Instructs OpenSSL to always use the tmp_rsa key when performing RSA
- operations.
-
SSL_OP_LEGACY_SERVER_CONNECT
Allows initial connection to servers that do not support RI.
-
- SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
-
-
-
- SSL_OP_MICROSOFT_SESS_ID_BUG
-
-
-
- SSL_OP_MSIE_SSLV2_RSA_PADDING
- Instructs OpenSSL to disable the workaround for a man-in-the-middle
- protocol-version vulnerability in the SSL 2.0 server implementation.
-
-
- SSL_OP_NETSCAPE_CA_DN_BUG
-
-
-
- SSL_OP_NETSCAPE_CHALLENGE_BUG
-
-
-
- SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
-
-
-
- SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
-
-
SSL_OP_NO_COMPRESSION
Instructs OpenSSL to disable support for SSL/TLS compression.
@@ -5005,14 +4855,6 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_NO_TLSv1_3
Instructs OpenSSL to turn off TLS v1.3
-
- SSL_OP_PKCS1_CHECK_1
-
-
-
- SSL_OP_PKCS1_CHECK_2
-
-
SSL_OP_PRIORITIZE_CHACHA
Instructs OpenSSL server to prioritize ChaCha20-Poly1305
@@ -5021,32 +4863,6 @@ See the [list of SSL OP Flags][] for details.
SSL_OP_CIPHER_SERVER_PREFERENCE
is not enabled.
-
- SSL_OP_SINGLE_DH_USE
- Instructs OpenSSL to always create a new key when using
- temporary/ephemeral DH parameters.
-
-
- SSL_OP_SINGLE_ECDH_USE
- Instructs OpenSSL to always create a new key when using
- temporary/ephemeral ECDH parameters.
-
-
- SSL_OP_SSLEAY_080_CLIENT_DH_BUG
-
-
-
- SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
-
-
-
- SSL_OP_TLS_BLOCK_PADDING_BUG
-
-
-
- SSL_OP_TLS_D5_BUG
-
-
SSL_OP_TLS_ROLLBACK_BUG
Instructs OpenSSL to disable version rollback attack detection.
diff --git a/content/api/v19/debugger.en.md b/content/api/v19/debugger.en.md
index 24edaeb5b4..c34a977b1b 100644
--- a/content/api/v19/debugger.en.md
+++ b/content/api/v19/debugger.en.md
@@ -206,11 +206,19 @@ debug>
after)
* `watch(expr)`: Add expression to watch list
* `unwatch(expr)`: Remove expression from watch list
+* `unwatch(index)`: Remove expression at specific index from watch list
* `watchers`: List all watchers and their values (automatically listed on each
breakpoint)
* `repl`: Open debugger's repl for evaluation in debugging script's context
* `exec expr`, `p expr`: Execute an expression in debugging script's context and
print its value
+* `profile`: Start CPU profiling session
+* `profileEnd`: Stop current CPU profiling session
+* `profiles`: List all completed CPU profiling sessions
+* `profiles[n].save(filepath = 'node.cpuprofile')`: Save CPU profiling session
+ to disk as JSON
+* `takeHeapSnapshot(filepath = 'node.heapsnapshot')`: Take a heap snapshot
+ and save to disk as JSON
#### Execution control
diff --git a/content/api/v19/deprecations.en.md b/content/api/v19/deprecations.en.md
index 6692825663..948cb7d948 100644
--- a/content/api/v19/deprecations.en.md
+++ b/content/api/v19/deprecations.en.md
@@ -1864,7 +1864,7 @@ In a future version of Node.js, [`message.headers`][],
[`dnsPromises.lookup()`]: /api/v19/dns#dnspromiseslookuphostname-options
[`domain`]: /api/v19/domain
[`ecdh.setPublicKey()`]: /api/v19/crypto#ecdhsetpublickeypublickey-encoding
-[`emitter.listenerCount(eventName)`]: /api/v19/events#emitterlistenercounteventname
+[`emitter.listenerCount(eventName)`]: /api/v19/events#emitterlistenercounteventname-listener
[`events.listenerCount(emitter, eventName)`]: /api/v19/events#eventslistenercountemitter-eventname
[`fs.FileHandle`]: /api/v19/fs#class-filehandle
[`fs.access()`]: /api/v19/fs#fsaccesspath-mode-callback
diff --git a/content/api/v19/dgram.en.md b/content/api/v19/dgram.en.md
index b5ad015964..cfddeef29b 100644
--- a/content/api/v19/dgram.en.md
+++ b/content/api/v19/dgram.en.md
@@ -15,11 +15,11 @@ Stable
-
+
The `node:dgram` module provides an implementation of UDP datagram sockets.
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
const server = dgram.createSocket('udp4');
@@ -40,9 +40,7 @@ server.on('listening', () => {
server.bind(41234);
// Prints: server listening 0.0.0.0:41234
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const server = dgram.createSocket('udp4');
@@ -148,7 +146,7 @@ When sharing a UDP socket across multiple `cluster` workers, the
`socket.addMembership()` function must be called only once or an
`EADDRINUSE` error will occur:
-```mjs
+```mjs|cjs
import cluster from 'node:cluster';
import dgram from 'node:dgram';
@@ -161,9 +159,7 @@ if (cluster.isPrimary) {
s.addMembership('224.0.0.114');
});
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const dgram = require('node:dgram');
@@ -236,7 +232,7 @@ attempting to bind with a closed socket), an [`Error`][] may be thrown.
Example of a UDP server listening on port 41234:
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
const server = dgram.createSocket('udp4');
@@ -257,9 +253,7 @@ server.on('listening', () => {
server.bind(41234);
// Prints: server listening 0.0.0.0:41234
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const server = dgram.createSocket('udp4');
@@ -511,7 +505,7 @@ This method throws [`ERR_SOCKET_BAD_PORT`][] if called on an unbound socket.
Example of sending a UDP packet to a port on `localhost`;
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';
@@ -520,9 +514,7 @@ const client = dgram.createSocket('udp4');
client.send(message, 41234, 'localhost', (err) => {
client.close();
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
@@ -536,7 +528,7 @@ client.send(message, 41234, 'localhost', (err) => {
Example of sending a UDP packet composed of multiple buffers to a port on
`127.0.0.1`;
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';
@@ -546,9 +538,7 @@ const client = dgram.createSocket('udp4');
client.send([buf1, buf2], 41234, (err) => {
client.close();
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
@@ -568,7 +558,7 @@ however, sending multiple buffers is faster.
Example of sending a UDP packet using a socket connected to a port on
`localhost`:
-```mjs
+```mjs|cjs
import dgram from 'node:dgram';
import { Buffer } from 'node:buffer';
@@ -579,9 +569,7 @@ client.connect(41234, 'localhost', (err) => {
client.close();
});
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
diff --git a/content/api/v19/diagnostics_channel.en.md b/content/api/v19/diagnostics_channel.en.md
index 4744e56562..710ad0f864 100644
--- a/content/api/v19/diagnostics_channel.en.md
+++ b/content/api/v19/diagnostics_channel.en.md
@@ -5,7 +5,7 @@ category: 'api'
version: 'v19'
---
-
+
@@ -15,18 +15,16 @@ Stable
-
+
The `node:diagnostics_channel` module provides an API to create named channels
to report arbitrary message data for diagnostics purposes.
It can be accessed using:
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
```
@@ -48,7 +46,7 @@ other modules.
Following is a simple overview of the public API.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
// Get a reusable channel object
@@ -71,9 +69,7 @@ if (channel.hasSubscribers) {
// Unsubscribe from the channel
diagnostics_channel.unsubscribe('my-channel', onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
// Get a reusable channel object
@@ -111,15 +107,13 @@ the message you want to send might be expensive to prepare.
This API is optional but helpful when trying to publish messages from very
performance-sensitive code.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
if (diagnostics_channel.hasSubscribers('my-channel')) {
// There are subscribers, prepare and publish message
}
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
if (diagnostics_channel.hasSubscribers('my-channel')) {
@@ -138,13 +132,11 @@ This is the primary entry-point for anyone wanting to publish to a named
channel. It produces a channel object which is optimized to reduce overhead at
publish time as much as possible.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -163,15 +155,13 @@ Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an [`'uncaughtException'`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
diagnostics_channel.subscribe('my-channel', (message, name) => {
// Received data
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
diagnostics_channel.subscribe('my-channel', (message, name) => {
@@ -190,7 +180,7 @@ diagnostics_channel.subscribe('my-channel', (message, name) => {
Remove a message handler previously registered to this channel with
[`diagnostics_channel.subscribe(name, onMessage)`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
function onMessage(message, name) {
@@ -200,9 +190,7 @@ function onMessage(message, name) {
diagnostics_channel.subscribe('my-channel', onMessage);
diagnostics_channel.unsubscribe('my-channel', onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
function onMessage(message, name) {
@@ -238,7 +226,7 @@ the message you want to send might be expensive to prepare.
This API is optional but helpful when trying to publish messages from very
performance-sensitive code.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -246,9 +234,7 @@ const channel = diagnostics_channel.channel('my-channel');
if (channel.hasSubscribers) {
// There are subscribers, prepare and publish message
}
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -267,7 +253,7 @@ if (channel.hasSubscribers) {
Publish a message to any subscribers to the channel. This will trigger
message handlers synchronously so they will execute within the same context.
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -275,9 +261,7 @@ const channel = diagnostics_channel.channel('my-channel');
channel.publish({
some: 'message',
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -305,7 +289,7 @@ Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an [`'uncaughtException'`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -313,9 +297,7 @@ const channel = diagnostics_channel.channel('my-channel');
channel.subscribe((message, name) => {
// Received data
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
@@ -341,7 +323,7 @@ Deprecated: Use [`diagnostics_channel.unsubscribe(name, onMessage)`][]
Remove a message handler previously registered to this channel with
[`channel.subscribe(onMessage)`][].
-```mjs
+```mjs|cjs
import diagnostics_channel from 'node:diagnostics_channel';
const channel = diagnostics_channel.channel('my-channel');
@@ -353,9 +335,7 @@ function onMessage(message, name) {
channel.subscribe(onMessage);
channel.unsubscribe(onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
diff --git a/content/api/v19/dns.en.md b/content/api/v19/dns.en.md
index e96b30f5c4..be3a739b75 100644
--- a/content/api/v19/dns.en.md
+++ b/content/api/v19/dns.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:dns` module enables name resolution. For example, use it to look up IP
addresses of host names.
diff --git a/content/api/v19/domain.en.md b/content/api/v19/domain.en.md
index 92abfa06e4..45d07cecd3 100644
--- a/content/api/v19/domain.en.md
+++ b/content/api/v19/domain.en.md
@@ -15,7 +15,7 @@ Deprecated
-
+
**This module is pending deprecation.** Once a replacement API has been
finalized, this module will be fully deprecated. Most developers should
diff --git a/content/api/v19/esm.en.md b/content/api/v19/esm.en.md
index a9170315ad..d759da372f 100644
--- a/content/api/v19/esm.en.md
+++ b/content/api/v19/esm.en.md
@@ -206,12 +206,10 @@ The default export can be used for, among other things, modifying the named
exports. Named exports of builtin modules are updated only by calling
[`module.syncBuiltinESMExports()`][].
-```js
+```js|js
import EventEmitter from 'node:events';
const e = new EventEmitter();
-```
-
-```js
+--------------
import { readFile } from 'node:fs';
readFile('./foo.txt', (err, source) => {
if (err) {
@@ -513,13 +511,11 @@ export const five = await Promise.resolve(5);
And a `b.mjs` with
-```js
+```js|bash
import { five } from './a.mjs';
console.log(five); // Logs `5`
-```
-
-```bash
+--------------
node b.mjs # works
```
@@ -583,14 +579,12 @@ These modules cannot access other modules that are not over `http:` or `https:`.
To still access local modules while avoiding the security concern, pass in
references to the local dependencies:
-```mjs
+```mjs|mjs
// file.mjs
import worker_threads from 'node:worker_threads';
import { configure, resize } from 'https://example.com/imagelib.mjs';
configure({ worker_threads });
-```
-
-```mjs
+--------------
// https://example.com/imagelib.mjs
let worker_threads;
export function configure(opts) {
@@ -667,7 +661,8 @@ prevent unintentional breaks in the chain.
* `specifier` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `context` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `conditions` string\[] Export conditions of the relevant `package.json`
- * `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object whose key-value pairs represent the
+ assertions for the module to import
* `parentURL` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The module importing this one, or undefined
if this is the Node.js entry point
* `nextResolve` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The subsequent `resolve` hook in the chain, or the
@@ -678,23 +673,24 @@ prevent unintentional breaks in the chain.
* `format` [`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) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) A hint to the load hook (it might be
ignored)
`'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'`
+ * `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The import assertions to use when
+ caching the module (optional; if excluded the input will be used)
* `shortCircuit` [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) A signal that this hook intends to
terminate the chain of `resolve` hooks. **Default:** `false`
* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The absolute URL to which this input resolves
-The `resolve` hook chain is responsible for resolving file URL for a given
-module specifier and parent URL, and optionally its format (such as `'module'`)
-as a hint to the `load` hook. If a format is specified, the `load` hook is
-ultimately responsible for providing the final `format` value (and it is free to
-ignore the hint provided by `resolve`); if `resolve` provides a `format`, a
-custom `load` hook is required even if only to pass the value to the Node.js
-default `load` hook.
-
-The module specifier is the string in an `import` statement or
-`import()` expression.
+The `resolve` hook chain is responsible for telling Node.js where to find and
+how to cache a given `import` statement or expression. It can optionally return
+its format (such as `'module'`) as a hint to the `load` hook. If a format is
+specified, the `load` hook is ultimately responsible for providing the final
+`format` value (and it is free to ignore the hint provided by `resolve`); if
+`resolve` provides a `format`, a custom `load` hook is required even if only to
+pass the value to the Node.js default `load` hook.
-The parent URL is the URL of the module that imported this one, or `undefined`
-if this is the main entry point for the application.
+Import type assertions are part of the cache key for saving loaded modules into
+the internal module cache. The `resolve` hook is responsible for
+returning an `importAssertions` object if the module should be cached with
+different assertions than were present in the source code.
The `conditions` property in `context` is an array of conditions for
[package exports conditions][Conditional Exports] that apply to this resolution
@@ -909,7 +905,7 @@ functionality, there are substantial downsides to actually using this loader:
performance is much slower than loading files from disk, there is no caching,
and there is no security.
-```js
+```js|js
// https-loader.mjs
import { get } from 'node:https';
@@ -957,9 +953,7 @@ export function load(url, context, nextLoad) {
// Let Node.js handle all other URLs.
return nextLoad(url);
}
-```
-
-```js
+--------------
// main.mjs
import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';
@@ -982,7 +976,7 @@ This is less performant than transpiling source files before running
Node.js; a transpiler loader should only be used for development and testing
purposes.
-```js
+```js|coffee
// coffeescript-loader.mjs
import { readFile } from 'node:fs/promises';
import { dirname, extname, resolve as resolvePath } from 'node:path';
@@ -1024,7 +1018,7 @@ export async function load(url, context, nextLoad) {
// file, search up the file system for the nearest parent package.json file
// and read its "type" field.
const format = await getPackageType(url);
- // When a hook returns a format of 'commonjs', `source` is be ignored.
+ // When a hook returns a format of 'commonjs', `source` is ignored.
// To handle CommonJS files, a handler needs to be registered with
// `require.extensions` in order to process the files with the CommonJS
// loader. Avoiding the need for a separate CommonJS handler is a future
@@ -1080,9 +1074,7 @@ async function getPackageType(url) {
// If at the root, stop and return false
return dir.length > 1 && getPackageType(resolvePath(dir, '..'));
}
-```
-
-```coffee
+--------------
# main.coffee
import { scream } from './scream.coffee'
console.log scream 'hello, world'
diff --git a/content/api/v19/events.en.md b/content/api/v19/events.en.md
index 05c0460656..046f747af5 100644
--- a/content/api/v19/events.en.md
+++ b/content/api/v19/events.en.md
@@ -15,7 +15,7 @@ Stable
-
+
Much of the Node.js core API is built around an idiomatic asynchronous
event-driven architecture in which certain kinds of objects (called "emitters")
@@ -39,7 +39,7 @@ The following example shows a simple `EventEmitter` instance with a single
listener. The `eventEmitter.on()` method is used to register listeners, while
the `eventEmitter.emit()` method is used to trigger the event.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
@@ -49,9 +49,7 @@ myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
@@ -71,7 +69,7 @@ an ordinary listener function is called, the standard `this` keyword
is intentionally set to reference the `EventEmitter` instance to which the
listener is attached.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -86,9 +84,7 @@ myEmitter.on('event', function(a, b) {
// } true
});
myEmitter.emit('event', 'a', 'b');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -108,7 +104,7 @@ myEmitter.emit('event', 'a', 'b');
It is possible to use ES6 Arrow Functions as listeners, however, when doing so,
the `this` keyword will no longer reference the `EventEmitter` instance:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -117,9 +113,7 @@ myEmitter.on('event', (a, b) => {
// Prints: a b {}
});
myEmitter.emit('event', 'a', 'b');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -138,7 +132,7 @@ events and helps avoid race conditions and logic errors. When appropriate,
listener functions can switch to an asynchronous mode of operation using
the `setImmediate()` or `process.nextTick()` methods:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -148,9 +142,7 @@ myEmitter.on('event', (a, b) => {
});
});
myEmitter.emit('event', 'a', 'b');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -167,7 +159,7 @@ myEmitter.emit('event', 'a', 'b');
When a listener is registered using the `eventEmitter.on()` method, that
listener is invoked _every time_ the named event is emitted.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -179,9 +171,7 @@ myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Prints: 2
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -199,7 +189,7 @@ Using the `eventEmitter.once()` method, it is possible to register a listener
that is called at most once for a particular event. Once the event is emitted,
the listener is unregistered and _then_ called.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -211,9 +201,7 @@ myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Ignored
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -237,15 +225,13 @@ If an `EventEmitter` does _not_ have at least one listener registered for the
`'error'` event, and an `'error'` event is emitted, the error is thrown, a
stack trace is printed, and the Node.js process exits.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// Throws and crashes Node.js
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -258,7 +244,7 @@ used. (Note, however, that the `node:domain` module is deprecated.)
As a best practice, listeners should always be added for the `'error'` events.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -267,9 +253,7 @@ myEmitter.on('error', (err) => {
});
myEmitter.emit('error', new Error('whoops!'));
// Prints: whoops! there was an error
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -283,7 +267,7 @@ myEmitter.emit('error', new Error('whoops!'));
It is possible to monitor `'error'` events without consuming the emitted error
by installing a listener using the symbol `events.errorMonitor`.
-```mjs
+```mjs|cjs
import { EventEmitter, errorMonitor } from 'node:events';
const myEmitter = new EventEmitter();
@@ -292,9 +276,7 @@ myEmitter.on(errorMonitor, (err) => {
});
myEmitter.emit('error', new Error('whoops!'));
// Still throws and crashes Node.js
-```
-
-```cjs
+--------------
const { EventEmitter, errorMonitor } = require('node:events');
const myEmitter = new EventEmitter();
@@ -310,15 +292,13 @@ myEmitter.emit('error', new Error('whoops!'));
Using `async` functions with event handlers is problematic, because it
can lead to an unhandled rejection in case of a thrown exception:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
ee.on('something', async (value) => {
throw new Error('kaboom');
});
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const ee = new EventEmitter();
ee.on('something', async (value) => {
@@ -332,7 +312,7 @@ handler on the `Promise`. This handler routes the exception
asynchronously to the [`Symbol.for('nodejs.rejection')`][rejection] method
if there is one, or to [`'error'`][error] event handler if there is none.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const ee1 = new EventEmitter({ captureRejections: true });
ee1.on('something', async (value) => {
@@ -347,9 +327,7 @@ ee2.on('something', async (value) => {
});
ee2[Symbol.for('nodejs.rejection')] = console.log;
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const ee1 = new EventEmitter({ captureRejections: true });
ee1.on('something', async (value) => {
@@ -369,7 +347,7 @@ ee2[Symbol.for('nodejs.rejection')] = console.log;
Setting `events.captureRejections = true` will change the default for all
new instances of `EventEmitter`.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
EventEmitter.captureRejections = true;
@@ -379,9 +357,7 @@ ee1.on('something', async (value) => {
});
ee1.on('error', console.log);
-```
-
-```cjs
+--------------
const events = require('node:events');
events.captureRejections = true;
const ee1 = new events.EventEmitter();
@@ -402,11 +378,9 @@ recommendation is to **not use `async` functions as `'error'` event handlers**.
The `EventEmitter` class is defined and exposed by the `node:events` module:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
```
@@ -437,7 +411,7 @@ but important side effect: any _additional_ listeners registered to the same
`name` _within_ the `'newListener'` callback are inserted _before_ the
listener that is in the process of being added.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
@@ -458,9 +432,7 @@ myEmitter.emit('event');
// Prints:
// B
// A
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
@@ -515,7 +487,7 @@ to each.
Returns `true` if the event had listeners, `false` otherwise.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const myEmitter = new EventEmitter();
@@ -546,9 +518,7 @@ myEmitter.emit('event', 1, 2, 3, 4, 5);
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const myEmitter = new EventEmitter();
@@ -590,7 +560,7 @@ myEmitter.emit('event', 1, 2, 3, 4, 5);
Returns an array listing the events for which the emitter has registered
listeners. The values in the array are strings or `Symbol`s.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
@@ -602,9 +572,7 @@ myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const myEE = new EventEmitter();
@@ -628,14 +596,17 @@ Returns the current max listener value for the `EventEmitter` which is either
set by [`emitter.setMaxListeners(n)`][] or defaults to
[`events.defaultMaxListeners`][].
-#### `emitter.listenerCount(eventName)`
+#### `emitter.listenerCount(eventName[, listener])`
-
+
* `eventName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) The name of the event being listened for
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The event handler function
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-Returns the number of listeners listening to the event named `eventName`.
+Returns the number of listeners listening for the event named `eventName`.
+If `listener` is provided, it will return how many times the listener is found
+in the list of the listeners of the event.
#### `emitter.listeners(eventName)`
@@ -690,7 +661,7 @@ By default, event listeners are invoked in the order they are added. The
`emitter.prependListener()` method can be used as an alternative to add the
event listener to the beginning of the listeners array.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
@@ -699,9 +670,7 @@ myEE.emit('foo');
// Prints:
// b
// a
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
@@ -735,7 +704,7 @@ By default, event listeners are invoked in the order they are added. The
`emitter.prependOnceListener()` method can be used as an alternative to add the
event listener to the beginning of the listeners array.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
@@ -744,9 +713,7 @@ myEE.emit('foo');
// Prints:
// b
// a
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
@@ -845,7 +812,7 @@ time of emitting are called in order. This implies that any
_before_ the last listener finishes execution will not remove them from
`emit()` in progress. Subsequent events behave as expected.
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -875,9 +842,7 @@ myEmitter.emit('event');
myEmitter.emit('event');
// Prints:
// A
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -920,7 +885,7 @@ event (as in the example below), `removeListener()` will remove the most
recently added instance. In the example the `once('ping')`
listener is removed:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const ee = new EventEmitter();
@@ -934,9 +899,7 @@ ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const ee = new EventEmitter();
@@ -979,7 +942,7 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
Returns a copy of the array of listeners for the event named `eventName`,
including any wrappers (such as those created by `.once()`).
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
@@ -1002,9 +965,7 @@ const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
@@ -1043,7 +1004,7 @@ promise rejection happens when emitting an event and
It is possible to use [`events.captureRejectionSymbol`][rejectionsymbol] in
place of `Symbol.for('nodejs.rejection')`.
-```mjs
+```mjs|cjs
import { EventEmitter, captureRejectionSymbol } from 'node:events';
class MyClass extends EventEmitter {
@@ -1060,9 +1021,7 @@ class MyClass extends EventEmitter {
// Tear the resource down here.
}
}
-```
-
-```cjs
+--------------
const { EventEmitter, captureRejectionSymbol } = require('node:events');
class MyClass extends EventEmitter {
@@ -1103,7 +1062,7 @@ that a "possible EventEmitter memory leak" has been detected. For any single
`EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()`
methods can be used to temporarily avoid this warning:
-```mjs
+```mjs|cjs
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
@@ -1111,9 +1070,7 @@ emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
@@ -1160,7 +1117,7 @@ the emitter.
For `EventTarget`s this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.
-```mjs
+```mjs|cjs
import { getEventListeners, EventEmitter } from 'node:events';
{
@@ -1175,9 +1132,7 @@ import { getEventListeners, EventEmitter } from 'node:events';
et.addEventListener('foo', listener);
console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
}
-```
-
-```cjs
+--------------
const { getEventListeners, EventEmitter } = require('node:events');
{
@@ -1213,7 +1168,7 @@ This method is intentionally generic and works with the web platform
[EventTarget][WHATWG-EventTarget] interface, which has no special
`'error'` event semantics and does not listen to the `'error'` event.
-```mjs
+```mjs|cjs
import { once, EventEmitter } from 'node:events';
import process from 'node:process';
@@ -1236,9 +1191,7 @@ try {
} catch (err) {
console.error('error happened', err);
}
-```
-
-```cjs
+--------------
const { once, EventEmitter } = require('node:events');
async function run() {
@@ -1271,7 +1224,7 @@ is used to wait for another event. If `events.once()` is used to wait for the
'`error'` event itself, then it is treated as any other kind of event without
special handling:
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
@@ -1283,9 +1236,7 @@ once(ee, 'error')
ee.emit('error', new Error('boom'));
// Prints: ok boom
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const ee = new EventEmitter();
@@ -1301,7 +1252,7 @@ ee.emit('error', new Error('boom'));
An [`AbortSignal`](/api/v19/globals#abortsignal) can be used to cancel waiting for the event:
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
@@ -1323,9 +1274,7 @@ async function foo(emitter, event, signal) {
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const ee = new EventEmitter();
@@ -1358,7 +1307,7 @@ because the `process.nextTick()` queue is drained before the `Promise` microtask
queue, and because `EventEmitter` emits all events synchronously, it is possible
for `events.once()` to miss an event.
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
import process from 'node:process';
@@ -1380,9 +1329,7 @@ process.nextTick(() => {
});
foo().then(() => console.log('done'));
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const myEE = new EventEmitter();
@@ -1409,7 +1356,7 @@ To catch both events, create each of the Promises _before_ awaiting either
of them, then it becomes possible to use `Promise.all()`, `Promise.race()`,
or `Promise.allSettled()`:
-```mjs
+```mjs|cjs
import { EventEmitter, once } from 'node:events';
import process from 'node:process';
@@ -1426,9 +1373,7 @@ process.nextTick(() => {
});
foo().then(() => console.log('done'));
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const myEE = new EventEmitter();
@@ -1478,7 +1423,7 @@ Deprecated: Use [`emitter.listenerCount()`][] instead.
A class method that returns the number of listeners for the given `eventName`
registered on the given `emitter`.
-```mjs
+```mjs|cjs
import { EventEmitter, listenerCount } from 'node:events';
const myEmitter = new EventEmitter();
@@ -1486,9 +1431,7 @@ myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
-```
-
-```cjs
+--------------
const { EventEmitter, listenerCount } = require('node:events');
const myEmitter = new EventEmitter();
@@ -1508,7 +1451,7 @@ console.log(listenerCount(myEmitter, 'event'));
* `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Can be used to cancel awaiting events.
* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) that iterates `eventName` events emitted by the `emitter`
-```mjs
+```mjs|cjs
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
@@ -1527,9 +1470,7 @@ for await (const event of on(ee, 'foo')) {
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
-```
-
-```cjs
+--------------
const { on, EventEmitter } = require('node:events');
(async () => {
@@ -1558,7 +1499,7 @@ composed of the emitted event arguments.
An [`AbortSignal`](/api/v19/globals#abortsignal) can be used to cancel waiting on events:
-```mjs
+```mjs|cjs
import { on, EventEmitter } from 'node:events';
import process from 'node:process';
@@ -1583,9 +1524,7 @@ const ac = new AbortController();
})();
process.nextTick(() => ac.abort());
-```
-
-```cjs
+--------------
const { on, EventEmitter } = require('node:events');
const ac = new AbortController();
@@ -1621,16 +1560,14 @@ process.nextTick(() => ac.abort());
or [`EventEmitter`](/api/v19/events#eventemitter) instances. If none are specified, `n` is set as the default
max for all newly created [`EventTarget`](/api/v19/events#eventtarget) and [`EventEmitter`](/api/v19/events#eventemitter) objects.
-```mjs
+```mjs|cjs
import { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
-```
-
-```cjs
+--------------
const {
setMaxListeners,
EventEmitter,
@@ -1650,7 +1587,7 @@ Integrates `EventEmitter` with [`AsyncResource`](/api/v19/async_hooks#asyncresou
require manual async tracking. Specifically, all events emitted by instances
of `events.EventEmitterAsyncResource` will run within its [async context][].
-```mjs
+```mjs|cjs
import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
import { notStrictEqual, strictEqual } from 'node:assert';
import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
@@ -1677,9 +1614,7 @@ Promise.resolve().then(() => {
ee1.emit('foo');
ee2.emit('foo');
});
-```
-
-```cjs
+--------------
const { EventEmitterAsyncResource, EventEmitter } = require('node:events');
const { notStrictEqual, strictEqual } = require('node:assert');
const { executionAsyncId, triggerAsyncId } = require('node:async_hooks');
@@ -2171,6 +2106,18 @@ equivalent `EventEmitter` API. The only difference between `addListener()` and
`addEventListener()` is that `addListener()` will return a reference to the
`EventTarget`.
+##### `nodeEventTarget.emit(type, arg)`
+
+
+
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `arg` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if event listeners registered for the `type` exist,
+ otherwise `false`.
+
+Node.js-specific extension to the `EventTarget` class that dispatches the
+`arg` to the list of handlers for `type`.
+
##### `nodeEventTarget.eventNames()`
@@ -2222,7 +2169,7 @@ of max event listeners.
* Returns: [`EventTarget`](/api/v19/events#eventtarget) this
-Node.js-specific alias for `eventTarget.removeListener()`.
+Node.js-specific alias for `eventTarget.removeEventListener()`.
##### `nodeEventTarget.on(type, listener)`
@@ -2234,7 +2181,7 @@ Node.js-specific alias for `eventTarget.removeListener()`.
* Returns: [`EventTarget`](/api/v19/events#eventtarget) this
-Node.js-specific alias for `eventTarget.addListener()`.
+Node.js-specific alias for `eventTarget.addEventListener()`.
##### `nodeEventTarget.once(type, listener)`
@@ -2287,7 +2234,7 @@ to the `EventTarget`.
[`EventTarget` error handling]: #eventtarget-error-handling
[`Event` Web API]: https://dom.spec.whatwg.org/#event
[`domain`]: /api/v19/domain
-[`emitter.listenerCount()`]: #emitterlistenercounteventname
+[`emitter.listenerCount()`]: #emitterlistenercounteventname-listener
[`emitter.removeListener()`]: #emitterremovelistenereventname-listener
[`emitter.setMaxListeners(n)`]: #emittersetmaxlistenersn
[`event.defaultPrevented`]: #eventdefaultprevented
diff --git a/content/api/v19/fs.en.md b/content/api/v19/fs.en.md
index ad6908d754..a204a260cc 100644
--- a/content/api/v19/fs.en.md
+++ b/content/api/v19/fs.en.md
@@ -15,28 +15,24 @@ Stable
-
+
The `node:fs` module enables interacting with the file system in a
way modeled on standard POSIX functions.
To use the promise-based APIs:
-```mjs
+```mjs|cjs
import * as fs from 'node:fs/promises';
-```
-
-```cjs
+--------------
const fs = require('node:fs/promises');
```
To use the callback and sync APIs:
-```mjs
+```mjs|cjs
import * as fs from 'node:fs';
-```
-
-```cjs
+--------------
const fs = require('node:fs');
```
@@ -48,7 +44,7 @@ forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).
Promise-based operations return a promise that is fulfilled when the
asynchronous operation is complete.
-```mjs
+```mjs|cjs
import { unlink } from 'node:fs/promises';
try {
@@ -57,9 +53,7 @@ try {
} catch (error) {
console.error('there was an error:', error.message);
}
-```
-
-```cjs
+--------------
const { unlink } = require('node:fs/promises');
(async function(path) {
@@ -80,16 +74,14 @@ the completion callback depend on the method, but the first argument is always
reserved for an exception. If the operation is completed successfully, then
the first argument is `null` or `undefined`.
-```mjs
+```mjs|cjs
import { unlink } from 'node:fs';
unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
-```
-
-```cjs
+--------------
const { unlink } = require('node:fs');
unlink('/tmp/hello', (err) => {
@@ -108,7 +100,7 @@ The synchronous APIs block the Node.js event loop and further JavaScript
execution until the operation is complete. Exceptions are thrown immediately
and can be handled using `try…catch`, or can be allowed to bubble up.
-```mjs
+```mjs|cjs
import { unlinkSync } from 'node:fs';
try {
@@ -117,9 +109,7 @@ try {
} catch (err) {
// handle the error
}
-```
-
-```cjs
+--------------
const { unlinkSync } = require('node:fs');
try {
@@ -418,7 +408,7 @@ Returns a `ReadableStream` that may be used to read the files data.
An error will be thrown if this method is called more than once or is called
after the `FileHandle` is closed or closing.
-```mjs
+```mjs|cjs
import {
open,
} from 'node:fs/promises';
@@ -429,9 +419,7 @@ for await (const chunk of file.readableWebStream())
console.log(chunk);
await file.close();
-```
-
-```cjs
+--------------
const {
open,
} = require('node:fs/promises');
@@ -488,7 +476,7 @@ of the file.
Convenience method to create a `readline` interface and stream over the file.
See [`filehandle.createReadStream()`][] for the options.
-```mjs
+```mjs|cjs
import { open } from 'node:fs/promises';
const file = await open('./some/file/to/read');
@@ -496,9 +484,7 @@ const file = await open('./some/file/to/read');
for await (const line of file.readLines()) {
console.log(line);
}
-```
-
-```cjs
+--------------
const { open } = require('node:fs/promises');
(async () => {
@@ -963,7 +949,7 @@ property indicating whether parent directories should be created. Calling
`fsPromises.mkdir()` when `path` is a directory that exists results in a
rejection only when `recursive` is false.
-```mjs
+```mjs|cjs
import { mkdir } from 'node:fs/promises';
try {
@@ -974,11 +960,9 @@ try {
} catch (err) {
console.error(err.message);
}
-```
-
-```cjs
+--------------
const { mkdir } = require('node:fs/promises');
-const { resolve, join } = require('node:path');
+const { join } = require('node:path');
async function makeDirectory() {
const projectFolder = join(__dirname, 'test', 'project');
@@ -1012,9 +996,11 @@ object with an `encoding` property specifying the character encoding to use.
```mjs
import { mkdtemp } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
try {
- await mkdtemp(path.join(os.tmpdir(), 'foo-'));
+ await mkdtemp(join(tmpdir(), 'foo-'));
} catch (err) {
console.error(err);
}
@@ -1143,7 +1129,7 @@ returned.
An example of reading a `package.json` file located in the same directory of the
running code:
-```mjs
+```mjs|cjs
import { readFile } from 'node:fs/promises';
try {
const filePath = new URL('./package.json', import.meta.url);
@@ -1152,9 +1138,7 @@ try {
} catch (err) {
console.error(err.message);
}
-```
-
-```cjs
+--------------
const { readFile } = require('node:fs/promises');
const { resolve } = require('node:path');
async function logFile() {
@@ -2498,8 +2482,10 @@ object with an `encoding` property specifying the character encoding to use.
```mjs
import { mkdtemp } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
-mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
+mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
if (err) throw err;
console.log(directory);
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
@@ -2567,6 +2553,45 @@ a colon, Node.js will open a file system stream, as described by
Functions based on `fs.open()` exhibit this behavior as well:
`fs.writeFile()`, `fs.readFile()`, etc.
+#### `fs.openAsBlob(path[, options])`
+
+
+
+
+
+Experimental
+
+
+
+* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`URL`](/api/v19/url#the-whatwg-url-api)
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) An optional mime type for the blob.
+* Return: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`Blob`](/api/v19/buffer#blob)
+
+Returns a [`Blob`](/api/v19/buffer#blob) whose data is backed by the given file.
+
+The file must not be modified after the [`Blob`](/api/v19/buffer#blob) is created. Any modifications
+will cause reading the [`Blob`](/api/v19/buffer#blob) data to fail with a `DOMException`.
+error. Synchronous stat operations on the file when the `Blob` is created, and
+before each read in order to detect whether the file data has been modified
+on disk.
+
+```mjs|cjs
+import { openAsBlob } from 'node:fs';
+
+const blob = await openAsBlob('the.file.txt');
+const ab = await blob.arrayBuffer();
+blob.stream();
+--------------
+const { openAsBlob } = require('node:fs');
+
+(async () => {
+ const blob = await openAsBlob('the.file.txt');
+ const ab = await blob.arrayBuffer();
+ blob.stream();
+})();
+```
+
#### `fs.opendir(path[, options], callback)`
@@ -3147,16 +3172,14 @@ Truncates the file. No arguments other than a possible exception are
given to the completion callback. A file descriptor can also be passed as the
first argument. In this case, `fs.ftruncate()` is called.
-```mjs
+```mjs|cjs
import { truncate } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was truncated');
});
-```
-
-```cjs
+--------------
const { truncate } = require('node:fs');
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
@@ -5660,6 +5683,8 @@ For example, the following is prone to error because the `fs.stat()`
operation might complete before the `fs.rename()` operation:
```js
+const fs = require('node:fs');
+
fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
console.log('renamed complete');
@@ -5673,28 +5698,26 @@ fs.stat('/tmp/world', (err, stats) => {
It is important to correctly order the operations by awaiting the results
of one before invoking the other:
-```mjs
+```mjs|cjs
import { rename, stat } from 'node:fs/promises';
-const from = '/tmp/hello';
-const to = '/tmp/world';
+const oldPath = '/tmp/hello';
+const newPath = '/tmp/world';
try {
- await rename(from, to);
- const stats = await stat(to);
+ await rename(oldPath, newPath);
+ const stats = await stat(newPath);
console.log(`stats: ${JSON.stringify(stats)}`);
} catch (error) {
console.error('there was an error:', error.message);
}
-```
-
-```cjs
+--------------
const { rename, stat } = require('node:fs/promises');
-(async function(from, to) {
+(async function(oldPath, newPath) {
try {
- await rename(from, to);
- const stats = await stat(to);
+ await rename(oldPath, newPath);
+ const stats = await stat(newPath);
console.log(`stats: ${JSON.stringify(stats)}`);
} catch (error) {
console.error('there was an error:', error.message);
@@ -5705,7 +5728,7 @@ const { rename, stat } = require('node:fs/promises');
Or, when using the callback APIs, move the `fs.stat()` call into the callback
of the `fs.rename()` operation:
-```mjs
+```mjs|cjs
import { rename, stat } from 'node:fs';
rename('/tmp/hello', '/tmp/world', (err) => {
@@ -5715,9 +5738,7 @@ rename('/tmp/hello', '/tmp/world', (err) => {
console.log(`stats: ${JSON.stringify(stats)}`);
});
});
-```
-
-```cjs
+--------------
const { rename, stat } = require('node:fs/promises');
rename('/tmp/hello', '/tmp/world', (err) => {
@@ -5750,7 +5771,7 @@ try {
fd = await open('/open/some/file.txt', 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
@@ -5764,7 +5785,7 @@ try {
fd = await open('file.txt', 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
@@ -5877,7 +5898,7 @@ try {
fd = await open(Buffer.from('/open/some/file.txt'), 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
diff --git a/content/api/v19/http.en.md b/content/api/v19/http.en.md
index 8c2ead8563..18ffcbc61f 100644
--- a/content/api/v19/http.en.md
+++ b/content/api/v19/http.en.md
@@ -13,7 +13,7 @@ Stable
-
+
To use the HTTP server and client one must `require('node:http')`.
@@ -2741,7 +2741,7 @@ Returns a new instance of [`http.Server`][].
The `requestListener` is a function which is automatically
added to the [`'request'`][] event.
-```cjs
+```cjs|cjs
const http = require('node:http');
// Create a local server to receive data from
@@ -2753,9 +2753,7 @@ const server = http.createServer((req, res) => {
});
server.listen(8000);
-```
-
-```cjs
+--------------
const http = require('node:http');
// Create a local server to receive data from
diff --git a/content/api/v19/http2.en.md b/content/api/v19/http2.en.md
index 9a1f21ce22..dd9474a989 100644
--- a/content/api/v19/http2.en.md
+++ b/content/api/v19/http2.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:http2` module provides an implementation of the [HTTP/2][] protocol.
It can be accessed using:
@@ -328,7 +328,7 @@ server.on('stream', (stream, headers) => {
stream.end('Hello World ');
});
-server.listen(80);
+server.listen(8000);
```
Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence,
@@ -2167,7 +2167,7 @@ server.on('stream', (stream, headers) => {
stream.end('Hello World ');
});
-server.listen(80);
+server.listen(8000);
```
#### `http2.createSecureServer(options[, onRequestHandler])`
@@ -2264,7 +2264,7 @@ server.on('stream', (stream, headers) => {
stream.end('Hello World ');
});
-server.listen(80);
+server.listen(8443);
```
#### `http2.connect(authority[, options][, listener])`
@@ -2666,7 +2666,7 @@ const client = http2.connect('http://localhost:8001');
// for CONNECT requests or an error will be thrown.
const req = client.request({
':method': 'CONNECT',
- ':authority': `localhost:${port}`,
+ ':authority': 'localhost:8000',
});
req.on('response', (headers) => {
diff --git a/content/api/v19/https.en.md b/content/api/v19/https.en.md
index c1573f2a2c..33622e3570 100644
--- a/content/api/v19/https.en.md
+++ b/content/api/v19/https.en.md
@@ -13,7 +13,7 @@ Stable
-
+
HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.
diff --git a/content/api/v19/inspector.en.md b/content/api/v19/inspector.en.md
index 3989404742..9fe1483b7e 100644
--- a/content/api/v19/inspector.en.md
+++ b/content/api/v19/inspector.en.md
@@ -13,28 +13,24 @@ Stable
-
+
The `node:inspector` module provides an API for interacting with the V8
inspector.
It can be accessed using:
-```mjs
+```mjs|cjs
import * as inspector from 'node:inspector/promises';
-```
-
-```cjs
+--------------
const inspector = require('node:inspector/promises');
```
or
-```mjs
+```mjs|cjs
import * as inspector from 'node:inspector';
-```
-
-```cjs
+--------------
const inspector = require('node:inspector');
```
diff --git a/content/api/v19/module.en.md b/content/api/v19/module.en.md
index a95a69881d..0eb966aa49 100644
--- a/content/api/v19/module.en.md
+++ b/content/api/v19/module.en.md
@@ -29,13 +29,11 @@ if a module is maintained by a third party or not.
`module` in this context isn't the same object that's provided
by the [module wrapper][]. To access it, require the `Module` module:
-```mjs
+```mjs|cjs
// module.mjs
// In an ECMAScript module
import { builtinModules as builtin } from 'node:module';
-```
-
-```cjs
+--------------
// module.cjs
// In a CommonJS module
const builtin = require('node:module').builtinModules;
@@ -127,13 +125,11 @@ To enable source map parsing, Node.js must be run with the flag
[`--enable-source-maps`][], or with code coverage enabled by setting
[`NODE_V8_COVERAGE=dir`][].
-```mjs
+```mjs|cjs
// module.mjs
// In an ECMAScript module
import { findSourceMap, SourceMap } from 'node:module';
-```
-
-```cjs
+--------------
// module.cjs
// In a CommonJS module
const { findSourceMap, SourceMap } = require('node:module');
diff --git a/content/api/v19/modules.en.md b/content/api/v19/modules.en.md
index bad8e83e8d..ac3f129bf0 100644
--- a/content/api/v19/modules.en.md
+++ b/content/api/v19/modules.en.md
@@ -752,11 +752,9 @@ See ["Accessing the main module"](#accessing-the-main-module).
In `entry.js` script:
-```js
+```js|bash
console.log(require.main);
-```
-
-```bash
+--------------
node entry.js
```
diff --git a/content/api/v19/n-api.en.md b/content/api/v19/n-api.en.md
index 80b30a0163..8fbf7ee838 100644
--- a/content/api/v19/n-api.en.md
+++ b/content/api/v19/n-api.en.md
@@ -54,12 +54,10 @@ following `node-addon-api` code. The first section shows the
`node-addon-api` code and the second section shows what actually gets
used in the addon.
-```cpp
+```cpp|cpp
Object obj = Object::New(env);
obj["foo"] = String::New(env, "bar");
-```
-
-```cpp
+--------------
napi_status status;
napi_value object, string;
status = napi_create_object(env, &object);
@@ -391,16 +389,14 @@ implementation of Node-API or any implementation of Node-API outside of Node.js.
to the addon and which instantiates the addon by calling into `addon.c` when the
addon is loaded into a Node.js environment.
-```c
+```c|c
// addon.h
#ifndef _ADDON_H_
#define _ADDON_H_
#include
napi_value create_addon(napi_env env);
#endif // _ADDON_H_
-```
-
-```c
+--------------
// addon.c
#include "addon.h"
@@ -5727,12 +5723,10 @@ Experimental
-```c
+```c|text
NAPI_EXTERN napi_status
node_api_get_module_file_name(napi_env env, const char** result);
-```
-
* `[in] env`: The environment that the API is invoked under.
* `[out] result`: A URL containing the absolute path of the
location from which the add-on was loaded. For a file on the local
diff --git a/content/api/v19/navigation.json b/content/api/v19/navigation.json
index 89ab549ee5..a4c27b7326 100644
--- a/content/api/v19/navigation.json
+++ b/content/api/v19/navigation.json
@@ -1,4 +1,1835 @@
{
"version": "v19",
- "items": []
+ "items": [
+ {
+ "slug": "/api/v19/addons/",
+ "title": "C addons",
+ "type": "module",
+ "name": "addons"
+ },
+ {
+ "slug": "/api/v19/assert/",
+ "title": "Assert",
+ "type": "module",
+ "name": "assert"
+ },
+ {
+ "slug": "/api/v19/assert/#assertassertionerror",
+ "title": "assertAssertionError",
+ "type": "class",
+ "name": "assert"
+ },
+ {
+ "slug": "/api/v19/assert/#assertcalltracker",
+ "title": "assertCallTracker",
+ "type": "class",
+ "name": "assert"
+ },
+ {
+ "slug": "/api/v19/async_context/",
+ "title": "Asynchronous context tracking",
+ "type": "module",
+ "name": "async_context"
+ },
+ {
+ "slug": "/api/v19/async_context/#asynclocalstorage",
+ "title": "AsyncLocalStorage",
+ "type": "class",
+ "name": "async_context"
+ },
+ {
+ "slug": "/api/v19/async_context/#asyncresource",
+ "title": "AsyncResource",
+ "type": "class",
+ "name": "async_context"
+ },
+ {
+ "slug": "/api/v19/async_hooks/",
+ "title": "Async hooks",
+ "type": "module",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v19/async_hooks/#asynchook",
+ "title": "AsyncHook",
+ "type": "class",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v19/async_hooks/#asynclocalstorage",
+ "title": "AsyncLocalStorage",
+ "type": "class",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v19/async_hooks/#asyncresource",
+ "title": "AsyncResource",
+ "type": "class",
+ "name": "async_hooks"
+ },
+ {
+ "slug": "/api/v19/buffer/",
+ "title": "Buffer",
+ "type": "module",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v19/buffer/#blob",
+ "title": "Blob",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v19/buffer/#buffer",
+ "title": "Buffer",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v19/buffer/#file",
+ "title": "File",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v19/buffer/#slowbuffer",
+ "title": "SlowBuffer",
+ "type": "class",
+ "name": "buffer"
+ },
+ {
+ "slug": "/api/v19/child_process/",
+ "title": "Child process",
+ "type": "module",
+ "name": "child_process"
+ },
+ {
+ "slug": "/api/v19/child_process/#childprocess",
+ "title": "ChildProcess",
+ "type": "class",
+ "name": "child_process"
+ },
+ {
+ "slug": "/api/v19/cli/",
+ "title": "Command-line API",
+ "type": "module",
+ "name": "cli"
+ },
+ {
+ "slug": "/api/v19/cluster/",
+ "title": "Cluster",
+ "type": "module",
+ "name": "cluster"
+ },
+ {
+ "slug": "/api/v19/cluster/#worker",
+ "title": "Worker",
+ "type": "class",
+ "name": "cluster"
+ },
+ {
+ "slug": "/api/v19/console/",
+ "title": "Console",
+ "type": "module",
+ "name": "console"
+ },
+ {
+ "slug": "/api/v19/console/#console",
+ "title": "Console",
+ "type": "class",
+ "name": "console"
+ },
+ {
+ "slug": "/api/v19/console/#console",
+ "title": "Console",
+ "type": "class",
+ "name": "console"
+ },
+ {
+ "slug": "/api/v19/corepack/",
+ "title": "Corepack",
+ "type": "module",
+ "name": "corepack"
+ },
+ {
+ "slug": "/api/v19/crypto/",
+ "title": "Crypto",
+ "type": "module",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#certificate",
+ "title": "Certificate",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#cipher",
+ "title": "Cipher",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#decipher",
+ "title": "Decipher",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#diffiehellman",
+ "title": "DiffieHellman",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#diffiehellmangroup",
+ "title": "DiffieHellmanGroup",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#ecdh",
+ "title": "ECDH",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#hash",
+ "title": "Hash",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#hmac",
+ "title": "Hmac",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#keyobject",
+ "title": "KeyObject",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#sign",
+ "title": "Sign",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#verify",
+ "title": "Verify",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/crypto/#x509certificate",
+ "title": "X509Certificate",
+ "type": "class",
+ "name": "crypto"
+ },
+ {
+ "slug": "/api/v19/debugger/",
+ "title": "Debugger",
+ "type": "module",
+ "name": "debugger"
+ },
+ {
+ "slug": "/api/v19/deprecations/",
+ "title": "Deprecated APIs",
+ "type": "module",
+ "name": "deprecations"
+ },
+ {
+ "slug": "/api/v19/dgram/",
+ "title": "UDPdatagram sockets",
+ "type": "module",
+ "name": "dgram"
+ },
+ {
+ "slug": "/api/v19/dgram/#dgramsocket",
+ "title": "dgramSocket",
+ "type": "class",
+ "name": "dgram"
+ },
+ {
+ "slug": "/api/v19/diagnostics_channel/",
+ "title": "Diagnostics Channel",
+ "type": "module",
+ "name": "diagnostics_channel"
+ },
+ {
+ "slug": "/api/v19/diagnostics_channel/#channel",
+ "title": "Channel",
+ "type": "class",
+ "name": "diagnostics_channel"
+ },
+ {
+ "slug": "/api/v19/dns/",
+ "title": "DNS",
+ "type": "module",
+ "name": "dns"
+ },
+ {
+ "slug": "/api/v19/dns/#dnspromisesresolver",
+ "title": "dnsPromisesResolver",
+ "type": "class",
+ "name": "dns"
+ },
+ {
+ "slug": "/api/v19/dns/#dnsresolver",
+ "title": "dnsResolver",
+ "type": "class",
+ "name": "dns"
+ },
+ {
+ "slug": "/api/v19/documentation/",
+ "title": "About this documentation",
+ "type": "module",
+ "name": "documentation"
+ },
+ {
+ "slug": "/api/v19/domain/",
+ "title": "Domain",
+ "type": "module",
+ "name": "domain"
+ },
+ {
+ "slug": "/api/v19/domain/#domain",
+ "title": "Domain",
+ "type": "class",
+ "name": "domain"
+ },
+ {
+ "slug": "/api/v19/embedding/",
+ "title": "C embedder API",
+ "type": "module",
+ "name": "embedding"
+ },
+ {
+ "slug": "/api/v19/errors/",
+ "title": "Errors",
+ "type": "module",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v19/errors/#assertionerror",
+ "title": "AssertionError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v19/errors/#error",
+ "title": "Error",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v19/errors/#rangeerror",
+ "title": "RangeError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v19/errors/#referenceerror",
+ "title": "ReferenceError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v19/errors/#syntaxerror",
+ "title": "SyntaxError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v19/errors/#systemerror",
+ "title": "SystemError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v19/errors/#typeerror",
+ "title": "TypeError",
+ "type": "class",
+ "name": "errors"
+ },
+ {
+ "slug": "/api/v19/esm/",
+ "title": "ECMAScript modules",
+ "type": "module",
+ "name": "esm"
+ },
+ {
+ "slug": "/api/v19/events/",
+ "title": "Events",
+ "type": "module",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v19/events/#customevent",
+ "title": "CustomEvent",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v19/events/#event",
+ "title": "Event",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v19/events/#eventemitter",
+ "title": "EventEmitter",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v19/events/#eventseventemitterasyncresource-extends-eventemitter",
+ "title": "eventsEventEmitterAsyncResource extends EventEmitter",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v19/events/#eventtarget",
+ "title": "EventTarget",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v19/events/#nodeeventtarget",
+ "title": "NodeEventTarget",
+ "type": "class",
+ "name": "events"
+ },
+ {
+ "slug": "/api/v19/fs/",
+ "title": "File system",
+ "type": "module",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v19/fs/#filehandle",
+ "title": "FileHandle",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v19/fs/#fsdir",
+ "title": "fsDir",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v19/fs/#fsdirent",
+ "title": "fsDirent",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v19/fs/#fsfswatcher",
+ "title": "fsFSWatcher",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v19/fs/#fsreadstream",
+ "title": "fsReadStream",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v19/fs/#fsstatfs",
+ "title": "fsStatFs",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v19/fs/#fsstats",
+ "title": "fsStats",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v19/fs/#fsstatwatcher",
+ "title": "fsStatWatcher",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v19/fs/#fswritestream",
+ "title": "fsWriteStream",
+ "type": "class",
+ "name": "fs"
+ },
+ {
+ "slug": "/api/v19/globals/",
+ "title": "Global objects",
+ "type": "module",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#abortcontroller",
+ "title": "AbortController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#abortcontroller",
+ "title": "AbortController",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#abortsignal",
+ "title": "AbortSignal",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#blob",
+ "title": "Blob",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#blob",
+ "title": "Blob",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#buffer",
+ "title": "Buffer",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#buffer",
+ "title": "Buffer",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#bytelengthqueuingstrategy",
+ "title": "ByteLengthQueuingStrategy",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#clearimmediateimmediateobject",
+ "title": "clearImmediate",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#clearintervalintervalobject",
+ "title": "clearInterval",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#cleartimeouttimeoutobject",
+ "title": "clearTimeout",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#compressionstream",
+ "title": "CompressionStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#console",
+ "title": "console",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#countqueuingstrategy",
+ "title": "CountQueuingStrategy",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#customevent",
+ "title": "CustomEvent",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#decompressionstream",
+ "title": "DecompressionStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#domexception",
+ "title": "DOMException",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#event",
+ "title": "Event",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#eventtarget",
+ "title": "EventTarget",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#global",
+ "title": "global",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#messagechannel",
+ "title": "MessageChannel",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#messageevent",
+ "title": "MessageEvent",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#messageport",
+ "title": "MessagePort",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#performanceentry",
+ "title": "PerformanceEntry",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#performancemark",
+ "title": "PerformanceMark",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#performancemeasure",
+ "title": "PerformanceMeasure",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#performanceobserver",
+ "title": "PerformanceObserver",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#performanceobserverentrylist",
+ "title": "PerformanceObserverEntryList",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#performanceresourcetiming",
+ "title": "PerformanceResourceTiming",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#process",
+ "title": "process",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#queuemicrotaskcallback",
+ "title": "queueMicrotask",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#readablebytestreamcontroller",
+ "title": "ReadableByteStreamController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#readablestream",
+ "title": "ReadableStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#readablestreambyobreader",
+ "title": "ReadableStreamBYOBReader",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#readablestreambyobrequest",
+ "title": "ReadableStreamBYOBRequest",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#readablestreamdefaultcontroller",
+ "title": "ReadableStreamDefaultController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#readablestreamdefaultreader",
+ "title": "ReadableStreamDefaultReader",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#setimmediatecallback-args",
+ "title": "setImmediate",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#setintervalcallback-delay-args",
+ "title": "setInterval",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#settimeoutcallback-delay-args",
+ "title": "setTimeout",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#structuredclonevalue-options",
+ "title": "structuredClone",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#textdecoder",
+ "title": "TextDecoder",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#textdecoderstream",
+ "title": "TextDecoderStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#textencoder",
+ "title": "TextEncoder",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#textencoderstream",
+ "title": "TextEncoderStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#transformstream",
+ "title": "TransformStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#transformstreamdefaultcontroller",
+ "title": "TransformStreamDefaultController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#url",
+ "title": "URL",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#urlsearchparams",
+ "title": "URLSearchParams",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#webassembly",
+ "title": "WebAssembly",
+ "type": "global",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#writablestream",
+ "title": "WritableStream",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#writablestreamdefaultcontroller",
+ "title": "WritableStreamDefaultController",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/globals/#writablestreamdefaultwriter",
+ "title": "WritableStreamDefaultWriter",
+ "type": "class",
+ "name": "globals"
+ },
+ {
+ "slug": "/api/v19/http/",
+ "title": "HTTP",
+ "type": "module",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v19/http/#httpagent",
+ "title": "httpAgent",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v19/http/#httpclientrequest",
+ "title": "httpClientRequest",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v19/http/#httpincomingmessage",
+ "title": "httpIncomingMessage",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v19/http/#httpoutgoingmessage",
+ "title": "httpOutgoingMessage",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v19/http/#httpserver",
+ "title": "httpServer",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v19/http/#httpserverresponse",
+ "title": "httpServerResponse",
+ "type": "class",
+ "name": "http"
+ },
+ {
+ "slug": "/api/v19/http2/",
+ "title": "HTTP2",
+ "type": "module",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/http2/#clienthttp2session",
+ "title": "ClientHttp2Session",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/http2/#clienthttp2stream",
+ "title": "ClientHttp2Stream",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/http2/#http2http2serverrequest",
+ "title": "http2Http2ServerRequest",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/http2/#http2http2serverresponse",
+ "title": "http2Http2ServerResponse",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/http2/#http2secureserver",
+ "title": "Http2SecureServer",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/http2/#http2server",
+ "title": "Http2Server",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/http2/#http2session",
+ "title": "Http2Session",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/http2/#http2stream",
+ "title": "Http2Stream",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/http2/#serverhttp2session",
+ "title": "ServerHttp2Session",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/http2/#serverhttp2stream",
+ "title": "ServerHttp2Stream",
+ "type": "class",
+ "name": "http2"
+ },
+ {
+ "slug": "/api/v19/https/",
+ "title": "HTTPS",
+ "type": "module",
+ "name": "https"
+ },
+ {
+ "slug": "/api/v19/https/#httpsagent",
+ "title": "httpsAgent",
+ "type": "class",
+ "name": "https"
+ },
+ {
+ "slug": "/api/v19/https/#httpsserver",
+ "title": "httpsServer",
+ "type": "class",
+ "name": "https"
+ },
+ {
+ "slug": "/api/v19/inspector/",
+ "title": "Inspector",
+ "type": "module",
+ "name": "inspector"
+ },
+ {
+ "slug": "/api/v19/inspector/#inspectorsession",
+ "title": "inspectorSession",
+ "type": "class",
+ "name": "inspector"
+ },
+ {
+ "slug": "/api/v19/inspector/#inspectorsession",
+ "title": "inspectorSession",
+ "type": "class",
+ "name": "inspector"
+ },
+ {
+ "slug": "/api/v19/intl/",
+ "title": "Internationalization support",
+ "type": "module",
+ "name": "intl"
+ },
+ {
+ "slug": "/api/v19/module/",
+ "title": "nodemodule API",
+ "type": "module",
+ "name": "module"
+ },
+ {
+ "slug": "/api/v19/module/#modulesourcemap",
+ "title": "moduleSourceMap",
+ "type": "class",
+ "name": "module"
+ },
+ {
+ "slug": "/api/v19/modules/",
+ "title": "CommonJS modules",
+ "type": "module",
+ "name": "modules"
+ },
+ {
+ "slug": "/api/v19/n-api/",
+ "title": "Node-API",
+ "type": "module",
+ "name": "n-api"
+ },
+ {
+ "slug": "/api/v19/net/",
+ "title": "Net",
+ "type": "module",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v19/net/#netblocklist",
+ "title": "netBlockList",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v19/net/#netserver",
+ "title": "netServer",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v19/net/#netsocket",
+ "title": "netSocket",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v19/net/#netsocketaddress",
+ "title": "netSocketAddress",
+ "type": "class",
+ "name": "net"
+ },
+ {
+ "slug": "/api/v19/os/",
+ "title": "OS",
+ "type": "module",
+ "name": "os"
+ },
+ {
+ "slug": "/api/v19/packages/",
+ "title": "Packages",
+ "type": "module",
+ "name": "packages"
+ },
+ {
+ "slug": "/api/v19/path/",
+ "title": "Path",
+ "type": "module",
+ "name": "path"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/",
+ "title": "Performance measurement APIs",
+ "type": "module",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#histogram",
+ "title": "Histogram",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#intervalhistogram-extends-histogram",
+ "title": "IntervalHistogram extends Histogram",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#performanceentry",
+ "title": "PerformanceEntry",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#performancemark",
+ "title": "PerformanceMark",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#performancemeasure",
+ "title": "PerformanceMeasure",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#performancenodeentry",
+ "title": "PerformanceNodeEntry",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#performancenodetiming",
+ "title": "PerformanceNodeTiming",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#performanceobserver",
+ "title": "PerformanceObserver",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#performanceobserverentrylist",
+ "title": "PerformanceObserverEntryList",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#performanceresourcetiming",
+ "title": "PerformanceResourceTiming",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/perf_hooks/#recordablehistogram-extends-histogram",
+ "title": "RecordableHistogram extends Histogram",
+ "type": "class",
+ "name": "perf_hooks"
+ },
+ {
+ "slug": "/api/v19/permissions/",
+ "title": "Permissions",
+ "type": "module",
+ "name": "permissions"
+ },
+ {
+ "slug": "/api/v19/policy/",
+ "title": "Policies",
+ "type": "module",
+ "name": "policy"
+ },
+ {
+ "slug": "/api/v19/process/",
+ "title": "Process",
+ "type": "module",
+ "name": "process"
+ },
+ {
+ "slug": "/api/v19/punycode/",
+ "title": "Punycode",
+ "type": "module",
+ "name": "punycode"
+ },
+ {
+ "slug": "/api/v19/querystring/",
+ "title": "Query string",
+ "type": "module",
+ "name": "querystring"
+ },
+ {
+ "slug": "/api/v19/readline/",
+ "title": "Readline",
+ "type": "module",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v19/readline/#interfaceconstructor",
+ "title": "InterfaceConstructor",
+ "type": "class",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v19/readline/#readlineinterface",
+ "title": "readlineInterface",
+ "type": "class",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v19/readline/#readlinepromisesinterface",
+ "title": "readlinePromisesInterface",
+ "type": "class",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v19/readline/#readlinepromisesreadline",
+ "title": "readlinePromisesReadline",
+ "type": "class",
+ "name": "readline"
+ },
+ {
+ "slug": "/api/v19/repl/",
+ "title": "REPL",
+ "type": "module",
+ "name": "repl"
+ },
+ {
+ "slug": "/api/v19/repl/#replserver",
+ "title": "REPLServer",
+ "type": "class",
+ "name": "repl"
+ },
+ {
+ "slug": "/api/v19/report/",
+ "title": "Diagnostic report",
+ "type": "module",
+ "name": "report"
+ },
+ {
+ "slug": "/api/v19/single-executable-applications/",
+ "title": "Single executable applications",
+ "type": "module",
+ "name": "single-executable-applications"
+ },
+ {
+ "slug": "/api/v19/stream/",
+ "title": "Stream",
+ "type": "module",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v19/stream/#streamduplex",
+ "title": "streamDuplex",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v19/stream/#streamduplex",
+ "title": "streamDuplex",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v19/stream/#streampassthrough",
+ "title": "streamPassThrough",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v19/stream/#streamreadable",
+ "title": "streamReadable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v19/stream/#streamreadable",
+ "title": "streamReadable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v19/stream/#streamtransform",
+ "title": "streamTransform",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v19/stream/#streamtransform",
+ "title": "streamTransform",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v19/stream/#streamwritable",
+ "title": "streamWritable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v19/stream/#streamwritable",
+ "title": "streamWritable",
+ "type": "class",
+ "name": "stream"
+ },
+ {
+ "slug": "/api/v19/string_decoder/",
+ "title": "String decoder",
+ "type": "module",
+ "name": "string_decoder"
+ },
+ {
+ "slug": "/api/v19/string_decoder/#stringdecoder",
+ "title": "StringDecoder",
+ "type": "class",
+ "name": "string_decoder"
+ },
+ {
+ "slug": "/api/v19/synopsis/",
+ "title": "Usage and example",
+ "type": "module",
+ "name": "synopsis"
+ },
+ {
+ "slug": "/api/v19/test/",
+ "title": "Test runner",
+ "type": "module",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v19/test/#mockfunctioncontext",
+ "title": "MockFunctionContext",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v19/test/#mocktracker",
+ "title": "MockTracker",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v19/test/#suitecontext",
+ "title": "SuiteContext",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v19/test/#testcontext",
+ "title": "TestContext",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v19/test/#testsstream",
+ "title": "TestsStream",
+ "type": "class",
+ "name": "test"
+ },
+ {
+ "slug": "/api/v19/timers/",
+ "title": "Timers",
+ "type": "module",
+ "name": "timers"
+ },
+ {
+ "slug": "/api/v19/timers/#immediate",
+ "title": "Immediate",
+ "type": "class",
+ "name": "timers"
+ },
+ {
+ "slug": "/api/v19/timers/#timeout",
+ "title": "Timeout",
+ "type": "class",
+ "name": "timers"
+ },
+ {
+ "slug": "/api/v19/tls/",
+ "title": "TLS ",
+ "type": "module",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v19/tls/#tlscryptostream",
+ "title": "tlsCryptoStream",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v19/tls/#tlssecurepair",
+ "title": "tlsSecurePair",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v19/tls/#tlsserver",
+ "title": "tlsServer",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v19/tls/#tlstlssocket",
+ "title": "tlsTLSSocket",
+ "type": "class",
+ "name": "tls"
+ },
+ {
+ "slug": "/api/v19/tracing/",
+ "title": "Trace events",
+ "type": "module",
+ "name": "tracing"
+ },
+ {
+ "slug": "/api/v19/tty/",
+ "title": "TTY",
+ "type": "module",
+ "name": "tty"
+ },
+ {
+ "slug": "/api/v19/tty/#ttyreadstream",
+ "title": "ttyReadStream",
+ "type": "class",
+ "name": "tty"
+ },
+ {
+ "slug": "/api/v19/tty/#ttywritestream",
+ "title": "ttyWriteStream",
+ "type": "class",
+ "name": "tty"
+ },
+ {
+ "slug": "/api/v19/url/",
+ "title": "URL",
+ "type": "module",
+ "name": "url"
+ },
+ {
+ "slug": "/api/v19/url/#url",
+ "title": "URL",
+ "type": "class",
+ "name": "url"
+ },
+ {
+ "slug": "/api/v19/url/#urlsearchparams",
+ "title": "URLSearchParams",
+ "type": "class",
+ "name": "url"
+ },
+ {
+ "slug": "/api/v19/util/",
+ "title": "Util",
+ "type": "module",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v19/util/#utilmimeparams",
+ "title": "utilMIMEParams",
+ "type": "class",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v19/util/#utilmimetype",
+ "title": "utilMIMEType",
+ "type": "class",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v19/util/#utiltextdecoder",
+ "title": "utilTextDecoder",
+ "type": "class",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v19/util/#utiltextencoder",
+ "title": "utilTextEncoder",
+ "type": "class",
+ "name": "util"
+ },
+ {
+ "slug": "/api/v19/v8/",
+ "title": "V8",
+ "type": "module",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v19/v8/#v8defaultdeserializer",
+ "title": "v8DefaultDeserializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v19/v8/#v8defaultserializer",
+ "title": "v8DefaultSerializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v19/v8/#v8deserializer",
+ "title": "v8Deserializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v19/v8/#v8gcprofiler",
+ "title": "v8GCProfiler",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v19/v8/#v8serializer",
+ "title": "v8Serializer",
+ "type": "class",
+ "name": "v8"
+ },
+ {
+ "slug": "/api/v19/vm/",
+ "title": "VM ",
+ "type": "module",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v19/vm/#vmmodule",
+ "title": "vmModule",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v19/vm/#vmscript",
+ "title": "vmScript",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v19/vm/#vmsourcetextmodule",
+ "title": "vmSourceTextModule",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v19/vm/#vmsyntheticmodule",
+ "title": "vmSyntheticModule",
+ "type": "class",
+ "name": "vm"
+ },
+ {
+ "slug": "/api/v19/wasi/",
+ "title": "WebAssembly System Interface ",
+ "type": "module",
+ "name": "wasi"
+ },
+ {
+ "slug": "/api/v19/wasi/#wasi",
+ "title": "WASI",
+ "type": "class",
+ "name": "wasi"
+ },
+ {
+ "slug": "/api/v19/webcrypto/",
+ "title": "Web Crypto API",
+ "type": "module",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#aescbcparams",
+ "title": "AesCbcParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#aesctrparams",
+ "title": "AesCtrParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#aesgcmparams",
+ "title": "AesGcmParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#aeskeygenparams",
+ "title": "AesKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#algorithmidentifier",
+ "title": "AlgorithmIdentifier",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#crypto",
+ "title": "Crypto",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#cryptokey",
+ "title": "CryptoKey",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#cryptokeypair",
+ "title": "CryptoKeyPair",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#ecdhkeyderiveparams",
+ "title": "EcdhKeyDeriveParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#ecdsaparams",
+ "title": "EcdsaParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#eckeygenparams",
+ "title": "EcKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#eckeyimportparams",
+ "title": "EcKeyImportParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#ed448params",
+ "title": "Ed448Params",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#hkdfparams",
+ "title": "HkdfParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#hmacimportparams",
+ "title": "HmacImportParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#hmackeygenparams",
+ "title": "HmacKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#pbkdf2params",
+ "title": "Pbkdf2Params",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#rsahashedimportparams",
+ "title": "RsaHashedImportParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#rsahashedkeygenparams",
+ "title": "RsaHashedKeyGenParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#rsaoaepparams",
+ "title": "RsaOaepParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#rsapssparams",
+ "title": "RsaPssParams",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webcrypto/#subtlecrypto",
+ "title": "SubtleCrypto",
+ "type": "class",
+ "name": "webcrypto"
+ },
+ {
+ "slug": "/api/v19/webstreams/",
+ "title": "Web Streams API",
+ "type": "module",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#bytelengthqueuingstrategy",
+ "title": "ByteLengthQueuingStrategy",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#compressionstream",
+ "title": "CompressionStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#countqueuingstrategy",
+ "title": "CountQueuingStrategy",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#decompressionstream",
+ "title": "DecompressionStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#readablebytestreamcontroller",
+ "title": "ReadableByteStreamController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#readablestream",
+ "title": "ReadableStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#readablestreambyobreader",
+ "title": "ReadableStreamBYOBReader",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#readablestreambyobrequest",
+ "title": "ReadableStreamBYOBRequest",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#readablestreamdefaultcontroller",
+ "title": "ReadableStreamDefaultController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#readablestreamdefaultreader",
+ "title": "ReadableStreamDefaultReader",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#textdecoderstream",
+ "title": "TextDecoderStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#textencoderstream",
+ "title": "TextEncoderStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#transformstream",
+ "title": "TransformStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#transformstreamdefaultcontroller",
+ "title": "TransformStreamDefaultController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#writablestream",
+ "title": "WritableStream",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#writablestreamdefaultcontroller",
+ "title": "WritableStreamDefaultController",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/webstreams/#writablestreamdefaultwriter",
+ "title": "WritableStreamDefaultWriter",
+ "type": "class",
+ "name": "webstreams"
+ },
+ {
+ "slug": "/api/v19/worker_threads/",
+ "title": "Worker threads",
+ "type": "module",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v19/worker_threads/#broadcastchannel-extends-eventtarget",
+ "title": "BroadcastChannel extends EventTarget",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v19/worker_threads/#messagechannel",
+ "title": "MessageChannel",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v19/worker_threads/#messageport",
+ "title": "MessagePort",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v19/worker_threads/#worker",
+ "title": "Worker",
+ "type": "class",
+ "name": "worker_threads"
+ },
+ {
+ "slug": "/api/v19/zlib/",
+ "title": "Zlib",
+ "type": "module",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#brotlioptions",
+ "title": "BrotliOptions",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#options",
+ "title": "Options",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#zlibbrotlicompress",
+ "title": "zlibBrotliCompress",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#zlibbrotlidecompress",
+ "title": "zlibBrotliDecompress",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#zlibdeflate",
+ "title": "zlibDeflate",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#zlibdeflateraw",
+ "title": "zlibDeflateRaw",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#zlibgunzip",
+ "title": "zlibGunzip",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#zlibgzip",
+ "title": "zlibGzip",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#zlibinflate",
+ "title": "zlibInflate",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#zlibinflateraw",
+ "title": "zlibInflateRaw",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#zlibunzip",
+ "title": "zlibUnzip",
+ "type": "class",
+ "name": "zlib"
+ },
+ {
+ "slug": "/api/v19/zlib/#zlibzlibbase",
+ "title": "zlibZlibBase",
+ "type": "class",
+ "name": "zlib"
+ }
+ ]
}
\ No newline at end of file
diff --git a/content/api/v19/net.en.md b/content/api/v19/net.en.md
index 5231a57ec2..f2573ec4ca 100644
--- a/content/api/v19/net.en.md
+++ b/content/api/v19/net.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:net` module provides an asynchronous network API for creating stream-based
TCP or [IPC][] servers ([`net.createServer()`][]) and clients
@@ -775,7 +775,7 @@ For TCP connections, available `options` are:
* `autoSelectFamilyAttemptTimeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type): The amount of time in milliseconds to wait
for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option.
If set to a positive integer less than `10`, then the value `10` will be used instead.
- **Default:** `250`.
+ **Default:** initially `250`, but it can be changed at runtime using [`net.setDefaultAutoSelectFamilyAttemptTimeout(value)`][]
For [IPC][] connections, available `options` are:
@@ -1288,22 +1288,6 @@ immediately initiates connection with
[`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`],
then returns the `net.Socket` that starts the connection.
-### `net.setDefaultAutoSelectFamily(value)`
-
-
-
-Sets the default value of the `autoSelectFamily` option of [`socket.connect(options)`][].
-
-* `value` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The new default value. The initial default value is `false`.
-
-### `net.getDefaultAutoSelectFamily()`
-
-
-
-Gets the current default value of the `autoSelectFamily` option of [`socket.connect(options)`][].
-
-* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The current default value of the `autoSelectFamily` option.
-
### `net.createServer([options][, connectionListener])`
@@ -1389,6 +1373,39 @@ Use `nc` to connect to a Unix domain socket server:
$ nc -U /tmp/echo.sock
```
+### `net.getDefaultAutoSelectFamily()`
+
+
+
+Gets the current default value of the `autoSelectFamily` option of [`socket.connect(options)`][].
+
+* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The current default value of the `autoSelectFamily` option.
+
+### `net.setDefaultAutoSelectFamily(value)`
+
+
+
+Sets the default value of the `autoSelectFamily` option of [`socket.connect(options)`][].
+
+* `value` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The new default value. The initial default value is `false`.
+
+### `net.getDefaultAutoSelectFamilyAttemptTimeout()`
+
+
+
+Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of [`socket.connect(options)`][].
+
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The current default value of the `autoSelectFamilyAttemptTimeout` option.
+
+### `net.setDefaultAutoSelectFamilyAttemptTimeout(value)`
+
+
+
+Sets the default value of the `autoSelectFamilyAttemptTimeout` option of [`socket.connect(options)`][].
+
+* `value` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The new default value, which must be a positive number. If the number is less than `10`,
+ the value `10` is used instead. The initial default value is `250`.
+
### `net.isIP(input)`
@@ -1468,6 +1485,7 @@ net.isIPv6('fhqwhgads'); // returns false
[`net.createConnection(port, host)`]: #netcreateconnectionport-host-connectlistener
[`net.createServer()`]: #netcreateserveroptions-connectionlistener
[`net.setDefaultAutoSelectFamily(value)`]: #netsetdefaultautoselectfamilyvalue
+[`net.setDefaultAutoSelectFamilyAttemptTimeout(value)`]: #netsetdefaultautoselectfamilyattempttimeoutvalue
[`new net.Socket(options)`]: #new-netsocketoptions
[`readable.setEncoding()`]: /api/v19/stream#readablesetencodingencoding
[`server.close()`]: #serverclosecallback
diff --git a/content/api/v19/os.en.md b/content/api/v19/os.en.md
index b935622604..0eb83122d9 100644
--- a/content/api/v19/os.en.md
+++ b/content/api/v19/os.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:os` module provides operating system-related utility methods and
properties. It can be accessed using:
diff --git a/content/api/v19/packages.en.md b/content/api/v19/packages.en.md
index 0261574e7b..23e48652db 100644
--- a/content/api/v19/packages.en.md
+++ b/content/api/v19/packages.en.md
@@ -478,7 +478,7 @@ targets, this expansion is dependent on only the files of the package itself.
To exclude private subfolders from patterns, `null` targets can be used:
-```json
+```json|js
// ./node_modules/es-module-package/package.json
{
"exports": {
@@ -486,9 +486,7 @@ To exclude private subfolders from patterns, `null` targets can be used:
"./features/private-internal/*": null
}
}
-```
-
-```js
+--------------
import featureInternal from 'es-module-package/features/private-internal/m.js';
// Throws: ERR_PACKAGE_PATH_NOT_EXPORTED
@@ -717,25 +715,21 @@ const { something } = require('a-package/foo.js'); // Loads from ./foo.js.
Finally, self-referencing also works with scoped packages. For example, this
code will also work:
-```json
+```json|cjs
// package.json
{
"name": "@my/package",
"exports": "./index.js"
}
-```
-
-```cjs
+--------------
// ./index.js
module.exports = 42;
```
-```cjs
+```cjs|console
// ./other.js
console.log(require('@my/package'));
-```
-
-```console
+--------------
$ node other.js
42
```
@@ -837,12 +831,10 @@ to be treated as ES modules, just as `"type": "commonjs"` would cause them
to be treated as CommonJS.
See [Enabling](esm.md#enabling).
-```cjs
+```cjs|js
// ./node_modules/pkg/index.cjs
exports.name = 'value';
-```
-
-```js
+--------------
// ./node_modules/pkg/wrapper.mjs
import cjsModule from './index.cjs';
export const name = cjsModule.name;
@@ -1109,14 +1101,12 @@ The nearest parent `package.json` is defined as the first `package.json` found
when searching in the current folder, that folder's parent, and so on up
until a node\_modules folder or the volume root is reached.
-```json
+```json|bash
// package.json
{
"type": "module"
}
-```
-
-```bash
+--------------
# In same folder as preceding package.json
node my-app.js # Runs as ES module
```
diff --git a/content/api/v19/path.en.md b/content/api/v19/path.en.md
index c09848424a..96e5242e3e 100644
--- a/content/api/v19/path.en.md
+++ b/content/api/v19/path.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:path` module provides utilities for working with file and directory
paths. It can be accessed using:
@@ -383,7 +383,7 @@ The returned object will have the following properties:
For example, on POSIX:
-```js
+```js|text
path.parse('/home/user/dir/file.txt');
// Returns:
// { root: '/',
@@ -391,9 +391,7 @@ path.parse('/home/user/dir/file.txt');
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
-```
-
-```text
+--------------
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
@@ -405,7 +403,7 @@ path.parse('/home/user/dir/file.txt');
On Windows:
-```js
+```js|text
path.parse('C:\\path\\dir\\file.txt');
// Returns:
// { root: 'C:\\',
@@ -413,9 +411,7 @@ path.parse('C:\\path\\dir\\file.txt');
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
-```
-
-```text
+--------------
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
diff --git a/content/api/v19/perf_hooks.en.md b/content/api/v19/perf_hooks.en.md
index 3ffcaee592..99c2e5e597 100644
--- a/content/api/v19/perf_hooks.en.md
+++ b/content/api/v19/perf_hooks.en.md
@@ -13,7 +13,7 @@ Stable
-
+
This module provides an implementation of a subset of the W3C
[Web Performance APIs][] as well as additional APIs for
diff --git a/content/api/v19/permissions.en.md b/content/api/v19/permissions.en.md
index 63b34e8fc5..89ca7ccebe 100644
--- a/content/api/v19/permissions.en.md
+++ b/content/api/v19/permissions.en.md
@@ -395,7 +395,7 @@ The following example, would allow access to `fs` for all `data:` resources:
Given an import map:
-```json
+```json|json
{
"imports": {
"react": "./app/node_modules/react/index.js"
@@ -406,9 +406,7 @@ Given an import map:
}
}
}
-```
-
-```json
+--------------
{
"dependencies": true,
"scopes": {
diff --git a/content/api/v19/process.en.md b/content/api/v19/process.en.md
index 096182e9c0..d0c7f22685 100644
--- a/content/api/v19/process.en.md
+++ b/content/api/v19/process.en.md
@@ -9,16 +9,14 @@ version: 'v19'
-
+
The `process` object provides information about, and control over, the current
Node.js process.
-```mjs
+```mjs|cjs
import process from 'node:process';
-```
-
-```cjs
+--------------
const process = require('node:process');
```
@@ -45,7 +43,7 @@ termination, such as calling [`process.exit()`][] or uncaught exceptions.
The `'beforeExit'` should _not_ be used as an alternative to the `'exit'` event
unless the intention is to schedule additional work.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('beforeExit', (code) => {
@@ -62,9 +60,7 @@ console.log('This message is displayed first.');
// This message is displayed first.
// Process beforeExit event with code: 0
// Process exit event with code: 0
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('beforeExit', (code) => {
@@ -110,15 +106,13 @@ The listener callback function is invoked with the exit code specified either
by the [`process.exitCode`][] property, or the `exitCode` argument passed to the
[`process.exit()`][] method.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('exit', (code) => {
console.log(`About to exit with code: ${code}`);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('exit', (code) => {
@@ -131,7 +125,7 @@ process will exit immediately after calling the `'exit'` event listeners
causing any additional work still queued in the event loop to be abandoned.
In the following example, for instance, the timeout will never occur:
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('exit', (code) => {
@@ -139,9 +133,7 @@ process.on('exit', (code) => {
console.log('This will not run');
}, 0);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('exit', (code) => {
@@ -203,7 +195,7 @@ example, [`Promise.race()`][] can trigger a `'multipleResolves'` event.
Because of the unreliability of the event in cases like the
[`Promise.race()`][] example above it has been deprecated.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('multipleResolves', (type, promise, reason) => {
@@ -230,9 +222,7 @@ main().then(console.log);
// at new Promise ()
// at main (*)
// First call
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('multipleResolves', (type, promise, reason) => {
@@ -291,7 +281,7 @@ In asynchronous code, the `'unhandledRejection'` event is emitted when the list
of unhandled rejections grows, and the `'rejectionHandled'` event is emitted
when the list of unhandled rejections shrinks.
-```mjs
+```mjs|cjs
import process from 'node:process';
const unhandledRejections = new Map();
@@ -301,9 +291,7 @@ process.on('unhandledRejection', (reason, promise) => {
process.on('rejectionHandled', (promise) => {
unhandledRejections.delete(promise);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
const unhandledRejections = new Map();
@@ -344,7 +332,7 @@ behavior. Alternatively, change the [`process.exitCode`][] in the
provided exit code. Otherwise, in the presence of such handler the process will
exit with 0.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('uncaughtException', (err, origin) => {
@@ -362,9 +350,7 @@ setTimeout(() => {
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('uncaughtException', (err, origin) => {
@@ -436,7 +422,7 @@ Installing an `'uncaughtExceptionMonitor'` listener does not change the behavior
once an `'uncaughtException'` event is emitted. The process will
still crash if no `'uncaughtException'` listener is installed.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('uncaughtExceptionMonitor', (err, origin) => {
@@ -446,9 +432,7 @@ process.on('uncaughtExceptionMonitor', (err, origin) => {
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
// Still crashes Node.js
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('uncaughtExceptionMonitor', (err, origin) => {
@@ -476,7 +460,7 @@ are propagated through a `Promise` chain. The `'unhandledRejection'` event is
useful for detecting and keeping track of promises that were rejected whose
rejections have not yet been handled.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('unhandledRejection', (reason, promise) => {
@@ -487,9 +471,7 @@ process.on('unhandledRejection', (reason, promise) => {
somePromise.then((res) => {
return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)
}); // No `.catch()` or `.then()`
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('unhandledRejection', (reason, promise) => {
@@ -505,7 +487,7 @@ somePromise.then((res) => {
The following will also trigger the `'unhandledRejection'` event to be
emitted:
-```mjs
+```mjs|cjs
import process from 'node:process';
function SomeResource() {
@@ -515,9 +497,7 @@ function SomeResource() {
const resource = new SomeResource();
// no .catch or .then on resource.loaded for at least a turn
-```
-
-```cjs
+--------------
const process = require('node:process');
function SomeResource() {
@@ -554,7 +534,7 @@ are not part of the normal Node.js and JavaScript error handling flow.
Node.js can emit warnings whenever it detects bad coding practices that could
lead to sub-optimal application performance, bugs, or security vulnerabilities.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('warning', (warning) => {
@@ -562,9 +542,7 @@ process.on('warning', (warning) => {
console.warn(warning.message); // Print the warning message
console.warn(warning.stack); // Print the stack trace
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('warning', (warning) => {
@@ -671,7 +649,7 @@ The signal handler will receive the signal's name (`'SIGINT'`,
The name of each event will be the uppercase common name for the signal (e.g.
`'SIGINT'` for `SIGINT` signals).
-```mjs
+```mjs|cjs
import process from 'node:process';
// Begin reading from stdin so the process does not exit.
@@ -688,9 +666,7 @@ function handle(signal) {
process.on('SIGINT', handle);
process.on('SIGTERM', handle);
-```
-
-```cjs
+--------------
const process = require('node:process');
// Begin reading from stdin so the process does not exit.
@@ -793,7 +769,7 @@ appear only _once_; each will begin with one or more dashes. Flags
passed through to V8 will contain underscores instead of non-leading
dashes:
-```mjs
+```mjs|cjs
import { allowedNodeEnvironmentFlags } from 'node:process';
allowedNodeEnvironmentFlags.forEach((flag) => {
@@ -802,9 +778,7 @@ allowedNodeEnvironmentFlags.forEach((flag) => {
// --abort_on_uncaught_exception
// ...
});
-```
-
-```cjs
+--------------
const { allowedNodeEnvironmentFlags } = require('node:process');
allowedNodeEnvironmentFlags.forEach((flag) => {
@@ -833,13 +807,11 @@ The operating system CPU architecture for which the Node.js binary was compiled.
Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`,
`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`.
-```mjs
+```mjs|cjs
import { arch } from 'node:process';
console.log(`This processor architecture is ${arch}`);
-```
-
-```cjs
+--------------
const { arch } = require('node:process');
console.log(`This processor architecture is ${arch}`);
@@ -860,16 +832,14 @@ arguments.
For example, assuming the following script for `process-args.js`:
-```mjs
+```mjs|cjs
import { argv } from 'node:process';
// print process.argv
argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
-```
-
-```cjs
+--------------
const { argv } = require('node:process');
// print process.argv
@@ -954,7 +924,7 @@ The `process.chdir()` method changes the current working directory of the
Node.js process or throws an exception if doing so fails (for instance, if
the specified `directory` does not exist).
-```mjs
+```mjs|cjs
import { chdir, cwd } from 'node:process';
console.log(`Starting directory: ${cwd()}`);
@@ -964,9 +934,7 @@ try {
} catch (err) {
console.error(`chdir: ${err}`);
}
-```
-
-```cjs
+--------------
const { chdir, cwd } = require('node:process');
console.log(`Starting directory: ${cwd()}`);
@@ -1072,7 +1040,7 @@ actual elapsed time if multiple CPU cores are performing work for this process.
The result of a previous call to `process.cpuUsage()` can be passed as the
argument to the function, to get a diff reading.
-```mjs
+```mjs|cjs
import { cpuUsage } from 'node:process';
const startUsage = cpuUsage();
@@ -1084,9 +1052,7 @@ while (Date.now() - now < 500);
console.log(cpuUsage(startUsage));
// { user: 514883, system: 11226 }
-```
-
-```cjs
+--------------
const { cpuUsage } = require('node:process');
const startUsage = cpuUsage();
@@ -1109,13 +1075,11 @@ console.log(cpuUsage(startUsage));
The `process.cwd()` method returns the current working directory of the Node.js
process.
-```mjs
+```mjs|cjs
import { cwd } from 'node:process';
console.log(`Current directory: ${cwd()}`);
-```
-
-```cjs
+--------------
const { cwd } = require('node:process');
console.log(`Current directory: ${cwd()}`);
@@ -1129,13 +1093,11 @@ console.log(`Current directory: ${cwd()}`);
The port used by the Node.js debugger when enabled.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.debugPort = 5858;
-```
-
-```cjs
+--------------
const process = require('node:process');
process.debugPort = 5858;
@@ -1182,7 +1144,7 @@ that exports a `foo` function. All the symbols are loaded before
the call returns, by passing the `RTLD_NOW` constant. In this example
the constant is assumed to be available.
-```mjs
+```mjs|cjs
import { dlopen } from 'node:process';
import { constants } from 'node:os';
import { fileURLToPath } from 'node:url';
@@ -1191,9 +1153,7 @@ const module = { exports: {} };
dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)),
constants.dlopen.RTLD_NOW);
module.exports.foo();
-```
-
-```cjs
+--------------
const { dlopen } = require('node:process');
const { constants } = require('node:os');
const { join } = require('node:path');
@@ -1221,7 +1181,7 @@ The `process.emitWarning()` method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
[`'warning'`][process_warning] event.
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning with a code and additional detail.
@@ -1232,9 +1192,7 @@ emitWarning('Something happened!', {
// Emits:
// (node:56338) [MY_WARNING] Warning: Something happened!
// This is some additional information
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning with a code and additional detail.
@@ -1251,7 +1209,7 @@ In this example, an `Error` object is generated internally by
`process.emitWarning()` and passed through to the
[`'warning'`][process_warning] handler.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('warning', (warning) => {
@@ -1261,9 +1219,7 @@ process.on('warning', (warning) => {
console.warn(warning.stack); // Stack trace
console.warn(warning.detail); // 'This is some additional information'
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('warning', (warning) => {
@@ -1293,15 +1249,13 @@ The `process.emitWarning()` method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
[`'warning'`][process_warning] event.
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning using a string.
emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning using a string.
@@ -1309,15 +1263,13 @@ emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
```
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning using a string and a type.
emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning using a string and a type.
@@ -1325,14 +1277,12 @@ emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!
```
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
emitWarning('Something happened!', 'CustomWarning', 'WARN001');
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');
@@ -1343,7 +1293,7 @@ In each of the previous examples, an `Error` object is generated internally by
`process.emitWarning()` and passed through to the [`'warning'`][process_warning]
handler.
-```mjs
+```mjs|cjs
import process from 'node:process';
process.on('warning', (warning) => {
@@ -1352,9 +1302,7 @@ process.on('warning', (warning) => {
console.warn(warning.code);
console.warn(warning.stack);
});
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('warning', (warning) => {
@@ -1369,7 +1317,7 @@ If `warning` is passed as an `Error` object, it will be passed through to the
`'warning'` event handler unmodified (and the optional `type`,
`code` and `ctor` arguments will be ignored):
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
// Emit a warning using an Error object.
@@ -1380,9 +1328,7 @@ myWarning.code = 'WARN001';
emitWarning(myWarning);
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
// Emit a warning using an Error object.
@@ -1416,7 +1362,7 @@ The following additional handling is implemented if the warning `type` is
As a best practice, warnings should be emitted only once per process. To do
so, place the `emitWarning()` behind a boolean.
-```mjs
+```mjs|cjs
import { emitWarning } from 'node:process';
function emitMyWarning() {
@@ -1429,9 +1375,7 @@ emitMyWarning();
// Emits: (node: 56339) Warning: Only warn once!
emitMyWarning();
// Emits nothing
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
function emitMyWarning() {
@@ -1483,14 +1427,12 @@ $ node -e 'process.env.foo = "bar"' && echo $foo
While the following will:
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.foo = 'bar';
@@ -1501,7 +1443,7 @@ Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.test = null;
@@ -1510,9 +1452,7 @@ console.log(env.test);
env.test = undefined;
console.log(env.test);
// => 'undefined'
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.test = null;
@@ -1525,16 +1465,14 @@ console.log(env.test);
Use `delete` to delete a property from `process.env`.
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.TEST = 1;
@@ -1545,15 +1483,13 @@ console.log(env.TEST);
On Windows operating systems, environment variables are case-insensitive.
-```mjs
+```mjs|cjs
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.TEST = 1;
@@ -1627,13 +1563,11 @@ called.
To exit with a 'failure' code:
-```mjs
+```mjs|cjs
import { exit } from 'node:process';
exit(1);
-```
-
-```cjs
+--------------
const { exit } = require('node:process');
exit(1);
@@ -1655,7 +1589,7 @@ For instance, the following example illustrates a _misuse_ of the
`process.exit()` method that could lead to data printed to stdout being
truncated and lost:
-```mjs
+```mjs|cjs
import { exit } from 'node:process';
// This is an example of what *not* to do:
@@ -1663,9 +1597,7 @@ if (someConditionNotMet()) {
printUsageToStdout();
exit(1);
}
-```
-
-```cjs
+--------------
const { exit } = require('node:process');
// This is an example of what *not* to do:
@@ -1684,7 +1616,7 @@ Rather than calling `process.exit()` directly, the code _should_ set the
`process.exitCode` and allow the process to exit naturally by avoiding
scheduling any additional work for the event loop:
-```mjs
+```mjs|cjs
import process from 'node:process';
// How to properly set the exit code while letting
@@ -1693,9 +1625,7 @@ if (someConditionNotMet()) {
printUsageToStdout();
process.exitCode = 1;
}
-```
-
-```cjs
+--------------
const process = require('node:process');
// How to properly set the exit code while letting
@@ -1742,7 +1672,7 @@ The `process.getActiveResourcesInfo()` method returns an array of strings
containing the types of the active resources that are currently keeping the
event loop alive.
-```mjs
+```mjs|cjs
import { getActiveResourcesInfo } from 'node:process';
import { setTimeout } from 'node:timers';
@@ -1752,9 +1682,7 @@ console.log('After:', getActiveResourcesInfo());
// Prints:
// Before: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap' ]
// After: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]
-```
-
-```cjs
+--------------
const { getActiveResourcesInfo } = require('node:process');
const { setTimeout } = require('node:timers');
@@ -1773,15 +1701,13 @@ console.log('After:', getActiveResourcesInfo());
The `process.getegid()` method returns the numerical effective group identity
of the Node.js process. (See getegid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getegid) {
console.log(`Current gid: ${process.getegid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getegid) {
@@ -1801,15 +1727,13 @@ Android).
The `process.geteuid()` method returns the numerical effective user identity of
the process. (See geteuid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.geteuid) {
console.log(`Current uid: ${process.geteuid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.geteuid) {
@@ -1829,15 +1753,13 @@ Android).
The `process.getgid()` method returns the numerical group identity of the
process. (See getgid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgid) {
console.log(`Current gid: ${process.getgid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgid) {
@@ -1858,15 +1780,13 @@ The `process.getgroups()` method returns an array with the supplementary group
IDs. POSIX leaves it unspecified if the effective group ID is included but
Node.js ensures it always is.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgroups) {
console.log(process.getgroups()); // [ 16, 21, 297 ]
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgroups) {
@@ -1886,15 +1806,13 @@ Android).
The `process.getuid()` method returns the numeric user identity of the process.
(See getuid(2).)
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getuid) {
console.log(`Current uid: ${process.getuid()}`);
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getuid) {
@@ -1944,7 +1862,7 @@ These times are relative to an arbitrary time in the
past, and not related to the time of day and therefore not subject to clock
drift. The primary use is for measuring performance between intervals:
-```mjs
+```mjs|cjs
import { hrtime } from 'node:process';
const NS_PER_SEC = 1e9;
@@ -1958,9 +1876,7 @@ setTimeout(() => {
console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
// Benchmark took 1000000552 nanoseconds
}, 1000);
-```
-
-```cjs
+--------------
const { hrtime } = require('node:process');
const NS_PER_SEC = 1e9;
@@ -1989,7 +1905,7 @@ Unlike [`process.hrtime()`][], it does not support an additional `time`
argument since the difference can just be computed directly
by subtraction of the two `bigint`s.
-```mjs
+```mjs|cjs
import { hrtime } from 'node:process';
const start = hrtime.bigint();
@@ -2002,9 +1918,7 @@ setTimeout(() => {
console.log(`Benchmark took ${end - start} nanoseconds`);
// Benchmark took 1154389282 nanoseconds
}, 1000);
-```
-
-```cjs
+--------------
const { hrtime } = require('node:process');
const start = hrtime.bigint();
@@ -2033,7 +1947,7 @@ access or the `CAP_SETGID` capability.
Use care when dropping privileges:
-```mjs
+```mjs|cjs
import { getgroups, initgroups, setgid } from 'node:process';
console.log(getgroups()); // [ 0 ]
@@ -2041,9 +1955,7 @@ initgroups('nodeuser', 1000); // switch user
console.log(getgroups()); // [ 27, 30, 46, 1000, 0 ]
setgid(1000); // drop root gid
console.log(getgroups()); // [ 27, 30, 46, 1000 ]
-```
-
-```cjs
+--------------
const { getgroups, initgroups, setgid } = require('node:process');
console.log(getgroups()); // [ 0 ]
@@ -2080,7 +1992,7 @@ Even though the name of this function is `process.kill()`, it is really just a
signal sender, like the `kill` system call. The signal sent may do something
other than kill the target process.
-```mjs
+```mjs|cjs
import process, { kill } from 'node:process';
process.on('SIGHUP', () => {
@@ -2093,9 +2005,7 @@ setTimeout(() => {
}, 100);
kill(process.pid, 'SIGHUP');
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('SIGHUP', () => {
@@ -2148,7 +2058,7 @@ is no entry script.
Returns an object describing the memory usage of the Node.js process measured in
bytes.
-```mjs
+```mjs|cjs
import { memoryUsage } from 'node:process';
console.log(memoryUsage());
@@ -2160,9 +2070,7 @@ console.log(memoryUsage());
// external: 49879,
// arrayBuffers: 9386
// }
-```
-
-```cjs
+--------------
const { memoryUsage } = require('node:process');
console.log(memoryUsage());
@@ -2211,14 +2119,12 @@ process, including all C++ and JavaScript objects and code.
This is the same value as the `rss` property provided by `process.memoryUsage()`
but `process.memoryUsage.rss()` is faster.
-```mjs
+```mjs|cjs
import { memoryUsage } from 'node:process';
console.log(memoryUsage.rss());
// 35655680
-```
-
-```cjs
+--------------
const { rss } = require('node:process');
console.log(memoryUsage.rss());
@@ -2238,7 +2144,7 @@ completion and before the event loop is allowed to continue. It's possible to
create an infinite loop if one were to recursively call `process.nextTick()`.
See the [Event Loop][] guide for more background.
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
console.log('start');
@@ -2250,9 +2156,7 @@ console.log('scheduled');
// start
// scheduled
// nextTick callback
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
console.log('start');
@@ -2270,7 +2174,7 @@ This is important when developing APIs in order to give users the opportunity
to assign event handlers _after_ an object has been constructed but before any
I/O has occurred:
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
function MyThing(options) {
@@ -2285,9 +2189,7 @@ const thing = new MyThing();
thing.getReadyForStuff();
// thing.startDoingStuff() gets called now, not before.
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
function MyThing(options) {
@@ -2335,7 +2237,7 @@ It is not clear whether `foo()` or `bar()` will be called first.
The following approach is much better:
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
function definitelyAsync(arg, cb) {
@@ -2346,9 +2248,7 @@ function definitelyAsync(arg, cb) {
fs.stat('file', cb);
}
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
function definitelyAsync(arg, cb) {
@@ -2369,7 +2269,7 @@ execute the then, catch, and finally handlers of resolved promises. Within
Node.js, every time the "next tick queue" is drained, the microtask queue
is drained immediately after.
-```mjs
+```mjs|cjs
import { nextTick } from 'node:process';
Promise.resolve().then(() => console.log(2));
@@ -2379,9 +2279,7 @@ nextTick(() => console.log(1));
// 1
// 2
// 3
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
Promise.resolve().then(() => console.log(2));
@@ -2459,13 +2357,11 @@ flag's behavior.
The `process.pid` property returns the PID of the process.
-```mjs
+```mjs|cjs
import { pid } from 'node:process';
console.log(`This process is pid ${pid}`);
-```
-
-```cjs
+--------------
const { pid } = require('node:process');
console.log(`This process is pid ${pid}`);
@@ -2490,13 +2386,11 @@ Currently possible values are:
* `'sunos'`
* `'win32'`
-```mjs
+```mjs|cjs
import { platform } from 'node:process';
console.log(`This platform is ${platform}`);
-```
-
-```cjs
+--------------
const { platform } = require('node:process');
console.log(`This platform is ${platform}`);
@@ -2515,13 +2409,11 @@ Android operating system. However, Android support in Node.js
The `process.ppid` property returns the PID of the parent of the
current process.
-```mjs
+```mjs|cjs
import { ppid } from 'node:process';
console.log(`The parent process is pid ${ppid}`);
-```
-
-```cjs
+--------------
const { ppid } = require('node:process');
console.log(`The parent process is pid ${ppid}`);
@@ -2593,13 +2485,11 @@ Write reports in a compact format, single-line JSON, more easily consumable
by log processing systems than the default multi-line format designed for
human consumption.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Reports are compact? ${report.compact}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Reports are compact? ${report.compact}`);
@@ -2615,13 +2505,11 @@ Directory where the report is written. The default value is the empty string,
indicating that reports are written to the current working directory of the
Node.js process.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report directory is ${report.directory}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report directory is ${report.directory}`);
@@ -2640,13 +2528,11 @@ value is the empty string.
If the value of `process.report.filename` is set to `'stdout'` or `'stderr'`,
the report is written to the stdout or stderr of the process respectively.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report filename is ${report.filename}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report filename is ${report.filename}`);
@@ -2663,7 +2549,7 @@ Returns a JavaScript Object representation of a diagnostic report for the
running process. The report's JavaScript stack trace is taken from `err`, if
present.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
const data = report.getReport();
@@ -2672,9 +2558,7 @@ console.log(data.header.nodejsVersion);
// Similar to process.report.writeReport()
import fs from 'node:fs';
fs.writeFileSync('my-report.log', util.inspect(data), 'utf8');
-```
-
-```cjs
+--------------
const { report } = require('node:process');
const data = report.getReport();
@@ -2696,13 +2580,11 @@ Additional documentation is available in the [report documentation][].
If `true`, a diagnostic report is generated on fatal errors, such as out of
memory errors or failed C++ assertions.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report on fatal error: ${report.reportOnFatalError}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report on fatal error: ${report.reportOnFatalError}`);
@@ -2717,13 +2599,11 @@ console.log(`Report on fatal error: ${report.reportOnFatalError}`);
If `true`, a diagnostic report is generated when the process receives the
signal specified by `process.report.signal`.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report on signal: ${report.reportOnSignal}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report on signal: ${report.reportOnSignal}`);
@@ -2737,13 +2617,11 @@ console.log(`Report on signal: ${report.reportOnSignal}`);
If `true`, a diagnostic report is generated on uncaught exception.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report on exception: ${report.reportOnUncaughtException}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report on exception: ${report.reportOnUncaughtException}`);
@@ -2758,13 +2636,11 @@ console.log(`Report on exception: ${report.reportOnUncaughtException}`);
The signal used to trigger the creation of a diagnostic report. Defaults to
`'SIGUSR2'`.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
console.log(`Report signal: ${report.signal}`);
-```
-
-```cjs
+--------------
const { report } = require('node:process');
console.log(`Report signal: ${report.signal}`);
@@ -2790,13 +2666,11 @@ JavaScript stack trace is taken from `err`, if present.
If the value of `filename` is set to `'stdout'` or `'stderr'`, the report is
written to the stdout or stderr of the process respectively.
-```mjs
+```mjs|cjs
import { report } from 'node:process';
report.writeReport();
-```
-
-```cjs
+--------------
const { report } = require('node:process');
report.writeReport();
@@ -2851,7 +2725,7 @@ Additional documentation is available in the [report documentation][].
process becoming runnable or because the current process exceeded its
time slice. This field is not supported on Windows.
-```mjs
+```mjs|cjs
import { resourceUsage } from 'node:process';
console.log(resourceUsage());
@@ -2876,9 +2750,7 @@ console.log(resourceUsage());
involuntaryContextSwitches: 1
}
*/
-```
-
-```cjs
+--------------
const { resourceUsage } = require('node:process');
console.log(resourceUsage());
@@ -2940,7 +2812,7 @@ The `process.setegid()` method sets the effective group identity of the process.
name string. If a group name is specified, this method blocks while resolving
the associated a numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getegid && process.setegid) {
@@ -2952,9 +2824,7 @@ if (process.getegid && process.setegid) {
console.error(`Failed to set gid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getegid && process.setegid) {
@@ -2983,7 +2853,7 @@ The `process.seteuid()` method sets the effective user identity of the process.
string. If a username is specified, the method blocks while resolving the
associated numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.geteuid && process.seteuid) {
@@ -2995,9 +2865,7 @@ if (process.geteuid && process.seteuid) {
console.error(`Failed to set uid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.geteuid && process.seteuid) {
@@ -3026,7 +2894,7 @@ setgid(2).) The `id` can be passed as either a numeric ID or a group name
string. If a group name is specified, this method blocks while resolving the
associated numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgid && process.setgid) {
@@ -3038,9 +2906,7 @@ if (process.getgid && process.setgid) {
console.error(`Failed to set gid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgid && process.setgid) {
@@ -3070,7 +2936,7 @@ process to have `root` or the `CAP_SETGID` capability.
The `groups` array can contain numeric group IDs, group names, or both.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getgroups && process.setgroups) {
@@ -3081,9 +2947,7 @@ if (process.getgroups && process.setgroups) {
console.error(`Failed to set groups: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgroups && process.setgroups) {
@@ -3111,7 +2975,7 @@ setuid(2).) The `id` can be passed as either a numeric ID or a username string.
If a username is specified, the method blocks while resolving the associated
numeric ID.
-```mjs
+```mjs|cjs
import process from 'node:process';
if (process.getuid && process.setuid) {
@@ -3123,9 +2987,7 @@ if (process.getuid && process.setuid) {
console.error(`Failed to set uid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getuid && process.setuid) {
@@ -3246,13 +3108,11 @@ a [Writable][] stream.
For example, to copy `process.stdin` to `process.stdout`:
-```mjs
+```mjs|cjs
import { stdin, stdout } from 'node:process';
stdin.pipe(stdout);
-```
-
-```cjs
+--------------
const { stdin, stdout } = require('node:process');
stdin.pipe(stdout);
@@ -3403,7 +3263,7 @@ processes inherit the mask from the parent process.
`process.umask(mask)` sets the Node.js process's file mode creation mask. Child
processes inherit the mask from the parent process. Returns the previous mask.
-```mjs
+```mjs|cjs
import { umask } from 'node:process';
const newmask = 0o022;
@@ -3411,9 +3271,7 @@ const oldmask = umask(newmask);
console.log(
`Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`,
);
-```
-
-```cjs
+--------------
const { umask } = require('node:process');
const newmask = 0o022;
@@ -3445,14 +3303,12 @@ seconds.
The `process.version` property contains the Node.js version string.
-```mjs
+```mjs|cjs
import { version } from 'node:process';
console.log(`Version: ${version}`);
// Version: v14.8.0
-```
-
-```cjs
+--------------
const { version } = require('node:process');
console.log(`Version: ${version}`);
@@ -3473,13 +3329,11 @@ Node.js and its dependencies. `process.versions.modules` indicates the current
ABI version, which is increased whenever a C++ API changes. Node.js will refuse
to load modules that were compiled against a different module ABI version.
-```mjs
+```mjs|cjs
import { versions } from 'node:process';
console.log(versions);
-```
-
-```cjs
+--------------
const { versions } = require('node:process');
console.log(versions);
diff --git a/content/api/v19/punycode.en.md b/content/api/v19/punycode.en.md
index 086fefbc88..840ff3b00e 100644
--- a/content/api/v19/punycode.en.md
+++ b/content/api/v19/punycode.en.md
@@ -15,7 +15,7 @@ Deprecated
-
+
**The version of the punycode module bundled in Node.js is being deprecated.**
In a future major version of Node.js this module will be removed. Users
diff --git a/content/api/v19/querystring.en.md b/content/api/v19/querystring.en.md
index a60600fab7..0a409cda27 100644
--- a/content/api/v19/querystring.en.md
+++ b/content/api/v19/querystring.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:querystring` module provides utilities for parsing and formatting URL
query strings. It can be accessed using:
diff --git a/content/api/v19/readline.en.md b/content/api/v19/readline.en.md
index 029e17e70e..f19cdd2974 100644
--- a/content/api/v19/readline.en.md
+++ b/content/api/v19/readline.en.md
@@ -13,35 +13,31 @@ Stable
-
+
The `node:readline` module provides an interface for reading data from a
[Readable][] stream (such as [`process.stdin`][]) one line at a time.
To use the promise-based APIs:
-```mjs
+```mjs|cjs
import * as readline from 'node:readline/promises';
-```
-
-```cjs
+--------------
const readline = require('node:readline/promises');
```
To use the callback and sync APIs:
-```mjs
+```mjs|cjs
import * as readline from 'node:readline';
-```
-
-```cjs
+--------------
const readline = require('node:readline');
```
The following simple example illustrates the basic use of the `node:readline`
module.
-```mjs
+```mjs|cjs
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
@@ -52,9 +48,7 @@ const answer = await rl.question('What do you think of Node.js? ');
console.log(`Thank you for your valuable feedback: ${answer}`);
rl.close();
-```
-
-```cjs
+--------------
const readline = require('node:readline');
const { stdin: input, stdout: output } = require('node:process');
diff --git a/content/api/v19/repl.en.md b/content/api/v19/repl.en.md
index 72efa7bc9f..a95343e630 100644
--- a/content/api/v19/repl.en.md
+++ b/content/api/v19/repl.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation
that is available both as a standalone program or includible in other
diff --git a/content/api/v19/single-executable-applications.en.md b/content/api/v19/single-executable-applications.en.md
index cb32a09864..9ff1b81641 100644
--- a/content/api/v19/single-executable-applications.en.md
+++ b/content/api/v19/single-executable-applications.en.md
@@ -13,7 +13,7 @@ Experimental: This feature is being designed and will change.
-
+
This feature allows the distribution of a Node.js application conveniently to a
system that does not have Node.js installed.
@@ -42,7 +42,24 @@ tool, [postject][]:
$ cp $(command -v node) hello
```
-3. Inject the JavaScript file into the copied binary by running `postject` with
+3. Remove the signature of the binary:
+
+ * On macOS:
+
+ ```console
+ $ codesign --remove-signature hello
+ ```
+
+ * On Windows (optional):
+
+ [signtool][] can be used from the installed [Windows SDK][]. If this step is
+ skipped, ignore any signature-related warning from postject.
+
+ ```console
+ $ signtool remove /s hello
+ ```
+
+4. Inject the JavaScript file into the copied binary by running `postject` with
the following options:
* `hello` - The name of the copy of the `node` executable created in step 2.
@@ -70,7 +87,24 @@ tool, [postject][]:
--macho-segment-name NODE_JS
```
-4. Run the binary:
+5. Sign the binary:
+
+ * On macOS:
+
+ ```console
+ $ codesign --sign - hello
+ ```
+
+ * On Windows (optional):
+
+ A certificate needs to be present for this to work. However, the unsigned
+ binary would still be runnable.
+
+ ```console
+ $ signtool sign /fd SHA256 hello
+ ```
+
+6. Run the binary:
```console
$ ./hello world
Hello, world!
@@ -128,7 +162,8 @@ platforms:
* Windows
* macOS
-* Linux (AMD64 only)
+* Linux (all distributions [supported by Node.js][] except Alpine and all
+ architectures [supported by Node.js][] except s390x and ppc64)
This is due to a lack of better tools to generate single-executables that can be
used to test this feature on other platforms.
@@ -141,9 +176,12 @@ to help us document them.
[ELF]: https://en.wikipedia.org/wiki/Executable_and_Linkable_Format
[Mach-O]: https://en.wikipedia.org/wiki/Mach-O
[PE]: https://en.wikipedia.org/wiki/Portable_Executable
+[Windows SDK]: https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/
[`process.execPath`]: /api/v19/process#processexecpath
[`require()`]: /api/v19/modules#requireid
[`require.main`]: /api/v19/modules#accessing-the-main-module
[fuse]: https://www.electronjs.org/docs/latest/tutorial/fuses
[postject]: https://github.com/nodejs/postject
+[signtool]: https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool
[single executable applications]: https://github.com/nodejs/single-executable
+[supported by Node.js]: https://github.com/nodejs/node/blob/main/BUILDING.md#platform-list
diff --git a/content/api/v19/stream.en.md b/content/api/v19/stream.en.md
index f2954d6db4..b535d1d3b7 100644
--- a/content/api/v19/stream.en.md
+++ b/content/api/v19/stream.en.md
@@ -13,7 +13,7 @@ Stable
-
+
A stream is an abstract interface for working with streaming data in Node.js.
The `node:stream` module provides an API for implementing the stream interface.
@@ -86,7 +86,7 @@ or `require('node:stream').promises`.
* `end` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills when the pipeline is complete.
-```cjs
+```cjs|mjs
const { pipeline } = require('node:stream/promises');
const fs = require('node:fs');
const zlib = require('node:zlib');
@@ -101,9 +101,7 @@ async function run() {
}
run().catch(console.error);
-```
-
-```mjs
+--------------
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
@@ -120,7 +118,7 @@ To use an `AbortSignal`, pass it inside an options object, as the last argument.
When the signal is aborted, `destroy` will be called on the underlying pipeline,
with an `AbortError`.
-```cjs
+```cjs|mjs
const { pipeline } = require('node:stream/promises');
const fs = require('node:fs');
const zlib = require('node:zlib');
@@ -139,9 +137,7 @@ async function run() {
}
run().catch(console.error); // AbortError
-```
-
-```mjs
+--------------
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
@@ -163,7 +159,7 @@ try {
The `pipeline` API also supports async generators:
-```cjs
+```cjs|mjs
const { pipeline } = require('node:stream/promises');
const fs = require('node:fs');
@@ -182,9 +178,7 @@ async function run() {
}
run().catch(console.error);
-```
-
-```mjs
+--------------
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
@@ -205,7 +199,7 @@ Remember to handle the `signal` argument passed into the async generator.
Especially in the case where the async generator is the source for the
pipeline (i.e. first argument) or the pipeline will never complete.
-```cjs
+```cjs|mjs
const { pipeline } = require('node:stream/promises');
const fs = require('node:fs');
@@ -221,9 +215,7 @@ async function run() {
}
run().catch(console.error);
-```
-
-```mjs
+--------------
import { pipeline } from 'node:stream/promises';
import fs from 'node:fs';
await pipeline(
@@ -251,7 +243,7 @@ The `pipeline` API provides [callback version][stream-pipeline]:
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills when the stream is no
longer readable or writable.
-```cjs
+```cjs|mjs
const { finished } = require('node:stream/promises');
const fs = require('node:fs');
@@ -264,9 +256,7 @@ async function run() {
run().catch(console.error);
rs.resume(); // Drain the stream.
-```
-
-```mjs
+--------------
import { finished } from 'node:stream/promises';
import { createReadStream } from 'node:fs';
@@ -618,7 +608,7 @@ This is a destructive and immediate way to destroy a stream. Previous calls to
Use `end()` instead of destroy if data should flush before close, or wait for
the `'drain'` event before destroying the stream.
-```cjs
+```cjs|cjs
const { Writable } = require('node:stream');
const myStream = new Writable();
@@ -626,9 +616,7 @@ const myStream = new Writable();
const fooErr = new Error('foo error');
myStream.destroy(fooErr);
myStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error
-```
-
-```cjs
+--------------
const { Writable } = require('node:stream');
const myStream = new Writable();
@@ -2070,7 +2058,7 @@ const anyBigFile = await Readable.from([
'file3',
]).some(async (fileName) => {
const stats = await stat(fileName);
- return stat.size > 1024 * 1024;
+ return stats.size > 1024 * 1024;
}, { concurrency: 2 });
console.log(anyBigFile); // `true` if any file in the list is bigger than 1MB
console.log('done'); // Stream has finished
@@ -2122,7 +2110,7 @@ const foundBigFile = await Readable.from([
'file3',
]).find(async (fileName) => {
const stats = await stat(fileName);
- return stat.size > 1024 * 1024;
+ return stats.size > 1024 * 1024;
}, { concurrency: 2 });
console.log(foundBigFile); // File name of large file, if any file in the list is bigger than 1MB
console.log('done'); // Stream has finished
@@ -2172,7 +2160,7 @@ const allBigFiles = await Readable.from([
'file3',
]).every(async (fileName) => {
const stats = await stat(fileName);
- return stat.size > 1024 * 1024;
+ return stats.size > 1024 * 1024;
}, { concurrency: 2 });
// `true` if all files in the list are bigger than 1MiB
console.log(allBigFiles);
@@ -2567,7 +2555,7 @@ const server = http.createServer((req, res) => {
#### `stream.compose(...streams)`
-
+
@@ -2575,7 +2563,8 @@ const server = http.createServer((req, res) => {
-* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]
+* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]|
+ ReadableStream\[]|WritableStream\[]|TransformStream\[]
* Returns: [`stream.Duplex`](/api/v19/stream#streamduplex)
Combines two or more streams into a `Duplex` stream that writes to the
@@ -2780,8 +2769,14 @@ Experimental
* `streamReadable` [`stream.Readable`](/api/v19/stream#streamreadable)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `strategy` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `size` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+ * `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The maximum internal queue size (of the created
+ `ReadableStream`) before backpressure is applied in reading from the given
+ `stream.Readable`. If no value is provided, it will be taken from the
+ given `stream.Readable`.
+ * `size` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A function that size of the given chunk of data.
+ If no value is provided, the size will be `1` for all the chunks.
+ * `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+ * Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`ReadableStream`](/api/v19/webstreams#readablestream)
#### `stream.Writable.fromWeb(writableStream[, options])`
@@ -2877,7 +2872,7 @@ Experimental
* `signal` [`AbortSignal`](/api/v19/globals#abortsignal)
* Returns: [`stream.Duplex`](/api/v19/stream#streamduplex)
-```mjs
+```mjs|cjs
import { Duplex } from 'node:stream';
import {
ReadableStream,
@@ -2907,9 +2902,7 @@ duplex.write('hello');
for await (const chunk of duplex) {
console.log('readable', chunk);
}
-```
-
-```cjs
+--------------
const { Duplex } = require('node:stream');
const {
ReadableStream,
@@ -2953,7 +2946,7 @@ Experimental
* `readable` [`ReadableStream`](/api/v19/webstreams#readablestream)
* `writable` [`WritableStream`](/api/v19/webstreams#writablestream)
-```mjs
+```mjs|cjs
import { Duplex } from 'node:stream';
const duplex = Duplex({
@@ -2973,9 +2966,7 @@ writable.getWriter().write('hello');
const { value } = await readable.getReader().read();
console.log('readable', value);
-```
-
-```cjs
+--------------
const { Duplex } = require('node:stream');
const duplex = Duplex({
diff --git a/content/api/v19/string_decoder.en.md b/content/api/v19/string_decoder.en.md
index eb5ba089e6..93145e5b85 100644
--- a/content/api/v19/string_decoder.en.md
+++ b/content/api/v19/string_decoder.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:string_decoder` module provides an API for decoding `Buffer` objects
into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
diff --git a/content/api/v19/test.en.md b/content/api/v19/test.en.md
index 4e4eea79ad..218dcc687f 100644
--- a/content/api/v19/test.en.md
+++ b/content/api/v19/test.en.md
@@ -7,33 +7,31 @@ version: 'v19'
+
+
Experimental
-
+
The `node:test` module facilitates the creation of JavaScript tests.
To access it:
-```mjs
+```mjs|cjs
import test from 'node:test';
-```
-
-```cjs
+--------------
const test = require('node:test');
```
This module is only available under the `node:` scheme. The following will not
work:
-```mjs
+```mjs|cjs
import test from 'test';
-```
-
-```cjs
+--------------
const test = require('test');
```
@@ -159,8 +157,7 @@ test('skip() method with message', (t) => {
Running tests can also be done using `describe` to declare a suite
and `it` to declare a test.
A suite is used to organize and group related tests together.
-`it` is an alias for `test`, except there is no test context passed,
-since nesting is done using suites.
+`it` is a shorthand for [`test()`][].
```js
describe('A thing', () => {
@@ -182,11 +179,9 @@ describe('A thing', () => {
`describe` and `it` are imported from the `node:test` module.
-```mjs
+```mjs|cjs
import { describe, it } from 'node:test';
-```
-
-```cjs
+--------------
const { describe, it } = require('node:test');
```
@@ -436,7 +431,7 @@ object. The following example creates a spy on a function that adds two numbers
together. The spy is then used to assert that the function was called as
expected.
-```mjs
+```mjs|cjs
import assert from 'node:assert';
import { mock, test } from 'node:test';
@@ -457,9 +452,7 @@ test('spies on a function', () => {
// Reset the globally tracked mocks.
mock.reset();
});
-```
-
-```cjs
+--------------
'use strict';
const assert = require('node:assert');
const { mock, test } = require('node:test');
@@ -522,8 +515,7 @@ flags for the test runner to use a specific reporter.
The following built-reporters are supported:
* `tap`
- The `tap` reporter is the default reporter used by the test runner. It outputs
- the test results in the [TAP][] format.
+ The `tap` reporter outputs the test results in the [TAP][] format.
* `spec`
The `spec` reporter outputs the test results in a human-readable format.
@@ -533,16 +525,19 @@ The following built-reporters are supported:
where each passing test is represented by a `.`,
and each failing test is represented by a `X`.
+When `stdout` is a [TTY][], the `spec` reporter is used by default.
+Otherwise, the `tap` reporter is used by default.
+
#### Custom reporters
[`--test-reporter`][] can be used to specify a path to custom reporter.
-a custom reporter is a module that exports a value
+A custom reporter is a module that exports a value
accepted by [stream.compose][].
Reporters should transform events emitted by a TestsStream
Example of a custom reporter using [`stream.Transform`](/api/v19/stream#streamtransform):
-```mjs
+```mjs|cjs
import { Transform } from 'node:stream';
const customReporter = new Transform({
@@ -564,14 +559,17 @@ const customReporter = new Transform({
case 'test:diagnostic':
callback(null, event.data.message);
break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ callback(null, `total line count: ${totalLineCount}\n`);
+ break;
+ }
}
},
});
export default customReporter;
-```
-
-```cjs
+--------------
const { Transform } = require('node:stream');
const customReporter = new Transform({
@@ -593,6 +591,11 @@ const customReporter = new Transform({
case 'test:diagnostic':
callback(null, event.data.message);
break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ callback(null, `total line count: ${totalLineCount}\n`);
+ break;
+ }
}
},
});
@@ -602,7 +605,7 @@ module.exports = customReporter;
Example of a custom reporter using a generator function:
-```mjs
+```mjs|cjs
export default async function * customReporter(source) {
for await (const event of source) {
switch (event.type) {
@@ -621,12 +624,15 @@ export default async function * customReporter(source) {
case 'test:diagnostic':
yield `${event.data.message}\n`;
break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ yield `total line count: ${totalLineCount}\n`;
+ break;
+ }
}
}
}
-```
-
-```cjs
+--------------
module.exports = async function * customReporter(source) {
for await (const event of source) {
switch (event.type) {
@@ -645,6 +651,11 @@ module.exports = async function * customReporter(source) {
case 'test:diagnostic':
yield `${event.data.message}\n`;
break;
+ case 'test:coverage': {
+ const { totalLineCount } = event.data.summary.totals;
+ yield `total line count: ${totalLineCount}\n`;
+ break;
+ }
}
}
};
@@ -687,6 +698,9 @@ unless a destination is explicitly provided.
**Default:** `false`.
* `files`: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the list of files to run.
**Default** matching files from [test runner execution model][].
+ * `setup` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A function that accepts the `TestsStream` instance
+ and can be used to setup listeners before any tests are run.
+ **Default:** `undefined`.
* `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows aborting an in-progress test execution.
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number of milliseconds the test execution will
fail after.
@@ -737,7 +751,8 @@ run({ files: [path.resolve('./tests/test.js')] })
to this function is a [`TestContext`][] object. If the test uses callbacks,
the callback function is passed as the second argument. **Default:** A no-op
function.
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Resolved with `undefined` once the test completes.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Resolved with `undefined` once
+ the test completes, or immediately if the test runs within [`describe()`][].
The `test()` function is the value imported from the `test` module. Each
invocation of this function results in reporting the test to the TestsStream.
@@ -746,10 +761,12 @@ The `TestContext` object passed to the `fn` argument can be used to perform
actions related to the current test. Examples include skipping the test, adding
additional diagnostic information, or creating subtests.
-`test()` returns a `Promise` that resolves once the test completes. The return
-value can usually be discarded for top level tests. However, the return value
-from subtests should be used to prevent the parent test from finishing first
-and cancelling the subtest as shown in the following example.
+`test()` returns a `Promise` that resolves once the test completes.
+if `test()` is called within a `describe()` block, it resolve immediately.
+The return value can usually be discarded for top level tests.
+However, the return value from subtests should be used to prevent the parent
+test from finishing first and cancelling the subtest
+as shown in the following example.
```js
test('top level test', async (t) => {
@@ -796,19 +813,20 @@ Shorthand for skipping a suite, same as [`describe([name], { skip: true }[, fn])
Shorthand for marking a suite as `TODO`, same as
[`describe([name], { todo: true }[, fn])`][describe options].
+### `describe.only([name][, options][, fn])`
+
+
+
+Shorthand for marking a suite as `only`, same as
+[`describe([name], { only: true }[, fn])`][describe options].
+
### `it([name][, options][, fn])`
-* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the test, which is displayed when reporting test
- results. **Default:** The `name` property of `fn`, or `''` if `fn`
- does not have a name.
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the suite.
- supports the same options as `test([name][, options][, fn])`.
-* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) The function under test.
- If the test uses callbacks, the callback function is passed as an argument.
- **Default:** A no-op function.
-* Returns: `undefined`.
+
-The `it()` function is the value imported from the `node:test` module.
+Shorthand for [`test()`][].
+
+The `it()` function is imported from the `node:test` module.
### `it.skip([name][, options][, fn])`
@@ -820,6 +838,13 @@ same as [`it([name], { skip: true }[, fn])`][it options].
Shorthand for marking a test as `TODO`,
same as [`it([name], { todo: true }[, fn])`][it options].
+### `it.only([name][, options][, fn])`
+
+
+
+Shorthand for marking a test as `only`,
+same as [`it([name], { only: true }[, fn])`][it options].
+
### `before([fn][, options])`
@@ -1562,6 +1587,7 @@ The name of the suite.
aborted.
[TAP]: https://testanything.org/
+[TTY]: /api/v19/tty
[`--experimental-test-coverage`]: /api/v19/cli#--experimental-test-coverage
[`--import`]: /api/v19/cli#--importmodule
[`--test-name-pattern`]: /api/v19/cli#--test-name-pattern
@@ -1578,6 +1604,7 @@ The name of the suite.
[`context.diagnostic`]: #contextdiagnosticmessage
[`context.skip`]: #contextskipmessage
[`context.todo`]: #contexttodomessage
+[`describe()`]: #describename-options-fn
[`run()`]: #runoptions
[`test()`]: #testname-options-fn
[describe options]: #describename-options-fn
diff --git a/content/api/v19/timers.en.md b/content/api/v19/timers.en.md
index 75c6ed883f..470cd13035 100644
--- a/content/api/v19/timers.en.md
+++ b/content/api/v19/timers.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `timer` module exposes a global API for scheduling functions to
be called at some future period of time. Because the timer functions are
@@ -306,15 +306,13 @@ The `timers/promises` API provides an alternative set of timer functions
that return `Promise` objects. The API is accessible via
`require('node:timers/promises')`.
-```mjs
+```mjs|cjs
import {
setTimeout,
setImmediate,
setInterval,
} from 'timers/promises';
-```
-
-```cjs
+--------------
const {
setTimeout,
setImmediate,
@@ -336,7 +334,7 @@ const {
* `signal` [`AbortSignal`](/api/v19/globals#abortsignal) An optional `AbortSignal` that can be used to
cancel the scheduled `Timeout`.
-```mjs
+```mjs|cjs
import {
setTimeout,
} from 'timers/promises';
@@ -344,9 +342,7 @@ import {
const res = await setTimeout(100, 'result');
console.log(res); // Prints 'result'
-```
-
-```cjs
+--------------
const {
setTimeout,
} = require('node:timers/promises');
@@ -368,7 +364,7 @@ setTimeout(100, 'result').then((res) => {
* `signal` [`AbortSignal`](/api/v19/globals#abortsignal) An optional `AbortSignal` that can be used to
cancel the scheduled `Immediate`.
-```mjs
+```mjs|cjs
import {
setImmediate,
} from 'timers/promises';
@@ -376,9 +372,7 @@ import {
const res = await setImmediate('result');
console.log(res); // Prints 'result'
-```
-
-```cjs
+--------------
const {
setImmediate,
} = require('node:timers/promises');
@@ -407,7 +401,7 @@ or implicitly to keep the event loop alive.
* `signal` [`AbortSignal`](/api/v19/globals#abortsignal) An optional `AbortSignal` that can be used to
cancel the scheduled `Timeout` between operations.
-```mjs
+```mjs|cjs
import {
setInterval,
} from 'timers/promises';
@@ -420,9 +414,7 @@ for await (const startTime of setInterval(interval, Date.now())) {
break;
}
console.log(Date.now());
-```
-
-```cjs
+--------------
const {
setInterval,
} = require('node:timers/promises');
diff --git a/content/api/v19/tls.en.md b/content/api/v19/tls.en.md
index d6c7289117..f0319f6c84 100644
--- a/content/api/v19/tls.en.md
+++ b/content/api/v19/tls.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:tls` module provides an implementation of the Transport Layer Security
(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
@@ -130,23 +130,17 @@ all sessions). Methods implementing this technique are called "ephemeral".
Currently two methods are commonly used to achieve perfect forward secrecy (note
the character "E" appended to the traditional abbreviations):
-* [DHE][]: An ephemeral version of the Diffie-Hellman key-agreement protocol.
* [ECDHE][]: An ephemeral version of the Elliptic Curve Diffie-Hellman
key-agreement protocol.
+* [DHE][]: An ephemeral version of the Diffie-Hellman key-agreement protocol.
-To use perfect forward secrecy using `DHE` with the `node:tls` module, it is
-required to generate Diffie-Hellman parameters and specify them with the
-`dhparam` option to [`tls.createSecureContext()`][]. The following illustrates
-the use of the OpenSSL command-line interface to generate such parameters:
-
-```bash
-openssl dhparam -outform PEM -out dhparam.pem 2048
-```
+Perfect forward secrecy using ECDHE is enabled by default. The `ecdhCurve`
+option can be used when creating a TLS server to customize the list of supported
+ECDH curves to use. See [`tls.createServer()`][] for more info.
-If using perfect forward secrecy using `ECDHE`, Diffie-Hellman parameters are
-not required and a default ECDHE curve will be used. The `ecdhCurve` property
-can be used when creating a TLS Server to specify the list of names of supported
-curves to use, see [`tls.createServer()`][] for more info.
+DHE is disabled by default but can be enabled alongside ECDHE by setting the
+`dhparam` option to `'auto'`. Custom DHE parameters are also supported but
+discouraged in favor of automatically selected, well-known parameters.
Perfect forward secrecy was optional up to TLSv1.2. As of TLSv1.3, (EC)DHE is
always used (with the exception of PSK-only connections).
@@ -363,6 +357,30 @@ export NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'
node server.js
```
+To verify, use the following command to show the set cipher list, note the
+difference between `defaultCoreCipherList` and `defaultCipherList`:
+
+```bash
+node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' -p crypto.constants.defaultCipherList | tr ':' '\n'
+ECDHE-RSA-AES128-GCM-SHA256
+!RC4
+```
+
+i.e. the `defaultCoreCipherList` list is set at compilation time and the
+`defaultCipherList` is set at runtime.
+
+To modify the default cipher suites from within the runtime, modify the
+`tls.DEFAULT_CIPHERS` variable, this must be performed before listening on any
+sockets, it will not affect sockets already opened. For example:
+
+```js
+// Remove Obsolete CBC Ciphers and RSA Key Exchange based Ciphers as they don't provide Forward Secrecy
+tls.DEFAULT_CIPHERS +=
+ ':!ECDHE-RSA-AES128-SHA:!ECDHE-RSA-AES128-SHA256:!ECDHE-RSA-AES256-SHA:!ECDHE-RSA-AES256-SHA384' +
+ ':!ECDHE-ECDSA-AES128-SHA:!ECDHE-ECDSA-AES128-SHA256:!ECDHE-ECDSA-AES256-SHA:!ECDHE-ECDSA-AES256-SHA384' +
+ ':!kRSA';
+```
+
The default can also be replaced on a per client or server basis using the
`ciphers` option from [`tls.createSecureContext()`][], which is also available
in [`tls.createServer()`][], [`tls.connect()`][], and when creating new
@@ -1555,7 +1573,7 @@ argument.
### `tls.createSecureContext([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `ca` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) Optionally override the trusted CA
@@ -1599,12 +1617,10 @@ argument.
client certificate.
* `crl` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) PEM formatted CRLs (Certificate
Revocation Lists).
- * `dhparam` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) Diffie-Hellman parameters, required for
- [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters.
- The key length must be greater than or equal to 1024 bits or else an error
- will be thrown. Although 1024 bits is permissible, use 2048 bits or larger
- for stronger security. If omitted or invalid, the parameters are silently
- discarded and DHE ciphers will not be available.
+ * `dhparam` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) `'auto'` or custom Diffie-Hellman parameters,
+ required for non-ECDHE [perfect forward secrecy][]. If omitted or invalid,
+ the parameters are silently discarded and DHE ciphers will not be available.
+ [ECDHE][]-based [perfect forward secrecy][] will still be available.
* `ecdhCurve` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string describing a named curve or a colon separated
list of curve NIDs or names, for example `P-521:P-384:P-256`, to use for
ECDH key agreement. Set to `auto` to select the
@@ -1691,6 +1707,13 @@ A key is _required_ for ciphers that use certificates. Either `key` or
If the `ca` option is not given, then Node.js will default to using
[Mozilla's publicly trusted list of CAs][].
+Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`
+option. When set to `'auto'`, well-known DHE parameters of sufficient strength
+will be selected automatically. Otherwise, if necessary, `openssl dhparam` can
+be used to create custom parameters. The key length must be greater than or
+equal to 1024 bits or else an error will be thrown. Although 1024 bits is
+permissible, use 2048 bits or larger for stronger security.
+
### `tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])`
@@ -1927,6 +1950,16 @@ information.
`'TLSv1.3'`. If multiple of the options are provided, the lowest minimum is
used.
+### `tls.DEFAULT_CIPHERS`
+
+
+
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The default value of the `ciphers` option of
+ [`tls.createSecureContext()`][]. It can be assigned any of the supported
+ OpenSSL ciphers. Defaults to the content of
+ `crypto.constants.defaultCoreCipherList`, unless changed using CLI options
+ using `--tls-default-ciphers`.
+
[CVE-2021-44531]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531
[Chrome's 'modern cryptography' setting]: https://www.chromium.org/Home/chromium-security/education/tls#TOC-Cipher-Suites
[DHE]: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
diff --git a/content/api/v19/tracing.en.md b/content/api/v19/tracing.en.md
index 6078e0c947..4a9ab6d550 100644
--- a/content/api/v19/tracing.en.md
+++ b/content/api/v19/tracing.en.md
@@ -13,7 +13,7 @@ Experimental
-
+
The `node:trace_events` module provides a mechanism to centralize tracing
information generated by V8, Node.js core, and userspace code.
diff --git a/content/api/v19/tty.en.md b/content/api/v19/tty.en.md
index ab81559b77..347034cd12 100644
--- a/content/api/v19/tty.en.md
+++ b/content/api/v19/tty.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`
classes. In most cases, it will not be necessary or possible to use this module
diff --git a/content/api/v19/url.en.md b/content/api/v19/url.en.md
index d623e1fe6f..a64c82d3f3 100644
--- a/content/api/v19/url.en.md
+++ b/content/api/v19/url.en.md
@@ -13,16 +13,14 @@ Stable
-
+
The `node:url` module provides utilities for URL resolution and parsing. It can
be accessed using:
-```mjs
+```mjs|cjs
import url from 'node:url';
-```
-
-```cjs
+--------------
const url = require('node:url');
```
@@ -74,13 +72,11 @@ const myURL =
Parsing the URL string using the legacy API:
-```mjs
+```mjs|cjs
import url from 'node:url';
const myURL =
url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
-```
-
-```cjs
+--------------
const url = require('node:url');
const myURL =
url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
@@ -91,14 +87,12 @@ const myURL =
It is possible to construct a WHATWG URL from component parts using either the
property setters or a template literal string:
-```js
+```js|js
const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';
-```
-
-```js
+--------------
const pathname = '/a/b/c';
const search = '?d=e';
const hash = '#fgh';
@@ -147,12 +141,10 @@ const myURL = new URL('/foo', 'https://example.org/');
The URL constructor is accessible as a property on the global object.
It can also be imported from the built-in url module:
-```mjs
+```mjs|cjs
import { URL } from 'node:url';
console.log(URL === globalThis.URL); // Prints 'true'.
-```
-
-```cjs
+--------------
console.log(URL === require('node:url').URL); // Prints 'true'.
```
@@ -299,13 +291,11 @@ will be thrown.
Gets the read-only serialization of the URL's origin.
-```js
+```js|js
const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);
// Prints https://example.org
-```
-
-```js
+--------------
const idnURL = new URL('https://測試');
console.log(idnURL.origin);
// Prints https://xn--g6w251d
@@ -539,14 +529,14 @@ instance, the `URL` object will not percent encode the ASCII tilde (`~`)
character, while `URLSearchParams` will always encode it:
```js
-const myUrl = new URL('https://example.org/abc?foo=~bar');
+const myURL = new URL('https://example.org/abc?foo=~bar');
-console.log(myUrl.search); // prints ?foo=~bar
+console.log(myURL.search); // prints ?foo=~bar
// Modify the URL via searchParams...
-myUrl.searchParams.sort();
+myURL.searchParams.sort();
-console.log(myUrl.search); // prints ?foo=%7Ebar
+console.log(myURL.search); // prints ?foo=%7Ebar
```
##### `url.username`
@@ -906,6 +896,12 @@ console.log(params.toString());
// Prints foo=def&abc=def&xyz=opq
```
+##### `urlSearchParams.size`
+
+
+
+The total number of parameter entries.
+
##### `urlSearchParams.sort()`
@@ -971,7 +967,7 @@ It performs the inverse operation to [`url.domainToUnicode()`][].
This feature is only available if the `node` executable was compiled with
[ICU][] enabled. If not, the domain names are passed through unchanged.
-```mjs
+```mjs|cjs
import url from 'node:url';
console.log(url.domainToASCII('español.com'));
@@ -980,9 +976,7 @@ console.log(url.domainToASCII('中文.com'));
// Prints xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
// Prints an empty string
-```
-
-```cjs
+--------------
const url = require('node:url');
console.log(url.domainToASCII('español.com'));
@@ -1008,7 +1002,7 @@ It performs the inverse operation to [`url.domainToASCII()`][].
This feature is only available if the `node` executable was compiled with
[ICU][] enabled. If not, the domain names are passed through unchanged.
-```mjs
+```mjs|cjs
import url from 'node:url';
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
@@ -1017,9 +1011,7 @@ console.log(url.domainToUnicode('xn--fiq228c.com'));
// Prints 中文.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
// Prints an empty string
-```
-
-```cjs
+--------------
const url = require('node:url');
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
@@ -1040,7 +1032,7 @@ console.log(url.domainToUnicode('xn--iñvalid.com'));
This function ensures the correct decodings of percent-encoded characters as
well as ensuring a cross-platform valid absolute path string.
-```mjs
+```mjs|cjs
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
@@ -1056,9 +1048,7 @@ fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX)
new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
-```
-
-```cjs
+--------------
const { fileURLToPath } = require('node:url');
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows)
@@ -1098,7 +1088,7 @@ string serializations of the URL. These are not, however, customizable in
any way. The `url.format(URL[, options])` method allows for basic customization
of the output.
-```mjs
+```mjs|cjs
import url from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');
@@ -1110,9 +1100,7 @@ console.log(myURL.toString());
console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://測試/?abc'
-```
-
-```cjs
+--------------
const url = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');
@@ -1136,7 +1124,7 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
This function ensures that `path` is resolved absolutely, and that the URL
control characters are correctly encoded when converting into a File URL.
-```mjs
+```mjs|cjs
import { pathToFileURL } from 'node:url';
new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1
@@ -1144,9 +1132,7 @@ pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)
new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX)
-```
-
-```cjs
+--------------
const { pathToFileURL } = require('node:url');
new URL(__filename); // Incorrect: throws (POSIX)
new URL(__filename); // Incorrect: C:\... (Windows)
@@ -1184,7 +1170,7 @@ pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSI
This utility function converts a URL object into an ordinary options object as
expected by the [`http.request()`][] and [`https.request()`][] APIs.
-```mjs
+```mjs|cjs
import { urlToHttpOptions } from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');
@@ -1201,13 +1187,11 @@ console.log(urlToHttpOptions(myURL));
auth: 'a:b'
}
*/
-```
-
-```cjs
+--------------
const { urlToHttpOptions } = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');
-console.log(urlToHttpOptions(myUrl));
+console.log(urlToHttpOptions(myURL));
/*
{
protocol: 'https:',
diff --git a/content/api/v19/util.en.md b/content/api/v19/util.en.md
index 369c97d828..c24041679a 100644
--- a/content/api/v19/util.en.md
+++ b/content/api/v19/util.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:util` module supports the needs of Node.js internal APIs. Many of the
utilities are useful for application and module developers as well. To access
@@ -897,13 +897,11 @@ properties for each of these components.
Creates a new `MIMEType` object by parsing the `input`.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/plain');
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/plain');
@@ -913,14 +911,12 @@ A `TypeError` will be thrown if the `input` is not a valid MIME. Note
that an effort will be made to coerce the given values into strings. For
instance:
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIME = new MIMEType({ toString: () => 'text/plain' });
console.log(String(myMIME));
// Prints: text/plain
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIME = new MIMEType({ toString: () => 'text/plain' });
console.log(String(myMIME));
@@ -933,7 +929,7 @@ console.log(String(myMIME));
Gets and sets the type portion of the MIME.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/javascript');
@@ -944,9 +940,7 @@ console.log(myMIME.type);
// Prints: application
console.log(String(myMIME));
// Prints: application/javascript
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/javascript');
@@ -965,7 +959,7 @@ console.log(String(myMIME));
Gets and sets the subtype portion of the MIME.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/ecmascript');
@@ -976,9 +970,7 @@ console.log(myMIME.subtype);
// Prints: javascript
console.log(String(myMIME));
// Prints: text/javascript
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/ecmascript');
@@ -998,7 +990,7 @@ console.log(String(myMIME));
Gets the essence of the MIME. This property is read only.
Use `mime.type` or `mime.subtype` to alter the MIME.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIME = new MIMEType('text/javascript;key=value');
@@ -1009,9 +1001,7 @@ console.log(myMIME.essence);
// Prints: application/javascript
console.log(String(myMIME));
// Prints: application/javascript;key=value
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIME = new MIMEType('text/javascript;key=value');
@@ -1050,7 +1040,7 @@ Alias for [`mime.toString()`][].
This method is automatically called when an `MIMEType` object is serialized
with [`JSON.stringify()`][].
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const myMIMES = [
@@ -1059,9 +1049,7 @@ const myMIMES = [
];
console.log(JSON.stringify(myMIMES));
// Prints: ["image/png", "image/gif"]
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIMES = [
@@ -1083,13 +1071,11 @@ The `MIMEParams` API provides read and write access to the parameters of a
Creates a new `MIMEParams` object by with empty parameters
-```mjs
+```mjs|cjs
import { MIMEParams } from 'node:util';
const myParams = new MIMEParams();
-```
-
-```cjs
+--------------
const { MIMEParams } = require('node:util');
const myParams = new MIMEParams();
@@ -1131,7 +1117,7 @@ Returns `true` if there is at least one name-value pair whose name is `name`.
Returns an iterator over the names of each name-value pair.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=0;bar=1');
@@ -1141,9 +1127,7 @@ for (const name of params.keys()) {
// Prints:
// foo
// bar
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const { params } = new MIMEType('text/plain;foo=0;bar=1');
@@ -1164,7 +1148,7 @@ Sets the value in the `MIMEParams` object associated with `name` to
`value`. If there are any pre-existing name-value pairs whose names are `name`,
set the first such pair's value to `value`.
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=0;bar=1');
@@ -1172,9 +1156,7 @@ params.set('foo', 'def');
params.set('baz', 'xyz');
console.log(params.toString());
// Prints: foo=def&bar=1&baz=xyz
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const { params } = new MIMEType('text/plain;foo=0;bar=1');
@@ -1196,7 +1178,7 @@ Returns an iterator over the values of each name-value pair.
Alias for [`mimeParams.entries()`][].
-```mjs
+```mjs|cjs
import { MIMEType } from 'node:util';
const { params } = new MIMEType('text/plain;foo=bar;xyz=baz');
@@ -1206,9 +1188,7 @@ for (const [name, value] of params) {
// Prints:
// foo bar
// xyz baz
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const { params } = new MIMEType('text/plain;foo=bar;xyz=baz');
@@ -1268,7 +1248,7 @@ Provides a higher level API for command-line argument parsing than interacting
with `process.argv` directly. Takes a specification for the expected arguments
and returns a structured object with the parsed options and positionals.
-```mjs
+```mjs|cjs
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
@@ -1286,9 +1266,7 @@ const {
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
-```
-
-```cjs
+--------------
const { parseArgs } = require('node:util');
const args = ['-f', '--bar', 'b'];
const options = {
@@ -1341,7 +1319,7 @@ For example to use the returned tokens to add support for a negated option
like `--no-color`, the tokens can be reprocessed to change the value stored
for the negated option.
-```mjs
+```mjs|cjs
import { parseArgs } from 'node:util';
const options = {
@@ -1371,9 +1349,7 @@ const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
-```
-
-```cjs
+--------------
const { parseArgs } = require('node:util');
const options = {
@@ -1813,7 +1789,7 @@ returns a promise that is fulfilled when the `signal` is
aborted. If the passed `resource` is garbage collected before the `signal` is
aborted, the returned promise shall remain pending indefinitely.
-```cjs
+```cjs|mjs
const { aborted } = require('node:util');
const dependent = obtainSomethingAbortable();
@@ -1825,9 +1801,7 @@ aborted(dependent.signal, dependent).then(() => {
dependent.on('event', () => {
dependent.abort();
});
-```
-
-```mjs
+--------------
import { aborted } from 'node:util';
const dependent = obtainSomethingAbortable();
@@ -2061,7 +2035,7 @@ properties. Such objects are created either by Node.js internals or native
addons. In JavaScript, they are [frozen][`Object.freeze()`] objects with a
`null` prototype.
-```c
+```c|js
#include
#include
napi_value result;
@@ -2077,9 +2051,7 @@ static napi_value MyNapi(napi_env env, napi_callback_info info) {
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...
-```
-
-```js
+--------------
const native = require('napi_addon.node');
const data = native.myNapi();
util.types.isExternal(data); // returns true
diff --git a/content/api/v19/v8.en.md b/content/api/v19/v8.en.md
index f17460790a..1de3c2d053 100644
--- a/content/api/v19/v8.en.md
+++ b/content/api/v19/v8.en.md
@@ -7,7 +7,7 @@ version: 'v19'
-
+
The `node:v8` module exposes APIs that are specific to the version of [V8][]
built into the Node.js binary. It can be accessed using:
@@ -649,13 +649,11 @@ stopHookSet();
**The `init` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onInit((promise, parent) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onInit((promise, parent) => {});
@@ -672,13 +670,11 @@ const stop = promiseHooks.onInit((promise, parent) => {});
**The `settled` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onSettled((promise) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onSettled((promise) => {});
@@ -695,13 +691,11 @@ const stop = promiseHooks.onSettled((promise) => {});
**The `before` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onBefore((promise) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onBefore((promise) => {});
@@ -718,13 +712,11 @@ const stop = promiseHooks.onBefore((promise) => {});
**The `after` hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.**
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stop = promiseHooks.onAfter((promise) => {});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stop = promiseHooks.onAfter((promise) => {});
@@ -754,15 +746,13 @@ be tracked, then only the `init` callback needs to be passed. The
specifics of all functions that can be passed to `callbacks` is in the
[Hook Callbacks][] section.
-```mjs
+```mjs|cjs
import { promiseHooks } from 'node:v8';
const stopAll = promiseHooks.createHook({
init(promise, parent) {},
});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stopAll = promiseHooks.createHook({
diff --git a/content/api/v19/vm.en.md b/content/api/v19/vm.en.md
index e559e2b96a..64049fdb00 100644
--- a/content/api/v19/vm.en.md
+++ b/content/api/v19/vm.en.md
@@ -15,7 +15,7 @@ Stable
-
+
The `node:vm` module enables compiling and running code within V8 Virtual
Machine contexts.
@@ -315,7 +315,7 @@ console.log(globalVar);
When the script is compiled from a source that contains a source map magic
comment, this property will be set to the URL of the source map.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const script = new vm.Script(`
@@ -325,9 +325,7 @@ function myFunc() {}
console.log(script.sourceMapURL);
// Prints: sourcemap.json
-```
-
-```cjs
+--------------
const vm = require('node:vm');
const script = new vm.Script(`
@@ -370,7 +368,7 @@ This implementation lies at a lower level than the [ECMAScript Module
loader][]. There is also no way to interact with the Loader yet, though
support is planned.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const contextifiedObject = vm.createContext({
@@ -439,9 +437,7 @@ await bar.link(linker);
// Prints 42.
await bar.evaluate();
-```
-
-```cjs
+--------------
const vm = require('node:vm');
const contextifiedObject = vm.createContext({
@@ -725,7 +721,7 @@ Properties assigned to the `import.meta` object that are objects may
allow the module to access information outside the specified `context`. Use
`vm.runInContext()` to create objects in a specific context.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const contextifiedObject = vm.createContext({ secret: 42 });
@@ -751,9 +747,7 @@ await module.evaluate();
// meta.prop = {};
// above with
// meta.prop = vm.runInContext('{}', contextifiedObject);
-```
-
-```cjs
+--------------
const vm = require('node:vm');
const contextifiedObject = vm.createContext({ secret: 42 });
(async () => {
@@ -874,7 +868,7 @@ This method is used after the module is linked to set the values of exports. If
it is called before the module is linked, an [`ERR_VM_MODULE_STATUS`][] error
will be thrown.
-```mjs
+```mjs|cjs
import vm from 'node:vm';
const m = new vm.SyntheticModule(['x'], () => {
@@ -885,9 +879,7 @@ await m.link(() => {});
await m.evaluate();
assert.strictEqual(m.namespace.x, 1);
-```
-
-```cjs
+--------------
const vm = require('node:vm');
(async () => {
const m = new vm.SyntheticModule(['x'], () => {
diff --git a/content/api/v19/wasi.en.md b/content/api/v19/wasi.en.md
index c3ca284fe5..7b4ef79a7f 100644
--- a/content/api/v19/wasi.en.md
+++ b/content/api/v19/wasi.en.md
@@ -13,18 +13,19 @@ Experimental
-
+
The WASI API provides an implementation of the [WebAssembly System Interface][]
specification. WASI gives sandboxed WebAssembly applications access to the
underlying operating system via a collection of POSIX-like functions.
-```mjs
+```mjs|cjs
import { readFile } from 'node:fs/promises';
import { WASI } from 'wasi';
import { argv, env } from 'node:process';
const wasi = new WASI({
+ version: 'preview1',
args: argv,
env,
preopens: {
@@ -32,19 +33,13 @@ const wasi = new WASI({
},
});
-// Some WASI binaries require:
-// const importObject = { wasi_unstable: wasi.wasiImport };
-const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
-
const wasm = await WebAssembly.compile(
await readFile(new URL('./demo.wasm', import.meta.url)),
);
-const instance = await WebAssembly.instantiate(wasm, importObject);
+const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject());
wasi.start(instance);
-```
-
-```cjs
+--------------
'use strict';
const { readFile } = require('node:fs/promises');
const { WASI } = require('wasi');
@@ -52,6 +47,7 @@ const { argv, env } = require('node:process');
const { join } = require('node:path');
const wasi = new WASI({
+ version: 'preview1',
args: argv,
env,
preopens: {
@@ -59,15 +55,11 @@ const wasi = new WASI({
},
});
-// Some WASI binaries require:
-// const importObject = { wasi_unstable: wasi.wasiImport };
-const importObject = { wasi_snapshot_preview1: wasi.wasiImport };
-
(async () => {
const wasm = await WebAssembly.compile(
await readFile(join(__dirname, 'demo.wasm')),
);
- const instance = await WebAssembly.instantiate(wasm, importObject);
+ const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject());
wasi.start(instance);
})();
@@ -127,7 +119,7 @@ sandbox directory structure configured explicitly.
#### `new WASI([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `args` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array of strings that the WebAssembly application will
@@ -149,6 +141,28 @@ sandbox directory structure configured explicitly.
WebAssembly application. **Default:** `1`.
* `stderr` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file descriptor used as standard error in the
WebAssembly application. **Default:** `2`.
+ * `version` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The version of WASI requested. Currently the only
+ supported versions are `unstable` and `preview1`. **Default:** `preview1`.
+
+#### `wasi.getImportObject()`
+
+
+
+Return an import object that can be passed to `WebAssembly.instantiate()` if
+no other WASM imports are needed beyond those provided by WASI.
+
+If version `unstable` was passed into the constructor it will return:
+
+```json
+{ wasi_unstable: wasi.wasiImport }
+```
+
+If version `preview1` was passed into the constructor or no version was
+specified it will return:
+
+```json
+{ wasi_snapshot_preview1: wasi.wasiImport }
+```
#### `wasi.start(instance)`
diff --git a/content/api/v19/webstreams.en.md b/content/api/v19/webstreams.en.md
index 73e2aca734..e11c21e140 100644
--- a/content/api/v19/webstreams.en.md
+++ b/content/api/v19/webstreams.en.md
@@ -36,7 +36,7 @@ This example creates a simple `ReadableStream` that pushes the current
`performance.now()` timestamp once every second forever. An async iterable
is used to read the data from the stream.
-```mjs
+```mjs|cjs
import {
ReadableStream,
} from 'node:stream/web';
@@ -60,9 +60,7 @@ const stream = new ReadableStream({
for await (const value of stream)
console.log(value);
-```
-
-```cjs
+--------------
const {
ReadableStream,
} = require('node:stream/web');
@@ -153,7 +151,7 @@ stream's data.
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) `'byob'` or `undefined`
* Returns: [`ReadableStreamDefaultReader`](/api/v19/webstreams#readablestreamdefaultreader) | [`ReadableStreamBYOBReader`](/api/v19/webstreams#readablestreambyobreader)
-```mjs
+```mjs|cjs
import { ReadableStream } from 'node:stream/web';
const stream = new ReadableStream();
@@ -161,9 +159,7 @@ const stream = new ReadableStream();
const reader = stream.getReader();
console.log(await reader.read());
-```
-
-```cjs
+--------------
const { ReadableStream } = require('node:stream/web');
const stream = new ReadableStream();
@@ -206,7 +202,7 @@ pipeline is configured, `transform.readable` is returned.
Causes the `readableStream.locked` to be `true` while the pipe operation
is active.
-```mjs
+```mjs|cjs
import {
ReadableStream,
TransformStream,
@@ -228,9 +224,7 @@ const transformedStream = stream.pipeThrough(transform);
for await (const chunk of transformedStream)
console.log(chunk);
-```
-
-```cjs
+--------------
const {
ReadableStream,
TransformStream,
@@ -1180,7 +1174,7 @@ streams.
They are accessed using:
-```mjs
+```mjs|cjs
import {
arrayBuffer,
blob,
@@ -1188,9 +1182,7 @@ import {
json,
text,
} from 'node:stream/consumers';
-```
-
-```cjs
+--------------
const {
arrayBuffer,
blob,
@@ -1208,7 +1200,7 @@ const {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an `ArrayBuffer` containing the full
contents of the stream.
-```mjs
+```mjs|cjs
import { buffer as arrayBuffer } from 'node:stream/consumers';
import { Readable } from 'node:stream';
import { TextEncoder } from 'node:util';
@@ -1219,9 +1211,7 @@ const dataArray = encoder.encode('hello world from consumers!');
const readable = Readable.from(dataArray);
const data = await arrayBuffer(readable);
console.log(`from readable: ${data.byteLength}`);
-```
-
-```cjs
+--------------
const { arrayBuffer } = require('node:stream/consumers');
const { Readable } = require('node:stream');
const { TextEncoder } = require('node:util');
@@ -1242,7 +1232,7 @@ arrayBuffer(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`Blob`](/api/v19/buffer#blob) containing the full contents
of the stream.
-```mjs
+```mjs|cjs
import { blob } from 'node:stream/consumers';
const dataBlob = new Blob(['hello world from consumers!']);
@@ -1250,9 +1240,7 @@ const dataBlob = new Blob(['hello world from consumers!']);
const readable = dataBlob.stream();
const data = await blob(readable);
console.log(`from readable: ${data.size}`);
-```
-
-```cjs
+--------------
const { blob } = require('node:stream/consumers');
const dataBlob = new Blob(['hello world from consumers!']);
@@ -1271,7 +1259,7 @@ blob(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`Buffer`](/api/v19/buffer#buffer) containing the full
contents of the stream.
-```mjs
+```mjs|cjs
import { buffer } from 'node:stream/consumers';
import { Readable } from 'node:stream';
import { Buffer } from 'node:buffer';
@@ -1281,9 +1269,7 @@ const dataBuffer = Buffer.from('hello world from consumers!');
const readable = Readable.from(dataBuffer);
const data = await buffer(readable);
console.log(`from readable: ${data.length}`);
-```
-
-```cjs
+--------------
const { buffer } = require('node:stream/consumers');
const { Readable } = require('node:stream');
const { Buffer } = require('node:buffer');
@@ -1304,7 +1290,7 @@ buffer(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the contents of the stream parsed as a
UTF-8 encoded string that is then passed through `JSON.parse()`.
-```mjs
+```mjs|cjs
import { json } from 'node:stream/consumers';
import { Readable } from 'node:stream';
@@ -1320,9 +1306,7 @@ const items = Array.from(
const readable = Readable.from(JSON.stringify(items));
const data = await json(readable);
console.log(`from readable: ${data.length}`);
-```
-
-```cjs
+--------------
const { json } = require('node:stream/consumers');
const { Readable } = require('node:stream');
@@ -1349,16 +1333,14 @@ json(readable).then((data) => {
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the contents of the stream parsed as a
UTF-8 encoded string.
-```mjs
+```mjs|cjs
import { text } from 'node:stream/consumers';
import { Readable } from 'node:stream';
const readable = Readable.from('Hello world from consumers!');
const data = await text(readable);
console.log(`from readable: ${data.length}`);
-```
-
-```cjs
+--------------
const { text } = require('node:stream/consumers');
const { Readable } = require('node:stream');
diff --git a/content/api/v19/worker_threads.en.md b/content/api/v19/worker_threads.en.md
index 5865ae6310..54c1f6f5c7 100644
--- a/content/api/v19/worker_threads.en.md
+++ b/content/api/v19/worker_threads.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:worker_threads` module enables the use of threads that execute
JavaScript in parallel. To access it:
@@ -789,7 +789,7 @@ if (isMainThread) {
#### `new Worker(filename[, options])`
-
+
* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) The path to the Worker's main script or module. Must
be either an absolute path or a relative path (i.e. relative to the
@@ -854,6 +854,9 @@ if (isMainThread) {
used for generated code.
* `stackSizeMb` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The default maximum stack size for the thread.
Small values may lead to unusable Worker instances. **Default:** `4`.
+ * `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) An optional `name` to be appended to the worker title
+ for debuggin/identification purposes, making the final title as
+ `[worker $id] $name`. **Default:** `''`.
#### `'error'`
@@ -1086,7 +1089,7 @@ with `stdio`. This means that `stdio` output originating from a `Worker` can
get blocked by synchronous code on the receiving end that is blocking the
Node.js event loop.
-```mjs
+```mjs|cjs
import {
Worker,
isMainThread,
@@ -1101,9 +1104,7 @@ if (isMainThread) {
// This output will be blocked by the for loop in the main thread.
console.log('foo');
}
-```
-
-```cjs
+--------------
'use strict';
const {
diff --git a/content/api/v19/zlib.en.md b/content/api/v19/zlib.en.md
index 4e5b6ab241..87dd25460e 100644
--- a/content/api/v19/zlib.en.md
+++ b/content/api/v19/zlib.en.md
@@ -13,7 +13,7 @@ Stable
-
+
The `node:zlib` module provides compression functionality implemented using
Gzip, Deflate/Inflate, and Brotli.
@@ -147,7 +147,7 @@ Using `zlib` encoding can be expensive, and the results ought to be cached.
See [Memory usage tuning][] for more information on the speed/memory/compression
tradeoffs involved in `zlib` usage.
-```js
+```js|js
// Client request example
const zlib = require('node:zlib');
const http = require('node:http');
@@ -184,9 +184,7 @@ request.on('response', (response) => {
break;
}
});
-```
-
-```js
+--------------
// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
diff --git a/content/api/v20/addons.en.md b/content/api/v20/addons.en.md
new file mode 100644
index 0000000000..5f39e813b0
--- /dev/null
+++ b/content/api/v20/addons.en.md
@@ -0,0 +1,1388 @@
+---
+title: 'addons'
+displayTitle: 'C++ addons'
+category: 'api'
+version: 'v20'
+---
+
+
+
+
+
+_Addons_ are dynamically-linked shared objects written in C++. The
+[`require()`][require] function can load addons as ordinary Node.js modules.
+Addons provide an interface between JavaScript and C/C++ libraries.
+
+There are three options for implementing addons: Node-API, nan, or direct
+use of internal V8, libuv, and Node.js libraries. Unless there is a need for
+direct access to functionality which is not exposed by Node-API, use Node-API.
+Refer to [C/C++ addons with Node-API](n-api.md) for more information on
+Node-API.
+
+When not using Node-API, implementing addons is complicated,
+involving knowledge of several components and APIs:
+
+* [V8][]: the C++ library Node.js uses to provide the
+ JavaScript implementation. V8 provides the mechanisms for creating objects,
+ calling functions, etc. V8's API is documented mostly in the
+ `v8.h` header file (`deps/v8/include/v8.h` in the Node.js source
+ tree), which is also available [online][v8-docs].
+
+* [libuv][]: The C library that implements the Node.js event loop, its worker
+ threads and all of the asynchronous behaviors of the platform. It also
+ serves as a cross-platform abstraction library, giving easy, POSIX-like
+ access across all major operating systems to many common system tasks, such
+ as interacting with the file system, sockets, timers, and system events. libuv
+ also provides a threading abstraction similar to POSIX threads for
+ more sophisticated asynchronous addons that need to move beyond the
+ standard event loop. Addon authors should
+ avoid blocking the event loop with I/O or other time-intensive tasks by
+ offloading work via libuv to non-blocking system operations, worker threads,
+ or a custom use of libuv threads.
+
+* Internal Node.js libraries. Node.js itself exports C++ APIs that addons can
+ use, the most important of which is the `node::ObjectWrap` class.
+
+* Node.js includes other statically linked libraries including OpenSSL. These
+ other libraries are located in the `deps/` directory in the Node.js source
+ tree. Only the libuv, OpenSSL, V8, and zlib symbols are purposefully
+ re-exported by Node.js and may be used to various extents by addons. See
+ [Linking to libraries included with Node.js][] for additional information.
+
+All of the following examples are available for [download][] and may
+be used as the starting-point for an addon.
+
+### Hello world
+
+This "Hello world" example is a simple addon, written in C++, that is the
+equivalent of the following JavaScript code:
+
+```js
+module.exports.hello = () => 'world';
+```
+
+First, create the file `hello.cc`:
+
+```cpp
+// hello.cc
+#include
+
+namespace demo {
+
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void Method(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ args.GetReturnValue().Set(String::NewFromUtf8(
+ isolate, "world").ToLocalChecked());
+}
+
+void Initialize(Local exports) {
+ NODE_SET_METHOD(exports, "hello", Method);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
+
+} // namespace demo
+```
+
+All Node.js addons must export an initialization function following
+the pattern:
+
+```cpp
+void Initialize(Local exports);
+NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
+```
+
+There is no semi-colon after `NODE_MODULE` as it's not a function (see
+`node.h`).
+
+The `module_name` must match the filename of the final binary (excluding
+the `.node` suffix).
+
+In the `hello.cc` example, then, the initialization function is `Initialize`
+and the addon module name is `addon`.
+
+When building addons with `node-gyp`, using the macro `NODE_GYP_MODULE_NAME` as
+the first parameter of `NODE_MODULE()` will ensure that the name of the final
+binary will be passed to `NODE_MODULE()`.
+
+Addons defined with `NODE_MODULE()` can not be loaded in multiple contexts or
+multiple threads at the same time.
+
+#### Context-aware addons
+
+There are environments in which Node.js addons may need to be loaded multiple
+times in multiple contexts. For example, the [Electron][] runtime runs multiple
+instances of Node.js in a single process. Each instance will have its own
+`require()` cache, and thus each instance will need a native addon to behave
+correctly when loaded via `require()`. This means that the addon
+must support multiple initializations.
+
+A context-aware addon can be constructed by using the macro
+`NODE_MODULE_INITIALIZER`, which expands to the name of a function which Node.js
+will expect to find when it loads an addon. An addon can thus be initialized as
+in the following example:
+
+```cpp
+using namespace v8;
+
+extern "C" NODE_MODULE_EXPORT void
+NODE_MODULE_INITIALIZER(Local exports,
+ Local module,
+ Local context) {
+ /* Perform addon initialization steps here. */
+}
+```
+
+Another option is to use the macro `NODE_MODULE_INIT()`, which will also
+construct a context-aware addon. Unlike `NODE_MODULE()`, which is used to
+construct an addon around a given addon initializer function,
+`NODE_MODULE_INIT()` serves as the declaration of such an initializer to be
+followed by a function body.
+
+The following three variables may be used inside the function body following an
+invocation of `NODE_MODULE_INIT()`:
+
+* `Local exports`,
+* `Local module`, and
+* `Local context`
+
+The choice to build a context-aware addon carries with it the responsibility of
+carefully managing global static data. Since the addon may be loaded multiple
+times, potentially even from different threads, any global static data stored
+in the addon must be properly protected, and must not contain any persistent
+references to JavaScript objects. The reason for this is that JavaScript
+objects are only valid in one context, and will likely cause a crash when
+accessed from the wrong context or from a different thread than the one on which
+they were created.
+
+The context-aware addon can be structured to avoid global static data by
+performing the following steps:
+
+* Define a class which will hold per-addon-instance data and which has a static
+ member of the form
+ ```cpp
+ static void DeleteInstance(void* data) {
+ // Cast `data` to an instance of the class and delete it.
+ }
+ ```
+* Heap-allocate an instance of this class in the addon initializer. This can be
+ accomplished using the `new` keyword.
+* Call `node::AddEnvironmentCleanupHook()`, passing it the above-created
+ instance and a pointer to `DeleteInstance()`. This will ensure the instance is
+ deleted when the environment is torn down.
+* Store the instance of the class in a `v8::External`, and
+* Pass the `v8::External` to all methods exposed to JavaScript by passing it
+ to `v8::FunctionTemplate::New()` or `v8::Function::New()` which creates the
+ native-backed JavaScript functions. The third parameter of
+ `v8::FunctionTemplate::New()` or `v8::Function::New()` accepts the
+ `v8::External` and makes it available in the native callback using the
+ `v8::FunctionCallbackInfo::Data()` method.
+
+This will ensure that the per-addon-instance data reaches each binding that can
+be called from JavaScript. The per-addon-instance data must also be passed into
+any asynchronous callbacks the addon may create.
+
+The following example illustrates the implementation of a context-aware addon:
+
+```cpp
+#include
+
+using namespace v8;
+
+class AddonData {
+ public:
+ explicit AddonData(Isolate* isolate):
+ call_count(0) {
+ // Ensure this per-addon-instance data is deleted at environment cleanup.
+ node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);
+ }
+
+ // Per-addon data.
+ int call_count;
+
+ static void DeleteInstance(void* data) {
+ delete static_cast(data);
+ }
+};
+
+static void Method(const v8::FunctionCallbackInfo& info) {
+ // Retrieve the per-addon-instance data.
+ AddonData* data =
+ reinterpret_cast(info.Data().As()->Value());
+ data->call_count++;
+ info.GetReturnValue().Set((double)data->call_count);
+}
+
+// Initialize this addon to be context-aware.
+NODE_MODULE_INIT(/* exports, module, context */) {
+ Isolate* isolate = context->GetIsolate();
+
+ // Create a new instance of `AddonData` for this instance of the addon and
+ // tie its life cycle to that of the Node.js environment.
+ AddonData* data = new AddonData(isolate);
+
+ // Wrap the data in a `v8::External` so we can pass it to the method we
+ // expose.
+ Local external = External::New(isolate, data);
+
+ // Expose the method `Method` to JavaScript, and make sure it receives the
+ // per-addon-instance data we created above by passing `external` as the
+ // third parameter to the `FunctionTemplate` constructor.
+ exports->Set(context,
+ String::NewFromUtf8(isolate, "method").ToLocalChecked(),
+ FunctionTemplate::New(isolate, Method, external)
+ ->GetFunction(context).ToLocalChecked()).FromJust();
+}
+```
+
+##### Worker support
+
+
+
+In order to be loaded from multiple Node.js environments,
+such as a main thread and a Worker thread, an add-on needs to either:
+
+* Be an Node-API addon, or
+* Be declared as context-aware using `NODE_MODULE_INIT()` as described above
+
+In order to support [`Worker`][] threads, addons need to clean up any resources
+they may have allocated when such a thread exists. This can be achieved through
+the usage of the `AddEnvironmentCleanupHook()` function:
+
+```cpp
+void AddEnvironmentCleanupHook(v8::Isolate* isolate,
+ void (*fun)(void* arg),
+ void* arg);
+```
+
+This function adds a hook that will run before a given Node.js instance shuts
+down. If necessary, such hooks can be removed before they are run using
+`RemoveEnvironmentCleanupHook()`, which has the same signature. Callbacks are
+run in last-in first-out order.
+
+If necessary, there is an additional pair of `AddEnvironmentCleanupHook()`
+and `RemoveEnvironmentCleanupHook()` overloads, where the cleanup hook takes a
+callback function. This can be used for shutting down asynchronous resources,
+such as any libuv handles registered by the addon.
+
+The following `addon.cc` uses `AddEnvironmentCleanupHook`:
+
+```cpp
+// addon.cc
+#include
+#include
+#include
+
+using node::AddEnvironmentCleanupHook;
+using v8::HandleScope;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+
+// Note: In a real-world application, do not rely on static/global data.
+static char cookie[] = "yum yum";
+static int cleanup_cb1_called = 0;
+static int cleanup_cb2_called = 0;
+
+static void cleanup_cb1(void* arg) {
+ Isolate* isolate = static_cast(arg);
+ HandleScope scope(isolate);
+ Local obj = Object::New(isolate);
+ assert(!obj.IsEmpty()); // assert VM is still alive
+ assert(obj->IsObject());
+ cleanup_cb1_called++;
+}
+
+static void cleanup_cb2(void* arg) {
+ assert(arg == static_cast(cookie));
+ cleanup_cb2_called++;
+}
+
+static void sanity_check(void*) {
+ assert(cleanup_cb1_called == 1);
+ assert(cleanup_cb2_called == 1);
+}
+
+// Initialize this addon to be context-aware.
+NODE_MODULE_INIT(/* exports, module, context */) {
+ Isolate* isolate = context->GetIsolate();
+
+ AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);
+ AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);
+ AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);
+}
+```
+
+Test in JavaScript by running:
+
+```js
+// test.js
+require('./build/Release/addon');
+```
+
+#### Building
+
+Once the source code has been written, it must be compiled into the binary
+`addon.node` file. To do so, create a file called `binding.gyp` in the
+top-level of the project describing the build configuration of the module
+using a JSON-like format. This file is used by [node-gyp][], a tool written
+specifically to compile Node.js addons.
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [ "hello.cc" ]
+ }
+ ]
+}
+```
+
+A version of the `node-gyp` utility is bundled and distributed with
+Node.js as part of `npm`. This version is not made directly available for
+developers to use and is intended only to support the ability to use the
+`npm install` command to compile and install addons. Developers who wish to
+use `node-gyp` directly can install it using the command
+`npm install -g node-gyp`. See the `node-gyp` [installation instructions][] for
+more information, including platform-specific requirements.
+
+Once the `binding.gyp` file has been created, use `node-gyp configure` to
+generate the appropriate project build files for the current platform. This
+will generate either a `Makefile` (on Unix platforms) or a `vcxproj` file
+(on Windows) in the `build/` directory.
+
+Next, invoke the `node-gyp build` command to generate the compiled `addon.node`
+file. This will be put into the `build/Release/` directory.
+
+When using `npm install` to install a Node.js addon, npm uses its own bundled
+version of `node-gyp` to perform this same set of actions, generating a
+compiled version of the addon for the user's platform on demand.
+
+Once built, the binary addon can be used from within Node.js by pointing
+[`require()`][require] to the built `addon.node` module:
+
+```js
+// hello.js
+const addon = require('./build/Release/addon');
+
+console.log(addon.hello());
+// Prints: 'world'
+```
+
+Because the exact path to the compiled addon binary can vary depending on how
+it is compiled (i.e. sometimes it may be in `./build/Debug/`), addons can use
+the [bindings][] package to load the compiled module.
+
+While the `bindings` package implementation is more sophisticated in how it
+locates addon modules, it is essentially using a `try…catch` pattern similar to:
+
+```js
+try {
+ return require('./build/Release/addon.node');
+} catch (err) {
+ return require('./build/Debug/addon.node');
+}
+```
+
+#### Linking to libraries included with Node.js
+
+Node.js uses statically linked libraries such as V8, libuv, and OpenSSL. All
+addons are required to link to V8 and may link to any of the other dependencies
+as well. Typically, this is as simple as including the appropriate
+`#include <...>` statements (e.g. `#include `) and `node-gyp` will locate
+the appropriate headers automatically. However, there are a few caveats to be
+aware of:
+
+* When `node-gyp` runs, it will detect the specific release version of Node.js
+ and download either the full source tarball or just the headers. If the full
+ source is downloaded, addons will have complete access to the full set of
+ Node.js dependencies. However, if only the Node.js headers are downloaded,
+ then only the symbols exported by Node.js will be available.
+
+* `node-gyp` can be run using the `--nodedir` flag pointing at a local Node.js
+ source image. Using this option, the addon will have access to the full set of
+ dependencies.
+
+#### Loading addons using `require()`
+
+The filename extension of the compiled addon binary is `.node` (as opposed
+to `.dll` or `.so`). The [`require()`][require] function is written to look for
+files with the `.node` file extension and initialize those as dynamically-linked
+libraries.
+
+When calling [`require()`][require], the `.node` extension can usually be
+omitted and Node.js will still find and initialize the addon. One caveat,
+however, is that Node.js will first attempt to locate and load modules or
+JavaScript files that happen to share the same base name. For instance, if
+there is a file `addon.js` in the same directory as the binary `addon.node`,
+then [`require('addon')`][require] will give precedence to the `addon.js` file
+and load it instead.
+
+### Native abstractions for Node.js
+
+Each of the examples illustrated in this document directly use the
+Node.js and V8 APIs for implementing addons. The V8 API can, and has, changed
+dramatically from one V8 release to the next (and one major Node.js release to
+the next). With each change, addons may need to be updated and recompiled in
+order to continue functioning. The Node.js release schedule is designed to
+minimize the frequency and impact of such changes but there is little that
+Node.js can do to ensure stability of the V8 APIs.
+
+The [Native Abstractions for Node.js][] (or `nan`) provide a set of tools that
+addon developers are recommended to use to keep compatibility between past and
+future releases of V8 and Node.js. See the `nan` [examples][] for an
+illustration of how it can be used.
+
+### Node-API
+
+
+
+Stable
+
+
+
+Node-API is an API for building native addons. It is independent from
+the underlying JavaScript runtime (e.g. V8) and is maintained as part of
+Node.js itself. This API will be Application Binary Interface (ABI) stable
+across versions of Node.js. It is intended to insulate addons from
+changes in the underlying JavaScript engine and allow modules
+compiled for one version to run on later versions of Node.js without
+recompilation. Addons are built/packaged with the same approach/tools
+outlined in this document (node-gyp, etc.). The only difference is the
+set of APIs that are used by the native code. Instead of using the V8
+or [Native Abstractions for Node.js][] APIs, the functions available
+in the Node-API are used.
+
+Creating and maintaining an addon that benefits from the ABI stability
+provided by Node-API carries with it certain
+[implementation considerations][].
+
+To use Node-API in the above "Hello world" example, replace the content of
+`hello.cc` with the following. All other instructions remain the same.
+
+```cpp
+// hello.cc using Node-API
+#include
+
+namespace demo {
+
+napi_value Method(napi_env env, napi_callback_info args) {
+ napi_value greeting;
+ napi_status status;
+
+ status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
+ if (status != napi_ok) return nullptr;
+ return greeting;
+}
+
+napi_value init(napi_env env, napi_value exports) {
+ napi_status status;
+ napi_value fn;
+
+ status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
+ if (status != napi_ok) return nullptr;
+
+ status = napi_set_named_property(env, exports, "hello", fn);
+ if (status != napi_ok) return nullptr;
+ return exports;
+}
+
+NAPI_MODULE(NODE_GYP_MODULE_NAME, init)
+
+} // namespace demo
+```
+
+The functions available and how to use them are documented in
+[C/C++ addons with Node-API](n-api.md).
+
+### Addon examples
+
+Following are some example addons intended to help developers get started. The
+examples use the V8 APIs. Refer to the online [V8 reference][v8-docs]
+for help with the various V8 calls, and V8's [Embedder's Guide][] for an
+explanation of several concepts used such as handles, scopes, function
+templates, etc.
+
+Each of these examples using the following `binding.gyp` file:
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [ "addon.cc" ]
+ }
+ ]
+}
+```
+
+In cases where there is more than one `.cc` file, simply add the additional
+filename to the `sources` array:
+
+```json
+"sources": ["addon.cc", "myexample.cc"]
+```
+
+Once the `binding.gyp` file is ready, the example addons can be configured and
+built using `node-gyp`:
+
+```bash
+node-gyp configure build
+```
+
+#### Function arguments
+
+Addons will typically expose objects and functions that can be accessed from
+JavaScript running within Node.js. When functions are invoked from JavaScript,
+the input arguments and return value must be mapped to and from the C/C++
+code.
+
+The following example illustrates how to read function arguments passed from
+JavaScript and how to return a result:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Exception;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+// This is the implementation of the "add" method
+// Input arguments are passed using the
+// const FunctionCallbackInfo& args struct
+void Add(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ // Check the number of arguments passed.
+ if (args.Length() < 2) {
+ // Throw an Error that is passed back to JavaScript
+ isolate->ThrowException(Exception::TypeError(
+ String::NewFromUtf8(isolate,
+ "Wrong number of arguments").ToLocalChecked()));
+ return;
+ }
+
+ // Check the argument types
+ if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
+ isolate->ThrowException(Exception::TypeError(
+ String::NewFromUtf8(isolate,
+ "Wrong arguments").ToLocalChecked()));
+ return;
+ }
+
+ // Perform the operation
+ double value =
+ args[0].As()->Value() + args[1].As()->Value();
+ Local num = Number::New(isolate, value);
+
+ // Set the return value (using the passed in
+ // FunctionCallbackInfo&)
+ args.GetReturnValue().Set(num);
+}
+
+void Init(Local exports) {
+ NODE_SET_METHOD(exports, "add", Add);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+Once compiled, the example addon can be required and used from within Node.js:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+console.log('This should be eight:', addon.add(3, 5));
+```
+
+#### Callbacks
+
+It is common practice within addons to pass JavaScript functions to a C++
+function and execute them from there. The following example illustrates how
+to invoke such callbacks:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Null;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void RunCallback(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+ Local cb = Local::Cast(args[0]);
+ const unsigned argc = 1;
+ Local argv[argc] = {
+ String::NewFromUtf8(isolate,
+ "hello world").ToLocalChecked() };
+ cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();
+}
+
+void Init(Local exports, Local module) {
+ NODE_SET_METHOD(module, "exports", RunCallback);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+This example uses a two-argument form of `Init()` that receives the full
+`module` object as the second argument. This allows the addon to completely
+overwrite `exports` with a single function instead of adding the function as a
+property of `exports`.
+
+To test it, run the following JavaScript:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+addon((msg) => {
+ console.log(msg);
+// Prints: 'hello world'
+});
+```
+
+In this example, the callback function is invoked synchronously.
+
+#### Object factory
+
+Addons can create and return new objects from within a C++ function as
+illustrated in the following example. An object is created and returned with a
+property `msg` that echoes the string passed to `createObject()`:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Context;
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void CreateObject(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ Local obj = Object::New(isolate);
+ obj->Set(context,
+ String::NewFromUtf8(isolate,
+ "msg").ToLocalChecked(),
+ args[0]->ToString(context).ToLocalChecked())
+ .FromJust();
+
+ args.GetReturnValue().Set(obj);
+}
+
+void Init(Local exports, Local module) {
+ NODE_SET_METHOD(module, "exports", CreateObject);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+To test it in JavaScript:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const obj1 = addon('hello');
+const obj2 = addon('world');
+console.log(obj1.msg, obj2.msg);
+// Prints: 'hello world'
+```
+
+#### Function factory
+
+Another common scenario is creating JavaScript functions that wrap C++
+functions and returning those back to JavaScript:
+
+```cpp
+// addon.cc
+#include
+
+namespace demo {
+
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void MyFunction(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ args.GetReturnValue().Set(String::NewFromUtf8(
+ isolate, "hello world").ToLocalChecked());
+}
+
+void CreateFunction(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ Local context = isolate->GetCurrentContext();
+ Local tpl = FunctionTemplate::New(isolate, MyFunction);
+ Local fn = tpl->GetFunction(context).ToLocalChecked();
+
+ // omit this to make it anonymous
+ fn->SetName(String::NewFromUtf8(
+ isolate, "theFunction").ToLocalChecked());
+
+ args.GetReturnValue().Set(fn);
+}
+
+void Init(Local exports, Local module) {
+ NODE_SET_METHOD(module, "exports", CreateFunction);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
+
+} // namespace demo
+```
+
+To test:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const fn = addon();
+console.log(fn());
+// Prints: 'hello world'
+```
+
+#### Wrapping C++ objects
+
+It is also possible to wrap C++ objects/classes in a way that allows new
+instances to be created using the JavaScript `new` operator:
+
+```cpp
+// addon.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using v8::Local;
+using v8::Object;
+
+void InitAll(Local exports) {
+ MyObject::Init(exports);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
+
+} // namespace demo
+```
+
+Then, in `myobject.h`, the wrapper class inherits from `node::ObjectWrap`:
+
+```cpp
+// myobject.h
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include
+#include
+
+namespace demo {
+
+class MyObject : public node::ObjectWrap {
+ public:
+ static void Init(v8::Local exports);
+
+ private:
+ explicit MyObject(double value = 0);
+ ~MyObject();
+
+ static void New(const v8::FunctionCallbackInfo& args);
+ static void PlusOne(const v8::FunctionCallbackInfo& args);
+
+ double value_;
+};
+
+} // namespace demo
+
+#endif
+```
+
+In `myobject.cc`, implement the various methods that are to be exposed.
+Below, the method `plusOne()` is exposed by adding it to the constructor's
+prototype:
+
+```cpp
+// myobject.cc
+#include "myobject.h"
+
+namespace demo {
+
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::ObjectTemplate;
+using v8::String;
+using v8::Value;
+
+MyObject::MyObject(double value) : value_(value) {
+}
+
+MyObject::~MyObject() {
+}
+
+void MyObject::Init(Local exports) {
+ Isolate* isolate = exports->GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ Local addon_data_tpl = ObjectTemplate::New(isolate);
+ addon_data_tpl->SetInternalFieldCount(1); // 1 field for the MyObject::New()
+ Local addon_data =
+ addon_data_tpl->NewInstance(context).ToLocalChecked();
+
+ // Prepare constructor template
+ Local tpl = FunctionTemplate::New(isolate, New, addon_data);
+ tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
+ tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+ // Prototype
+ NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
+
+ Local constructor = tpl->GetFunction(context).ToLocalChecked();
+ addon_data->SetInternalField(0, constructor);
+ exports->Set(context, String::NewFromUtf8(
+ isolate, "MyObject").ToLocalChecked(),
+ constructor).FromJust();
+}
+
+void MyObject::New(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ if (args.IsConstructCall()) {
+ // Invoked as constructor: `new MyObject(...)`
+ double value = args[0]->IsUndefined() ?
+ 0 : args[0]->NumberValue(context).FromMaybe(0);
+ MyObject* obj = new MyObject(value);
+ obj->Wrap(args.This());
+ args.GetReturnValue().Set(args.This());
+ } else {
+ // Invoked as plain function `MyObject(...)`, turn into construct call.
+ const int argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons =
+ args.Data().As()->GetInternalField(0).As();
+ Local result =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+ args.GetReturnValue().Set(result);
+ }
+}
+
+void MyObject::PlusOne(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ MyObject* obj = ObjectWrap::Unwrap(args.Holder());
+ obj->value_ += 1;
+
+ args.GetReturnValue().Set(Number::New(isolate, obj->value_));
+}
+
+} // namespace demo
+```
+
+To build this example, the `myobject.cc` file must be added to the
+`binding.gyp`:
+
+```json
+{
+ "targets": [
+ {
+ "target_name": "addon",
+ "sources": [
+ "addon.cc",
+ "myobject.cc"
+ ]
+ }
+ ]
+}
+```
+
+Test it with:
+
+```js
+// test.js
+const addon = require('./build/Release/addon');
+
+const obj = new addon.MyObject(10);
+console.log(obj.plusOne());
+// Prints: 11
+console.log(obj.plusOne());
+// Prints: 12
+console.log(obj.plusOne());
+// Prints: 13
+```
+
+The destructor for a wrapper object will run when the object is
+garbage-collected. For destructor testing, there are command-line flags that
+can be used to make it possible to force garbage collection. These flags are
+provided by the underlying V8 JavaScript engine. They are subject to change
+or removal at any time. They are not documented by Node.js or V8, and they
+should never be used outside of testing.
+
+During shutdown of the process or worker threads destructors are not called
+by the JS engine. Therefore it's the responsibility of the user to track
+these objects and ensure proper destruction to avoid resource leaks.
+
+#### Factory of wrapped objects
+
+Alternatively, it is possible to use a factory pattern to avoid explicitly
+creating object instances using the JavaScript `new` operator:
+
+```js
+const obj = addon.createObject();
+// instead of:
+// const obj = new addon.Object();
+```
+
+First, the `createObject()` method is implemented in `addon.cc`:
+
+```cpp
+// addon.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using v8::FunctionCallbackInfo;
+using v8::Isolate;
+using v8::Local;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+void CreateObject(const FunctionCallbackInfo& args) {
+ MyObject::NewInstance(args);
+}
+
+void InitAll(Local exports, Local module) {
+ MyObject::Init(exports->GetIsolate());
+
+ NODE_SET_METHOD(module, "exports", CreateObject);
+}
+
+NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)
+
+} // namespace demo
+```
+
+In `myobject.h`, the static method `NewInstance()` is added to handle
+instantiating the object. This method takes the place of using `new` in
+JavaScript:
+
+```cpp
+// myobject.h
+#ifndef MYOBJECT_H
+#define MYOBJECT_H
+
+#include
+#include
+
+namespace demo {
+
+class MyObject : public node::ObjectWrap {
+ public:
+ static void Init(v8::Isolate* isolate);
+ static void NewInstance(const v8::FunctionCallbackInfo& args);
+
+ private:
+ explicit MyObject(double value = 0);
+ ~MyObject();
+
+ static void New(const v8::FunctionCallbackInfo& args);
+ static void PlusOne(const v8::FunctionCallbackInfo& args);
+ static v8::Global constructor;
+ double value_;
+};
+
+} // namespace demo
+
+#endif
+```
+
+The implementation in `myobject.cc` is similar to the previous example:
+
+```cpp
+// myobject.cc
+#include
+#include "myobject.h"
+
+namespace demo {
+
+using node::AddEnvironmentCleanupHook;
+using v8::Context;
+using v8::Function;
+using v8::FunctionCallbackInfo;
+using v8::FunctionTemplate;
+using v8::Global;
+using v8::Isolate;
+using v8::Local;
+using v8::Number;
+using v8::Object;
+using v8::String;
+using v8::Value;
+
+// Warning! This is not thread-safe, this addon cannot be used for worker
+// threads.
+Global MyObject::constructor;
+
+MyObject::MyObject(double value) : value_(value) {
+}
+
+MyObject::~MyObject() {
+}
+
+void MyObject::Init(Isolate* isolate) {
+ // Prepare constructor template
+ Local tpl = FunctionTemplate::New(isolate, New);
+ tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject").ToLocalChecked());
+ tpl->InstanceTemplate()->SetInternalFieldCount(1);
+
+ // Prototype
+ NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
+
+ Local context = isolate->GetCurrentContext();
+ constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());
+
+ AddEnvironmentCleanupHook(isolate, [](void*) {
+ constructor.Reset();
+ }, nullptr);
+}
+
+void MyObject::New(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+ Local context = isolate->GetCurrentContext();
+
+ if (args.IsConstructCall()) {
+ // Invoked as constructor: `new MyObject(...)`
+ double value = args[0]->IsUndefined() ?
+ 0 : args[0]->NumberValue(context).FromMaybe(0);
+ MyObject* obj = new MyObject(value);
+ obj->Wrap(args.This());
+ args.GetReturnValue().Set(args.This());
+ } else {
+ // Invoked as plain function `MyObject(...)`, turn into construct call.
+ const int argc = 1;
+ Local argv[argc] = { args[0] };
+ Local cons = Local::New(isolate, constructor);
+ Local instance =
+ cons->NewInstance(context, argc, argv).ToLocalChecked();
+ args.GetReturnValue().Set(instance);
+ }
+}
+
+void MyObject::NewInstance(const FunctionCallbackInfo& args) {
+ Isolate* isolate = args.GetIsolate();
+
+ const unsigned argc = 1;
+ Local