diff --git a/content/about/governance.pt.md b/content/about/governance.pt.md
new file mode 100644
index 0000000000..05835f3b0b
--- /dev/null
+++ b/content/about/governance.pt.md
@@ -0,0 +1,32 @@
+---
+title: governance
+displayTitle: Governação
+description: 'Governação do Projeto | Node.js'
+authors: XhmikosR, fhemberger, thefourtheye, ryanmurakami, refack, nazarepiedady
+category: about
+---
+
+## Processo de Procura de Consenso
+
+O projeto da Node.js segue um modelo de tomada de decisão conhecido como [Procura de Consenso][consensus seeking].
+
+## Colaboradores
+
+O repositório principal [nodejs/node][] da GitHub é mantido pelos Colaboradores que são adicionados pela Comissão Diretiva Técnica ([TSC, sigla em Inglês][tsc]) sobre uma base em curso.
+
+Os indivíduos fazendo contribuições significantes e valiosas são feitos Colaboradores e dado acesso de envio ao projeto. Estes indivíduos são identificados pela TSC e suas nomeações são discutidas com os Colaboradores existentes.
+
+Para ter a atual lista de Colaboradores, consulte o [README.md][] do projeto.
+
+Um guia para os Colaboradores é mantido no [collaborator-guide.md][].
+
+## Comissões de Alto Nível
+
+O projeto é governado pela [Comissão Diretiva Técnica (TSC, sigla em Inglês)][technical steering committee (tsc)] que é responsável pela diretriz de alto nível do projeto.
+
+[consensus seeking]: https://en.wikipedia.org/wiki/Consensus-seeking_decision-making
+[readme.md]: https://github.com/nodejs/node/blob/main/README.md#current-project-team-members
+[tsc]: https://github.com/nodejs/TSC
+[technical steering committee (tsc)]: https://github.com/nodejs/TSC/blob/main/TSC-Charter.md
+[collaborator-guide.md]: https://github.com/nodejs/node/blob/main/doc/contributing/collaborator-guide.md
+[nodejs/node]: https://github.com/nodejs/node
diff --git a/content/about/releases.pt.md b/content/about/releases.pt.md
new file mode 100644
index 0000000000..bff9f2da2a
--- /dev/null
+++ b/content/about/releases.pt.md
@@ -0,0 +1,11 @@
+---
+title: releases
+displayTitle: Lançamentos
+description: 'Lançamentos | Node.js'
+authors: ZYSzys, nstanard, mikeal, fhemberger, garybernhardt, piepmatz, boneskull, bjb568, nazarepiedady
+category: about
+---
+
+As versões principais da Node.js entram em estado de lançamento _Atual_ por seis meses, o que dá aos autores de biblioteca tempo para adicionar suporte para elas. Depois de seis meses, os lançamentos numerados com ímpares (9, 11, etc.) tornam-se insuportáveis, e os lançamentos numerados com pares (10, 12, etc) movem-se para o estado _LTS Ativa_ e estão prontas para uso geral. O estado de lançamento _LTS_ é "long-term support" ou "suporte a longo prazo" em Português, o qual garante tipicamente que os bugs críticos serão corrigidos por um total de 30 meses. As aplicações de produção deveriam apenas usar os lançamentos de _LTS Ativa_ ou _LTS de Manutenção_.
+
+
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/about/resources.en.md b/content/about/resources.pt.md
similarity index 50%
rename from content/about/resources.en.md
rename to content/about/resources.pt.md
index e33c0dbaf1..ba02d4aab6 100644
--- a/content/about/resources.en.md
+++ b/content/about/resources.pt.md
@@ -1,32 +1,32 @@
---
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
+displayTitle: Recursos
+description: 'Recursos | Node.js'
+authors: XhmikosR, mikeal, fhemberger, Fishrock123, yous, tomgco, tniessen, SMcCandlish, saadq, Trott, Gornstats, piperchester, naoufal, lpinca, j9t, bnoordhuis, harshadsabne, Chris911, MrJithil, nazarepiedady
category: about
---
-## Logo Downloads
+## Descarregamentos do Logótipo
-Please review the [trademark policy](https://trademark-policy.openjsf.org/) for information about permissible use of Node.js® logos and marks.
+Revise a [política comercial da marca](https://trademark-policy.openjsf.org/) para informações a respeito do uso permissível das marcas e logótipos da Node.js®.
-Guidelines for the visual display of the Node.js mark are described in the [Visual Guidelines](/static/documents/foundation-visual-guidelines.pdf).
+As diretrizes para a exibição visual da marca da Node.js estão descritas nas [Diretrizes Visuais](/static/documents/foundation-visual-guidelines.pdf).
@@ -5304,7 +5310,7 @@ are available.
###### File mode constants
-The following constants are meant for use with the [`fs.Stats`](/api/fs#fsstats) object's
+The following constants are meant for use with the [`fs.Stats`](/api/v16/fs#fsstats) object's
`mode` property for determining the access permissions for a file.
@@ -4890,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.
@@ -4977,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
@@ -4993,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.
@@ -5201,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
@@ -5237,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 89da9f87a0..5c0a921404 100644
--- a/content/api/v18/debugger.en.md
+++ b/content/api/v18/debugger.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v18'
---
-
+
-
+
-
+Stable
+
+
+
+
Node.js includes a command-line debugging utility. The Node.js debugger client
is not a full-featured debugger, but simple stepping and inspection are
@@ -23,6 +27,7 @@ $ node inspect myscript.js
< Debugger listening on ws://127.0.0.1:9229/621111f9-ffcb-4e82-b718-48a145fa5db8
< For help, see: https://nodejs.org/en/docs/inspector
<
+connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
<
ok
@@ -137,9 +142,9 @@ $ node inspect main.js
< Debugger listening on ws://127.0.0.1:9229/48a5b28a-550c-471b-b5e1-d13dd7165df9
< For help, see: https://nodejs.org/en/docs/inspector
<
+connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
<
- ok
Break on start in main.js:1
> 1 const mod = require('./mod.js');
2 mod.hello();
@@ -163,6 +168,8 @@ given expression evaluates to `true`:
$ node inspect main.js
< Debugger listening on ws://127.0.0.1:9229/ce24daa8-3816-44d4-b8ab-8273c8a66d35
< For help, see: https://nodejs.org/en/docs/inspector
+<
+connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
Break on start in main.js:7
5 }
@@ -199,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 ade61300cd..2b677f8310 100644
--- a/content/api/v18/deprecations.en.md
+++ b/content/api/v18/deprecations.en.md
@@ -5,9 +5,9 @@ category: 'api'
version: 'v18'
---
-
+
-
+
Node.js APIs might be deprecated for any of the following reasons:
@@ -48,7 +48,7 @@ However, the deprecation identifier will not be modified.
#### DEP0001: `http.OutgoingMessage.prototype.flush`
-
+
Type: End-of-Life
@@ -57,7 +57,7 @@ Type: End-of-Life
#### DEP0002: `require('_linklist')`
-
+
Type: End-of-Life
@@ -65,7 +65,7 @@ The `_linklist` module is deprecated. Please use a userland alternative.
#### DEP0003: `_writableState.buffer`
-
+
Type: End-of-Life
@@ -74,7 +74,7 @@ instead.
#### DEP0004: `CryptoStream.prototype.readyState`
-
+
Type: End-of-Life
@@ -82,7 +82,7 @@ The `CryptoStream.prototype.readyState` property was removed.
#### DEP0005: `Buffer()` constructor
-
+
Type: Runtime (supports [`--pending-deprecation`][])
@@ -112,7 +112,7 @@ warning results no matter where the `Buffer()` usage occurs.
#### DEP0006: `child_process` `options.customFds`
-
+
Type: End-of-Life
@@ -122,7 +122,7 @@ option should be used instead.
#### DEP0007: Replace `cluster` `worker.suicide` with `worker.exitedAfterDisconnect`
-
+
Type: End-of-Life
@@ -135,7 +135,7 @@ precisely describe the actual semantics and was unnecessarily emotion-laden.
#### DEP0008: `require('node:constants')`
-
+
Type: Documentation-only
@@ -146,7 +146,7 @@ to the `constants` property exposed by the relevant module. For instance,
#### DEP0009: `crypto.pbkdf2` without digest
-
+
Type: End-of-Life
@@ -164,7 +164,7 @@ Now, however, passing either `undefined` or `null` will throw a `TypeError`.
#### DEP0010: `crypto.createCredentials`
-
+
Type: End-of-Life
@@ -173,7 +173,7 @@ The `crypto.createCredentials()` API was removed. Please use
#### DEP0011: `crypto.Credentials`
-
+
Type: End-of-Life
@@ -182,7 +182,7 @@ instead.
#### DEP0012: `Domain.dispose`
-
+
Type: End-of-Life
@@ -191,7 +191,7 @@ explicitly via error event handlers set on the domain instead.
#### DEP0013: `fs` asynchronous function without callback
-
+
Type: End-of-Life
@@ -200,7 +200,7 @@ in Node.js 10.0.0 onwards. See [https://github.com/nodejs/node/pull/12562](https
#### DEP0014: `fs.read` legacy String interface
-
+
Type: End-of-Life
@@ -209,7 +209,7 @@ API as mentioned in the documentation instead.
#### DEP0015: `fs.readSync` legacy String interface
-
+
Type: End-of-Life
@@ -218,7 +218,7 @@ The [`fs.readSync()`][] legacy `String` interface is deprecated. Use the
#### DEP0016: `GLOBAL`/`root`
-
+
Type: End-of-Life
@@ -227,7 +227,7 @@ in Node.js 6.0.0 and have since been removed.
#### DEP0017: `Intl.v8BreakIterator`
-
+
Type: End-of-Life
@@ -236,7 +236,7 @@ See [`Intl.Segmenter`](https://github.com/tc39/proposal-intl-segmenter).
#### DEP0018: Unhandled promise rejections
-
+
Type: End-of-Life
@@ -247,7 +247,7 @@ code. To change the way Node.js treats unhandled rejections, use the
#### DEP0019: `require('.')` resolved outside directory
-
+
Type: End-of-Life
@@ -256,7 +256,7 @@ This behavior has been removed.
#### DEP0020: `Server.connections`
-
+
Type: End-of-Life
@@ -265,7 +265,7 @@ been removed. Please use the [`Server.getConnections()`][] method instead.
#### DEP0021: `Server.listenFD`
-
+
Type: End-of-Life
@@ -274,7 +274,7 @@ The `Server.listenFD()` method was deprecated and removed. Please use
#### DEP0022: `os.tmpDir()`
-
+
Type: End-of-Life
@@ -283,7 +283,7 @@ removed. Please use [`os.tmpdir()`][] instead.
#### DEP0023: `os.getNetworkInterfaces()`
-
+
Type: End-of-Life
@@ -292,7 +292,7 @@ The `os.getNetworkInterfaces()` method is deprecated. Please use the
#### DEP0024: `REPLServer.prototype.convertToContext()`
-
+
Type: End-of-Life
@@ -300,7 +300,7 @@ The `REPLServer.prototype.convertToContext()` API has been removed.
#### DEP0025: `require('node:sys')`
-
+
Type: Runtime
@@ -308,7 +308,7 @@ The `node:sys` module is deprecated. Please use the [`util`][] module instead.
#### DEP0026: `util.print()`
-
+
Type: End-of-Life
@@ -316,7 +316,7 @@ Type: End-of-Life
#### DEP0027: `util.puts()`
-
+
Type: End-of-Life
@@ -324,7 +324,7 @@ Type: End-of-Life
#### DEP0028: `util.debug()`
-
+
Type: End-of-Life
@@ -332,7 +332,7 @@ Type: End-of-Life
#### DEP0029: `util.error()`
-
+
Type: End-of-Life
@@ -340,7 +340,7 @@ Type: End-of-Life
#### DEP0030: `SlowBuffer`
-
+
Type: Documentation-only
@@ -349,7 +349,7 @@ The [`SlowBuffer`][] class is deprecated. Please use
#### DEP0031: `ecdh.setPublicKey()`
-
+
Type: Documentation-only
@@ -358,7 +358,7 @@ API is not useful.
#### DEP0032: `node:domain` module
-
+
Type: Documentation-only
@@ -366,7 +366,7 @@ The [`domain`][] module is deprecated and should not be used.
#### DEP0033: `EventEmitter.listenerCount()`
-
+
Type: Documentation-only
@@ -375,7 +375,7 @@ deprecated. Please use [`emitter.listenerCount(eventName)`][] instead.
#### DEP0034: `fs.exists(path, callback)`
-
+
Type: Documentation-only
@@ -384,7 +384,7 @@ The [`fs.exists(path, callback)`][] API is deprecated. Please use
#### DEP0035: `fs.lchmod(path, mode, callback)`
-
+
Type: Documentation-only
@@ -392,7 +392,7 @@ The [`fs.lchmod(path, mode, callback)`][] API is deprecated.
#### DEP0036: `fs.lchmodSync(path, mode)`
-
+
Type: Documentation-only
@@ -400,7 +400,7 @@ The [`fs.lchmodSync(path, mode)`][] API is deprecated.
#### DEP0037: `fs.lchown(path, uid, gid, callback)`
-
+
Type: Deprecation revoked
@@ -410,7 +410,7 @@ libuv.
#### DEP0038: `fs.lchownSync(path, uid, gid)`
-
+
Type: Deprecation revoked
@@ -419,7 +419,7 @@ revoked because the requisite supporting APIs were added in libuv.
#### DEP0039: `require.extensions`
-
+
Type: Documentation-only
@@ -427,7 +427,7 @@ The [`require.extensions`][] property is deprecated.
#### DEP0040: `node:punycode` module
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -436,7 +436,7 @@ instead.
#### DEP0041: `NODE_REPL_HISTORY_FILE` environment variable
-
+
Type: End-of-Life
@@ -445,7 +445,7 @@ The `NODE_REPL_HISTORY_FILE` environment variable was removed. Please use
#### DEP0042: `tls.CryptoStream`
-
+
Type: End-of-Life
@@ -454,7 +454,7 @@ The [`tls.CryptoStream`][] class was removed. Please use
#### DEP0043: `tls.SecurePair`
-
+
Type: Documentation-only
@@ -463,7 +463,7 @@ The [`tls.SecurePair`][] class is deprecated. Please use
#### DEP0044: `util.isArray()`
-
+
Type: Documentation-only
@@ -472,7 +472,7 @@ instead.
#### DEP0045: `util.isBoolean()`
-
+
Type: Documentation-only
@@ -480,7 +480,7 @@ The [`util.isBoolean()`][] API is deprecated.
#### DEP0046: `util.isBuffer()`
-
+
Type: Documentation-only
@@ -489,7 +489,7 @@ The [`util.isBuffer()`][] API is deprecated. Please use
#### DEP0047: `util.isDate()`
-
+
Type: Documentation-only
@@ -497,7 +497,7 @@ The [`util.isDate()`][] API is deprecated.
#### DEP0048: `util.isError()`
-
+
Type: Documentation-only
@@ -505,7 +505,7 @@ The [`util.isError()`][] API is deprecated.
#### DEP0049: `util.isFunction()`
-
+
Type: Documentation-only
@@ -513,7 +513,7 @@ The [`util.isFunction()`][] API is deprecated.
#### DEP0050: `util.isNull()`
-
+
Type: Documentation-only
@@ -521,7 +521,7 @@ The [`util.isNull()`][] API is deprecated.
#### DEP0051: `util.isNullOrUndefined()`
-
+
Type: Documentation-only
@@ -529,7 +529,7 @@ The [`util.isNullOrUndefined()`][] API is deprecated.
#### DEP0052: `util.isNumber()`
-
+
Type: Documentation-only
@@ -537,7 +537,7 @@ The [`util.isNumber()`][] API is deprecated.
#### DEP0053: `util.isObject()`
-
+
Type: Documentation-only
@@ -545,7 +545,7 @@ The [`util.isObject()`][] API is deprecated.
#### DEP0054: `util.isPrimitive()`
-
+
Type: Documentation-only
@@ -553,7 +553,7 @@ The [`util.isPrimitive()`][] API is deprecated.
#### DEP0055: `util.isRegExp()`
-
+
Type: Documentation-only
@@ -561,7 +561,7 @@ The [`util.isRegExp()`][] API is deprecated.
#### DEP0056: `util.isString()`
-
+
Type: Documentation-only
@@ -569,7 +569,7 @@ The [`util.isString()`][] API is deprecated.
#### DEP0057: `util.isSymbol()`
-
+
Type: Documentation-only
@@ -577,7 +577,7 @@ The [`util.isSymbol()`][] API is deprecated.
#### DEP0058: `util.isUndefined()`
-
+
Type: Documentation-only
@@ -585,7 +585,7 @@ The [`util.isUndefined()`][] API is deprecated.
#### DEP0059: `util.log()`
-
+
Type: Documentation-only
@@ -593,7 +593,7 @@ The [`util.log()`][] API is deprecated.
#### DEP0060: `util._extend()`
-
+
Type: Documentation-only
@@ -601,7 +601,7 @@ The [`util._extend()`][] API is deprecated.
#### DEP0061: `fs.SyncWriteStream`
-
+
Type: End-of-Life
@@ -611,7 +611,7 @@ alternative.
#### DEP0062: `node --debug`
-
+
Type: End-of-Life
@@ -621,7 +621,7 @@ instead.
#### DEP0063: `ServerResponse.prototype.writeHeader()`
-
+
Type: Documentation-only
@@ -633,7 +633,7 @@ officially supported API.
#### DEP0064: `tls.createSecurePair()`
-
+
Type: Runtime
@@ -642,7 +642,7 @@ The `tls.createSecurePair()` API was deprecated in documentation in Node.js
#### DEP0065: `repl.REPL_MODE_MAGIC` and `NODE_REPL_MODE=magic`
-
+
Type: End-of-Life
@@ -657,7 +657,7 @@ removed. Please use `sloppy` instead.
#### DEP0066: `OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames`
-
+
Type: Runtime
@@ -677,7 +677,7 @@ officially supported properties.
#### DEP0067: `OutgoingMessage.prototype._renderHeaders`
-
+
Type: Documentation-only
@@ -689,7 +689,7 @@ an officially supported API.
#### DEP0068: `node debug`
-
+
Type: End-of-Life
@@ -698,7 +698,7 @@ a V8-inspector based CLI debugger available through `node inspect`.
#### DEP0069: `vm.runInDebugContext(string)`
-
+
Type: End-of-Life
@@ -708,7 +708,7 @@ DebugContext was an experimental API.
#### DEP0070: `async_hooks.currentId()`
-
+
Type: End-of-Life
@@ -719,7 +719,7 @@ This change was made while `async_hooks` was an experimental API.
#### DEP0071: `async_hooks.triggerId()`
-
+
Type: End-of-Life
@@ -730,7 +730,7 @@ This change was made while `async_hooks` was an experimental API.
#### DEP0072: `async_hooks.AsyncResource.triggerId()`
-
+
Type: End-of-Life
@@ -741,7 +741,7 @@ This change was made while `async_hooks` was an experimental API.
#### DEP0073: Several internal properties of `net.Server`
-
+
Type: End-of-Life
@@ -753,7 +753,7 @@ code, no replacement API is provided.
#### DEP0074: `REPLServer.bufferedCommand`
-
+
Type: End-of-Life
@@ -762,7 +762,7 @@ The `REPLServer.bufferedCommand` property was deprecated in favor of
#### DEP0075: `REPLServer.parseREPLKeyword()`
-
+
Type: End-of-Life
@@ -770,7 +770,7 @@ Type: End-of-Life
#### DEP0076: `tls.parseCertString()`
-
+
Type: End-of-Life
@@ -784,7 +784,7 @@ not handle all certificate subjects correctly and should not be used.
#### DEP0077: `Module._debug()`
-
+
Type: Runtime
@@ -795,7 +795,7 @@ supported API.
#### DEP0078: `REPLServer.turnOffEditorMode()`
-
+
Type: End-of-Life
@@ -803,7 +803,7 @@ Type: End-of-Life
#### DEP0079: Custom inspection function on objects via `.inspect()`
-
+
Type: End-of-Life
@@ -814,7 +814,7 @@ can be specified.
#### DEP0080: `path._makeLong()`
-
+
Type: Documentation-only
@@ -824,7 +824,7 @@ and replaced with an identical, public `path.toNamespacedPath()` method.
#### DEP0081: `fs.truncate()` using a file descriptor
-
+
Type: Runtime
@@ -834,7 +834,7 @@ file descriptors.
#### DEP0082: `REPLServer.prototype.memory()`
-
+
Type: End-of-Life
@@ -843,7 +843,7 @@ the `REPLServer` itself. Do not use this function.
#### DEP0083: Disabling ECDH by setting `ecdhCurve` to `false`
-
+
Type: End-of-Life.
@@ -854,7 +854,7 @@ the client and is now unsupported. Use the `ciphers` parameter instead.
#### DEP0084: requiring bundled internal dependencies
-
+
Type: End-of-Life
@@ -886,7 +886,7 @@ code modification is necessary if that is done.
#### DEP0085: AsyncHooks sensitive API
-
+
Type: End-of-Life
@@ -896,7 +896,7 @@ Use the `AsyncResource` API instead. See
#### DEP0086: Remove `runInAsyncIdScope`
-
+
Type: End-of-Life
@@ -905,7 +905,7 @@ cause a lot of issues. See [https://github.com/nodejs/node/issues/14328](https:/
#### DEP0089: `require('node:assert')`
-
+
Type: Deprecation revoked
@@ -916,7 +916,7 @@ confusion.
#### DEP0090: Invalid GCM authentication tag lengths
-
+
Type: End-of-Life
@@ -928,7 +928,7 @@ bits are allowed. Authentication tags of other lengths are invalid per
#### DEP0091: `crypto.DEFAULT_ENCODING`
-
+
Type: Runtime
@@ -936,7 +936,7 @@ The [`crypto.DEFAULT_ENCODING`][] property is deprecated.
#### DEP0092: Top-level `this` bound to `module.exports`
-
+
Type: Documentation-only
@@ -946,7 +946,7 @@ or `module.exports` instead.
#### DEP0093: `crypto.fips` is deprecated and replaced
-
+
Type: Documentation-only
@@ -955,7 +955,7 @@ and `crypto.getFips()` instead.
#### DEP0094: Using `assert.fail()` with more than one argument
-
+
Type: Runtime
@@ -965,7 +965,7 @@ method.
#### DEP0095: `timers.enroll()`
-
+
Type: Runtime
@@ -974,7 +974,7 @@ Type: Runtime
#### DEP0096: `timers.unenroll()`
-
+
Type: Runtime
@@ -983,7 +983,7 @@ Type: Runtime
#### DEP0097: `MakeCallback` with `domain` property
-
+
Type: Runtime
@@ -993,7 +993,7 @@ should start using the `async_context` variant of `MakeCallback` or
#### DEP0098: AsyncHooks embedder `AsyncResource.emitBefore` and `AsyncResource.emitAfter` APIs
-
+
Type: End-of-Life
@@ -1007,7 +1007,7 @@ safer, and more convenient, alternative. See
#### DEP0099: Async context-unaware `node::MakeCallback` C++ APIs
-
+
Type: Compile-time
@@ -1017,7 +1017,7 @@ parameter.
#### DEP0100: `process.assert()`
-
+
Type: Runtime
@@ -1027,7 +1027,7 @@ This was never a documented feature.
#### DEP0101: `--with-lttng`
-
+
Type: End-of-Life
@@ -1035,7 +1035,7 @@ The `--with-lttng` compile-time option has been removed.
#### DEP0102: Using `noAssert` in `Buffer#(read|write)` operations
-
+
Type: End-of-Life
@@ -1045,7 +1045,7 @@ could lead to hard-to-find errors and crashes.
#### DEP0103: `process.binding('util').is[...]` typechecks
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1057,7 +1057,7 @@ This deprecation has been superseded by the deprecation of the
#### DEP0104: `process.env` string coercion
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1069,7 +1069,7 @@ assigning it to `process.env`.
#### DEP0105: `decipher.finaltol`
-
+
Type: End-of-Life
@@ -1079,7 +1079,7 @@ Type: End-of-Life
#### DEP0106: `crypto.createCipher` and `crypto.createDecipher`
-
+
Type: Runtime
@@ -1092,7 +1092,7 @@ initialization vectors. It is recommended to derive a key using
#### DEP0107: `tls.convertNPNProtocols()`
-
+
Type: End-of-Life
@@ -1101,7 +1101,7 @@ core and obsoleted by the removal of NPN (Next Protocol Negotiation) support.
#### DEP0108: `zlib.bytesRead`
-
+
Type: Runtime
@@ -1112,7 +1112,7 @@ expose values under these names.
#### DEP0109: `http`, `https`, and `tls` support for invalid URLs
-
+
Type: End-of-Life
@@ -1125,7 +1125,7 @@ deprecated and support will be removed in the future.
#### DEP0110: `vm.Script` cached data
-
+
Type: Documentation-only
@@ -1134,7 +1134,7 @@ The `produceCachedData` option is deprecated. Use
#### DEP0111: `process.binding()`
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1142,7 +1142,7 @@ Type: Documentation-only (supports [`--pending-deprecation`][])
#### DEP0112: `dgram` private APIs
-
+
Type: Runtime
@@ -1155,7 +1155,7 @@ to accessed outside of Node.js core: `Socket.prototype._handle`,
#### DEP0113: `Cipher.setAuthTag()`, `Decipher.getAuthTag()`
-
+
Type: End-of-Life
@@ -1164,7 +1164,7 @@ were never documented and would throw when called.
#### DEP0114: `crypto._toBuf()`
-
+
Type: End-of-Life
@@ -1173,7 +1173,7 @@ of Node.js core and was removed.
#### DEP0115: `crypto.prng()`, `crypto.pseudoRandomBytes()`, `crypto.rng()`
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1185,17 +1185,17 @@ future release.
#### DEP0116: Legacy URL API
-
+
Type: Deprecation revoked
-The [Legacy URL API][] is deprecated. This includes [`url.format()`][],
+The [legacy URL API][] is deprecated. This includes [`url.format()`][],
[`url.parse()`][], [`url.resolve()`][], and the [legacy `urlObject`][]. Please
use the [WHATWG URL API][] instead.
#### DEP0117: Native crypto handles
-
+
Type: End-of-Life
@@ -1207,7 +1207,7 @@ object can lead to crashing the application.
#### DEP0118: `dns.lookup()` support for a falsy host name
-
+
Type: Runtime
@@ -1218,7 +1218,7 @@ It will become an error in future versions of Node.js.
#### DEP0119: `process.binding('uv').errname()` private API
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1227,7 +1227,7 @@ Type: Documentation-only (supports [`--pending-deprecation`][])
#### DEP0120: Windows Performance Counter support
-
+
Type: End-of-Life
@@ -1239,7 +1239,7 @@ undocumented `COUNTER_NET_SERVER_CONNECTION()`,
#### DEP0121: `net._setSimultaneousAccepts()`
-
+
Type: Runtime
@@ -1251,7 +1251,7 @@ generally useful and is being removed. See discussion here:
#### DEP0122: `tls` `Server.prototype.setOptions()`
-
+
Type: Runtime
@@ -1259,7 +1259,7 @@ Please use `Server.prototype.setSecureContext()` instead.
#### DEP0123: setting the TLS ServerName to an IP address
-
+
Type: Runtime
@@ -1268,7 +1268,7 @@ Setting the TLS ServerName to an IP address is not permitted by
#### DEP0124: using `REPLServer.rli`
-
+
Type: End-of-Life
@@ -1276,7 +1276,7 @@ This property is a reference to the instance itself.
#### DEP0125: `require('node:_stream_wrap')`
-
+
Type: Runtime
@@ -1284,7 +1284,7 @@ The `node:_stream_wrap` module is deprecated.
#### DEP0126: `timers.active()`
-
+
Type: Runtime
@@ -1295,7 +1295,7 @@ with no performance impact since Node.js 10.
#### DEP0127: `timers._unrefActive()`
-
+
Type: Runtime
@@ -1306,7 +1306,7 @@ with no performance impact since Node.js 10.
#### DEP0128: modules with an invalid `main` entry and an `index.js` file
-
+
Type: Runtime
@@ -1317,7 +1317,7 @@ Node.js versions.
#### DEP0129: `ChildProcess._channel`
-
+
Type: Runtime
@@ -1327,7 +1327,7 @@ instead.
#### DEP0130: `Module.createRequireFromPath()`
-
+
Type: End-of-Life
@@ -1335,7 +1335,7 @@ Use [`module.createRequire()`][] instead.
#### DEP0131: Legacy HTTP parser
-
+
Type: End-of-Life
@@ -1346,7 +1346,7 @@ legacy parser.
#### DEP0132: `worker.terminate()` with callback
-
+
Type: Runtime
@@ -1355,7 +1355,7 @@ Passing a callback to [`worker.terminate()`][] is deprecated. Use the returned
#### DEP0133: `http` `connection`
-
+
Type: Documentation-only
@@ -1364,7 +1364,7 @@ Prefer [`response.socket`][] over [`response.connection`][] and
#### DEP0134: `process._tickCallback`
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1373,7 +1373,7 @@ an officially supported API.
#### DEP0135: `WriteStream.open()` and `ReadStream.open()` are internal
-
+
Type: Runtime
@@ -1384,7 +1384,7 @@ and [`fs.createReadStream()`][]) or by passing a file descriptor in options.
#### DEP0136: `http` `finished`
-
+
Type: Documentation-only
@@ -1400,7 +1400,7 @@ To maintain existing behavior `response.finished` should be replaced with
#### DEP0137: Closing fs.FileHandle on garbage collection
-
+
Type: Runtime
@@ -1426,7 +1426,7 @@ async function openAndClose() {
#### DEP0138: `process.mainModule`
-
+
Type: Documentation-only
@@ -1439,7 +1439,7 @@ purpose and is only available on CommonJS environment.
#### DEP0139: `process.umask()` with no arguments
-
+
Type: Documentation-only
@@ -1450,7 +1450,7 @@ API.
#### DEP0140: Use `request.destroy()` instead of `request.abort()`
-
+
Type: Documentation-only
@@ -1458,7 +1458,7 @@ Use [`request.destroy()`][] instead of [`request.abort()`][].
#### DEP0141: `repl.inputStream` and `repl.outputStream`
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1467,7 +1467,7 @@ instead of `.inputStream` and `.output` instead of `.outputStream`.
#### DEP0142: `repl._builtinLibs`
-
+
Type: Documentation-only
@@ -1477,7 +1477,7 @@ upon `require('node:module').builtinModules`.
#### DEP0143: `Transform._transformState`
-
+
Type: Runtime
`Transform._transformState` will be removed in future versions where it is
@@ -1485,7 +1485,7 @@ no longer required due to simplification of the implementation.
#### DEP0144: `module.parent`
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1513,7 +1513,7 @@ const moduleParents = Object.values(require.cache)
#### DEP0145: `socket.bufferSize`
-
+
Type: Documentation-only
@@ -1521,7 +1521,7 @@ Type: Documentation-only
#### DEP0146: `new crypto.Certificate()`
-
+
Type: Documentation-only
@@ -1530,7 +1530,7 @@ The [`crypto.Certificate()` constructor][] is deprecated. Use
#### DEP0147: `fs.rmdir(path, { recursive: true })`
-
+
Type: Runtime
@@ -1543,7 +1543,7 @@ Use `fs.rm(path, { recursive: true, force: true })`,
#### DEP0148: Folder mappings in `"exports"` (trailing `"/"`)
-
+
Type: Runtime
@@ -1553,7 +1553,7 @@ Using a trailing `"/"` to define subpath folder mappings in the
#### DEP0149: `http.IncomingMessage#connection`
-
+
Type: Documentation-only.
@@ -1561,7 +1561,7 @@ Prefer [`message.socket`][] over [`message.connection`][].
#### DEP0150: Changing the value of `process.config`
-
+
Type: End-of-Life
@@ -1571,7 +1571,7 @@ to change the value will be removed in a future version of Node.js.
#### DEP0151: Main index lookup and extension searching
-
+
Type: Runtime
@@ -1583,11 +1583,11 @@ an explicit [`"exports"` or `"main"` entry][] with the exact file extension.
#### DEP0152: Extension PerformanceEntry properties
-
+
Type: Runtime
-The `'gc'`, `'http2'`, and `'http'` [`PerformanceEntry`](/api/perf_hooks#performanceentry) object types have
+The `'gc'`, `'http2'`, and `'http'` [`PerformanceEntry`](/api/v18/perf_hooks#performanceentry) object types have
additional properties assigned to them that provide additional information.
These properties are now available within the standard `detail` property
of the `PerformanceEntry` object. The existing accessors have been
@@ -1595,7 +1595,7 @@ deprecated and should no longer be used.
#### DEP0153: `dns.lookup` and `dnsPromises.lookup` options type coercion
-
+
Type: End-of-Life
@@ -1607,7 +1607,7 @@ option, or a non-nullish non-boolean value for `verbatim` option in
#### DEP0154: RSA-PSS generate key pair options
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1616,7 +1616,7 @@ and `'mgf1HashAlgorithm'`.
#### DEP0155: Trailing slashes in pattern specifier resolutions
-
+
Type: Runtime
@@ -1625,11 +1625,11 @@ for package `"exports"` and `"imports"` pattern resolutions.
#### DEP0156: `.aborted` property and `'abort'`, `'aborted'` event in `http`
-
+
Type: Documentation-only
-Move to [`Stream`](/api/stream#stream) API instead, as the [`http.ClientRequest`][],
+Move to [`Stream`](/api/v18/stream#stream) API instead, as the [`http.ClientRequest`][],
[`http.ServerResponse`][], and [`http.IncomingMessage`][] are all stream-based.
Check `stream.destroyed` instead of the `.aborted` property, and listen for
`'close'` instead of `'abort'`, `'aborted'` event.
@@ -1643,7 +1643,7 @@ it was an aborted or graceful destroy.
#### DEP0157: Thenable support in streams
-
+
Type: End-of-Life
@@ -1660,13 +1660,13 @@ const w = new Writable({
async final(callback) {
await someOp();
callback();
- }
+ },
});
```
#### DEP0158: `buffer.slice(start, end)`
-
+
Type: Documentation-only
@@ -1677,7 +1677,7 @@ Use [`buffer.subarray`][] which does the same thing instead.
#### DEP0159: `ERR_INVALID_CALLBACK`
-
+
Type: End-of-Life
@@ -1686,7 +1686,7 @@ the errors used for value type validation.
#### DEP0160: `process.on('multipleResolves', handler)`
-
+
Type: Runtime.
@@ -1695,7 +1695,7 @@ which diminished its usefulness.
#### DEP0161: `process._getActiveRequests()` and `process._getActiveHandles()`
-
+
Type: Documentation-only
@@ -1708,7 +1708,7 @@ resources and not the actual references.
#### DEP0162: `fs.write()`, `fs.writeFileSync()` coercion to string
-
+
Type: End-of-Life
@@ -1719,7 +1719,7 @@ Convert them to primitive strings.
#### DEP0163: `channel.subscribe(onMessage)`, `channel.unsubscribe(onMessage)`
-
+
Type: Documentation-only
@@ -1732,7 +1732,7 @@ thing instead.
#### DEP0164: `process.exit(code)`, `process.exitCode` coercion to integer
-
+
Type: Documentation-only
@@ -1742,7 +1742,7 @@ Values other than `undefined`, `null`, integer numbers, and integer strings
#### DEP0165: `--trace-atomics-wait`
-
+
Type: Documentation-only
@@ -1750,7 +1750,7 @@ The [`--trace-atomics-wait`][] flag is deprecated.
#### DEP0166: Double slashes in imports and exports targets
-
+
Type: Runtime
@@ -1761,7 +1761,7 @@ starting or ending in a slash.
#### DEP0167: Weak `DiffieHellmanGroup` instances (`modp1`, `modp2`, `modp5`)
-
+
Type: Documentation-only
@@ -1774,9 +1774,9 @@ rely on these groups should evaluate using stronger MODP groups instead.
#### DEP0168: Unhandled exception in Node-API callbacks
-
+
-Type: Runtime.
+Type: Runtime
The implicit suppression of uncaught exceptions in Node-API callbacks is now
deprecated.
@@ -1785,7 +1785,36 @@ Set the flag [`--force-node-api-uncaught-exceptions-policy`][] to force Node.js
to emit an [`'uncaughtException'`][] event if the exception is not handled in
Node-API callbacks.
-[Legacy URL API]: /api/v18/url#legacy-url-api
+#### DEP0169: Insecure url.parse()
+
+
+
+Type: Documentation-only
+
+[`url.parse()`][] behavior is not standardized and prone to errors that
+have security implications. Use the [WHATWG URL API][] instead. CVEs are not
+issued for `url.parse()` vulnerabilities.
+
+#### DEP0170: Invalid port when using `url.parse()`
+
+
+
+Type: Documentation-only
+
+[`url.parse()`][] accepts URLs with ports that are not numbers. This behavior
+might result in host name spoofing with unexpected input. These URLs will throw
+an error in future versions of Node.js, as the [WHATWG URL API][] does already.
+
+#### DEP0171: Setters for `http.IncomingMessage` headers and trailers
+
+
+
+Type: Documentation-only
+
+In a future version of Node.js, [`message.headers`][],
+[`message.headersDistinct`][], [`message.trailers`][], and
+[`message.trailersDistinct`][] will be read-only.
+
[NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
[RFC 6066]: https://tools.ietf.org/html/rfc6066#section-3
[RFC 8247 Section 2.4]: https://www.rfc-editor.org/rfc/rfc8247#section-2.4
@@ -1835,7 +1864,7 @@ Node-API callbacks.
[`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
@@ -1862,7 +1891,11 @@ Node-API callbacks.
[`https.get()`]: /api/v18/https#httpsgetoptions-callback
[`https.request()`]: /api/v18/https#httpsrequestoptions-callback
[`message.connection`]: /api/v18/http#messageconnection
+[`message.headersDistinct`]: /api/v18/http#messageheadersdistinct
+[`message.headers`]: /api/v18/http#messageheaders
[`message.socket`]: /api/v18/http#messagesocket
+[`message.trailersDistinct`]: /api/v18/http#messagetrailersdistinct
+[`message.trailers`]: /api/v18/http#messagetrailers
[`module.createRequire()`]: /api/v18/module#modulecreaterequirefilename
[`os.networkInterfaces()`]: /api/v18/os#osnetworkinterfaces
[`os.tmpdir()`]: /api/v18/os#ostmpdir
@@ -1931,6 +1964,7 @@ Node-API callbacks.
[alloc_unsafe_size]: /api/v18/buffer#static-method-bufferallocunsafesize
[from_arraybuffer]: /api/v18/buffer#static-method-bufferfromarraybuffer-byteoffset-length
[from_string_encoding]: /api/v18/buffer#static-method-bufferfromstring-encoding
+[legacy URL API]: /api/v18/url#legacy-url-api
[legacy `urlObject`]: /api/v18/url#legacy-urlobject
[static methods of `crypto.Certificate()`]: /api/v18/crypto#class-certificate
[subpath exports]: /api/v18/packages#subpath-exports
diff --git a/content/api/v18/dgram.en.md b/content/api/v18/dgram.en.md
index 744557ce6d..ff64e61bd1 100644
--- a/content/api/v18/dgram.en.md
+++ b/content/api/v18/dgram.en.md
@@ -5,23 +5,27 @@ category: 'api'
version: 'v18'
---
-
+
-
+
-
+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');
server.on('error', (err) => {
- console.log(`server error:\n${err.stack}`);
+ console.error(`server error:\n${err.stack}`);
server.close();
});
@@ -36,14 +40,12 @@ 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');
server.on('error', (err) => {
- console.log(`server error:\n${err.stack}`);
+ console.error(`server error:\n${err.stack}`);
server.close();
});
@@ -62,9 +64,9 @@ server.bind(41234);
### `dgram.Socket`
-
+
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v18/events#eventemitter)
Encapsulates the datagram functionality.
@@ -73,21 +75,21 @@ The `new` keyword is not to be used to create `dgram.Socket` instances.
#### `'close'`
-
+
The `'close'` event is emitted after a socket is closed with [`close()`][].
Once triggered, no new `'message'` events will be emitted on this socket.
#### `'connect'`
-
+
The `'connect'` event is emitted after a socket is associated to a remote
address as a result of a successful [`connect()`][] call.
#### `'error'`
-
+
* `exception` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -96,7 +98,7 @@ function is passed a single `Error` object.
#### `'listening'`
-
+
The `'listening'` event is emitted once the `dgram.Socket` is addressable and
can receive data. This happens either explicitly with `socket.bind()` or
@@ -106,12 +108,12 @@ exist and calls such as `socket.address()` and `socket.setTTL()` will fail.
#### `'message'`
-
+
The `'message'` event is emitted when a new datagram is available on a socket.
The event handler function is passed two arguments: `msg` and `rinfo`.
-* `msg` [`Buffer`](/api/buffer#buffer) The message.
+* `msg` [`Buffer`](/api/v18/buffer#buffer) The message.
* `rinfo` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Remote address information.
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The sender address.
* `family` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The address family (`'IPv4'` or `'IPv6'`).
@@ -126,7 +128,7 @@ is the interface name as a zone ID suffix.
#### `socket.addMembership(multicastAddress[, multicastInterface])`
-
+
* `multicastAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `multicastInterface` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -144,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';
@@ -157,9 +159,7 @@ if (cluster.isPrimary) {
s.addMembership('224.0.0.114');
});
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const dgram = require('node:dgram');
@@ -176,7 +176,7 @@ if (cluster.isPrimary) {
#### `socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`
-
+
* `sourceAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `groupAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -194,7 +194,7 @@ port, listening on all interfaces.
#### `socket.address()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -206,7 +206,7 @@ This method throws `EBADF` if called on an unbound socket.
#### `socket.bind([port][, address][, callback])`
-
+
* `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -232,13 +232,13 @@ 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');
server.on('error', (err) => {
- console.log(`server error:\n${err.stack}`);
+ console.error(`server error:\n${err.stack}`);
server.close();
});
@@ -253,14 +253,12 @@ 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');
server.on('error', (err) => {
- console.log(`server error:\n${err.stack}`);
+ console.error(`server error:\n${err.stack}`);
server.close();
});
@@ -279,7 +277,7 @@ server.bind(41234);
#### `socket.bind(options[, callback])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Required. Supports the following properties:
* `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -325,13 +323,13 @@ An example socket listening on an exclusive port is shown below.
socket.bind({
address: 'localhost',
port: 8000,
- exclusive: true
+ exclusive: true,
});
```
#### `socket.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called when the socket has been closed.
@@ -340,7 +338,7 @@ provided, it is added as a listener for the [`'close'`][] event.
#### `socket.connect(port[, address][, callback])`
-
+
* `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -358,7 +356,7 @@ the `callback` is called or, failing this, an `'error'` event is emitted.
#### `socket.disconnect()`
-
+
A synchronous function that disassociates a connected `dgram.Socket` from
its remote address. Trying to call `disconnect()` on an unbound or already
@@ -367,7 +365,7 @@ exception.
#### `socket.dropMembership(multicastAddress[, multicastInterface])`
-
+
* `multicastAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `multicastInterface` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -382,7 +380,7 @@ drop membership on all valid interfaces.
#### `socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`
-
+
* `sourceAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `groupAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -399,7 +397,7 @@ drop membership on all valid interfaces.
#### `socket.getRecvBufferSize()`
-
+
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the `SO_RCVBUF` socket receive buffer size in bytes.
@@ -407,7 +405,7 @@ This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
#### `socket.getSendBufferSize()`
-
+
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the `SO_SNDBUF` socket send buffer size in bytes.
@@ -415,22 +413,22 @@ This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
#### `socket.getSendQueueSize()`
-
+
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes queued for sending.
#### `socket.getSendQueueCount()`
-
+
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of send requests currently in the queue awaiting
to be processed.
#### `socket.ref()`
-
+
-* Returns: [`dgram.Socket`](/api/dgram#dgramsocket)
+* Returns: [`dgram.Socket`](/api/v18/dgram#dgramsocket)
By default, binding a socket will cause it to block the Node.js process from
exiting as long as the socket is open. The `socket.unref()` method can be used
@@ -445,7 +443,7 @@ chained.
#### `socket.remoteAddress()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -455,9 +453,9 @@ if the socket is not connected.
#### `socket.send(msg[, offset, length][, port][, address][, callback])`
-
+
-* `msg` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Message to be sent.
+* `msg` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Message to be sent.
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Offset in the buffer where the message starts.
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes in the message.
* `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Destination port.
@@ -507,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';
@@ -516,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');
@@ -532,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';
@@ -542,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');
@@ -564,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';
@@ -575,9 +569,7 @@ client.connect(41234, 'localhost', (err) => {
client.close();
});
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
@@ -619,7 +611,7 @@ source that the data did not reach its intended recipient.
#### `socket.setBroadcast(flag)`
-
+
* `flag` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -630,7 +622,7 @@ This method throws `EBADF` if called on an unbound socket.
#### `socket.setMulticastInterface(multicastInterface)`
-
+
* `multicastInterface` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -710,7 +702,7 @@ for future multicast packets.
#### `socket.setMulticastLoopback(flag)`
-
+
* `flag` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -721,7 +713,7 @@ This method throws `EBADF` if called on an unbound socket.
#### `socket.setMulticastTTL(ttl)`
-
+
* `ttl` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -737,7 +729,7 @@ This method throws `EBADF` if called on an unbound socket.
#### `socket.setRecvBufferSize(size)`
-
+
* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -748,7 +740,7 @@ This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
#### `socket.setSendBufferSize(size)`
-
+
* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -759,7 +751,7 @@ This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
#### `socket.setTTL(ttl)`
-
+
* `ttl` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -776,9 +768,9 @@ This method throws `EBADF` if called on an unbound socket.
#### `socket.unref()`
-
+
-* Returns: [`dgram.Socket`](/api/dgram#dgramsocket)
+* Returns: [`dgram.Socket`](/api/v18/dgram#dgramsocket)
By default, binding a socket will cause it to block the Node.js process from
exiting as long as the socket is open. The `socket.unref()` method can be used
@@ -795,7 +787,7 @@ chained.
#### `dgram.createSocket(options[, callback])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Available options are:
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The family of socket. Must be either `'udp4'` or `'udp6'`.
@@ -809,9 +801,9 @@ chained.
* `recvBufferSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the `SO_RCVBUF` socket value.
* `sendBufferSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the `SO_SNDBUF` socket value.
* `lookup` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Custom lookup function. **Default:** [`dns.lookup()`][].
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An AbortSignal that may be used to close a socket.
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) An AbortSignal that may be used to close a socket.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Attached as a listener for `'message'` events. Optional.
-* Returns: [`dgram.Socket`](/api/dgram#dgramsocket)
+* Returns: [`dgram.Socket`](/api/v18/dgram#dgramsocket)
Creates a `dgram.Socket` object. Once the socket is created, calling
[`socket.bind()`][] will instruct the socket to begin listening for datagram
@@ -837,11 +829,11 @@ controller.abort();
#### `dgram.createSocket(type[, callback])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Either `'udp4'` or `'udp6'`.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Attached as a listener to `'message'` events.
-* Returns: [`dgram.Socket`](/api/dgram#dgramsocket)
+* Returns: [`dgram.Socket`](/api/v18/dgram#dgramsocket)
Creates a `dgram.Socket` object of the specified `type`.
diff --git a/content/api/v18/diagnostics_channel.en.md b/content/api/v18/diagnostics_channel.en.md
index 8ddc843b73..1267e6f41c 100644
--- a/content/api/v18/diagnostics_channel.en.md
+++ b/content/api/v18/diagnostics_channel.en.md
@@ -5,22 +5,26 @@ category: 'api'
version: 'v18'
---
-
+
-
+
-
+
+
+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');
```
@@ -42,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
@@ -59,15 +63,13 @@ diagnostics_channel.subscribe('my-channel', onMessage);
if (channel.hasSubscribers) {
// Publish data to the channel
channel.publish({
- some: 'data'
+ some: 'data',
});
}
// Unsubscribe from the channel
diagnostics_channel.unsubscribe('my-channel', onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
// Get a reusable channel object
@@ -84,7 +86,7 @@ diagnostics_channel.subscribe('my-channel', onMessage);
if (channel.hasSubscribers) {
// Publish data to the channel
channel.publish({
- some: 'data'
+ some: 'data',
});
}
@@ -94,7 +96,7 @@ diagnostics_channel.unsubscribe('my-channel', onMessage);
##### `diagnostics_channel.hasSubscribers(name)`
-
+
* `name` [`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 channel name
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If there are active subscribers
@@ -105,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')) {
@@ -123,22 +123,20 @@ if (diagnostics_channel.hasSubscribers('my-channel')) {
##### `diagnostics_channel.channel(name)`
-
+
* `name` [`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 channel name
-* Returns: [`Channel`](/api/diagnostics_channel#channel) The named channel object
+* Returns: [`Channel`](/api/v18/diagnostics_channel#channel) The named channel object
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');
@@ -146,7 +144,7 @@ const channel = diagnostics_channel.channel('my-channel');
##### `diagnostics_channel.subscribe(name, onMessage)`
-
+
* `name` [`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 channel name
* `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The handler to receive channel messages
@@ -157,16 +155,14 @@ 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
-import diagnostics_channel from 'diagnostics_channel';
+```mjs|cjs
+import diagnostics_channel from 'node:diagnostics_channel';
diagnostics_channel.subscribe('my-channel', (message, name) => {
// Received data
});
-```
-
-```cjs
-const diagnostics_channel = require('diagnostics_channel');
+--------------
+const diagnostics_channel = require('node:diagnostics_channel');
diagnostics_channel.subscribe('my-channel', (message, name) => {
// Received data
@@ -175,7 +171,7 @@ diagnostics_channel.subscribe('my-channel', (message, name) => {
##### `diagnostics_channel.unsubscribe(name, onMessage)`
-
+
* `name` [`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 channel name
* `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The previous subscribed handler to remove
@@ -184,8 +180,8 @@ diagnostics_channel.subscribe('my-channel', (message, name) => {
Remove a message handler previously registered to this channel with
[`diagnostics_channel.subscribe(name, onMessage)`][].
-```mjs
-import diagnostics_channel from 'diagnostics_channel';
+```mjs|cjs
+import diagnostics_channel from 'node:diagnostics_channel';
function onMessage(message, name) {
// Received data
@@ -194,10 +190,8 @@ function onMessage(message, name) {
diagnostics_channel.subscribe('my-channel', onMessage);
diagnostics_channel.unsubscribe('my-channel', onMessage);
-```
-
-```cjs
-const diagnostics_channel = require('diagnostics_channel');
+--------------
+const diagnostics_channel = require('node:diagnostics_channel');
function onMessage(message, name) {
// Received data
@@ -210,7 +204,7 @@ diagnostics_channel.unsubscribe('my-channel', onMessage);
#### `Channel`
-
+
The class `Channel` represents an individual named channel within the data
pipeline. It is used to track subscribers and to publish messages when there
@@ -222,7 +216,7 @@ with `new Channel(name)` is not supported.
##### `channel.hasSubscribers`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If there are active subscribers
@@ -232,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');
@@ -240,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');
@@ -254,38 +246,40 @@ if (channel.hasSubscribers) {
##### `channel.publish(message)`
-
+
* `message` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The message to send to the channel subscribers
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');
channel.publish({
- some: 'message'
+ some: 'message',
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
channel.publish({
- some: 'message'
+ some: 'message',
});
```
##### `channel.subscribe(onMessage)`
-
+
-
+
+
+Deprecated: Use [`diagnostics_channel.subscribe(name, onMessage)`][]
+
+
* `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The handler to receive channel messages
* `message` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The message data
@@ -295,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');
@@ -303,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');
@@ -317,9 +309,13 @@ channel.subscribe((message, name) => {
##### `channel.unsubscribe(onMessage)`
-
+
-
+
+
+Deprecated: Use [`diagnostics_channel.unsubscribe(name, onMessage)`][]
+
+
* `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The previous subscribed handler to remove
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the handler was found, `false` otherwise.
@@ -327,7 +323,7 @@ channel.subscribe((message, name) => {
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');
@@ -339,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');
@@ -357,54 +351,64 @@ channel.unsubscribe(onMessage);
#### Built-in Channels
+
+
+Experimental
+
+
+
+While the diagnostics\_channel API is now considered stable, the built-in
+channels currently available are not. Each channel must be declared stable
+independently.
+
##### HTTP
`http.client.request.start`
-* `request` [`http.ClientRequest`](/api/http#httpclientrequest)
+* `request` [`http.ClientRequest`](/api/v18/http#httpclientrequest)
Emitted when client starts a request.
`http.client.response.finish`
-* `request` [`http.ClientRequest`](/api/http#httpclientrequest)
-* `response` [`http.IncomingMessage`](/api/http#httpincomingmessage)
+* `request` [`http.ClientRequest`](/api/v18/http#httpclientrequest)
+* `response` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
Emitted when client receives a response.
`http.server.request.start`
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `response` [`http.ServerResponse`](/api/http#httpserverresponse)
-* `socket` [`net.Socket`](/api/net#netsocket)
-* `server` [`http.Server`](/api/http#httpserver)
+* `request` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
+* `response` [`http.ServerResponse`](/api/v18/http#httpserverresponse)
+* `socket` [`net.Socket`](/api/v18/net#netsocket)
+* `server` [`http.Server`](/api/v18/http#httpserver)
Emitted when server receives a request.
`http.server.response.finish`
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `response` [`http.ServerResponse`](/api/http#httpserverresponse)
-* `socket` [`net.Socket`](/api/net#netsocket)
-* `server` [`http.Server`](/api/http#httpserver)
+* `request` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
+* `response` [`http.ServerResponse`](/api/v18/http#httpserverresponse)
+* `socket` [`net.Socket`](/api/v18/net#netsocket)
+* `server` [`http.Server`](/api/v18/http#httpserver)
Emitted when server sends a response.
`net.client.socket`
-* `socket` [`net.Socket`](/api/net#netsocket)
+* `socket` [`net.Socket`](/api/v18/net#netsocket)
Emitted when a new TCP or pipe client socket is created.
`net.server.socket`
-* `socket` [`net.Socket`](/api/net#netsocket)
+* `socket` [`net.Socket`](/api/v18/net#netsocket)
Emitted when a new TCP or pipe connection is received.
`udp.socket`
-* `socket` [`dgram.Socket`](/api/dgram#dgramsocket)
+* `socket` [`dgram.Socket`](/api/v18/dgram#dgramsocket)
Emitted when a new UDP socket is created.
diff --git a/content/api/v18/dns.en.md b/content/api/v18/dns.en.md
index ed44e40f03..4f0ab40d10 100644
--- a/content/api/v18/dns.en.md
+++ b/content/api/v18/dns.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v18'
---
-
+
-
+
-
+Stable
+
+
+
+
The `node:dns` module enables name resolution. For example, use it to look up IP
addresses of host names.
@@ -58,7 +62,7 @@ See the [Implementation considerations section][] for more information.
### `dns.Resolver`
-
+
An independent resolver for DNS requests.
@@ -99,7 +103,7 @@ The following methods from the `node:dns` module are available:
#### `Resolver([options])`
-
+
Create a new resolver.
@@ -111,14 +115,14 @@ Create a new resolver.
#### `resolver.cancel()`
-
+
Cancel all outstanding DNS queries made by this resolver. The corresponding
callbacks will be called with an error with code `ECANCELLED`.
#### `resolver.setLocalAddress([ipv4][, ipv6])`
-
+
* `ipv4` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string representation of an IPv4 address.
**Default:** `'0.0.0.0'`
@@ -138,7 +142,7 @@ The `rrtype` of resolution requests has no impact on the local address used.
### `dns.getServers()`
-
+
* Returns: string\[]
@@ -157,7 +161,7 @@ section if a custom port is used.
### `dns.lookup(hostname[, options], callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -228,7 +232,7 @@ is not set to `true`, it returns a `Promise` for an `Object` with `address` and
#### Supported getaddrinfo flags
-
+
The following flags can be passed as hints to [`dns.lookup()`][].
@@ -243,7 +247,7 @@ The following flags can be passed as hints to [`dns.lookup()`][].
### `dns.lookupService(address, port, callback)`
-
+
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -274,7 +278,7 @@ If this method is invoked as its [`util.promisify()`][]ed version, it returns a
### `dns.resolve(hostname[, rrtype], callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `rrtype` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Resource record type. **Default:** `'A'`.
@@ -307,7 +311,7 @@ On error, `err` is an [`Error`][] object, where `err.code` is one of the
### `dns.resolve4(hostname[, options], callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -326,7 +330,7 @@ will contain an array of IPv4 addresses (e.g.
### `dns.resolve6(hostname[, options], callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -344,7 +348,7 @@ will contain an array of IPv6 addresses.
### `dns.resolveAny(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -394,7 +398,7 @@ queries. It may be better to call individual methods like [`dns.resolve4()`][],
### `dns.resolveCname(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -408,7 +412,7 @@ will contain an array of canonical name records available for the `hostname`
### `dns.resolveCaa(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -423,7 +427,7 @@ available for the `hostname` (e.g. `[{critical: 0, iodef:
### `dns.resolveMx(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -437,7 +441,7 @@ property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
### `dns.resolveNaptr(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -468,7 +472,7 @@ function will contain an array of objects with the following properties:
### `dns.resolveNs(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -482,7 +486,7 @@ contain an array of name server records available for `hostname`
### `dns.resolvePtr(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -495,7 +499,7 @@ be an array of strings containing the reply records.
### `dns.resolveSoa(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -528,7 +532,7 @@ be an object with the following properties:
### `dns.resolveSrv(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -555,7 +559,7 @@ be an array of objects with the following properties:
### `dns.resolveTxt(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -571,7 +575,7 @@ treated separately.
### `dns.reverse(ip, callback)`
-
+
* `ip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -586,7 +590,7 @@ one of the [DNS error codes][].
### `dns.setDefaultResultOrder(order)`
-
+
* `order` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) must be `'ipv4first'` or `'verbatim'`.
@@ -596,14 +600,14 @@ Set the default value of `verbatim` in [`dns.lookup()`][] and
* `ipv4first`: sets default `verbatim` `false`.
* `verbatim`: sets default `verbatim` `true`.
-The default is `ipv4first` and [`dns.setDefaultResultOrder()`][] have higher
+The default is `verbatim` and [`dns.setDefaultResultOrder()`][] have higher
priority than [`--dns-result-order`][]. When using [worker threads][],
[`dns.setDefaultResultOrder()`][] from the main thread won't affect the default
dns orders in workers.
### `dns.setServers(servers)`
-
+
* `servers` string\[] array of [RFC 5952][] formatted addresses
@@ -638,7 +642,7 @@ earlier ones time out or result in some other error.
### DNS promises API
-
+
The `dns.promises` API provides an alternative set of asynchronous DNS methods
that return `Promise` objects rather than using callbacks. The API is accessible
@@ -646,7 +650,7 @@ via `require('node:dns').promises` or `require('node:dns/promises')`.
#### `dnsPromises.Resolver`
-
+
An independent resolver for DNS requests.
@@ -692,14 +696,14 @@ The following methods from the `dnsPromises` API are available:
#### `resolver.cancel()`
-
+
Cancel all outstanding DNS queries made by this resolver. The corresponding
promises will be rejected with an error with the code `ECANCELLED`.
#### `dnsPromises.getServers()`
-
+
* Returns: string\[]
@@ -718,7 +722,7 @@ section if a custom port is used.
#### `dnsPromises.lookup(hostname[, options])`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -783,7 +787,7 @@ dnsPromises.lookup('example.com', options).then((result) => {
#### `dnsPromises.lookupService(address, port)`
-
+
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -808,7 +812,7 @@ dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
#### `dnsPromises.resolve(hostname[, rrtype])`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `rrtype` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Resource record type. **Default:** `'A'`.
@@ -838,7 +842,7 @@ is one of the [DNS error codes][].
#### `dnsPromises.resolve4(hostname[, options])`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -853,7 +857,7 @@ addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
#### `dnsPromises.resolve6(hostname[, options])`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -868,7 +872,7 @@ addresses.
#### `dnsPromises.resolveAny(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -911,7 +915,7 @@ Here is an example of the result object:
#### `dnsPromises.resolveCaa(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -923,7 +927,7 @@ certification authority authorization records available for the `hostname`
#### `dnsPromises.resolveCname(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -933,7 +937,7 @@ the `hostname` (e.g. `['bar.example.com']`).
#### `dnsPromises.resolveMx(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -944,7 +948,7 @@ containing both a `priority` and `exchange` property (e.g.
#### `dnsPromises.resolveNaptr(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -972,7 +976,7 @@ of objects with the following properties:
#### `dnsPromises.resolveNs(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -983,7 +987,7 @@ records available for `hostname` (e.g.
#### `dnsPromises.resolvePtr(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -993,7 +997,7 @@ containing the reply records.
#### `dnsPromises.resolveSoa(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1023,7 +1027,7 @@ following properties:
#### `dnsPromises.resolveSrv(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1047,7 +1051,7 @@ the following properties:
#### `dnsPromises.resolveTxt(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1060,7 +1064,7 @@ treated separately.
#### `dnsPromises.reverse(ip)`
-
+
* `ip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1072,7 +1076,7 @@ is one of the [DNS error codes][].
#### `dnsPromises.setDefaultResultOrder(order)`
-
+
* `order` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) must be `'ipv4first'` or `'verbatim'`.
@@ -1082,14 +1086,14 @@ Set the default value of `verbatim` in [`dns.lookup()`][] and
* `ipv4first`: sets default `verbatim` `false`.
* `verbatim`: sets default `verbatim` `true`.
-The default is `ipv4first` and [`dnsPromises.setDefaultResultOrder()`][] have
+The default is `verbatim` and [`dnsPromises.setDefaultResultOrder()`][] have
higher priority than [`--dns-result-order`][]. When using [worker threads][],
[`dnsPromises.setDefaultResultOrder()`][] from the main thread won't affect the
default dns orders in workers.
#### `dnsPromises.setServers(servers)`
-
+
* `servers` string\[] array of [RFC 5952][] formatted addresses
diff --git a/content/api/v18/documentation.en.md b/content/api/v18/documentation.en.md
index aee9636ca0..6d6dfcea8d 100644
--- a/content/api/v18/documentation.en.md
+++ b/content/api/v18/documentation.en.md
@@ -5,9 +5,9 @@ category: 'api'
version: 'v18'
---
-
+
-
+
Welcome to the official API reference documentation for Node.js!
@@ -20,7 +20,7 @@ Report errors in this documentation in [the issue tracker][]. See
### Stability index
-
+
Throughout the documentation are indications of a section's stability. Some APIs
are so proven and so relied upon that they are unlikely to ever change at all.
@@ -28,13 +28,29 @@ Others are brand new and experimental, or known to be hazardous.
The stability indices are as follows:
-
+
- occur in any future release. Use of the feature is not recommended in\n> production environments."}}} />
+Deprecated. The feature may emit warnings. Backward compatibility is not guaranteed.
-
+
- maintained, and other alternatives are available."}}} />
+
+
+Experimental. The feature is not subject to [semantic versioning][] rules. Non-backward compatible changes or removal may occur in any future release. Use of the feature is not recommended in production environments.
+
+
+
+
+
+Stable. Compatibility with the npm ecosystem is a high priority.
+
+
+
+
+
+Legacy. Although this feature is unlikely to be removed and is still covered by semantic versioning guarantees, it is no longer actively maintained, and other alternatives are available.
+
+
Features are marked as legacy rather than being deprecated if their use does no
harm, and they are widely relied upon within the npm ecosystem. Bugs found in
@@ -50,7 +66,7 @@ a command-line flag. Experimental features may also emit a [warning][].
### JSON output
-
+
Every `.html` document has a corresponding `.json` document. This is for IDEs
and other utilities that consume the documentation.
diff --git a/content/api/v18/domain.en.md b/content/api/v18/domain.en.md
index b418b2cb5f..622b8036e2 100644
--- a/content/api/v18/domain.en.md
+++ b/content/api/v18/domain.en.md
@@ -5,13 +5,17 @@ category: 'api'
version: 'v18'
---
-
+
-
+
-
+
-
+Deprecated
+
+
+
+
**This module is pending deprecation.** Once a replacement API has been
finalized, this module will be fully deprecated. Most developers should
@@ -29,7 +33,7 @@ exit immediately with an error code.
### Warning: Don't ignore errors!
-
+
Domain error handlers are not a substitute for closing down a
process when an error occurs.
@@ -183,7 +187,7 @@ function handleRequest(req, res) {
### Additions to `Error` objects
-
+
Any time an `Error` object is routed through a domain, a few extra fields
are added to it.
@@ -198,7 +202,7 @@ are added to it.
### Implicit binding
-
+
If domains are in use, then all **new** `EventEmitter` objects (including
Stream objects, requests, responses, etc.) will be implicitly bound to
@@ -224,7 +228,7 @@ Implicit binding only takes care of thrown errors and `'error'` events.
### Explicit binding
-
+
Sometimes, the domain in use is not the one that ought to be used for a
specific event emitter. Or, the event emitter could have been created
@@ -266,11 +270,11 @@ serverDomain.run(() => {
### `domain.create()`
-* Returns: [`Domain`](/api/domain#domain)
+* Returns: [`Domain`](/api/v18/domain#domain)
### `Domain`
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v18/events#eventemitter)
The `Domain` class encapsulates the functionality of routing errors and
uncaught exceptions to the active `Domain` object.
@@ -286,7 +290,7 @@ to the domain.
#### `domain.add(emitter)`
-* `emitter` [`EventEmitter`](/api/events#eventemitter) | [`Timer`](/api/timers#timers) emitter or timer to be added to the domain
+* `emitter` [`EventEmitter`](/api/v18/events#eventemitter) | [`Timer`](/api/v18/timers#timers) emitter or timer to be added to the domain
Explicitly adds an emitter to the domain. If any event handlers called by
the emitter throw an error, or if the emitter emits an `'error'` event, it
@@ -390,7 +394,7 @@ d.on('error', (er) => {
#### `domain.remove(emitter)`
-* `emitter` [`EventEmitter`](/api/events#eventemitter) | [`Timer`](/api/timers#timers) emitter or timer to be removed from the domain
+* `emitter` [`EventEmitter`](/api/v18/events#eventemitter) | [`Timer`](/api/v18/timers#timers) emitter or timer to be removed from the domain
The opposite of [`domain.add(emitter)`][]. Removes domain handling from the
specified emitter.
diff --git a/content/api/v18/embedding.en.md b/content/api/v18/embedding.en.md
index f76cf07273..7eaab28cfb 100644
--- a/content/api/v18/embedding.en.md
+++ b/content/api/v18/embedding.en.md
@@ -5,7 +5,7 @@ category: 'api'
version: 'v18'
---
-
+
Node.js provides a number of C++ APIs that can be used to execute JavaScript
in a Node.js environment from other C++ software.
@@ -79,7 +79,7 @@ int main(int argc, char** argv) {
#### Per-instance state
-
+
Node.js has a concept of a “Node.js instance”, that is commonly being referred
to as `node::Environment`. Each `node::Environment` is associated with:
diff --git a/content/api/v18/errors.en.md b/content/api/v18/errors.en.md
index 47c73b391b..64d920af79 100644
--- a/content/api/v18/errors.en.md
+++ b/content/api/v18/errors.en.md
@@ -5,9 +5,9 @@ category: 'api'
version: 'v18'
---
-
+
-
+
Applications running in Node.js will generally experience four categories of
errors:
@@ -28,7 +28,7 @@ to provide _at least_ the properties available on that class.
### Error propagation and interception
-
+
Node.js supports several mechanisms for propagating and handling errors that
occur while an application is running. How these errors are reported and
@@ -132,7 +132,7 @@ exactly how errors raised by those methods are propagated.
#### Error-first callbacks
-
+
Most asynchronous methods exposed by the Node.js core API follow an idiomatic
pattern referred to as an _error-first callback_. With this pattern, a callback
@@ -186,7 +186,7 @@ cases. If [domains][] are enabled, or a handler has been registered with
### `Error`
-
+
A generic JavaScript [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object that does not denote any specific
circumstance of why the error occurred. `Error` objects capture a "stack trace"
@@ -263,7 +263,7 @@ not capture any frames.
#### `error.cause`
-
+
* [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -407,14 +407,14 @@ loop tick.
### `AssertionError`
-* Extends: [`errors.Error`](/api/errors#error)
+* Extends: [`errors.Error`](/api/v18/errors#error)
Indicates the failure of an assertion. For details, see
[`Class: assert.AssertionError`][].
### `RangeError`
-* Extends: [`errors.Error`](/api/errors#error)
+* Extends: [`errors.Error`](/api/v18/errors#error)
Indicates that a provided argument was not within the set or range of
acceptable values for a function; whether that is a numeric range, or
@@ -430,7 +430,7 @@ of argument validation.
### `ReferenceError`
-* Extends: [`errors.Error`](/api/errors#error)
+* Extends: [`errors.Error`](/api/v18/errors#error)
Indicates that an attempt is being made to access a variable that is not
defined. Such errors commonly indicate typos in code, or an otherwise broken
@@ -449,7 +449,7 @@ Unless an application is dynamically generating and running code,
### `SyntaxError`
-* Extends: [`errors.Error`](/api/errors#error)
+* Extends: [`errors.Error`](/api/v18/errors#error)
Indicates that a program is not valid JavaScript. These errors may only be
generated and propagated as a result of code evaluation. Code evaluation may
@@ -469,7 +469,7 @@ they may only be caught by other contexts.
### `SystemError`
-* Extends: [`errors.Error`](/api/errors#error)
+* Extends: [`errors.Error`](/api/v18/errors#error)
Node.js generates system errors when exceptions occur within its runtime
environment. These usually occur when an application violates an operating
@@ -613,7 +613,7 @@ program. For a comprehensive list, see the [`errno`(3) man page][].
### `TypeError`
-* Extends [`errors.Error`](/api/errors#error)
+* Extends [`errors.Error`](/api/v18/errors#error)
Indicates that a provided argument is not an allowable type. For example,
passing a function to a parameter which expects a string would be a `TypeError`.
@@ -628,7 +628,7 @@ of argument validation.
### Exceptions vs. errors
-
+
A JavaScript exception is a value that is thrown as a result of an invalid
operation or as the target of a `throw` statement. While it is not required
@@ -671,7 +671,7 @@ A human-readable string describing the reason for the error.
#### `ABORT_ERR`
-
+
Used when an operation has been aborted (typically using an `AbortController`).
@@ -706,13 +706,6 @@ A special type of error that can be triggered whenever Node.js detects an
exceptional logic violation that should never occur. These are raised typically
by the `node:assert` module.
-
-
-#### `ERR_ASSERT_SNAPSHOT_NOT_SUPPORTED`
-
-An attempt was made to use `assert.snapshot()` in an environment that
-does not support snapshots, such as the REPL, or when using `node --eval`.
-
#### `ERR_ASYNC_CALLBACK`
@@ -795,7 +788,7 @@ STDERR/STDOUT, and the data's length is longer than the `maxBuffer` option.
#### `ERR_CLOSED_MESSAGE_PORT`
-
+
There was an attempt to use a `MessagePort` instance in a closed
state, usually after `.close()` has been called.
@@ -811,7 +804,7 @@ non-writable `stdout` or `stderr` stream.
#### `ERR_CONSTRUCT_CALL_INVALID`
-
+
A class constructor was called that is not callable.
@@ -902,7 +895,7 @@ The selected public or private key encoding is incompatible with other options.
#### `ERR_CRYPTO_INITIALIZATION_FAILED`
-
+
Initialization of the crypto subsystem failed.
@@ -910,7 +903,7 @@ Initialization of the crypto subsystem failed.
#### `ERR_CRYPTO_INVALID_AUTH_TAG`
-
+
An invalid authentication tag was provided.
@@ -918,7 +911,7 @@ An invalid authentication tag was provided.
#### `ERR_CRYPTO_INVALID_COUNTER`
-
+
An invalid counter was provided for a counter-mode cipher.
@@ -926,7 +919,7 @@ An invalid counter was provided for a counter-mode cipher.
#### `ERR_CRYPTO_INVALID_CURVE`
-
+
An invalid elliptic-curve was provided.
@@ -940,7 +933,7 @@ An invalid [crypto digest algorithm][] was specified.
#### `ERR_CRYPTO_INVALID_IV`
-
+
An invalid initialization vector was provided.
@@ -948,7 +941,7 @@ An invalid initialization vector was provided.
#### `ERR_CRYPTO_INVALID_JWK`
-
+
An invalid JSON Web Key was provided.
@@ -962,7 +955,7 @@ The given crypto key object's type is invalid for the attempted operation.
#### `ERR_CRYPTO_INVALID_KEYLEN`
-
+
An invalid key length was provided.
@@ -970,7 +963,7 @@ An invalid key length was provided.
#### `ERR_CRYPTO_INVALID_KEYPAIR`
-
+
An invalid key pair was provided.
@@ -978,7 +971,7 @@ An invalid key pair was provided.
#### `ERR_CRYPTO_INVALID_KEYTYPE`
-
+
An invalid key type was provided.
@@ -986,7 +979,7 @@ An invalid key type was provided.
#### `ERR_CRYPTO_INVALID_MESSAGELEN`
-
+
An invalid message length was provided.
@@ -994,7 +987,7 @@ An invalid message length was provided.
#### `ERR_CRYPTO_INVALID_SCRYPT_PARAMS`
-
+
Invalid scrypt algorithm parameters were provided.
@@ -1009,7 +1002,7 @@ instance, calling [`cipher.getAuthTag()`][] before calling `cipher.final()`.
#### `ERR_CRYPTO_INVALID_TAG_LENGTH`
-
+
An invalid authentication tag length was provided.
@@ -1017,7 +1010,7 @@ An invalid authentication tag length was provided.
#### `ERR_CRYPTO_JOB_INIT_FAILED`
-
+
Initialization of an asynchronous crypto operation failed.
@@ -1039,7 +1032,7 @@ Key's Asymmetric Key Type is not registered for use in the
#### `ERR_CRYPTO_OPERATION_FAILED`
-
+
A crypto operation failed for an otherwise unspecified reason.
@@ -1094,7 +1087,7 @@ An unknown Diffie-Hellman group name was given. See
#### `ERR_CRYPTO_UNSUPPORTED_OPERATION`
-
+
An attempt to invoke an unsupported crypto operation was made.
@@ -1102,7 +1095,7 @@ An attempt to invoke an unsupported crypto operation was made.
#### `ERR_DEBUGGER_ERROR`
-
+
An error occurred with the [debugger][].
@@ -1110,7 +1103,7 @@ An error occurred with the [debugger][].
#### `ERR_DEBUGGER_STARTUP_ERROR`
-
+
The [debugger][] timed out waiting for the required host/port to be free.
@@ -1118,7 +1111,7 @@ The [debugger][] timed out waiting for the required host/port to be free.
#### `ERR_DLOPEN_DISABLED`
-
+
Loading native addons has been disabled using [`--no-addons`][].
@@ -1126,7 +1119,7 @@ Loading native addons has been disabled using [`--no-addons`][].
#### `ERR_DLOPEN_FAILED`
-
+
A call to `process.dlopen()` failed.
@@ -1140,7 +1133,7 @@ The [`fs.Dir`][] was previously closed.
#### `ERR_DIR_CONCURRENT_OPERATION`
-
+
A synchronous read or close call was attempted on an [`fs.Dir`][] which has
ongoing asynchronous operations.
@@ -1222,7 +1215,7 @@ falsy value.
#### `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`
-
+
Used when a feature that is not available
to the current platform which is running Node.js is used.
@@ -1231,7 +1224,7 @@ to the current platform which is running Node.js is used.
#### `ERR_FS_CP_DIR_TO_NON_DIR`
-
+
An attempt was made to copy a directory to a non-directory (file, symlink,
etc.) using [`fs.cp()`][].
@@ -1240,7 +1233,7 @@ etc.) using [`fs.cp()`][].
#### `ERR_FS_CP_EEXIST`
-
+
An attempt was made to copy over a file that already existed with
[`fs.cp()`][], with the `force` and `errorOnExist` set to `true`.
@@ -1249,7 +1242,7 @@ An attempt was made to copy over a file that already existed with
#### `ERR_FS_CP_EINVAL`
-
+
When using [`fs.cp()`][], `src` or `dest` pointed to an invalid path.
@@ -1263,7 +1256,7 @@ Response body size doesn't match with the specified content-length header value.
#### `ERR_FS_CP_FIFO_PIPE`
-
+
An attempt was made to copy a named pipe with [`fs.cp()`][].
@@ -1271,7 +1264,7 @@ An attempt was made to copy a named pipe with [`fs.cp()`][].
#### `ERR_FS_CP_NON_DIR_TO_DIR`
-
+
An attempt was made to copy a non-directory (file, symlink, etc.) to a directory
using [`fs.cp()`][].
@@ -1280,7 +1273,7 @@ using [`fs.cp()`][].
#### `ERR_FS_CP_SOCKET`
-
+
An attempt was made to copy to a socket with [`fs.cp()`][].
@@ -1288,7 +1281,7 @@ An attempt was made to copy to a socket with [`fs.cp()`][].
#### `ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY`
-
+
When using [`fs.cp()`][], a symlink in `dest` pointed to a subdirectory
of `src`.
@@ -1297,7 +1290,7 @@ of `src`.
#### `ERR_FS_CP_UNKNOWN`
-
+
An attempt was made to copy to an unknown file type with [`fs.cp()`][].
@@ -1645,7 +1638,7 @@ made to mark a stream and dependent of itself.
#### `ERR_HTTP2_TOO_MANY_INVALID_FRAMES`
-
+
The limit of acceptable invalid HTTP/2 protocol frames sent by the peer,
as specified through the `maxSessionInvalidFrames` option, has been exceeded.
@@ -1682,7 +1675,7 @@ An attempt was made to construct an object using a non-public constructor.
#### `ERR_IMPORT_ASSERTION_TYPE_FAILED`
-
+
An import assertion has failed, preventing the specified module to be imported.
@@ -1690,7 +1683,7 @@ An import assertion has failed, preventing the specified module to be imported.
#### `ERR_IMPORT_ASSERTION_TYPE_MISSING`
-
+
An import assertion is missing, preventing the specified module to be imported.
@@ -1698,7 +1691,7 @@ An import assertion is missing, preventing the specified module to be imported.
#### `ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED`
-
+
An import assertion is not supported by this version of Node.js.
@@ -1713,7 +1706,11 @@ time.
#### `ERR_INPUT_TYPE_NOT_ALLOWED`
-
+
+
+Experimental
+
+
The `--input-type` flag was used to attempt to execute a file. This flag can
only be used with input via `--eval`, `--print`, or `STDIN`.
@@ -1873,11 +1870,17 @@ An invalid HTTP token was supplied.
An IP address is not valid.
+
+
+#### `ERR_INVALID_MIME_SYNTAX`
+
+The syntax of a MIME is not valid.
+
#### `ERR_INVALID_MODULE`
-
+
An attempt was made to load a module that does not exist or was otherwise not
valid.
@@ -1961,7 +1964,7 @@ type on execution, such as when a function is expected to return a promise.
#### `ERR_INVALID_STATE`
-
+
Indicates that an operation cannot be completed due to an invalid state.
For instance, an object may have already been destroyed, or may be
@@ -2062,7 +2065,7 @@ for more information.
#### `ERR_LOADER_CHAIN_INCOMPLETE`
-
+
An ESM loader hook returned without calling `next()` and without explicitly
signaling a short circuit.
@@ -2140,7 +2143,7 @@ failed.
#### `ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE`
-
+
A message posted to a [`MessagePort`][] could not be deserialized in the target
[vm][] `Context`. Not all Node.js objects can be successfully instantiated in
@@ -2188,7 +2191,7 @@ this error will not occur with standard builds of Node.js.
#### `ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST`
-
+
An object that needs to be explicitly listed in the `transferList` argument
is in the object passed to a [`postMessage()`][] call, but is not provided
@@ -2324,7 +2327,7 @@ cannot be imported through the package resolution, unless using an absolute URL.
#### `ERR_PARSE_ARGS_INVALID_OPTION_VALUE`
-
+
When `strict` set to `true`, thrown by [`util.parseArgs()`][] if a [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
value is provided for an option of type [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type), or if a [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2334,7 +2337,7 @@ value is provided for an option of type [`boolean`](https://developer.mozilla.or
#### `ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL`
-
+
Thrown by [`util.parseArgs()`][], when a positional argument is provided and
`allowPositionals` is set to `false`.
@@ -2343,7 +2346,7 @@ Thrown by [`util.parseArgs()`][], when a positional argument is provided and
#### `ERR_PARSE_ARGS_UNKNOWN_OPTION`
-
+
When `strict` set to `true`, thrown by [`util.parseArgs()`][] if an argument
is not configured in `options`.
@@ -2373,7 +2376,11 @@ object.
#### `ERR_REQUIRE_ESM`
-
+
+
+Experimental
+
+
An attempt was made to `require()` an [ES Module][].
@@ -2445,6 +2452,13 @@ could not be determined.
An attempt was made to operate on an already closed socket.
+
+
+#### `ERR_SOCKET_CLOSED_BEFORE_CONNECTION`
+
+When calling [`net.Socket.write()`][] on a connecting socket and the socket was
+closed before the connection was established.
+
#### `ERR_SOCKET_DGRAM_IS_CONNECTED`
@@ -2562,6 +2576,25 @@ An unspecified or non-specific system error has occurred within the Node.js
process. The error object will have an `err.info` object property with
additional details.
+
+
+#### `ERR_TAP_LEXER_ERROR`
+
+An error representing a failing lexer state.
+
+
+
+#### `ERR_TAP_PARSER_ERROR`
+
+An error representing a failing parser state. Additional information about
+the token causing the error is available via the `cause` property.
+
+
+
+#### `ERR_TAP_VALIDATION_ERROR`
+
+This error represents a failed TAP validation.
+
#### `ERR_TEST_FAILURE`
@@ -2606,7 +2639,7 @@ connection.
#### `ERR_TLS_INVALID_CONTEXT`
-
+
The context must be a `SecureContext`.
@@ -2627,7 +2660,7 @@ Valid TLS protocol versions are `'TLSv1'`, `'TLSv1.1'`, or `'TLSv1.2'`.
#### `ERR_TLS_INVALID_STATE`
-
+
The TLS socket must be connected and securely established. Ensure the 'secure'
event is emitted before continuing.
@@ -2649,7 +2682,8 @@ Failed to set PSK identity hint. Hint may be too long.
#### `ERR_TLS_RENEGOTIATION_DISABLED`
-An attempt was made to renegotiate TLS on a socket instance with TLS disabled.
+An attempt was made to renegotiate TLS on a socket instance with renegotiation
+disabled.
@@ -2758,7 +2792,11 @@ An invalid or unknown encoding option was passed to an API.
#### `ERR_UNKNOWN_FILE_EXTENSION`
-
+
+
+Experimental
+
+
An attempt was made to load a module with an unknown or unsupported file
extension.
@@ -2767,7 +2805,11 @@ extension.
#### `ERR_UNKNOWN_MODULE_FORMAT`
-
+
+
+Experimental
+
+
An attempt was made to load a module with an unknown or unsupported format.
@@ -2802,7 +2844,11 @@ import 'package-name'; // supported
#### `ERR_USE_AFTER_CLOSE`
-
+
+
+Experimental
+
+
An attempt was made to use something that was already closed.
@@ -2884,7 +2930,7 @@ The WASI instance has not been started.
#### `ERR_WEBASSEMBLY_RESPONSE`
-
+
The `Response` that has been passed to `WebAssembly.compileStreaming` or to
`WebAssembly.instantiateStreaming` is not a valid WebAssembly response.
@@ -2943,7 +2989,7 @@ Creation of a [`zlib`][] object failed due to incorrect configuration.
#### `HPE_HEADER_OVERFLOW`
-
+
Too much HTTP header data was received. In order to protect against malicious or
malconfigured clients, if more than 8 KiB of HTTP header data is received then
@@ -2966,20 +3012,24 @@ Use `Content-Length` or `Transfer-Encoding: chunked`.
#### `MODULE_NOT_FOUND`
-
+
A module file could not be resolved by the CommonJS modules loader while
attempting a [`require()`][] operation or when loading the program entry point.
### Legacy Node.js error codes
-
+
+
+Deprecated. These error codes are either inconsistent, or have been removed.
+
+
#### `ERR_CANNOT_TRANSFER_OBJECT`
-
+
The value passed to `postMessage()` contained an object that is not supported
for transferring.
@@ -2988,7 +3038,7 @@ for transferring.
#### `ERR_CRYPTO_HASH_DIGEST_NO_UTF16`
-
+
The UTF-16 encoding was used with [`hash.digest()`][]. While the
`hash.digest()` method does allow an `encoding` argument to be passed in,
@@ -2999,7 +3049,7 @@ encoding (e.g. `ucs` or `utf16le`) is not supported.
#### `ERR_HTTP2_FRAME_ERROR`
-
+
Used when a failure occurs sending an individual frame on the HTTP/2
session.
@@ -3008,7 +3058,7 @@ session.
#### `ERR_HTTP2_HEADERS_OBJECT`
-
+
Used when an HTTP/2 Headers Object is expected.
@@ -3016,7 +3066,7 @@ Used when an HTTP/2 Headers Object is expected.
#### `ERR_HTTP2_HEADER_REQUIRED`
-
+
Used when a required header is missing in an HTTP/2 message.
@@ -3024,7 +3074,7 @@ Used when a required header is missing in an HTTP/2 message.
#### `ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND`
-
+
HTTP/2 informational headers must only be sent _prior_ to calling the
`Http2Stream.prototype.respond()` method.
@@ -3033,7 +3083,7 @@ HTTP/2 informational headers must only be sent _prior_ to calling the
#### `ERR_HTTP2_STREAM_CLOSED`
-
+
Used when an action has been performed on an HTTP/2 Stream that has already
been closed.
@@ -3042,7 +3092,7 @@ been closed.
#### `ERR_HTTP_INVALID_CHAR`
-
+
Used when an invalid character is found in an HTTP response status message
(reason phrase).
@@ -3051,7 +3101,7 @@ Used when an invalid character is found in an HTTP response status message
#### `ERR_INDEX_OUT_OF_RANGE`
-
+
A given index was out of the accepted range (e.g. negative offsets).
@@ -3059,7 +3109,7 @@ A given index was out of the accepted range (e.g. negative offsets).
#### `ERR_INVALID_OPT_VALUE`
-
+
An invalid or unexpected value was passed in an options object.
@@ -3067,7 +3117,7 @@ An invalid or unexpected value was passed in an options object.
#### `ERR_INVALID_OPT_VALUE_ENCODING`
-
+
An invalid or unknown file encoding was passed.
@@ -3075,7 +3125,7 @@ An invalid or unknown file encoding was passed.
#### `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`
-
+
This error code was replaced by [`ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST`][]
in Node.js v15.0.0, because it is no longer accurate as other types of
@@ -3085,7 +3135,7 @@ transferable objects also exist now.
#### `ERR_NAPI_CONS_PROTOTYPE_OBJECT`
-
+
Used by the `Node-API` when `Constructor.prototype` is not an object.
@@ -3093,7 +3143,11 @@ Used by the `Node-API` when `Constructor.prototype` is not an object.
#### `ERR_NETWORK_IMPORT_BAD_RESPONSE`
-
+
+
+Experimental
+
+
Response was received but was invalid when importing a module over the network.
@@ -3101,7 +3155,11 @@ Response was received but was invalid when importing a module over the network.
#### `ERR_NETWORK_IMPORT_DISALLOWED`
-
+
+
+Experimental
+
+
A network module attempted to load another module that it is not allowed to
load. Likely this restriction is for security reasons.
@@ -3117,7 +3175,7 @@ A Node.js API was called in an unsupported manner, such as
#### `ERR_OPERATION_FAILED`
-
+
An operation failed. This is typically used to signal the general failure
of an asynchronous operation.
@@ -3126,7 +3184,7 @@ of an asynchronous operation.
#### `ERR_OUTOFMEMORY`
-
+
Used generically to identify that an operation caused an out of memory
condition.
@@ -3135,7 +3193,7 @@ condition.
#### `ERR_PARSE_HISTORY_DATA`
-
+
The `node:repl` module was unable to parse data from the REPL history file.
@@ -3143,7 +3201,7 @@ The `node:repl` module was unable to parse data from the REPL history file.
#### `ERR_SOCKET_CANNOT_SEND`
-
+
Data could not be sent on a socket.
@@ -3151,7 +3209,7 @@ Data could not be sent on a socket.
#### `ERR_STDERR_CLOSE`
-
+
An attempt was made to close the `process.stderr` stream. By design, Node.js
does not allow `stdout` or `stderr` streams to be closed by user code.
@@ -3160,7 +3218,7 @@ does not allow `stdout` or `stderr` streams to be closed by user code.
#### `ERR_STDOUT_CLOSE`
-
+
An attempt was made to close the `process.stdout` stream. By design, Node.js
does not allow `stdout` or `stderr` streams to be closed by user code.
@@ -3169,7 +3227,7 @@ does not allow `stdout` or `stderr` streams to be closed by user code.
#### `ERR_STREAM_READ_NOT_IMPLEMENTED`
-
+
Used when an attempt is made to use a readable stream that has not implemented
[`readable._read()`][].
@@ -3178,7 +3236,7 @@ Used when an attempt is made to use a readable stream that has not implemented
#### `ERR_TLS_RENEGOTIATION_FAILED`
-
+
Used when a TLS renegotiation request has failed in a non-specific way.
@@ -3186,7 +3244,7 @@ Used when a TLS renegotiation request has failed in a non-specific way.
#### `ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER`
-
+
A `SharedArrayBuffer` whose memory is not managed by the JavaScript engine
or by Node.js was encountered during serialization. Such a `SharedArrayBuffer`
@@ -3199,7 +3257,7 @@ This can only happen when native addons create `SharedArrayBuffer`s in
#### `ERR_UNKNOWN_STDIN_TYPE`
-
+
An attempt was made to launch a Node.js process with an unknown `stdin` file
type. This error is usually an indication of a bug within Node.js itself,
@@ -3209,7 +3267,7 @@ although it is possible for user code to trigger it.
#### `ERR_UNKNOWN_STREAM_TYPE`
-
+
An attempt was made to launch a Node.js process with an unknown `stdout` or
`stderr` file type. This error is usually an indication of a bug within Node.js
@@ -3225,7 +3283,7 @@ The V8 `BreakIterator` API was used but the full ICU data set is not installed.
#### `ERR_VALUE_OUT_OF_RANGE`
-
+
Used when a given value is out of the accepted range.
@@ -3239,7 +3297,7 @@ The module must be successfully linked before instantiation.
#### `ERR_VM_MODULE_LINKING_ERRORED`
-
+
The linker function returned a module for which linking has failed.
@@ -3247,7 +3305,7 @@ The linker function returned a module for which linking has failed.
#### `ERR_WORKER_UNSUPPORTED_EXTENSION`
-
+
The pathname used for the main script of a worker has an
unknown file extension.
@@ -3256,7 +3314,7 @@ unknown file extension.
#### `ERR_ZLIB_BINDING_CLOSED`
-
+
Used when an attempt is made to use a `zlib` object after it has already been
closed.
@@ -3265,7 +3323,7 @@ closed.
#### `ERR_CPU_USAGE`
-
+
The native call from `process.cpuUsage` could not be processed.
@@ -3319,6 +3377,7 @@ The native call from `process.cpuUsage` could not be processed.
[`http`]: /api/v18/http
[`https`]: /api/v18/https
[`libuv Error handling`]: https://docs.libuv.org/en/v1.x/errors.html
+[`net.Socket.write()`]: /api/v18/net#socketwritedata-encoding-callback
[`net`]: /api/v18/net
[`new URL(input)`]: /api/v18/url#new-urlinput-base
[`new URLSearchParams(iterable)`]: /api/v18/url#new-urlsearchparamsiterable
diff --git a/content/api/v18/esm.en.md b/content/api/v18/esm.en.md
index d0f9ca872b..733d4776d6 100644
--- a/content/api/v18/esm.en.md
+++ b/content/api/v18/esm.en.md
@@ -5,17 +5,21 @@ category: 'api'
version: 'v18'
---
-
+
-
+
-
+
-
+
+
+Stable
+
+
### Introduction
-
+
ECMAScript modules are [the official standard format][] to package JavaScript
code for reuse. Modules are defined using a variety of [`import`][] and
@@ -50,7 +54,7 @@ provides interoperability between them and its original module format,
### Enabling
-
+
Node.js has two module systems: [CommonJS][] modules and ECMAScript modules.
@@ -135,7 +139,7 @@ details), it is recommended to use [url.pathToFileURL][] when importing a path.
##### `data:` imports
-
+
[`data:` URLs][] are supported for importing with the following MIME types:
@@ -157,7 +161,7 @@ is no concept of relative resolution for `data:` URLs.
##### `node:` imports
-
+
`node:` URLs are supported as an alternative means to load Node.js builtin
modules. This URL scheme allows for builtin modules to be referenced by valid
@@ -169,9 +173,13 @@ import fs from 'node:fs/promises';
### Import assertions
-
+
+
+
-
+Experimental
+
+
The [Import Assertions proposal][] adds an inline syntax for module import
statements to pass on more information alongside the module specifier.
@@ -198,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) {
@@ -253,15 +259,19 @@ const buffer = readFileSync(new URL('./data.proto', import.meta.url));
#### `import.meta.resolve(specifier[, parent])`
-
+
+
+
-
+Experimental
+
+
This feature is only available with the `--experimental-import-meta-resolve`
command flag enabled.
* `specifier` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The module specifier to resolve relative to `parent`.
-* `parent` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) The absolute parent module URL to resolve from. If none
+* `parent` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api) The absolute parent module URL to resolve from. If none
is specified, the value of `import.meta.url` is used as the default.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
@@ -399,9 +409,9 @@ These CommonJS variables are not available in ES modules.
`__filename` and `__dirname` use cases can be replicated via
[`import.meta.url`][].
-##### No Native Module Loading
+##### No Addon Loading
-Native modules are not currently supported with ES module imports.
+[Addons][] are not currently supported with ES module imports.
They can instead be loaded with [`module.createRequire()`][] or
[`process.dlopen`][].
@@ -434,7 +444,11 @@ separate cache.
### JSON modules
-
+
+
+Experimental
+
+
JSON files can be referenced by `import`:
@@ -453,7 +467,11 @@ imported from the same path.
### Wasm modules
-
+
+
+Experimental
+
+
Importing WebAssembly modules is supported under the
`--experimental-wasm-modules` flag, allowing any `.wasm` files to be
@@ -481,7 +499,7 @@ would provide the exports interface for the instantiation of `module.wasm`.
### Top-level `await`
-
+
The `await` keyword may be used in the top level body of an ECMAScript module.
@@ -493,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
```
@@ -522,7 +538,11 @@ spawn(execPath, [
### HTTPS and HTTP imports
-
+
+
+Experimental
+
+
Importing network based modules using `https:` and `http:` is supported under
the `--experimental-network-imports` flag. This allows web browser-like imports
@@ -559,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) {
@@ -589,13 +607,17 @@ of Node.js applications.
### Loaders
-
+
+
+
-
+Experimental
+
+
> This API is currently being redesigned and will still change.
-
+
To customize the default module resolution, loader hooks can optionally be
provided via a `--experimental-loader ./loader-name.mjs` argument to Node.js.
@@ -630,7 +652,7 @@ prevent unintentional breaks in the chain.
##### `resolve(specifier, context, nextResolve)`
-
+
> The loaders API is being redesigned. This hook may disappear or its
> signature may change. Do not rely on the API described below.
@@ -710,7 +732,7 @@ export async function resolve(specifier, context, nextResolve) {
##### `load(url, context, nextLoad)`
-
+
> The loaders API is being redesigned. This hook may disappear or its
> signature may change. Do not rely on the API described below.
@@ -801,7 +823,7 @@ source to a supported one (see [Examples](#examples) below).
##### `globalPreload()`
-
+
> The loaders API is being redesigned. This hook may disappear or its
> signature may change. Do not rely on the API described below.
@@ -810,7 +832,7 @@ source to a supported one (see [Examples](#examples) below).
> `getGlobalPreloadCode`.
* `context` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Information to assist the preload code
- * `port` [`MessagePort`](/api/worker_threads#messageport)
+ * `port` [`MessagePort`](/api/v18/worker_threads#messageport)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Code to run before application startup
Sometimes it might be necessary to run some code inside of the same global
@@ -880,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';
@@ -893,7 +915,7 @@ export function resolve(specifier, context, nextResolve) {
if (specifier.startsWith('https://')) {
return {
shortCircuit: true,
- url: specifier
+ url: specifier,
};
} else if (parentURL && parentURL.startsWith('https://')) {
return {
@@ -928,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';
@@ -953,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';
@@ -974,7 +994,7 @@ export async function resolve(specifier, context, nextResolve) {
// specifiers ending in the CoffeeScript file extensions.
return {
shortCircuit: true,
- url: new URL(specifier, parentURL).href
+ url: new URL(specifier, parentURL).href,
};
}
@@ -995,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
@@ -1051,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'
@@ -1387,7 +1405,11 @@ _isImports_, _conditions_)
#### Customizing ESM specifier resolution algorithm
-
+
+
+Experimental
+
+
> Do not rely on this flag. We plan to remove it once the
> [Loaders API][] has advanced to the point that equivalent functionality can
@@ -1413,9 +1435,10 @@ $ node --experimental-specifier-resolution=node index
success!
```
-
+
[6.1.7 Array Index]: https://tc39.es/ecma262/#integer-index
+[Addons]: /api/v18/addons
[CommonJS]: /api/v18/modules
[Conditional exports]: /api/v18/packages#conditional-exports
[Core modules]: /api/v18/modules#core-modules
diff --git a/content/api/v18/events.en.md b/content/api/v18/events.en.md
index 4836414623..4b53b06bd4 100644
--- a/content/api/v18/events.en.md
+++ b/content/api/v18/events.en.md
@@ -5,13 +5,17 @@ category: 'api'
version: 'v18'
---
-
+
-
+
-
+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")
@@ -35,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 {}
@@ -45,9 +49,7 @@ myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
@@ -67,16 +69,34 @@ an ordinary listener function is called, the standard `this` keyword
is intentionally set to reference the `EventEmitter` instance to which the
listener is attached.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+myEmitter.on('event', function(a, b) {
+ console.log(a, b, this, this === myEmitter);
+ // Prints:
+ // a b MyEmitter {
+ // _events: [Object: null prototype] { event: [Function (anonymous)] },
+ // _eventsCount: 1,
+ // _maxListeners: undefined,
+ // [Symbol(kCapture)]: false
+ // } true
+});
+myEmitter.emit('event', 'a', 'b');
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
console.log(a, b, this, this === myEmitter);
// Prints:
// a b MyEmitter {
- // domain: null,
- // _events: { event: [Function] },
+ // _events: [Object: null prototype] { event: [Function (anonymous)] },
// _eventsCount: 1,
- // _maxListeners: undefined } true
+ // _maxListeners: undefined,
+ // [Symbol(kCapture)]: false
+ // } true
});
myEmitter.emit('event', 'a', 'b');
```
@@ -84,7 +104,18 @@ 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:
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+myEmitter.on('event', (a, b) => {
+ console.log(a, b, this);
+ // Prints: a b {}
+});
+myEmitter.emit('event', 'a', 'b');
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
console.log(a, b, this);
@@ -101,7 +132,19 @@ 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:
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+myEmitter.on('event', (a, b) => {
+ setImmediate(() => {
+ console.log('this happens asynchronously');
+ });
+});
+myEmitter.emit('event', 'a', 'b');
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
setImmediate(() => {
@@ -116,7 +159,21 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+let m = 0;
+myEmitter.on('event', () => {
+ console.log(++m);
+});
+myEmitter.emit('event');
+// Prints: 1
+myEmitter.emit('event');
+// Prints: 2
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
let m = 0;
myEmitter.on('event', () => {
@@ -132,7 +189,21 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+let m = 0;
+myEmitter.once('event', () => {
+ console.log(++m);
+});
+myEmitter.emit('event');
+// Prints: 1
+myEmitter.emit('event');
+// Ignored
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
let m = 0;
myEmitter.once('event', () => {
@@ -154,7 +225,15 @@ 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.
-```js
+```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
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// Throws and crashes Node.js
@@ -165,7 +244,18 @@ used. (Note, however, that the `node:domain` module is deprecated.)
As a best practice, listeners should always be added for the `'error'` events.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+myEmitter.on('error', (err) => {
+ console.error('whoops! there was an error');
+});
+myEmitter.emit('error', new Error('whoops!'));
+// Prints: whoops! there was an error
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('error', (err) => {
console.error('whoops! there was an error');
@@ -177,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();
@@ -186,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();
@@ -204,7 +292,14 @@ 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:
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const ee = new EventEmitter();
+ee.on('something', async (value) => {
+ throw new Error('kaboom');
+});
+--------------
+const EventEmitter = require('node:events');
const ee = new EventEmitter();
ee.on('something', async (value) => {
throw new Error('kaboom');
@@ -217,7 +312,23 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const ee1 = new EventEmitter({ captureRejections: true });
+ee1.on('something', async (value) => {
+ throw new Error('kaboom');
+});
+
+ee1.on('error', console.log);
+
+const ee2 = new EventEmitter({ captureRejections: true });
+ee2.on('something', async (value) => {
+ throw new Error('kaboom');
+});
+
+ee2[Symbol.for('nodejs.rejection')] = console.log;
+--------------
+const EventEmitter = require('node:events');
const ee1 = new EventEmitter({ captureRejections: true });
ee1.on('something', async (value) => {
throw new Error('kaboom');
@@ -236,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;
@@ -246,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();
@@ -265,15 +374,13 @@ recommendation is to **not use `async` functions as `'error'` event handlers**.
### `EventEmitter`
-
+
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');
```
@@ -288,7 +395,7 @@ It supports the following option:
#### `'newListener'`
-
+
* `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
@@ -304,7 +411,29 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+
+const myEmitter = new MyEmitter();
+// Only do this once so we don't loop forever
+myEmitter.once('newListener', (event, listener) => {
+ if (event === 'event') {
+ // Insert a new listener in front
+ myEmitter.on('event', () => {
+ console.log('B');
+ });
+ }
+});
+myEmitter.on('event', () => {
+ console.log('A');
+});
+myEmitter.emit('event');
+// Prints:
+// B
+// A
+--------------
+const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -328,7 +457,7 @@ myEmitter.emit('event');
#### `'removeListener'`
-
+
* `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 event name
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The event handler function
@@ -337,7 +466,7 @@ The `'removeListener'` event is emitted _after_ the `listener` is removed.
#### `emitter.addListener(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)
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -346,7 +475,7 @@ Alias for `emitter.on(eventName, listener)`.
#### `emitter.emit(eventName[, ...args])`
-
+
* `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)
* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -358,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();
@@ -389,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();
@@ -426,14 +553,14 @@ myEmitter.emit('event', 1, 2, 3, 4, 5);
#### `emitter.eventNames()`
-
+
* Returns: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
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();
@@ -445,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();
@@ -463,7 +588,7 @@ console.log(myEE.eventNames());
#### `emitter.getMaxListeners()`
-
+
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -471,18 +596,21 @@ 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)`
-
+
* `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)
* Returns: Function\[]
@@ -499,21 +627,21 @@ console.log(util.inspect(server.listeners('connection')));
#### `emitter.off(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)
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v18/events#eventemitter)
Alias for [`emitter.removeListener()`][].
#### `emitter.on(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.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v18/events#eventemitter)
Adds the `listener` function to the end of the listeners array for the
event named `eventName`. No checks are made to see if the `listener` has
@@ -533,7 +661,17 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const myEE = new EventEmitter();
+myEE.on('foo', () => console.log('a'));
+myEE.prependListener('foo', () => console.log('b'));
+myEE.emit('foo');
+// Prints:
+// b
+// a
+--------------
+const EventEmitter = require('node:events');
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
@@ -545,11 +683,11 @@ myEE.emit('foo');
#### `emitter.once(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.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v18/events#eventemitter)
Adds a **one-time** `listener` function for the event named `eventName`. The
next time `eventName` is triggered, this listener is removed and then invoked.
@@ -566,7 +704,17 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const myEE = new EventEmitter();
+myEE.once('foo', () => console.log('a'));
+myEE.prependOnceListener('foo', () => console.log('b'));
+myEE.emit('foo');
+// Prints:
+// b
+// a
+--------------
+const EventEmitter = require('node:events');
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
@@ -578,11 +726,11 @@ myEE.emit('foo');
#### `emitter.prependListener(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.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v18/events#eventemitter)
Adds the `listener` function to the _beginning_ of the listeners array for the
event named `eventName`. No checks are made to see if the `listener` has
@@ -600,11 +748,11 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
#### `emitter.prependOnceListener(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.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v18/events#eventemitter)
Adds a **one-time** `listener` function for the event named `eventName` to the
_beginning_ of the listeners array. The next time `eventName` is triggered, this
@@ -620,10 +768,10 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
#### `emitter.removeAllListeners([eventName])`
-
+
* `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)
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v18/events#eventemitter)
Removes all listeners, or those of the specified `eventName`.
@@ -635,11 +783,11 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
#### `emitter.removeListener(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)
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v18/events#eventemitter)
Removes the specified `listener` from the listener array for the event named
`eventName`.
@@ -664,7 +812,39 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+
+const callbackA = () => {
+ console.log('A');
+ myEmitter.removeListener('event', callbackB);
+};
+
+const callbackB = () => {
+ console.log('B');
+};
+
+myEmitter.on('event', callbackA);
+
+myEmitter.on('event', callbackB);
+
+// callbackA removes listener callbackB but it will still be called.
+// Internal listener array at time of emit [callbackA, callbackB]
+myEmitter.emit('event');
+// Prints:
+// A
+// B
+
+// callbackB is now removed.
+// Internal listener array [callbackA]
+myEmitter.emit('event');
+// Prints:
+// A
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
@@ -705,7 +885,22 @@ event (as in the example below), `removeListener()` will remove the most
recently added instance. In the example the `once('ping')`
listener is removed:
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const ee = new EventEmitter();
+
+function pong() {
+ console.log('pong');
+}
+
+ee.on('ping', pong);
+ee.once('ping', pong);
+ee.removeListener('ping', pong);
+
+ee.emit('ping');
+ee.emit('ping');
+--------------
+const EventEmitter = require('node:events');
const ee = new EventEmitter();
function pong() {
@@ -724,10 +919,10 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
#### `emitter.setMaxListeners(n)`
-
+
* `n` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v18/events#eventemitter)
By default `EventEmitter`s will print a warning if more than `10` listeners are
added for a particular event. This is a useful default that helps finding
@@ -739,7 +934,7 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
#### `emitter.rawListeners(eventName)`
-
+
* `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)
* Returns: Function\[]
@@ -747,7 +942,31 @@ 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()`).
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const emitter = new EventEmitter();
+emitter.once('log', () => console.log('log once'));
+
+// Returns a new Array with a function `onceWrapper` which has a property
+// `listener` which contains the original listener bound above
+const listeners = emitter.rawListeners('log');
+const logFnWrapper = listeners[0];
+
+// Logs "log once" to the console and does not unbind the `once` event
+logFnWrapper.listener();
+
+// Logs "log once" to the console and removes the listener
+logFnWrapper();
+
+emitter.on('log', () => console.log('log persistently'));
+// Will return a new Array with a single function bound by `.on()` above
+const newListeners = emitter.rawListeners('log');
+
+// Logs "log persistently" twice
+newListeners[0]();
+emitter.emit('log');
+--------------
+const EventEmitter = require('node:events');
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
@@ -773,7 +992,7 @@ emitter.emit('log');
#### `emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`
-
+
* `err` Error
* `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)
@@ -785,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 {
@@ -802,9 +1021,7 @@ class MyClass extends EventEmitter {
// Tear the resource down here.
}
}
-```
-
-```cjs
+--------------
const { EventEmitter, captureRejectionSymbol } = require('node:events');
class MyClass extends EventEmitter {
@@ -825,7 +1042,7 @@ class MyClass extends EventEmitter {
### `events.defaultMaxListeners`
-
+
By default, a maximum of `10` listeners can be registered for any single
event. This limit can be changed for individual `EventEmitter` instances
@@ -845,7 +1062,17 @@ 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:
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const emitter = new EventEmitter();
+emitter.setMaxListeners(emitter.getMaxListeners() + 1);
+emitter.once('event', () => {
+ // do stuff
+ emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
+});
+--------------
+const EventEmitter = require('node:events');
+const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
@@ -864,7 +1091,7 @@ Its `name` property is set to `'MaxListenersExceededWarning'`.
### `events.errorMonitor`
-
+
This symbol shall be used to install a listener for only monitoring `'error'`
events. Listeners installed using this symbol are called before the regular
@@ -876,9 +1103,9 @@ regular `'error'` listener is installed.
### `events.getEventListeners(emitterOrTarget, eventName)`
-
+
-* `emitterOrTarget` [`EventEmitter`](/api/events#eventemitter) | [`EventTarget`](/api/events#eventtarget)
+* `emitterOrTarget` [`EventEmitter`](/api/v18/events#eventemitter) | [`EventTarget`](/api/v18/events#eventtarget)
* `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)
* Returns: Function\[]
@@ -890,48 +1117,46 @@ 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] ]
}
```
### `events.once(emitter, name[, options])`
-
+
-* `emitter` [`EventEmitter`](/api/events#eventemitter)
+* `emitter` [`EventEmitter`](/api/v18/events#eventemitter)
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Can be used to cancel waiting for the event.
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) Can be used to cancel waiting for the event.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
@@ -943,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';
@@ -964,11 +1189,9 @@ process.nextTick(() => {
try {
await once(ee, 'myevent');
} catch (err) {
- console.log('error happened', err);
+ console.error('error happened', err);
}
-```
-
-```cjs
+--------------
const { once, EventEmitter } = require('node:events');
async function run() {
@@ -989,7 +1212,7 @@ async function run() {
try {
await once(ee, 'myevent');
} catch (err) {
- console.log('error happened', err);
+ console.error('error happened', err);
}
}
@@ -1001,37 +1224,35 @@ 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();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
- .catch((err) => console.log('error', err.message));
+ .catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
- .catch((err) => console.log('error', err.message));
+ .catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
```
-An [`AbortSignal`](/api/globals#abortsignal) can be used to cancel waiting for the event:
+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();
@@ -1053,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();
@@ -1088,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';
@@ -1110,9 +1329,7 @@ process.nextTick(() => {
});
foo().then(() => console.log('done'));
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const myEE = new EventEmitter();
@@ -1139,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';
@@ -1156,9 +1373,7 @@ process.nextTick(() => {
});
foo().then(() => console.log('done'));
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const myEE = new EventEmitter();
@@ -1178,7 +1393,7 @@ foo().then(() => console.log('done'));
### `events.captureRejections`
-
+
Value: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1186,7 +1401,7 @@ Change the default `captureRejections` option on all new `EventEmitter` objects.
### `events.captureRejectionSymbol`
-
+
Value: `Symbol.for('nodejs.rejection')`
@@ -1194,17 +1409,21 @@ See how to write a custom [rejection handler][rejection].
### `events.listenerCount(emitter, eventName)`
-
+
-
+
-* `emitter` [`EventEmitter`](/api/events#eventemitter) The emitter to query
+Deprecated: Use [`emitter.listenerCount()`][] instead.
+
+
+
+* `emitter` [`EventEmitter`](/api/v18/events#eventemitter) The emitter to query
* `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 event name
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();
@@ -1212,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();
@@ -1226,15 +1443,15 @@ console.log(listenerCount(myEmitter, 'event'));
### `events.on(emitter, eventName[, options])`
-
+
-* `emitter` [`EventEmitter`](/api/events#eventemitter)
+* `emitter` [`EventEmitter`](/api/v18/events#eventemitter)
* `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
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Can be used to cancel awaiting events.
+ * `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';
@@ -1253,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 () => {
@@ -1282,9 +1497,9 @@ if the `EventEmitter` emits `'error'`. It removes all listeners when
exiting the loop. The `value` returned by each iteration is an array
composed of the emitted event arguments.
-An [`AbortSignal`](/api/globals#abortsignal) can be used to cancel waiting on events:
+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';
@@ -1309,9 +1524,7 @@ const ac = new AbortController();
})();
process.nextTick(() => ac.abort());
-```
-
-```cjs
+--------------
const { on, EventEmitter } = require('node:events');
const ac = new AbortController();
@@ -1339,27 +1552,25 @@ process.nextTick(() => ac.abort());
### `events.setMaxListeners(n[, ...eventTargets])`
-
+
* `n` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A non-negative number. The maximum number of listeners per
`EventTarget` event.
-* `...eventsTargets` EventTarget\[]|EventEmitter\[] Zero or more [`EventTarget`](/api/events#eventtarget)
- or [`EventEmitter`](/api/events#eventemitter) instances. If none are specified, `n` is set as the default
- max for all newly created [`EventTarget`](/api/events#eventtarget) and [`EventEmitter`](/api/events#eventemitter) objects.
+* `...eventsTargets` EventTarget\[]|EventEmitter\[] Zero or more [`EventTarget`](/api/v18/events#eventtarget)
+ 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
+ EventEmitter,
} = require('node:events');
const target = new EventTarget();
@@ -1370,13 +1581,13 @@ setMaxListeners(5, target, emitter);
### `events.EventEmitterAsyncResource extends EventEmitter`
-
+
-Integrates `EventEmitter` with [`AsyncResource`](/api/async_hooks#asyncresource) for `EventEmitter`s that
+Integrates `EventEmitter` with [`AsyncResource`](/api/v18/async_hooks#asyncresource) for `EventEmitter`s that
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';
@@ -1403,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');
@@ -1437,7 +1646,7 @@ Promise.resolve().then(() => {
The `EventEmitterAsyncResource` class has the same methods and takes the
same options as `EventEmitter` and `AsyncResource` themselves.
-#### `new events.EventEmitterAsyncResource(options)`
+#### `new events.EventEmitterAsyncResource([options])`
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `captureRejections` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) It enables
@@ -1461,7 +1670,7 @@ same options as `EventEmitter` and `AsyncResource` themselves.
#### `eventemitterasyncresource.asyncResource`
-* Type: The underlying [`AsyncResource`](/api/async_hooks#asyncresource).
+* Type: The underlying [`AsyncResource`](/api/v18/async_hooks#asyncresource).
The returned `AsyncResource` object has an additional `eventEmitter` property
that provides a reference to this `EventEmitterAsyncResource`.
@@ -1482,7 +1691,7 @@ never be called.
### `EventTarget` and `Event` API
-
+
The `EventTarget` and `Event` objects are a Node.js-specific implementation
of the [`EventTarget` Web API][] that are exposed by some Node.js core APIs.
@@ -1522,9 +1731,8 @@ and cannot be used in place of an `EventEmitter` in most cases.
ignored.
2. The `NodeEventTarget` does not emulate the full `EventEmitter` API.
Specifically the `prependListener()`, `prependOnceListener()`,
- `rawListeners()`, `setMaxListeners()`, `getMaxListeners()`, and
- `errorMonitor` APIs are not emulated. The `'newListener'` and
- `'removeListener'` events will also not be emitted.
+ `rawListeners()`, and `errorMonitor` APIs are not emulated.
+ The `'newListener'` and `'removeListener'` events will also not be emitted.
3. The `NodeEventTarget` does not implement any special default behavior
for events with type `'error'`.
4. The `NodeEventTarget` supports `EventListener` objects as well as
@@ -1565,13 +1773,13 @@ async function handler2(event) {
const handler3 = {
handleEvent(event) {
console.log(event.type); // Prints 'foo'
- }
+ },
};
const handler4 = {
async handleEvent(event) {
console.log(event.type); // Prints 'foo'
- }
+ },
};
const target = new EventTarget();
@@ -1603,35 +1811,43 @@ be aligned with the new behavior.
#### `Event`
-
+
The `Event` object is an adaptation of the [`Event` Web API][]. Instances
are created internally by Node.js.
##### `event.bubbles`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Always returns `false`.
This is not used in Node.js and is provided purely for completeness.
-##### `event.cancelBubble()`
+##### `event.cancelBubble`
-
+
-Alias for `event.stopPropagation()`. This is not used in Node.js and is
-provided purely for completeness.
+
+
+Legacy: Use [`event.stopPropagation()`][] instead.
+
+
+
+* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+Alias for `event.stopPropagation()` if set to `true`. This is not used
+in Node.js and is provided purely for completeness.
##### `event.cancelable`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True if the event was created with the `cancelable` option.
##### `event.composed`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Always returns `false`.
@@ -1639,7 +1855,7 @@ This is not used in Node.js and is provided purely for completeness.
##### `event.composedPath()`
-
+
Returns an array containing the current `EventTarget` as the only entry or
empty if the event is not being dispatched. This is not used in
@@ -1647,15 +1863,15 @@ Node.js and is provided purely for completeness.
##### `event.currentTarget`
-
+
-* Type: [`EventTarget`](/api/events#eventtarget) The `EventTarget` dispatching the event.
+* Type: [`EventTarget`](/api/v18/events#eventtarget) The `EventTarget` dispatching the event.
Alias for `event.target`.
##### `event.defaultPrevented`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1664,7 +1880,7 @@ called.
##### `event.eventPhase`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns `0` while an event is not being dispatched, `2` while
it is being dispatched.
@@ -1673,56 +1889,69 @@ This is not used in Node.js and is provided purely for completeness.
##### `event.isTrusted`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-The [`AbortSignal`](/api/globals#abortsignal) `"abort"` event is emitted with `isTrusted` set to `true`. The
+The [`AbortSignal`](/api/v18/globals#abortsignal) `"abort"` event is emitted with `isTrusted` set to `true`. The
value is `false` in all other cases.
##### `event.preventDefault()`
-
+
Sets the `defaultPrevented` property to `true` if `cancelable` is `true`.
##### `event.returnValue`
-
+
+
+
+
+Legacy: Use [`event.defaultPrevented`][] instead.
+
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True if the event has not been canceled.
+The value of `event.returnValue` is always the opposite of `event.defaultPrevented`.
This is not used in Node.js and is provided purely for completeness.
##### `event.srcElement`
-
+
+
+
+
+Legacy: Use [`event.target`][] instead.
-* Type: [`EventTarget`](/api/events#eventtarget) The `EventTarget` dispatching the event.
+
+
+* Type: [`EventTarget`](/api/v18/events#eventtarget) The `EventTarget` dispatching the event.
Alias for `event.target`.
##### `event.stopImmediatePropagation()`
-
+
Stops the invocation of event listeners after the current one completes.
##### `event.stopPropagation()`
-
+
This is not used in Node.js and is provided purely for completeness.
##### `event.target`
-
+
-* Type: [`EventTarget`](/api/events#eventtarget) The `EventTarget` dispatching the event.
+* Type: [`EventTarget`](/api/v18/events#eventtarget) The `EventTarget` dispatching the event.
##### `event.timeStamp`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1730,7 +1959,7 @@ The millisecond timestamp when the `Event` object was created.
##### `event.type`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1738,14 +1967,14 @@ The event type identifier.
#### `EventTarget`
-
+
##### `eventTarget.addEventListener(type, listener[, options])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v18/events#listener)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `once` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, the listener is automatically removed
when it is first invoked. **Default:** `false`.
@@ -1754,7 +1983,7 @@ The event type identifier.
**Default:** `false`.
* `capture` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Not directly used by Node.js. Added for API
completeness. **Default:** `false`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) The listener will be removed when the given
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) The listener will be removed when the given
AbortSignal object's `abort()` method is called.
Adds a new handler for the `type` event. Any given `listener` is added
@@ -1785,9 +2014,9 @@ target.removeEventListener('foo', handler, { capture: true });
##### `eventTarget.dispatchEvent(event)`
-
+
-* `event` [`Event`](/api/events#event)
+* `event` [`Event`](/api/v18/events#event)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if either event's `cancelable` attribute value is
false or its `preventDefault()` method was not invoked, otherwise `false`.
@@ -1796,12 +2025,12 @@ Dispatches the `event` to the list of handlers for `event.type`.
The registered event listeners is synchronously invoked in the order they
were registered.
-##### `eventTarget.removeEventListener(type, listener)`
+##### `eventTarget.removeEventListener(type, listener[, options])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v18/events#listener)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `capture` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1809,20 +2038,28 @@ Removes the `listener` from the list of handlers for event `type`.
#### `CustomEvent`
-
+
+
+
+
+Experimental.
-
+
-* Extends: [`Event`](/api/events#event)
+* Extends: [`Event`](/api/v18/events#event)
The `CustomEvent` object is an adaptation of the [`CustomEvent` Web API][].
Instances are created internally by Node.js.
##### `event.detail`
-
+
+
+
+
+Experimental.
-
+
* Type: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Returns custom data passed when initializing.
@@ -1830,34 +2067,43 @@ Read-only.
#### `NodeEventTarget`
-
+
-* Extends: [`EventTarget`](/api/events#eventtarget)
+* Extends: [`EventTarget`](/api/v18/events#eventtarget)
The `NodeEventTarget` is a Node.js-specific extension to `EventTarget`
that emulates a subset of the `EventEmitter` API.
-##### `nodeEventTarget.addListener(type, listener[, options])`
+##### `nodeEventTarget.addListener(type, listener)`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v18/events#listener)
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `once` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+* Returns: [`EventTarget`](/api/v18/events#eventtarget) this
Node.js-specific extension to the `EventTarget` class that emulates the
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()`
-
+
* Returns: string\[]
@@ -1866,7 +2112,7 @@ of event `type` names for which event listeners are registered.
##### `nodeEventTarget.listenerCount(type)`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1875,44 +2121,60 @@ of event `type` names for which event listeners are registered.
Node.js-specific extension to the `EventTarget` class that returns the number
of event listeners registered for the `type`.
-##### `nodeEventTarget.off(type, listener)`
+##### `nodeEventTarget.setMaxListeners(n)`
-
+
-* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `n` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Node.js-specific extension to the `EventTarget` class that sets the number
+of max event listeners as `n`.
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+##### `nodeEventTarget.getMaxListeners()`
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+
-Node.js-specific alias for `eventTarget.removeListener()`.
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Node.js-specific extension to the `EventTarget` class that returns the number
+of max event listeners.
-##### `nodeEventTarget.on(type, listener[, options])`
+##### `nodeEventTarget.off(type, listener[, options])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v18/events#listener)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `once` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+ * `capture` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+* Returns: [`EventTarget`](/api/v18/events#eventtarget) this
-Node.js-specific alias for `eventTarget.addListener()`.
+Node.js-specific alias for `eventTarget.removeEventListener()`.
-##### `nodeEventTarget.once(type, listener[, options])`
+##### `nodeEventTarget.on(type, listener)`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v18/events#listener)
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+* Returns: [`EventTarget`](/api/v18/events#eventtarget) this
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+Node.js-specific alias for `eventTarget.addEventListener()`.
+
+##### `nodeEventTarget.once(type, listener)`
+
+
+
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v18/events#listener)
+
+* Returns: [`EventTarget`](/api/v18/events#eventtarget) this
Node.js-specific extension to the `EventTarget` class that adds a `once`
listener for the given event `type`. This is equivalent to calling `on`
@@ -1920,25 +2182,28 @@ with the `once` option set to `true`.
##### `nodeEventTarget.removeAllListeners([type])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+* Returns: [`EventTarget`](/api/v18/events#eventtarget) this
Node.js-specific extension to the `EventTarget` class. If `type` is specified,
removes all registered listeners for `type`, otherwise removes all registered
listeners.
-##### `nodeEventTarget.removeListener(type, listener)`
+##### `nodeEventTarget.removeListener(type, listener[, options])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v18/events#listener)
+
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `capture` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+* Returns: [`EventTarget`](/api/v18/events#eventtarget) this
Node.js-specific extension to the `EventTarget` class that removes the
`listener` for the given `type`. The only difference between `removeListener()`
@@ -1952,9 +2217,12 @@ 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
+[`event.stopPropagation()`]: #eventstoppropagation
+[`event.target`]: #eventtarget
[`events.defaultMaxListeners`]: #eventsdefaultmaxlisteners
[`fs.ReadStream`]: /api/v18/fs#class-fsreadstream
[`net.Server`]: /api/v18/net#class-netserver
diff --git a/content/api/v18/fs.en.md b/content/api/v18/fs.en.md
index ae261e78df..ae2aacd81e 100644
--- a/content/api/v18/fs.en.md
+++ b/content/api/v18/fs.en.md
@@ -5,34 +5,34 @@ category: 'api'
version: 'v18'
---
-
+
-
+
-
+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');
```
@@ -44,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 {
@@ -53,9 +53,7 @@ try {
} catch (error) {
console.error('there was an error:', error.message);
}
-```
-
-```cjs
+--------------
const { unlink } = require('node:fs/promises');
(async function(path) {
@@ -76,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) => {
@@ -104,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 {
@@ -113,9 +109,7 @@ try {
} catch (err) {
// handle the error
}
-```
-
-```cjs
+--------------
const { unlinkSync } = require('node:fs');
try {
@@ -128,7 +122,7 @@ try {
### Promises API
-
+
The `fs/promises` API provides asynchronous file system methods that return
promises.
@@ -140,33 +134,33 @@ concurrent modifications on the same file or data corruption may occur.
#### `FileHandle`
-
+
-A [`FileHandle`](/api/fs#filehandle) object is an object wrapper for a numeric file descriptor.
+A [`FileHandle`](/api/v18/fs#filehandle) object is an object wrapper for a numeric file descriptor.
-Instances of the [`FileHandle`](/api/fs#filehandle) object are created by the `fsPromises.open()`
+Instances of the [`FileHandle`](/api/v18/fs#filehandle) object are created by the `fsPromises.open()`
method.
-All [`FileHandle`](/api/fs#filehandle) objects are [`EventEmitter`](/api/events#eventemitter)s.
+All [`FileHandle`](/api/v18/fs#filehandle) objects are [`EventEmitter`](/api/v18/events#eventemitter)s.
-If a [`FileHandle`](/api/fs#filehandle) is not closed using the `filehandle.close()` method, it will
+If a [`FileHandle`](/api/v18/fs#filehandle) is not closed using the `filehandle.close()` method, it will
try to automatically close the file descriptor and emit a process warning,
helping to prevent memory leaks. Please do not rely on this behavior because
it can be unreliable and the file may not be closed. Instead, always explicitly
-close [`FileHandle`](/api/fs#filehandle)s. Node.js may change this behavior in the future.
+close [`FileHandle`](/api/v18/fs#filehandle)s. Node.js may change this behavior in the future.
##### `'close'`
-
+
-The `'close'` event is emitted when the [`FileHandle`](/api/fs#filehandle) has been closed and can no
+The `'close'` event is emitted when the [`FileHandle`](/api/v18/fs#filehandle) has been closed and can no
longer be used.
##### `filehandle.appendFile(data[, options])`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/stream#stream)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/v18/stream#stream)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -179,7 +173,7 @@ to with [`fsPromises.open()`][]. Therefore, this is equivalent to
##### `filehandle.chmod(mode)`
-
+
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the file mode bit mask.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -188,7 +182,7 @@ Modifies the permissions on the file. See chmod(2).
##### `filehandle.chown(uid, gid)`
-
+
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new owner's user id.
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new group's group id.
@@ -198,7 +192,7 @@ Changes the ownership of the file. A wrapper for chown(2).
##### `filehandle.close()`
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -218,7 +212,7 @@ try {
##### `filehandle.createReadStream([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `null`
@@ -227,9 +221,9 @@ try {
* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `Infinity`
* `highWaterMark` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `64 * 1024`
-* Returns: [`fs.ReadStream`](/api/fs#fsreadstream)
+* Returns: [`fs.ReadStream`](/api/v18/fs#fsreadstream)
-Unlike the 16 KiB default `highWaterMark` for a [`stream.Readable`](/api/stream#streamreadable), the stream
+Unlike the 16 KiB default `highWaterMark` for a [`stream.Readable`](/api/v18/stream#streamreadable), the stream
returned by this method has a default `highWaterMark` of 64 KiB.
`options` can include `start` and `end` values to read a range of bytes from
@@ -238,7 +232,7 @@ start counting at 0, allowed values are in the
\[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `start` is
omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from
the current file position. The `encoding` can be any one of those accepted by
-[`Buffer`](/api/buffer#buffer).
+[`Buffer`](/api/v18/buffer#buffer).
If the `FileHandle` points to a character device that only supports blocking
reads (such as keyboard or sound card), read operations do not finish until data
@@ -283,20 +277,20 @@ fd.createReadStream({ start: 90, end: 99 });
##### `filehandle.createWriteStream([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `autoClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `emitClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* Returns: [`fs.WriteStream`](/api/fs#fswritestream)
+* Returns: [`fs.WriteStream`](/api/v18/fs#fswritestream)
`options` may also include a `start` option to allow writing data at some
position past the beginning of the file, allowed values are in the
\[0, [`Number.MAX_SAFE_INTEGER`][]] range. Modifying a file rather than
replacing it may require the `flags` `open` option to be set to `r+` rather than
-the default `r`. The `encoding` can be any one of those accepted by [`Buffer`](/api/buffer#buffer).
+the default `r`. The `encoding` can be any one of those accepted by [`Buffer`](/api/v18/buffer#buffer).
If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`
the file descriptor will be closed automatically. If `autoClose` is false,
@@ -309,7 +303,7 @@ destroyed. Set the `emitClose` option to `false` to change this behavior.
##### `filehandle.datasync()`
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -321,15 +315,15 @@ Unlike `filehandle.sync` this method does not flush modified metadata.
##### `filehandle.fd`
-
+
-* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The numeric file descriptor managed by the [`FileHandle`](/api/fs#filehandle) object.
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The numeric file descriptor managed by the [`FileHandle`](/api/v18/fs#filehandle) object.
##### `filehandle.read(buffer, offset, length, position)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
file data read.
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The location in the buffer at which to start filling.
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes to read.
@@ -339,7 +333,7 @@ Unlike `filehandle.sync` this method does not flush modified metadata.
file position will remain unchanged.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills upon success with an object with two properties:
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes read
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
+ * `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
argument.
Reads data from the file and stores that in the given buffer.
@@ -349,10 +343,10 @@ number of bytes read is zero.
##### `filehandle.read([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
+ * `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
file data read. **Default:** `Buffer.alloc(16384)`
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The location in the buffer at which to start filling.
**Default:** `0`
@@ -364,7 +358,7 @@ number of bytes read is zero.
file position will remain unchanged. **Default:**: `null`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills upon success with an object with two properties:
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes read
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
+ * `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
argument.
Reads data from the file and stores that in the given buffer.
@@ -374,9 +368,9 @@ number of bytes read is zero.
##### `filehandle.read(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
file data read.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The location in the buffer at which to start filling.
@@ -389,7 +383,7 @@ number of bytes read is zero.
file position will remain unchanged. **Default:**: `null`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills upon success with an object with two properties:
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes read
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
+ * `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
argument.
Reads data from the file and stores that in the given buffer.
@@ -399,18 +393,22 @@ number of bytes read is zero.
##### `filehandle.readableWebStream()`
-
+
+
+
-
+Experimental
-* Returns: [`ReadableStream`](/api/webstreams#readablestream)
+
+
+* Returns: [`ReadableStream`](/api/v18/webstreams#readablestream)
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';
@@ -421,9 +419,7 @@ for await (const chunk of file.readableWebStream())
console.log(chunk);
await file.close();
-```
-
-```cjs
+--------------
const {
open,
} = require('node:fs/promises');
@@ -444,20 +440,20 @@ close the `FileHandle` automatically. User code must still call the
##### `filehandle.readFile(options)`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `null`
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting an in-progress readFile
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) allows aborting an in-progress readFile
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills upon a successful read with the contents of the
file. If no encoding is specified (using `options.encoding`), the data is
- returned as a [`Buffer`](/api/buffer#buffer) object. Otherwise, the data will be a string.
+ returned as a [`Buffer`](/api/v18/buffer#buffer) object. Otherwise, the data will be a string.
Asynchronously reads the entire contents of a file.
If `options` is a string, then it specifies the `encoding`.
-The [`FileHandle`](/api/fs#filehandle) has to support reading.
+The [`FileHandle`](/api/v18/fs#filehandle) has to support reading.
If one or more `filehandle.read()` calls are made on a file handle and then a
`filehandle.readFile()` call is made, the data will be read from the current
@@ -466,7 +462,7 @@ of the file.
##### `filehandle.readLines([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `null`
@@ -475,12 +471,12 @@ of the file.
* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `Infinity`
* `highWaterMark` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `64 * 1024`
-* Returns: [`readline.InterfaceConstructor`](/api/readline#interfaceconstructor)
+* Returns: [`readline.InterfaceConstructor`](/api/v18/readline#interfaceconstructor)
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');
@@ -488,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 () => {
@@ -504,7 +498,7 @@ const { open } = require('node:fs/promises');
##### `filehandle.readv(buffers[, position])`
-
+
* `buffers` Buffer\[]|TypedArray\[]|DataView\[]
* `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The offset from the beginning of the file where
@@ -519,16 +513,16 @@ Read from a file and write to an array of [`ArrayBufferView`](https://developer.
##### `filehandle.stat([options])`
-
+
* `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.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an [`fs.Stats`](/api/fs#fsstats) for the file.
+ [`fs.Stats`](/api/v18/fs#fsstats) object should be `bigint`. **Default:** `false`.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an [`fs.Stats`](/api/v18/fs#fsstats) for the file.
##### `filehandle.sync()`
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -538,7 +532,7 @@ Refer to the POSIX fsync(2) documentation for more detail.
##### `filehandle.truncate(len)`
-
+
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -569,20 +563,20 @@ If `len` is negative then `0` will be used.
##### `filehandle.utimes(atime, mtime)`
-
+
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
-Change the file system timestamps of the object referenced by the [`FileHandle`](/api/fs#filehandle)
+Change the file system timestamps of the object referenced by the [`FileHandle`](/api/v18/fs#filehandle)
then resolves the promise with no arguments upon success.
##### `filehandle.write(buffer, offset[, length[, position]])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The start position from within `buffer` where the data
to write begins.
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes from `buffer` to write. **Default:**
@@ -598,7 +592,7 @@ Write `buffer` to the file.
The promise is resolved with an object containing two properties:
* `bytesWritten` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the number of bytes written
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) a reference to the
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) a reference to the
`buffer` written.
It is unsafe to use `filehandle.write()` multiple times on the same file
@@ -611,9 +605,9 @@ the end of the file.
##### `filehandle.write(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
@@ -628,7 +622,7 @@ default with the above values.
##### `filehandle.write(string[, position[, encoding]])`
-
+
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The offset from the beginning of the file where the
@@ -656,9 +650,9 @@ the end of the file.
##### `filehandle.writeFile(data, options)`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/stream#stream)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/v18/stream#stream)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The expected character encoding when `data` is a
string. **Default:** `'utf8'`
@@ -670,7 +664,7 @@ The promise is resolved with no arguments upon success.
If `options` is a string, then it specifies the `encoding`.
-The [`FileHandle`](/api/fs#filehandle) has to support writing.
+The [`FileHandle`](/api/v18/fs#filehandle) has to support writing.
It is unsafe to use `filehandle.writeFile()` multiple times on the same file
without waiting for the promise to be resolved (or rejected).
@@ -682,7 +676,7 @@ beginning of the file.
##### `filehandle.writev(buffers[, position])`
-
+
* `buffers` Buffer\[]|TypedArray\[]|DataView\[]
* `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The offset from the beginning of the file where the
@@ -707,9 +701,9 @@ the end of the file.
#### `fsPromises.access(path[, mode])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `fs.constants.F_OK`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -745,10 +739,10 @@ the error raised if the file is not accessible.
#### `fsPromises.appendFile(path, data[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`FileHandle`](/api/fs#filehandle) filename or [`FileHandle`](/api/fs#filehandle)
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `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) | [`FileHandle`](/api/v18/fs#filehandle) filename or [`FileHandle`](/api/v18/fs#filehandle)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
@@ -756,21 +750,21 @@ the error raised if the file is not accessible.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
Asynchronously append data to a file, creating the file if it does not yet
-exist. `data` can be a string or a [`Buffer`](/api/buffer#buffer).
+exist. `data` can be a string or a [`Buffer`](/api/v18/buffer#buffer).
If `options` is a string, then it specifies the `encoding`.
The `mode` option only affects the newly created file. See [`fs.open()`][]
for more details.
-The `path` may be specified as a [`FileHandle`](/api/fs#filehandle) that has been opened
+The `path` may be specified as a [`FileHandle`](/api/v18/fs#filehandle) that has been opened
for appending (using `fsPromises.open()`).
#### `fsPromises.chmod(path, mode)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -778,9 +772,9 @@ Changes the permissions of a file.
#### `fsPromises.chown(path, uid, gid)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -789,10 +783,10 @@ Changes the ownership of a file.
#### `fsPromises.copyFile(src, dest[, mode])`
-
+
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) source filename to copy
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) destination filename of the copy operation
+* `src` [`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) source filename to copy
+* `dest` [`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) destination filename of the copy operation
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Optional modifiers that specify the behavior of the copy
operation. It is possible to create a mask consisting of the bitwise OR of
two or more values (e.g.
@@ -822,7 +816,7 @@ try {
await copyFile('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
} catch {
- console.log('The file could not be copied');
+ console.error('The file could not be copied');
}
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
@@ -830,18 +824,22 @@ try {
await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
console.log('source.txt was copied to destination.txt');
} catch {
- console.log('The file could not be copied');
+ console.error('The file could not be copied');
}
```
#### `fsPromises.cp(src, dest[, options])`
-
+
+
+
-
+Experimental
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) source path to copy.
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) destination path to copy to.
+
+
+* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api) source path to copy.
+* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api) destination path to copy to.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `dereference` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) dereference symlinks. **Default:** `false`.
* `errorOnExist` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) when `force` is `false`, and the destination
@@ -849,6 +847,9 @@ try {
* `filter` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Function to filter copied files/directories. Return
`true` to copy the item, `false` to ignore it. Can also return a `Promise`
that resolves to `true` or `false` **Default:** `undefined`.
+ * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) source path to copy.
+ * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) destination path to copy to.
+ * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the `errorOnExist` option to change this behavior.
@@ -868,9 +869,9 @@ behavior is similar to `cp dir1/ dir2/`.
#### `fsPromises.lchmod(path, mode)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -880,9 +881,9 @@ This method is only implemented on macOS.
#### `fsPromises.lchown(path, uid, gid)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -891,9 +892,9 @@ Changes the ownership on a symbolic link.
#### `fsPromises.lutimes(path, atime, mtime)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -905,10 +906,10 @@ the symbolic link itself are changed.
#### `fsPromises.link(existingPath, newPath)`
-
+
-* `existingPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `existingPath` [`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)
+* `newPath` [`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)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
Creates a new link from the `existingPath` to the `newPath`. See the POSIX
@@ -916,13 +917,13 @@ link(2) documentation for more detail.
#### `fsPromises.lstat(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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.Stats`](/api/fs#fsstats) 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.Stats`](/api/fs#fsstats) object for the given
+ [`fs.Stats`](/api/v18/fs#fsstats) 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.Stats`](/api/v18/fs#fsstats) object for the given
symbolic link `path`.
Equivalent to [`fsPromises.stat()`][] unless `path` refers to a symbolic link,
@@ -931,9 +932,9 @@ Refer to the POSIX lstat(2) document for more detail.
#### `fsPromises.mkdir(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `recursive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Not supported on Windows. **Default:** `0o777`.
@@ -948,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 {
@@ -959,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');
@@ -978,12 +977,12 @@ makeDirectory().catch(console.error);
#### `fsPromises.mkdtemp(prefix[, options])`
-
+
* `prefix` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a string containing the filesystem path
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a string containing the file system path
of the newly created temporary directory.
Creates a unique temporary directory. A unique directory name is generated by
@@ -997,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);
}
@@ -1013,16 +1014,16 @@ characters directly to the `prefix` string. For instance, given a directory
#### `fsPromises.open(path, flags[, mode])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) See [support of file system `flags`][].
**Default:** `'r'`.
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the file mode (permission and sticky bits)
if the file is created. **Default:** `0o666` (readable and writable)
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`FileHandle`](/api/fs#filehandle) object.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`FileHandle`](/api/v18/fs#filehandle) object.
-Opens a [`FileHandle`](/api/fs#filehandle).
+Opens a [`FileHandle`](/api/v18/fs#filehandle).
Refer to the POSIX open(2) documentation for more detail.
@@ -1033,20 +1034,20 @@ a colon, Node.js will open a file system stream, as described by
#### `fsPromises.opendir(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `encoding` [`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) **Default:** `'utf8'`
* `bufferSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of directory entries that are buffered
internally when reading from the directory. Higher values lead to better
performance but higher memory usage. **Default:** `32`
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an [`fs.Dir`](/api/fs#fsdir).
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an [`fs.Dir`](/api/v18/fs#fsdir).
Asynchronously open a directory for iterative scanning. See the POSIX
opendir(3) documentation for more detail.
-Creates an [`fs.Dir`](/api/fs#fsdir), which contains all further functions for reading from
+Creates an [`fs.Dir`](/api/v18/fs#fsdir), which contains all further functions for reading from
and cleaning up the directory.
The `encoding` option sets the encoding for the `path` while opening the
@@ -1066,14 +1067,14 @@ try {
}
```
-When using the async iterator, the [`fs.Dir`](/api/fs#fsdir) object will be automatically
+When using the async iterator, the [`fs.Dir`](/api/v18/fs#fsdir) object will be automatically
closed after the iterator exits.
#### `fsPromises.readdir(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `withFileTypes` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
@@ -1085,10 +1086,10 @@ Reads the contents of a directory.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the filenames. If the `encoding` is set to `'buffer'`, the filenames returned
-will be passed as [`Buffer`](/api/buffer#buffer) objects.
+will be passed as [`Buffer`](/api/v18/buffer#buffer) objects.
If `options.withFileTypes` is set to `true`, the resolved array will contain
-[`fs.Dirent`](/api/fs#fsdirent) objects.
+[`fs.Dirent`](/api/v18/fs#fsdirent) objects.
```mjs
import { readdir } from 'node:fs/promises';
@@ -1104,19 +1105,19 @@ try {
#### `fsPromises.readFile(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`FileHandle`](/api/fs#filehandle) filename or `FileHandle`
+* `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) | [`FileHandle`](/api/v18/fs#filehandle) filename or `FileHandle`
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `null`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'r'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting an in-progress readFile
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) allows aborting an in-progress readFile
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the contents of the file.
Asynchronously reads the entire contents of a file.
If no encoding is specified (using `options.encoding`), the data is returned
-as a [`Buffer`](/api/buffer#buffer) object. Otherwise, the data will be a string.
+as a [`Buffer`](/api/v18/buffer#buffer) object. Otherwise, the data will be a string.
If `options` is a string, then it specifies the encoding.
@@ -1128,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);
@@ -1137,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() {
@@ -1154,7 +1153,7 @@ async function logFile() {
logFile();
```
-It is possible to abort an ongoing `readFile` using an [`AbortSignal`](/api/globals#abortsignal). If a
+It is possible to abort an ongoing `readFile` using an [`AbortSignal`](/api/v18/globals#abortsignal). If a
request is aborted the promise returned is rejected with an `AbortError`:
```mjs
@@ -1178,13 +1177,13 @@ try {
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering `fs.readFile` performs.
-Any specified [`FileHandle`](/api/fs#filehandle) has to support reading.
+Any specified [`FileHandle`](/api/v18/fs#filehandle) has to support reading.
#### `fsPromises.readlink(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the `linkString` upon success.
@@ -1196,13 +1195,13 @@ readlink(2) documentation for more detail. The promise is resolved with the
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the link path returned. If the `encoding` is set to `'buffer'`, the link path
-returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+returned will be passed as a [`Buffer`](/api/v18/buffer#buffer) object.
#### `fsPromises.realpath(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the resolved path upon success.
@@ -1215,7 +1214,7 @@ Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path. If the `encoding` is set to `'buffer'`, the path returned will be
-passed as a [`Buffer`](/api/buffer#buffer) object.
+passed as a [`Buffer`](/api/v18/buffer#buffer) object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on `/proc` in order for this function to work. Glibc does not have
@@ -1223,19 +1222,19 @@ this restriction.
#### `fsPromises.rename(oldPath, newPath)`
-
+
-* `oldPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `oldPath` [`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)
+* `newPath` [`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)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
Renames `oldPath` to `newPath`.
#### `fsPromises.rmdir(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `maxRetries` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
`EPERM` error is encountered, Node.js retries the operation with a linear
@@ -1261,9 +1260,9 @@ To get a behavior similar to the `rm -rf` Unix command, use
#### `fsPromises.rm(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, exceptions will be ignored if `path` does
not exist. **Default:** `false`.
@@ -1283,21 +1282,32 @@ Removes files and directories (modeled on the standard POSIX `rm` utility).
#### `fsPromises.stat(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.Stats`](/api/v18/fs#fsstats) 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.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/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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.Stats`](/api/fs#fsstats) 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.Stats`](/api/fs#fsstats) object for the
+ 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])`
-
+
-* `target` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `target` [`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)
+* `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)
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'file'`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -1310,9 +1320,9 @@ automatically be normalized to absolute path.
#### `fsPromises.truncate(path[, len])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -1321,9 +1331,9 @@ bytes.
#### `fsPromises.unlink(path)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
If `path` refers to a symbolic link, then the link is removed without affecting
@@ -1333,9 +1343,9 @@ documentation for more detail.
#### `fsPromises.utimes(path, atime, mtime)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -1351,9 +1361,9 @@ The `atime` and `mtime` arguments follow these rules:
#### `fsPromises.watch(filename[, options])`
-
+
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `filename` [`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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `persistent` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates whether the process should continue to run
as long as files are being watched. **Default:** `true`.
@@ -1363,11 +1373,11 @@ The `atime` and `mtime` arguments follow these rules:
`false`.
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Specifies the character encoding to be used for the
filename passed to the listener. **Default:** `'utf8'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An [`AbortSignal`](/api/globals#abortsignal) used to signal when the watcher
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) An [`AbortSignal`](/api/v18/globals#abortsignal) used to signal when the watcher
should stop.
* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) of objects with the properties:
* `eventType` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of change
- * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) The name of the file changed.
+ * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) The name of the file changed.
Returns an async iterator that watches for changes on `filename`, where `filename`
is either a file or a directory.
@@ -1399,15 +1409,15 @@ All the [caveats][] for `fs.watch()` also apply to `fsPromises.watch()`.
#### `fsPromises.writeFile(file, data[, options])`
-
+
-* `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`FileHandle`](/api/fs#filehandle) filename or `FileHandle`
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/stream#stream)
+* `file` [`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) | [`FileHandle`](/api/v18/fs#filehandle) filename or `FileHandle`
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/v18/stream#stream)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'w'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting an in-progress writeFile
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) allows aborting an in-progress writeFile
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
Asynchronously writes data to a file, replacing the file if it already exists.
@@ -1420,7 +1430,7 @@ If `options` is a string, then it specifies the encoding.
The `mode` option only affects the newly created file. See [`fs.open()`][]
for more details.
-Any specified [`FileHandle`](/api/fs#filehandle) has to support writing.
+Any specified [`FileHandle`](/api/v18/fs#filehandle) has to support writing.
It is unsafe to use `fsPromises.writeFile()` multiple times on the same file
without waiting for the promise to be settled.
@@ -1430,7 +1440,7 @@ method that performs multiple `write` calls internally to write the buffer
passed to it. For performance sensitive code consider using
[`fs.createWriteStream()`][] or [`filehandle.createWriteStream()`][].
-It is possible to use an [`AbortSignal`](/api/globals#abortsignal) to cancel an `fsPromises.writeFile()`.
+It is possible to use an [`AbortSignal`](/api/v18/globals#abortsignal) to cancel an `fsPromises.writeFile()`.
Cancelation is "best effort", and some amount of data is likely still
to be written.
@@ -1459,6 +1469,8 @@ system requests but rather the internal buffering `fs.writeFile` performs.
#### `fsPromises.constants`
+
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
Returns an object containing commonly used constants for file system
@@ -1477,9 +1489,9 @@ concurrent modifications on the same file or data corruption may occur.
#### `fs.access(path[, mode], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `fs.constants.F_OK`
* `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)
@@ -1647,10 +1659,10 @@ the user from reading or writing to it.
#### `fs.appendFile(path, data[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `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) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
@@ -1659,7 +1671,7 @@ the user from reading or writing to it.
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
Asynchronously append data to a file, creating the file if it does not yet
-exist. `data` can be a string or a [`Buffer`](/api/buffer#buffer).
+exist. `data` can be a string or a [`Buffer`](/api/v18/buffer#buffer).
The `mode` option only affects the newly created file. See [`fs.open()`][]
for more details.
@@ -1711,9 +1723,9 @@ open('message.txt', 'a', (err, fd) => {
#### `fs.chmod(path, mode, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `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)
@@ -1784,9 +1796,9 @@ implemented.
#### `fs.chown(path, uid, gid, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1799,7 +1811,7 @@ See the POSIX chown(2) documentation for more detail.
#### `fs.close(fd[, callback])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1815,10 +1827,10 @@ See the POSIX close(2) documentation for more detail.
#### `fs.copyFile(src, dest[, mode], callback)`
-
+
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) source filename to copy
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) destination filename of the copy operation
+* `src` [`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) source filename to copy
+* `dest` [`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) destination filename of the copy operation
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) modifiers for copy operation. **Default:** `0`.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1859,12 +1871,16 @@ copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
#### `fs.cp(src, dest[, options], callback)`
-
+
+
+
-
+Experimental
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) source path to copy.
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) destination path to copy to.
+
+
+* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api) source path to copy.
+* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api) destination path to copy to.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `dereference` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) dereference symlinks. **Default:** `false`.
* `errorOnExist` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) when `force` is `false`, and the destination
@@ -1872,6 +1888,9 @@ copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
* `filter` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Function to filter copied files/directories. Return
`true` to copy the item, `false` to ignore it. Can also return a `Promise`
that resolves to `true` or `false` **Default:** `undefined`.
+ * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) source path to copy.
+ * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) destination path to copy to.
+ * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the `errorOnExist` option to change this behavior.
@@ -1891,14 +1910,14 @@ behavior is similar to `cp dir1/ dir2/`.
#### `fs.createReadStream(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:**
`'r'`.
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `null`
- * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/fs#filehandle) **Default:** `null`
+ * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/v18/fs#filehandle) **Default:** `null`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
* `autoClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `emitClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
@@ -1906,9 +1925,9 @@ behavior is similar to `cp dir1/ dir2/`.
* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `Infinity`
* `highWaterMark` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `64 * 1024`
* `fs` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
-* Returns: [`fs.ReadStream`](/api/fs#fsreadstream)
+* Returns: [`fs.ReadStream`](/api/v18/fs#fsreadstream)
-Unlike the 16 KiB default `highWaterMark` for a [`stream.Readable`](/api/stream#streamreadable), the stream
+Unlike the 16 KiB default `highWaterMark` for a [`stream.Readable`](/api/v18/stream#streamreadable), the stream
returned by this method has a default `highWaterMark` of 64 KiB.
`options` can include `start` and `end` values to read a range of bytes from
@@ -1917,12 +1936,12 @@ start counting at 0, allowed values are in the
\[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `fd` is specified and `start` is
omitted or `undefined`, `fs.createReadStream()` reads sequentially from the
current file position. The `encoding` can be any one of those accepted by
-[`Buffer`](/api/buffer#buffer).
+[`Buffer`](/api/v18/buffer#buffer).
If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
the specified file descriptor. This means that no `'open'` event will be
emitted. `fd` should be blocking; non-blocking `fd`s should be passed to
-[`net.Socket`](/api/net#netsocket).
+[`net.Socket`](/api/v18/net#netsocket).
If `fd` points to a character device that only supports blocking reads
(such as keyboard or sound card), read operations do not finish until data is
@@ -1976,26 +1995,26 @@ If `options` is a string, then it specifies the encoding.
#### `fs.createWriteStream(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:**
`'w'`.
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
- * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/fs#filehandle) **Default:** `null`
+ * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/v18/fs#filehandle) **Default:** `null`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
* `autoClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `emitClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `fs` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
-* Returns: [`fs.WriteStream`](/api/fs#fswritestream)
+* Returns: [`fs.WriteStream`](/api/v18/fs#fswritestream)
`options` may also include a `start` option to allow writing data at some
position past the beginning of the file, allowed values are in the
\[0, [`Number.MAX_SAFE_INTEGER`][]] range. Modifying a file rather than
replacing it may require the `flags` option to be set to `r+` rather than the
-default `w`. The `encoding` can be any one of those accepted by [`Buffer`](/api/buffer#buffer).
+default `w`. The `encoding` can be any one of those accepted by [`Buffer`](/api/v18/buffer#buffer).
If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`
the file descriptor will be closed automatically. If `autoClose` is false,
@@ -2014,20 +2033,24 @@ will be disabled. When providing the `fs` option, overrides for at least one of
for `open` is also required. If `autoClose` is `true`, an override for `close`
is also required.
-Like [`fs.ReadStream`](/api/fs#fsreadstream), if `fd` is specified, [`fs.WriteStream`](/api/fs#fswritestream) will ignore the
+Like [`fs.ReadStream`](/api/v18/fs#fsreadstream), if `fd` is specified, [`fs.WriteStream`](/api/v18/fs#fswritestream) will ignore the
`path` argument and will use the specified file descriptor. This means that no
`'open'` event will be emitted. `fd` should be blocking; non-blocking `fd`s
-should be passed to [`net.Socket`](/api/net#netsocket).
+should be passed to [`net.Socket`](/api/v18/net#netsocket).
If `options` is a string, then it specifies the encoding.
#### `fs.exists(path, callback)`
-
+
+
+
-
+Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+
+
+* `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)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* `exists` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2161,7 +2184,7 @@ process.
#### `fs.fchmod(fd, mode, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2175,7 +2198,7 @@ See the POSIX fchmod(2) documentation for more detail.
#### `fs.fchown(fd, uid, gid, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2190,7 +2213,7 @@ See the POSIX fchown(2) documentation for more detail.
#### `fs.fdatasync(fd, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -2203,23 +2226,23 @@ exception are given to the completion callback.
#### `fs.fstat(fd[, options], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `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.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
+ [`fs.Stats`](/api/v18/fs#fsstats) 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.Stats`](/api/fs#fsstats)
+ * `stats` [`fs.Stats`](/api/v18/fs#fsstats)
-Invokes the callback with the [`fs.Stats`](/api/fs#fsstats) for the file descriptor.
+Invokes the callback with the [`fs.Stats`](/api/v18/fs#fsstats) for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
#### `fs.fsync(fd, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -2232,7 +2255,7 @@ than a possible exception are given to the completion callback.
#### `fs.ftruncate(fd[, len], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
@@ -2281,7 +2304,7 @@ If `len` is negative then `0` will be used.
#### `fs.futimes(fd, atime, mtime, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -2294,9 +2317,9 @@ descriptor. See [`fs.utimes()`][].
#### `fs.lchmod(path, mode, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `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) | [`AggregateError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError)
@@ -2310,9 +2333,9 @@ See the POSIX lchmod(2) documentation for more detail.
#### `fs.lchown(path, uid, gid, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -2325,9 +2348,9 @@ See the POSIX lchown(2) documentation for more detail.
#### `fs.lutimes(path, atime, mtime, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -2343,10 +2366,10 @@ callback.
#### `fs.link(existingPath, newPath, callback)`
-
+
-* `existingPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `existingPath` [`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)
+* `newPath` [`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)
* `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)
@@ -2356,18 +2379,18 @@ exception are given to the completion callback.
#### `fs.lstat(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
+ [`fs.Stats`](/api/v18/fs#fsstats) 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.Stats`](/api/fs#fsstats)
+ * `stats` [`fs.Stats`](/api/v18/fs#fsstats)
-Retrieves the [`fs.Stats`](/api/fs#fsstats) for the symbolic link referred to by the path.
-The callback gets two arguments `(err, stats)` where `stats` is a [`fs.Stats`](/api/fs#fsstats)
+Retrieves the [`fs.Stats`](/api/v18/fs#fsstats) for the symbolic link referred to by the path.
+The callback gets two arguments `(err, stats)` where `stats` is a [`fs.Stats`](/api/v18/fs#fsstats)
object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic
link, then the link itself is stat-ed, not the file that it refers to.
@@ -2375,9 +2398,9 @@ See the POSIX lstat(2) documentation for more details.
#### `fs.mkdir(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `recursive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Not supported on Windows. **Default:** `0o777`.
@@ -2423,7 +2446,7 @@ See the POSIX mkdir(2) documentation for more details.
#### `fs.mkdtemp(prefix[, options], callback)`
-
+
* `prefix` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2448,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
@@ -2491,9 +2516,9 @@ mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
#### `fs.open(path[, flags[, mode]], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) See [support of file system `flags`][].
**Default:** `'r'`.
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666` (readable and writable)
@@ -2519,9 +2544,9 @@ Functions based on `fs.open()` exhibit this behavior as well:
#### `fs.opendir(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `encoding` [`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) **Default:** `'utf8'`
* `bufferSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of directory entries that are buffered
@@ -2529,12 +2554,12 @@ Functions based on `fs.open()` exhibit this behavior as well:
performance but higher memory usage. **Default:** `32`
* `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)
- * `dir` [`fs.Dir`](/api/fs#fsdir)
+ * `dir` [`fs.Dir`](/api/v18/fs#fsdir)
Asynchronously open a directory. See the POSIX opendir(3) documentation for
more details.
-Creates an [`fs.Dir`](/api/fs#fsdir), which contains all further functions for reading from
+Creates an [`fs.Dir`](/api/v18/fs#fsdir), which contains all further functions for reading from
and cleaning up the directory.
The `encoding` option sets the encoding for the `path` while opening the
@@ -2542,10 +2567,10 @@ directory and subsequent read operations.
#### `fs.read(fd, buffer, offset, length, position, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The buffer that the data will be
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The buffer that the data will be
written to.
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The position in `buffer` to write the data to.
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes to read.
@@ -2556,7 +2581,7 @@ directory and subsequent read operations.
* `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)
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `buffer` [`Buffer`](/api/buffer#buffer)
+ * `buffer` [`Buffer`](/api/v18/buffer#buffer)
Read data from the file specified by `fd`.
@@ -2570,18 +2595,18 @@ a promise for an `Object` with `bytesRead` and `buffer` properties.
#### `fs.read(fd[, options], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) **Default:** `Buffer.alloc(16384)`
+ * `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) **Default:** `Buffer.alloc(16384)`
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
* `position` [`integer`](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) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
* `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)
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `buffer` [`Buffer`](/api/buffer#buffer)
+ * `buffer` [`Buffer`](/api/v18/buffer#buffer)
Similar to the [`fs.read()`][] function, this version takes an optional
`options` object. If no `options` object is specified, it will default with the
@@ -2589,10 +2614,10 @@ above values.
#### `fs.read(fd, buffer[, options], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The buffer that the data will be
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The buffer that the data will be
written to.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
@@ -2601,7 +2626,7 @@ above values.
* `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)
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `buffer` [`Buffer`](/api/buffer#buffer)
+ * `buffer` [`Buffer`](/api/v18/buffer#buffer)
Similar to the [`fs.read()`][] function, this version takes an optional
`options` object. If no `options` object is specified, it will default with the
@@ -2609,9 +2634,9 @@ above values.
#### `fs.readdir(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `withFileTypes` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
@@ -2628,23 +2653,23 @@ See the POSIX readdir(3) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the filenames passed to the callback. If the `encoding` is set to `'buffer'`,
-the filenames returned will be passed as [`Buffer`](/api/buffer#buffer) objects.
+the filenames returned will be passed as [`Buffer`](/api/v18/buffer#buffer) objects.
If `options.withFileTypes` is set to `true`, the `files` array will contain
-[`fs.Dirent`](/api/fs#fsdirent) objects.
+[`fs.Dirent`](/api/v18/fs#fsdirent) objects.
#### `fs.readFile(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `null`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'r'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting an in-progress readFile
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) allows aborting an in-progress readFile
* `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) | [`AggregateError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError)
- * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+ * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
Asynchronously reads the entire contents of a file.
@@ -2744,14 +2769,14 @@ different Node.js versions.
#### `fs.readlink(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `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)
- * `linkString` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+ * `linkString` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
Reads the contents of the symbolic link referred to by `path`. The callback gets
two arguments `(err, linkString)`.
@@ -2761,11 +2786,11 @@ See the POSIX readlink(2) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the link path passed to the callback. If the `encoding` is set to `'buffer'`,
-the link path returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+the link path returned will be passed as a [`Buffer`](/api/v18/buffer#buffer) object.
#### `fs.readv(fd, buffers[, position], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `buffers` ArrayBufferView\[]
@@ -2790,14 +2815,14 @@ a promise for an `Object` with `bytesRead` and `buffers` properties.
#### `fs.realpath(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `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)
- * `resolvedPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+ * `resolvedPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
Asynchronously computes the canonical pathname by resolving `.`, `..`, and
symbolic links.
@@ -2820,21 +2845,21 @@ Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path passed to the callback. If the `encoding` is set to `'buffer'`,
-the path returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+the path returned will be passed as a [`Buffer`](/api/v18/buffer#buffer) object.
If `path` resolves to a socket or a pipe, the function will return a system
dependent name for that object.
#### `fs.realpath.native(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `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)
- * `resolvedPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+ * `resolvedPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
Asynchronous realpath(3).
@@ -2845,7 +2870,7 @@ Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path passed to the callback. If the `encoding` is set to `'buffer'`,
-the path returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+the path returned will be passed as a [`Buffer`](/api/v18/buffer#buffer) object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on `/proc` in order for this function to work. Glibc does not have
@@ -2853,10 +2878,10 @@ this restriction.
#### `fs.rename(oldPath, newPath, callback)`
-
+
-* `oldPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `oldPath` [`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)
+* `newPath` [`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)
* `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)
@@ -2879,9 +2904,9 @@ rename('oldFile.txt', 'newFile.txt', (err) => {
#### `fs.rmdir(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `maxRetries` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
`EPERM` error is encountered, Node.js retries the operation with a linear
@@ -2908,9 +2933,9 @@ with options `{ recursive: true, force: true }`.
#### `fs.rm(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, exceptions will be ignored if `path` does
not exist. **Default:** `false`.
@@ -2933,18 +2958,18 @@ completion callback.
#### `fs.stat(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
+ [`fs.Stats`](/api/v18/fs#fsstats) 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.Stats`](/api/fs#fsstats)
+ * `stats` [`fs.Stats`](/api/v18/fs#fsstats)
Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
-`stats` is an [`fs.Stats`](/api/fs#fsstats) object.
+`stats` is an [`fs.Stats`](/api/v18/fs#fsstats) object.
In case of an error, the `err.code` will be one of [Common System Errors][].
@@ -3026,12 +3051,30 @@ 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)`
-
+
-* `target` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `target` [`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)
+* `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)
* `type` [`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) **Default:** `null`
* `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)
@@ -3068,9 +3111,9 @@ $ tree .
#### `fs.truncate(path[, len], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `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) | [`AggregateError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError)
@@ -3079,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) => {
@@ -3104,9 +3145,9 @@ See the POSIX truncate(2) documentation for more details.
#### `fs.unlink(path, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `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)
@@ -3129,9 +3170,9 @@ See the POSIX unlink(2) documentation for more details.
#### `fs.unwatchFile(filename[, listener])`
-
+
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `filename` [`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)
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional, a listener previously attached using
`fs.watchFile()`
@@ -3148,9 +3189,9 @@ and `fs.unwatchFile()` when possible.
#### `fs.utimes(path, atime, mtime, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -3167,9 +3208,9 @@ The `atime` and `mtime` arguments follow these rules:
#### `fs.watch(filename[, options][, listener])`
-
+
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `filename` [`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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `persistent` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates whether the process should continue to run
as long as files are being watched. **Default:** `true`.
@@ -3179,11 +3220,11 @@ The `atime` and `mtime` arguments follow these rules:
`false`.
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Specifies the character encoding to be used for the
filename passed to the listener. **Default:** `'utf8'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows closing the watcher with an AbortSignal.
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) allows closing the watcher with an AbortSignal.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) **Default:** `undefined`
* `eventType` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
- * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
-* Returns: [`fs.FSWatcher`](/api/fs#fsfswatcher)
+ * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
+* Returns: [`fs.FSWatcher`](/api/v18/fs#fsfswatcher)
Watch for changes on `filename`, where `filename` is either a file or a
directory.
@@ -3199,15 +3240,15 @@ On most platforms, `'rename'` is emitted whenever a filename appears or
disappears in the directory.
The listener callback is attached to the `'change'` event fired by
-[`fs.FSWatcher`](/api/fs#fsfswatcher), but it is not the same thing as the `'change'` value of
+[`fs.FSWatcher`](/api/v18/fs#fsfswatcher), but it is not the same thing as the `'change'` value of
`eventType`.
If a `signal` is passed, aborting the corresponding AbortController will close
-the returned [`fs.FSWatcher`](/api/fs#fsfswatcher).
+the returned [`fs.FSWatcher`](/api/v18/fs#fsfswatcher).
##### Caveats
-
+
The `fs.watch` API is not 100% consistent across platforms, and is
unavailable in some situations.
@@ -3221,10 +3262,10 @@ renamed. An `EPERM` error is reported when the watched directory is deleted.
###### Availability
-
+
This feature depends on the underlying operating system providing a way
-to be notified of filesystem changes.
+to be notified of file system changes.
* On Linux systems, this uses [`inotify(7)`][].
* On BSD systems, this uses [`kqueue(2)`][].
@@ -3246,7 +3287,7 @@ this method is slower and less reliable.
###### Inodes
-
+
On Linux and macOS systems, `fs.watch()` resolves the path to an [inode][] and
watches the inode. If the watched path is deleted and recreated, it is assigned
@@ -3260,7 +3301,7 @@ content, and one for truncation).
###### Filename argument
-
+
Providing `filename` argument in the callback is only supported on Linux,
macOS, Windows, and AIX. Even on supported platforms, `filename` is not always
@@ -3281,17 +3322,17 @@ watch('somedir', (eventType, filename) => {
#### `fs.watchFile(filename[, options], listener)`
-
+
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `filename` [`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) **Default:** `false`
* `persistent` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `interval` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `5007`
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
- * `current` [`fs.Stats`](/api/fs#fsstats)
- * `previous` [`fs.Stats`](/api/fs#fsstats)
-* Returns: [`fs.StatWatcher`](/api/fs#fsstatwatcher)
+ * `current` [`fs.Stats`](/api/v18/fs#fsstats)
+ * `previous` [`fs.Stats`](/api/v18/fs#fsstats)
+* Returns: [`fs.StatWatcher`](/api/v18/fs#fsstatwatcher)
Watch for changes on `filename`. The callback `listener` will be called each
time the file is accessed.
@@ -3342,17 +3383,17 @@ This happens when:
#### `fs.write(fd, buffer, offset[, length[, position]], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
* `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
* `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)
* `bytesWritten` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+ * `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
Write `buffer` to the file specified by `fd`.
@@ -3379,10 +3420,10 @@ the end of the file.
#### `fs.write(fd, buffer[, options], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
@@ -3390,7 +3431,7 @@ the end of the file.
* `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)
* `bytesWritten` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+ * `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
Write `buffer` to the file specified by `fd`.
@@ -3400,7 +3441,7 @@ default with the above values.
#### `fs.write(fd, string[, position[, encoding]], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -3442,15 +3483,15 @@ details.
#### `fs.writeFile(file, data[, options], callback)`
-
+
-* `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`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) | [`Buffer`](/api/v18/buffer#buffer) | [`URL`](/api/v18/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'w'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting an in-progress writeFile
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) allows aborting an in-progress writeFile
* `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) | [`AggregateError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError)
@@ -3493,7 +3534,7 @@ Similarly to `fs.readFile` - `fs.writeFile` is a convenience method that
performs multiple `write` calls internally to write the buffer passed to it.
For performance sensitive code consider using [`fs.createWriteStream()`][].
-It is possible to use an [`AbortSignal`](/api/globals#abortsignal) to cancel an `fs.writeFile()`.
+It is possible to use an [`AbortSignal`](/api/v18/globals#abortsignal) to cancel an `fs.writeFile()`.
Cancelation is "best effort", and some amount of data is likely still
to be written.
@@ -3545,7 +3586,7 @@ to contain only `', World'`.
#### `fs.writev(fd, buffers[, position], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `buffers` ArrayBufferView\[]
@@ -3582,9 +3623,9 @@ event loop until the operation completes or fails.
#### `fs.accessSync(path[, mode])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `fs.constants.F_OK`
Synchronously tests a user's permissions for the file or directory specified
@@ -3611,17 +3652,17 @@ try {
#### `fs.appendFileSync(path, data[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `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) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'a'`.
Synchronously append data to a file, creating the file if it does not yet
-exist. `data` can be a string or a [`Buffer`](/api/buffer#buffer).
+exist. `data` can be a string or a [`Buffer`](/api/v18/buffer#buffer).
The `mode` option only affects the newly created file. See [`fs.open()`][]
for more details.
@@ -3667,9 +3708,9 @@ try {
#### `fs.chmodSync(path, mode)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
For detailed information, see the documentation of the asynchronous version of
@@ -3679,9 +3720,9 @@ See the POSIX chmod(2) documentation for more detail.
#### `fs.chownSync(path, uid, gid)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3692,7 +3733,7 @@ See the POSIX chown(2) documentation for more detail.
#### `fs.closeSync(fd)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3705,10 +3746,10 @@ See the POSIX close(2) documentation for more detail.
#### `fs.copyFileSync(src, dest[, mode])`
-
+
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) source filename to copy
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) destination filename of the copy operation
+* `src` [`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) source filename to copy
+* `dest` [`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) destination filename of the copy operation
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) modifiers for copy operation. **Default:** `0`.
Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it
@@ -3743,18 +3784,25 @@ copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
#### `fs.cpSync(src, dest[, options])`
-
+
+
+
-
+Experimental
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) source path to copy.
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) destination path to copy to.
+
+
+* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api) source path to copy.
+* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api) destination path to copy to.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `dereference` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) dereference symlinks. **Default:** `false`.
* `errorOnExist` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) when `force` is `false`, and the destination
exists, throw an error. **Default:** `false`.
* `filter` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Function to filter copied files/directories. Return
`true` to copy the item, `false` to ignore it. **Default:** `undefined`
+ * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) source path to copy.
+ * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) destination path to copy to.
+ * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the `errorOnExist` option to change this behavior.
@@ -3773,9 +3821,9 @@ behavior is similar to `cp dir1/ dir2/`.
#### `fs.existsSync(path)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
Returns `true` if the path exists, `false` otherwise.
@@ -3796,7 +3844,7 @@ if (existsSync('/etc/passwd'))
#### `fs.fchmodSync(fd, mode)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3807,7 +3855,7 @@ See the POSIX fchmod(2) documentation for more detail.
#### `fs.fchownSync(fd, uid, gid)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new owner's user id.
@@ -3819,7 +3867,7 @@ See the POSIX fchown(2) documentation for more detail.
#### `fs.fdatasyncSync(fd)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3829,21 +3877,21 @@ fdatasync(2) documentation for details. Returns `undefined`.
#### `fs.fstatSync(fd[, options])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `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.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
-* Returns: [`fs.Stats`](/api/fs#fsstats)
+ [`fs.Stats`](/api/v18/fs#fsstats) object should be `bigint`. **Default:** `false`.
+* Returns: [`fs.Stats`](/api/v18/fs#fsstats)
-Retrieves the [`fs.Stats`](/api/fs#fsstats) for the file descriptor.
+Retrieves the [`fs.Stats`](/api/v18/fs#fsstats) for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
#### `fs.fsyncSync(fd)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3853,7 +3901,7 @@ Refer to the POSIX fsync(2) documentation for more detail. Returns `undefined`.
#### `fs.ftruncateSync(fd[, len])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
@@ -3865,7 +3913,7 @@ this API: [`fs.ftruncate()`][].
#### `fs.futimesSync(fd, atime, mtime)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -3875,9 +3923,9 @@ Synchronous version of [`fs.futimes()`][]. Returns `undefined`.
#### `fs.lchmodSync(path, mode)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
Changes the permissions on a symbolic link. Returns `undefined`.
@@ -3888,9 +3936,9 @@ See the POSIX lchmod(2) documentation for more detail.
#### `fs.lchownSync(path, uid, gid)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new owner's user id.
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new group's group id.
@@ -3900,9 +3948,9 @@ See the POSIX lchown(2) documentation for more details.
#### `fs.lutimesSync(path, atime, mtime)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -3912,36 +3960,36 @@ the operation fails. This is the synchronous version of [`fs.lutimes()`][].
#### `fs.linkSync(existingPath, newPath)`
-
+
-* `existingPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `existingPath` [`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)
+* `newPath` [`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)
Creates a new link from the `existingPath` to the `newPath`. See the POSIX
link(2) documentation for more detail. Returns `undefined`.
#### `fs.lstatSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
+ [`fs.Stats`](/api/v18/fs#fsstats) object should be `bigint`. **Default:** `false`.
* `throwIfNoEntry` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether an exception will be thrown
if no file system entry exists, rather than returning `undefined`.
**Default:** `true`.
-* Returns: [`fs.Stats`](/api/fs#fsstats)
+* Returns: [`fs.Stats`](/api/v18/fs#fsstats)
-Retrieves the [`fs.Stats`](/api/fs#fsstats) for the symbolic link referred to by `path`.
+Retrieves the [`fs.Stats`](/api/v18/fs#fsstats) for the symbolic link referred to by `path`.
See the POSIX lstat(2) documentation for more details.
#### `fs.mkdirSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `recursive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Not supported on Windows. **Default:** `0o777`.
@@ -3955,7 +4003,7 @@ See the POSIX mkdir(2) documentation for more details.
#### `fs.mkdtempSync(prefix[, options])`
-
+
* `prefix` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -3972,19 +4020,19 @@ object with an `encoding` property specifying the character encoding to use.
#### `fs.opendirSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `encoding` [`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) **Default:** `'utf8'`
* `bufferSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of directory entries that are buffered
internally when reading from the directory. Higher values lead to better
performance but higher memory usage. **Default:** `32`
-* Returns: [`fs.Dir`](/api/fs#fsdir)
+* Returns: [`fs.Dir`](/api/v18/fs#fsdir)
Synchronously open a directory. See opendir(3).
-Creates an [`fs.Dir`](/api/fs#fsdir), which contains all further functions for reading from
+Creates an [`fs.Dir`](/api/v18/fs#fsdir), which contains all further functions for reading from
and cleaning up the directory.
The `encoding` option sets the encoding for the `path` while opening the
@@ -3992,9 +4040,9 @@ directory and subsequent read operations.
#### `fs.openSync(path[, flags[, mode]])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `'r'`.
See [support of file system `flags`][].
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
@@ -4007,9 +4055,9 @@ this API: [`fs.open()`][].
#### `fs.readdirSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `withFileTypes` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
@@ -4022,20 +4070,20 @@ See the POSIX readdir(3) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the filenames returned. If the `encoding` is set to `'buffer'`,
-the filenames returned will be passed as [`Buffer`](/api/buffer#buffer) objects.
+the filenames returned will be passed as [`Buffer`](/api/v18/buffer#buffer) objects.
If `options.withFileTypes` is set to `true`, the result will contain
-[`fs.Dirent`](/api/fs#fsdirent) objects.
+[`fs.Dirent`](/api/v18/fs#fsdirent) objects.
#### `fs.readFileSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `null`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'r'`.
-* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
Returns the contents of the `path`.
@@ -4061,12 +4109,12 @@ readFileSync(''); // =>
#### `fs.readlinkSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
-* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
Returns the symbolic link's string value.
@@ -4075,14 +4123,14 @@ See the POSIX readlink(2) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the link path returned. If the `encoding` is set to `'buffer'`,
-the link path returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+the link path returned will be passed as a [`Buffer`](/api/v18/buffer#buffer) object.
#### `fs.readSync(fd, buffer, offset, length[, position])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `position` [`integer`](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) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
@@ -4095,10 +4143,10 @@ this API: [`fs.read()`][].
#### `fs.readSync(fd, buffer[, options])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
@@ -4115,7 +4163,7 @@ this API: [`fs.read()`][].
#### `fs.readvSync(fd, buffers[, position])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `buffers` ArrayBufferView\[]
@@ -4127,12 +4175,12 @@ this API: [`fs.readv()`][].
#### `fs.realpathSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
-* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
Returns the resolved pathname.
@@ -4141,12 +4189,12 @@ this API: [`fs.realpath()`][].
#### `fs.realpathSync.native(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
-* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
Synchronous realpath(3).
@@ -4155,7 +4203,7 @@ Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path returned. If the `encoding` is set to `'buffer'`,
-the path returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+the path returned will be passed as a [`Buffer`](/api/v18/buffer#buffer) object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on `/proc` in order for this function to work. Glibc does not have
@@ -4163,10 +4211,10 @@ this restriction.
#### `fs.renameSync(oldPath, newPath)`
-
+
-* `oldPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `oldPath` [`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)
+* `newPath` [`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)
Renames the file from `oldPath` to `newPath`. Returns `undefined`.
@@ -4174,9 +4222,9 @@ See the POSIX rename(2) documentation for more details.
#### `fs.rmdirSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `maxRetries` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
`EPERM` error is encountered, Node.js retries the operation with a linear
@@ -4200,9 +4248,9 @@ with options `{ recursive: true, force: true }`.
#### `fs.rmSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, exceptions will be ignored if `path` does
not exist. **Default:** `false`.
@@ -4222,25 +4270,40 @@ utility). Returns `undefined`.
#### `fs.statSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
+ [`fs.Stats`](/api/v18/fs#fsstats) object should be `bigint`. **Default:** `false`.
* `throwIfNoEntry` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether an exception will be thrown
if no file system entry exists, rather than returning `undefined`.
**Default:** `true`.
-* Returns: [`fs.Stats`](/api/fs#fsstats)
+* Returns: [`fs.Stats`](/api/v18/fs#fsstats)
+
+Retrieves the [`fs.Stats`](/api/v18/fs#fsstats) for the path.
+
+#### `fs.statfsSync(path[, options])`
-Retrieves the [`fs.Stats`](/api/fs#fsstats) for the path.
+
+
+* `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])`
-
+
-* `target` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `target` [`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)
+* `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)
* `type` [`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) **Default:** `null`
Returns `undefined`.
@@ -4250,9 +4313,9 @@ this API: [`fs.symlink()`][].
#### `fs.truncateSync(path[, len])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
Truncates the file. Returns `undefined`. A file descriptor can also be
@@ -4263,17 +4326,17 @@ in the future.
#### `fs.unlinkSync(path)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
Synchronous unlink(2). Returns `undefined`.
#### `fs.utimesSync(path, atime, mtime)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -4284,10 +4347,10 @@ this API: [`fs.utimes()`][].
#### `fs.writeFileSync(file, data[, options])`
-
+
-* `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`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) | [`Buffer`](/api/v18/buffer#buffer) | [`URL`](/api/v18/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
@@ -4303,10 +4366,10 @@ this API: [`fs.writeFile()`][].
#### `fs.writeSync(fd, buffer, offset[, length[, position]])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
* `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
@@ -4317,10 +4380,10 @@ this API: [`fs.write(fd, buffer...)`][].
#### `fs.writeSync(fd, buffer[, options])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
@@ -4332,7 +4395,7 @@ this API: [`fs.write(fd, buffer...)`][].
#### `fs.writeSync(fd, string[, position[, encoding]])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -4345,7 +4408,7 @@ this API: [`fs.write(fd, string...)`][].
#### `fs.writevSync(fd, buffers[, position])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `buffers` ArrayBufferView\[]
@@ -4362,7 +4425,7 @@ The common objects are shared by all of the file system API variants
#### `fs.Dir`
-
+
A class representing a directory stream.
@@ -4381,12 +4444,12 @@ try {
}
```
-When using the async iterator, the [`fs.Dir`](/api/fs#fsdir) object will be automatically
+When using the async iterator, the [`fs.Dir`](/api/v18/fs#fsdir) object will be automatically
closed after the iterator exits.
##### `dir.close()`
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
@@ -4398,7 +4461,7 @@ closed.
##### `dir.close(callback)`
-
+
* `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)
@@ -4410,14 +4473,14 @@ The `callback` will be called after the resource handle has been closed.
##### `dir.closeSync()`
-
+
Synchronously close the directory's underlying resource handle.
Subsequent reads will result in errors.
##### `dir.path`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -4426,14 +4489,14 @@ The read-only path of this directory as was provided to [`fs.opendir()`][],
##### `dir.read()`
-
+
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`fs.Dirent`](/api/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`fs.Dirent`](/api/v18/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
Asynchronously read the next directory entry via readdir(3) as an
-[`fs.Dirent`](/api/fs#fsdirent).
+[`fs.Dirent`](/api/v18/fs#fsdirent).
-A promise is returned that will be resolved with an [`fs.Dirent`](/api/fs#fsdirent), or `null`
+A promise is returned that will be resolved with an [`fs.Dirent`](/api/v18/fs#fsdirent), or `null`
if there are no more directory entries to read.
Directory entries returned by this function are in no particular order as
@@ -4443,17 +4506,17 @@ included in the iteration results.
##### `dir.read(callback)`
-
+
* `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)
- * `dirent` [`fs.Dirent`](/api/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
+ * `dirent` [`fs.Dirent`](/api/v18/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
Asynchronously read the next directory entry via readdir(3) as an
-[`fs.Dirent`](/api/fs#fsdirent).
+[`fs.Dirent`](/api/v18/fs#fsdirent).
After the read is completed, the `callback` will be called with an
-[`fs.Dirent`](/api/fs#fsdirent), or `null` if there are no more directory entries to read.
+[`fs.Dirent`](/api/v18/fs#fsdirent), or `null` if there are no more directory entries to read.
Directory entries returned by this function are in no particular order as
provided by the operating system's underlying directory mechanisms.
@@ -4462,11 +4525,11 @@ included in the iteration results.
##### `dir.readSync()`
-
+
-* Returns: [`fs.Dirent`](/api/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
+* Returns: [`fs.Dirent`](/api/v18/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
-Synchronously read the next directory entry as an [`fs.Dirent`](/api/fs#fsdirent). See the
+Synchronously read the next directory entry as an [`fs.Dirent`](/api/v18/fs#fsdirent). See the
POSIX readdir(3) documentation for more detail.
If there are no more directory entries to read, `null` will be returned.
@@ -4478,17 +4541,17 @@ included in the iteration results.
##### `dir[Symbol.asyncIterator]()`
-
+
-* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) of [`fs.Dirent`](/api/fs#fsdirent)
+* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) of [`fs.Dirent`](/api/v18/fs#fsdirent)
Asynchronously iterates over the directory until all entries have
been read. Refer to the POSIX readdir(3) documentation for more detail.
-Entries returned by the async iterator are always an [`fs.Dirent`](/api/fs#fsdirent).
+Entries returned by the async iterator are always an [`fs.Dirent`](/api/v18/fs#fsdirent).
The `null` case from `dir.read()` is handled internally.
-See [`fs.Dir`](/api/fs#fsdir) for an example.
+See [`fs.Dir`](/api/v18/fs#fsdir) for an example.
Directory entries returned by this iterator are in no particular order as
provided by the operating system's underlying directory mechanisms.
@@ -4497,108 +4560,108 @@ included in the iteration results.
#### `fs.Dirent`
-
+
A representation of a directory entry, which can be a file or a subdirectory
-within the directory, as returned by reading from an [`fs.Dir`](/api/fs#fsdir). The
+within the directory, as returned by reading from an [`fs.Dir`](/api/v18/fs#fsdir). The
directory entry is a combination of the file name and file type pairs.
Additionally, when [`fs.readdir()`][] or [`fs.readdirSync()`][] is called with
the `withFileTypes` option set to `true`, the resulting array is filled with
-[`fs.Dirent`](/api/fs#fsdirent) objects, rather than strings or [`Buffer`](/api/buffer#buffer)s.
+[`fs.Dirent`](/api/v18/fs#fsdirent) objects, rather than strings or [`Buffer`](/api/v18/buffer#buffer)s.
##### `dirent.isBlockDevice()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a block device.
+Returns `true` if the [`fs.Dirent`](/api/v18/fs#fsdirent) object describes a block device.
##### `dirent.isCharacterDevice()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a character device.
+Returns `true` if the [`fs.Dirent`](/api/v18/fs#fsdirent) object describes a character device.
##### `dirent.isDirectory()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a file system
+Returns `true` if the [`fs.Dirent`](/api/v18/fs#fsdirent) object describes a file system
directory.
##### `dirent.isFIFO()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a first-in-first-out
+Returns `true` if the [`fs.Dirent`](/api/v18/fs#fsdirent) object describes a first-in-first-out
(FIFO) pipe.
##### `dirent.isFile()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a regular file.
+Returns `true` if the [`fs.Dirent`](/api/v18/fs#fsdirent) object describes a regular file.
##### `dirent.isSocket()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a socket.
+Returns `true` if the [`fs.Dirent`](/api/v18/fs#fsdirent) object describes a socket.
##### `dirent.isSymbolicLink()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a symbolic link.
+Returns `true` if the [`fs.Dirent`](/api/v18/fs#fsdirent) object describes a symbolic link.
##### `dirent.name`
-
+
-* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
-The file name that this [`fs.Dirent`](/api/fs#fsdirent) object refers to. The type of this
+The file name that this [`fs.Dirent`](/api/v18/fs#fsdirent) object refers to. The type of this
value is determined by the `options.encoding` passed to [`fs.readdir()`][] or
[`fs.readdirSync()`][].
#### `fs.FSWatcher`
-
+
-* Extends [`EventEmitter`](/api/events#eventemitter)
+* Extends [`EventEmitter`](/api/v18/events#eventemitter)
-A successful call to [`fs.watch()`][] method will return a new [`fs.FSWatcher`](/api/fs#fsfswatcher)
+A successful call to [`fs.watch()`][] method will return a new [`fs.FSWatcher`](/api/v18/fs#fsfswatcher)
object.
-All [`fs.FSWatcher`](/api/fs#fsfswatcher) objects emit a `'change'` event whenever a specific watched
+All [`fs.FSWatcher`](/api/v18/fs#fsfswatcher) objects emit a `'change'` event whenever a specific watched
file is modified.
##### `'change'`
-
+
* `eventType` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of change event that has occurred
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) The filename that changed (if relevant/available)
+* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) The filename that changed (if relevant/available)
Emitted when something changes in a watched directory or file.
See more details in [`fs.watch()`][].
The `filename` argument may not be provided depending on operating system
-support. If `filename` is provided, it will be provided as a [`Buffer`](/api/buffer#buffer) if
+support. If `filename` is provided, it will be provided as a [`Buffer`](/api/v18/buffer#buffer) if
`fs.watch()` is called with its `encoding` option set to `'buffer'`, otherwise
`filename` will be a UTF-8 string.
@@ -4615,122 +4678,122 @@ watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
##### `'close'`
-
+
Emitted when the watcher stops watching for changes. The closed
-[`fs.FSWatcher`](/api/fs#fsfswatcher) object is no longer usable in the event handler.
+[`fs.FSWatcher`](/api/v18/fs#fsfswatcher) object is no longer usable in the event handler.
##### `'error'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
Emitted when an error occurs while watching the file. The errored
-[`fs.FSWatcher`](/api/fs#fsfswatcher) object is no longer usable in the event handler.
+[`fs.FSWatcher`](/api/v18/fs#fsfswatcher) object is no longer usable in the event handler.
##### `watcher.close()`
-
+
-Stop watching for changes on the given [`fs.FSWatcher`](/api/fs#fsfswatcher). Once stopped, the
-[`fs.FSWatcher`](/api/fs#fsfswatcher) object is no longer usable.
+Stop watching for changes on the given [`fs.FSWatcher`](/api/v18/fs#fsfswatcher). Once stopped, the
+[`fs.FSWatcher`](/api/v18/fs#fsfswatcher) object is no longer usable.
##### `watcher.ref()`
-
+
-* Returns: [`fs.FSWatcher`](/api/fs#fsfswatcher)
+* Returns: [`fs.FSWatcher`](/api/v18/fs#fsfswatcher)
When called, requests that the Node.js event loop _not_ exit so long as the
-[`fs.FSWatcher`](/api/fs#fsfswatcher) is active. Calling `watcher.ref()` multiple times will have
+[`fs.FSWatcher`](/api/v18/fs#fsfswatcher) is active. Calling `watcher.ref()` multiple times will have
no effect.
-By default, all [`fs.FSWatcher`](/api/fs#fsfswatcher) objects are "ref'ed", making it normally
+By default, all [`fs.FSWatcher`](/api/v18/fs#fsfswatcher) objects are "ref'ed", making it normally
unnecessary to call `watcher.ref()` unless `watcher.unref()` had been
called previously.
##### `watcher.unref()`
-
+
-* Returns: [`fs.FSWatcher`](/api/fs#fsfswatcher)
+* Returns: [`fs.FSWatcher`](/api/v18/fs#fsfswatcher)
-When called, the active [`fs.FSWatcher`](/api/fs#fsfswatcher) object will not require the Node.js
+When called, the active [`fs.FSWatcher`](/api/v18/fs#fsfswatcher) object will not require the Node.js
event loop to remain active. If there is no other activity keeping the
-event loop running, the process may exit before the [`fs.FSWatcher`](/api/fs#fsfswatcher) object's
+event loop running, the process may exit before the [`fs.FSWatcher`](/api/v18/fs#fsfswatcher) object's
callback is invoked. Calling `watcher.unref()` multiple times will have
no effect.
#### `fs.StatWatcher`
-
+
-* Extends [`EventEmitter`](/api/events#eventemitter)
+* Extends [`EventEmitter`](/api/v18/events#eventemitter)
-A successful call to `fs.watchFile()` method will return a new [`fs.StatWatcher`](/api/fs#fsstatwatcher)
+A successful call to `fs.watchFile()` method will return a new [`fs.StatWatcher`](/api/v18/fs#fsstatwatcher)
object.
##### `watcher.ref()`
-
+
-* Returns: [`fs.StatWatcher`](/api/fs#fsstatwatcher)
+* Returns: [`fs.StatWatcher`](/api/v18/fs#fsstatwatcher)
When called, requests that the Node.js event loop _not_ exit so long as the
-[`fs.StatWatcher`](/api/fs#fsstatwatcher) is active. Calling `watcher.ref()` multiple times will have
+[`fs.StatWatcher`](/api/v18/fs#fsstatwatcher) is active. Calling `watcher.ref()` multiple times will have
no effect.
-By default, all [`fs.StatWatcher`](/api/fs#fsstatwatcher) objects are "ref'ed", making it normally
+By default, all [`fs.StatWatcher`](/api/v18/fs#fsstatwatcher) objects are "ref'ed", making it normally
unnecessary to call `watcher.ref()` unless `watcher.unref()` had been
called previously.
##### `watcher.unref()`
-
+
-* Returns: [`fs.StatWatcher`](/api/fs#fsstatwatcher)
+* Returns: [`fs.StatWatcher`](/api/v18/fs#fsstatwatcher)
-When called, the active [`fs.StatWatcher`](/api/fs#fsstatwatcher) object will not require the Node.js
+When called, the active [`fs.StatWatcher`](/api/v18/fs#fsstatwatcher) object will not require the Node.js
event loop to remain active. If there is no other activity keeping the
-event loop running, the process may exit before the [`fs.StatWatcher`](/api/fs#fsstatwatcher) object's
+event loop running, the process may exit before the [`fs.StatWatcher`](/api/v18/fs#fsstatwatcher) object's
callback is invoked. Calling `watcher.unref()` multiple times will have
no effect.
#### `fs.ReadStream`
-
+
-* Extends: [`stream.Readable`](/api/stream#streamreadable)
+* Extends: [`stream.Readable`](/api/v18/stream#streamreadable)
-Instances of [`fs.ReadStream`](/api/fs#fsreadstream) are created and returned using the
+Instances of [`fs.ReadStream`](/api/v18/fs#fsreadstream) are created and returned using the
[`fs.createReadStream()`][] function.
##### `'close'`
-
+
-Emitted when the [`fs.ReadStream`](/api/fs#fsreadstream)'s underlying file descriptor has been closed.
+Emitted when the [`fs.ReadStream`](/api/v18/fs#fsreadstream)'s underlying file descriptor has been closed.
##### `'open'`
-
+
-* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Integer file descriptor used by the [`fs.ReadStream`](/api/fs#fsreadstream).
+* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Integer file descriptor used by the [`fs.ReadStream`](/api/v18/fs#fsreadstream).
-Emitted when the [`fs.ReadStream`](/api/fs#fsreadstream)'s file descriptor has been opened.
+Emitted when the [`fs.ReadStream`](/api/v18/fs#fsreadstream)'s file descriptor has been opened.
##### `'ready'`
-
+
-Emitted when the [`fs.ReadStream`](/api/fs#fsreadstream) is ready to be used.
+Emitted when the [`fs.ReadStream`](/api/v18/fs#fsreadstream) is ready to be used.
Fires immediately after `'open'`.
##### `readStream.bytesRead`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -4738,19 +4801,19 @@ The number of bytes that have been read so far.
##### `readStream.path`
-
+
-* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer)
The path to the file the stream is reading from as specified in the first
argument to `fs.createReadStream()`. If `path` is passed as a string, then
-`readStream.path` will be a string. If `path` is passed as a [`Buffer`](/api/buffer#buffer), then
-`readStream.path` will be a [`Buffer`](/api/buffer#buffer). If `fd` is specified, then
+`readStream.path` will be a string. If `path` is passed as a [`Buffer`](/api/v18/buffer#buffer), then
+`readStream.path` will be a [`Buffer`](/api/v18/buffer#buffer). If `fd` is specified, then
`readStream.path` will be `undefined`.
##### `readStream.pending`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -4759,9 +4822,9 @@ i.e. before the `'ready'` event is emitted.
#### `fs.Stats`
-
+
-A [`fs.Stats`](/api/fs#fsstats) object provides information about a file.
+A [`fs.Stats`](/api/v18/fs#fsstats) object provides information about a file.
Objects returned from [`fs.stat()`][], [`fs.lstat()`][], [`fs.fstat()`][], and
their synchronous counterparts are of this type.
@@ -4821,64 +4884,64 @@ BigIntStats {
##### `stats.isBlockDevice()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a block device.
+Returns `true` if the [`fs.Stats`](/api/v18/fs#fsstats) object describes a block device.
##### `stats.isCharacterDevice()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a character device.
+Returns `true` if the [`fs.Stats`](/api/v18/fs#fsstats) object describes a character device.
##### `stats.isDirectory()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a file system directory.
+Returns `true` if the [`fs.Stats`](/api/v18/fs#fsstats) object describes a file system directory.
-If the [`fs.Stats`](/api/fs#fsstats) object was obtained from [`fs.lstat()`][], this method will
+If the [`fs.Stats`](/api/v18/fs#fsstats) object was obtained from [`fs.lstat()`][], this method will
always return `false`. This is because [`fs.lstat()`][] returns information
about a symbolic link itself and not the path it resolves to.
##### `stats.isFIFO()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a first-in-first-out (FIFO)
+Returns `true` if the [`fs.Stats`](/api/v18/fs#fsstats) object describes a first-in-first-out (FIFO)
pipe.
##### `stats.isFile()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a regular file.
+Returns `true` if the [`fs.Stats`](/api/v18/fs#fsstats) object describes a regular file.
##### `stats.isSocket()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a socket.
+Returns `true` if the [`fs.Stats`](/api/v18/fs#fsstats) object describes a socket.
##### `stats.isSymbolicLink()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a symbolic link.
+Returns `true` if the [`fs.Stats`](/api/v18/fs#fsstats) object describes a symbolic link.
This method is only valid when using [`fs.lstat()`][].
@@ -4947,7 +5010,7 @@ The number of blocks allocated for this file.
##### `stats.atimeMs`
-
+
* [`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)
@@ -4956,7 +5019,7 @@ milliseconds since the POSIX Epoch.
##### `stats.mtimeMs`
-
+
* [`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)
@@ -4965,7 +5028,7 @@ milliseconds since the POSIX Epoch.
##### `stats.ctimeMs`
-
+
* [`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)
@@ -4974,7 +5037,7 @@ in milliseconds since the POSIX Epoch.
##### `stats.birthtimeMs`
-
+
* [`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)
@@ -4983,7 +5046,7 @@ milliseconds since the POSIX Epoch.
##### `stats.atimeNs`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -4994,7 +5057,7 @@ nanoseconds since the POSIX Epoch.
##### `stats.mtimeNs`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -5005,7 +5068,7 @@ nanoseconds since the POSIX Epoch.
##### `stats.ctimeNs`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -5016,7 +5079,7 @@ in nanoseconds since the POSIX Epoch.
##### `stats.birthtimeNs`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -5027,7 +5090,7 @@ nanoseconds since the POSIX Epoch.
##### `stats.atime`
-
+
* [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -5035,7 +5098,7 @@ The timestamp indicating the last time this file was accessed.
##### `stats.mtime`
-
+
* [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -5043,7 +5106,7 @@ The timestamp indicating the last time this file was modified.
##### `stats.ctime`
-
+
* [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -5051,7 +5114,7 @@ The timestamp indicating the last time the file status was changed.
##### `stats.birthtime`
-
+
* [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -5087,7 +5150,7 @@ The times in the stat object have the following semantics:
link(2), mknod(2), rename(2), unlink(2), utimes(2),
read(2), and write(2) system calls.
* `birthtime` "Birth Time": Time of file creation. Set once when the
- file is created. On filesystems where birthtime is not available,
+ file is created. On file systems where birthtime is not available,
this field may instead hold either the `ctime` or
`1970-01-01T00:00Z` (ie, Unix epoch timestamp `0`). This value may be greater
than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants,
@@ -5097,47 +5160,139 @@ 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`
-
+
-* Extends [`stream.Writable`](/api/stream#streamwritable)
+* Extends [`stream.Writable`](/api/v18/stream#streamwritable)
-Instances of [`fs.WriteStream`](/api/fs#fswritestream) are created and returned using the
+Instances of [`fs.WriteStream`](/api/v18/fs#fswritestream) are created and returned using the
[`fs.createWriteStream()`][] function.
##### `'close'`
-
+
-Emitted when the [`fs.WriteStream`](/api/fs#fswritestream)'s underlying file descriptor has been closed.
+Emitted when the [`fs.WriteStream`](/api/v18/fs#fswritestream)'s underlying file descriptor has been closed.
##### `'open'`
-
+
-* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Integer file descriptor used by the [`fs.WriteStream`](/api/fs#fswritestream).
+* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Integer file descriptor used by the [`fs.WriteStream`](/api/v18/fs#fswritestream).
-Emitted when the [`fs.WriteStream`](/api/fs#fswritestream)'s file is opened.
+Emitted when the [`fs.WriteStream`](/api/v18/fs#fswritestream)'s file is opened.
##### `'ready'`
-
+
-Emitted when the [`fs.WriteStream`](/api/fs#fswritestream) is ready to be used.
+Emitted when the [`fs.WriteStream`](/api/v18/fs#fswritestream) is ready to be used.
Fires immediately after `'open'`.
##### `writeStream.bytesWritten`
-
+
The number of bytes written so far. Does not include data that is still queued
for writing.
##### `writeStream.close([callback])`
-
+
* `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)
@@ -5148,16 +5303,16 @@ is closed.
##### `writeStream.path`
-
+
The path to the file the stream is writing to as specified in the first
argument to [`fs.createWriteStream()`][]. If `path` is passed as a string, then
-`writeStream.path` will be a string. If `path` is passed as a [`Buffer`](/api/buffer#buffer), then
-`writeStream.path` will be a [`Buffer`](/api/buffer#buffer).
+`writeStream.path` will be a string. If `path` is passed as a [`Buffer`](/api/v18/buffer#buffer), then
+`writeStream.path` will be a [`Buffer`](/api/v18/buffer#buffer).
##### `writeStream.pending`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -5191,7 +5346,7 @@ import { open, constants } from 'node:fs';
const {
O_RDWR,
O_CREAT,
- O_EXCL
+ O_EXCL,
} = constants;
open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {
@@ -5363,7 +5518,7 @@ On Windows, only `O_APPEND`, `O_CREAT`, `O_EXCL`, `O_RDONLY`, `O_RDWR`,
###### File type constants
-The following constants are meant for use with the [`fs.Stats`](/api/fs#fsstats) object's
+The following constants are meant for use with the [`fs.Stats`](/api/v18/fs#fsstats) object's
`mode` property for determining a file's type.
@@ -5410,7 +5565,7 @@ are available.
###### File mode constants
-The following constants are meant for use with the [`fs.Stats`](/api/fs#fsstats) object's
+The following constants are meant for use with the [`fs.Stats`](/api/v18/fs#fsstats) object's
`mode` property for determining the access permissions for a file.
@@ -5482,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');
@@ -5495,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);
@@ -5527,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) => {
@@ -5537,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) => {
@@ -5554,7 +5707,7 @@ rename('/tmp/hello', '/tmp/world', (err) => {
#### File paths
Most `fs` operations accept file paths that may be specified in the form of
-a string, a [`Buffer`](/api/buffer#buffer), or a [`URL`](/api/url#the-whatwg-url-api) object using the `file:` protocol.
+a string, a [`Buffer`](/api/v18/buffer#buffer), or a [`URL`](/api/v18/url#the-whatwg-url-api) object using the `file:` protocol.
##### String paths
@@ -5572,7 +5725,7 @@ try {
fd = await open('/open/some/file.txt', 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
@@ -5586,16 +5739,16 @@ try {
fd = await open('file.txt', 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
##### File URL paths
-
+
For most `node:fs` module functions, the `path` or `filename` argument may be
-passed as a [`URL`](/api/url#the-whatwg-url-api) object using the `file:` protocol.
+passed as a [`URL`](/api/v18/url#the-whatwg-url-api) object using the `file:` protocol.
```mjs
import { readFileSync } from 'node:fs';
@@ -5607,8 +5760,8 @@ readFileSync(new URL('file:///tmp/hello'));
###### Platform-specific considerations
-On Windows, `file:` [`URL`](/api/url#the-whatwg-url-api)s with a host name convert to UNC paths, while `file:`
-[`URL`](/api/url#the-whatwg-url-api)s with drive letters convert to local absolute paths. `file:` [`URL`](/api/url#the-whatwg-url-api)s
+On Windows, `file:` [`URL`](/api/v18/url#the-whatwg-url-api)s with a host name convert to UNC paths, while `file:`
+[`URL`](/api/v18/url#the-whatwg-url-api)s with drive letters convert to local absolute paths. `file:` [`URL`](/api/v18/url#the-whatwg-url-api)s
with no host name and no drive letter will result in an error:
```mjs
@@ -5629,10 +5782,10 @@ readFileSync(new URL('file:///c/p/a/t/h/file'));
// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
```
-`file:` [`URL`](/api/url#the-whatwg-url-api)s with drive letters must use `:` as a separator just after
+`file:` [`URL`](/api/v18/url#the-whatwg-url-api)s with drive letters must use `:` as a separator just after
the drive letter. Using another separator will result in an error.
-On all other platforms, `file:` [`URL`](/api/url#the-whatwg-url-api)s with a host name are unsupported and
+On all other platforms, `file:` [`URL`](/api/v18/url#the-whatwg-url-api)s with a host name are unsupported and
will result in an error:
```mjs
@@ -5649,7 +5802,7 @@ readFileSync(new URL('file://hostname/p/a/t/h/file'));
readFileSync(new URL('file:///tmp/hello'));
```
-A `file:` [`URL`](/api/url#the-whatwg-url-api) having encoded slash characters will result in an error on all
+A `file:` [`URL`](/api/v18/url#the-whatwg-url-api) having encoded slash characters will result in an error on all
platforms:
```mjs
@@ -5668,7 +5821,7 @@ readFileSync(new URL('file:///p/a/t/h/%2f'));
/ characters */
```
-On Windows, `file:` [`URL`](/api/url#the-whatwg-url-api)s having encoded backslash will result in an error:
+On Windows, `file:` [`URL`](/api/v18/url#the-whatwg-url-api)s having encoded backslash will result in an error:
```mjs
import { readFileSync } from 'node:fs';
@@ -5682,10 +5835,10 @@ readFileSync(new URL('file:///C:/path/%5c'));
##### Buffer paths
-Paths specified using a [`Buffer`](/api/buffer#buffer) are useful primarily on certain POSIX
+Paths specified using a [`Buffer`](/api/v18/buffer#buffer) are useful primarily on certain POSIX
operating systems that treat file paths as opaque byte sequences. On such
systems, it is possible for a single file path to contain sub-sequences that
-use multiple character encodings. As with string paths, [`Buffer`](/api/buffer#buffer) paths may
+use multiple character encodings. As with string paths, [`Buffer`](/api/v18/buffer#buffer) paths may
be relative or absolute:
Example using an absolute path on POSIX:
@@ -5699,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();
}
```
@@ -5760,7 +5913,7 @@ open('/open/some/file.txt', 'r', (err, fd) => {
});
```
-The promise-based APIs use a [`FileHandle`](/api/fs#filehandle) object in place of the numeric
+The promise-based APIs use a [`FileHandle`](/api/v18/fs#filehandle) object in place of the numeric
file descriptor. These objects are better managed by the system to ensure
that resources are not leaked. However, it is still required that they are
closed when operations are completed:
@@ -5922,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/globals.en.md b/content/api/v18/globals.en.md
index 346cb81d73..2681a2c482 100644
--- a/content/api/v18/globals.en.md
+++ b/content/api/v18/globals.en.md
@@ -5,9 +5,9 @@ category: 'api'
version: 'v18'
---
-
+
-
+
These objects are available in all modules. The following variables may appear
to be global but are not. They exist only in the scope of modules, see the
@@ -25,9 +25,9 @@ accessible.
### `AbortController`
-
+
-
+
A utility class used to signal cancelation in selected `Promise`-based APIs.
The API is based on the Web API [`AbortController`][].
@@ -45,7 +45,7 @@ console.log(ac.signal.aborted); // Prints True
#### `abortController.abort([reason])`
-
+
* `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) An optional reason, retrievable on the `AbortSignal`'s
`reason` property.
@@ -55,31 +55,31 @@ the `'abort'` event.
#### `abortController.signal`
-
+
-* Type: [`AbortSignal`](/api/globals#abortsignal)
+* Type: [`AbortSignal`](/api/v18/globals#abortsignal)
#### `AbortSignal`
-
+
-* Extends: [`EventTarget`](/api/events#eventtarget)
+* Extends: [`EventTarget`](/api/v18/events#eventtarget)
The `AbortSignal` is used to notify observers when the
`abortController.abort()` method is called.
##### Static method: `AbortSignal.abort([reason])`
-
+
* `reason`: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
-* Returns: [`AbortSignal`](/api/globals#abortsignal)
+* Returns: [`AbortSignal`](/api/v18/globals#abortsignal)
Returns a new already aborted `AbortSignal`.
##### Static method: `AbortSignal.timeout(delay)`
-
+
* `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before triggering
the AbortSignal.
@@ -88,7 +88,7 @@ Returns a new `AbortSignal` which will be aborted in `delay` milliseconds.
##### `'abort'`
-
+
The `'abort'` event is emitted when the `abortController.abort()` method
is called. The callback is invoked with a single object argument with a
@@ -121,13 +121,13 @@ result in memory leaks.
##### `abortSignal.aborted`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True after the `AbortController` has been aborted.
##### `abortSignal.onabort`
-
+
* Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -136,7 +136,7 @@ when the `abortController.abort()` function has been called.
##### `abortSignal.reason`
-
+
* Type: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -150,23 +150,23 @@ console.log(ac.signal.reason); // Error('boom!');
##### `abortSignal.throwIfAborted()`
-
+
If `abortSignal.aborted` is `true`, throws `abortSignal.reason`.
### `Blob`
-
+
-
+
-See [`Blob`](/api/buffer#blob).
+See [`Blob`](/api/v18/buffer#blob).
### `Buffer`
-
+
-
+
* [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -174,9 +174,13 @@ Used to handle binary data. See the [buffer section][].
### `ByteLengthQueuingStrategy`
-
+
-
+
+
+Experimental.
+
+
A browser-compatible implementation of [`ByteLengthQueuingStrategy`][].
@@ -190,63 +194,75 @@ This variable may appear to be global but is not. See [`__filename`][].
### `atob(data)`
-
+
+
+
+
+Legacy. Use `Buffer.from(data, 'base64')` instead.
-
+
Global alias for [`buffer.atob()`][].
### `BroadcastChannel`
-
+
-See [`BroadcastChannel`](/api/worker_threads#broadcastchannel-extends-eventtarget).
+See [`BroadcastChannel`](/api/v18/worker_threads#broadcastchannel-extends-eventtarget).
### `btoa(data)`
-
+
-
+
+
+Legacy. Use `buf.toString('base64')` instead.
+
+
Global alias for [`buffer.btoa()`][].
### `clearImmediate(immediateObject)`
-
+
-
+
[`clearImmediate`][] is described in the [timers][] section.
### `clearInterval(intervalObject)`
-
+
-
+
[`clearInterval`][] is described in the [timers][] section.
### `clearTimeout(timeoutObject)`
-
+
-
+
[`clearTimeout`][] is described in the [timers][] section.
### `CompressionStream`
-
+
+
+
+
+Experimental.
-
+
A browser-compatible implementation of [`CompressionStream`][].
### `console`
-
+
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -254,72 +270,96 @@ Used to print to stdout and stderr. See the [`console`][] section.
### `CountQueuingStrategy`
-
+
-
+
+
+Experimental.
+
+
A browser-compatible implementation of [`CountQueuingStrategy`][].
### `Crypto`
-
+
+
+
+
+Experimental. Enable this API with the [`--experimental-global-webcrypto`][] CLI flag.
-
+
-A browser-compatible implementation of [`Crypto`](/api/webcrypto#crypto). This global is available
+A browser-compatible implementation of [`Crypto`](/api/v18/webcrypto#crypto). This global is available
only if the Node.js binary was compiled with including support for the
`node:crypto` module.
### `crypto`
-
+
-
+
+
+Experimental. Enable this API with the [`--experimental-global-webcrypto`][] CLI flag.
+
+
A browser-compatible implementation of the [Web Crypto API][].
### `CryptoKey`
-
+
+
+
-
+Experimental. Enable this API with the [`--experimental-global-webcrypto`][] CLI flag.
-A browser-compatible implementation of [`CryptoKey`](/api/webcrypto#cryptokey). This global is available
+
+
+A browser-compatible implementation of [`CryptoKey`](/api/v18/webcrypto#cryptokey). This global is available
only if the Node.js binary was compiled with including support for the
`node:crypto` module.
### `CustomEvent`
-
+
+
+
-
+Experimental. Enable this API with the [`--experimental-global-customevent`][] CLI flag.
-
+
+
+
A browser-compatible implementation of the [`CustomEvent` Web API][].
### `DecompressionStream`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`DecompressionStream`][].
### `Event`
-
+
-
+
A browser-compatible implementation of the `Event` class. See
[`EventTarget` and `Event` API][] for more details.
### `EventTarget`
-
+
-
+
A browser-compatible implementation of the `EventTarget` class. See
[`EventTarget` and `Event` API][] for more details.
@@ -330,25 +370,33 @@ This variable may appear to be global but is not. See [`exports`][].
### `fetch`
-
+
+
+
+
+Experimental. Disable this API with the [`--no-experimental-fetch`][] CLI flag.
-
+
A browser-compatible implementation of the [`fetch()`][] function.
### Class `FormData`
-
+
-
+
+
+Experimental. Disable this API with the [`--no-experimental-fetch`][] CLI flag.
+
+
A browser-compatible implementation of [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
### `global`
-
+
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The global namespace object.
@@ -359,33 +407,37 @@ Node.js this is different. The top-level scope is not the global scope;
### Class `Headers`
-
+
+
+
+
+Experimental. Disable this API with the [`--no-experimental-fetch`][] CLI flag.
-
+
A browser-compatible implementation of [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers).
### `MessageChannel`
-
+
-
+
The `MessageChannel` class. See [`MessageChannel`][] for more details.
### `MessageEvent`
-
+
-
+
The `MessageEvent` class. See [`MessageEvent`][] for more details.
### `MessagePort`
-
+
-
+
The `MessagePort` class. See [`MessagePort`][] for more details.
@@ -395,15 +447,15 @@ This variable may appear to be global but is not. See [`module`][].
### `performance`
-
+
The [`perf_hooks.performance`][] object.
### `process`
-
+
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -411,9 +463,9 @@ The process object. See the [`process` object][] section.
### `queueMicrotask(callback)`
-
+
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Function to be queued.
@@ -449,49 +501,73 @@ DataHandler.prototype.load = async function load(key) {
### `ReadableByteStreamController`
-
+
-
+
+
+Experimental.
+
+
A browser-compatible implementation of [`ReadableByteStreamController`][].
### `ReadableStream`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`ReadableStream`][].
### `ReadableStreamBYOBReader`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`ReadableStreamBYOBReader`][].
### `ReadableStreamBYOBRequest`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`ReadableStreamBYOBRequest`][].
### `ReadableStreamDefaultController`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`ReadableStreamDefaultController`][].
### `ReadableStreamDefaultReader`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`ReadableStreamDefaultReader`][].
@@ -501,139 +577,167 @@ This variable may appear to be global but is not. See [`require()`][].
### `Response`
-
+
+
+
-
+Experimental. Disable this API with the [`--no-experimental-fetch`][] CLI flag.
+
+
A browser-compatible implementation of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
### `Request`
-
+
+
+
-
+Experimental. Disable this API with the [`--no-experimental-fetch`][] CLI flag.
+
+
A browser-compatible implementation of [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request).
### `setImmediate(callback[, ...args])`
-
+
-
+
[`setImmediate`][] is described in the [timers][] section.
### `setInterval(callback, delay[, ...args])`
-
+
-
+
[`setInterval`][] is described in the [timers][] section.
### `setTimeout(callback, delay[, ...args])`
-
+
-
+
[`setTimeout`][] is described in the [timers][] section.
### `structuredClone(value[, options])`
-
+
-
+
The WHATWG [`structuredClone`][] method.
### `SubtleCrypto`
-
+
+
+
+
+Experimental. Enable this API with the [`--experimental-global-webcrypto`][] CLI flag.
-
+
-A browser-compatible implementation of [`SubtleCrypto`](/api/webcrypto#subtlecrypto). This global is available
+A browser-compatible implementation of [`SubtleCrypto`](/api/v18/webcrypto#subtlecrypto). This global is available
only if the Node.js binary was compiled with including support for the
`node:crypto` module.
### `DOMException`
-
+
-
+
The WHATWG `DOMException` class. See [`DOMException`][] for more details.
### `TextDecoder`
-
+
-
+
The WHATWG `TextDecoder` class. See the [`TextDecoder`][] section.
### `TextDecoderStream`
-
+
-
+
+
+Experimental.
+
+
A browser-compatible implementation of [`TextDecoderStream`][].
### `TextEncoder`
-
+
-
+
The WHATWG `TextEncoder` class. See the [`TextEncoder`][] section.
### `TextEncoderStream`
-
+
+
+
+
+Experimental.
-
+
A browser-compatible implementation of [`TextEncoderStream`][].
### `TransformStream`
-
+
-
+
+
+Experimental.
+
+
A browser-compatible implementation of [`TransformStream`][].
### `TransformStreamDefaultController`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`TransformStreamDefaultController`][].
### `URL`
-
+
-
+
The WHATWG `URL` class. See the [`URL`][] section.
### `URLSearchParams`
-
+
-
+
The WHATWG `URLSearchParams` class. See the [`URLSearchParams`][] section.
### `WebAssembly`
-
+
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -643,25 +747,37 @@ The object that acts as the namespace for all W3C
### `WritableStream`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`WritableStream`][].
### `WritableStreamDefaultController`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`WritableStreamDefaultController`][].
### `WritableStreamDefaultWriter`
-
+
+
+
+
+Experimental.
-
+
A browser-compatible implementation of [`WritableStreamDefaultWriter`][].
diff --git a/content/api/v18/http.en.md b/content/api/v18/http.en.md
index aa79171ed4..6b1fcbe35f 100644
--- a/content/api/v18/http.en.md
+++ b/content/api/v18/http.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v18'
---
-
+
-
+
-
+Stable
+
+
+
+
To use the HTTP server and client one must `require('node:http')`.
@@ -54,7 +58,7 @@ list like the following:
### `http.Agent`
-
+
An `Agent` is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
@@ -105,7 +109,7 @@ http.get({
hostname: 'localhost',
port: 80,
path: '/',
- agent: false // Create a new agent just for this one request
+ agent: false, // Create a new agent just for this one request
}, (res) => {
// Do stuff with response
});
@@ -113,7 +117,7 @@ http.get({
#### `new Agent([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Set of configurable options to set on the agent.
Can have the following fields:
@@ -176,12 +180,12 @@ http.request(options, onResponseCallback);
#### `agent.createConnection(options[, callback])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Options containing connection details. Check
[`net.createConnection()`][] for the format of the options
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback function that receives the created socket
-* Returns: [`stream.Duplex`](/api/stream#streamduplex)
+* Returns: [`stream.Duplex`](/api/v18/stream#streamduplex)
Produces a socket/stream to be used for HTTP requests.
@@ -191,17 +195,17 @@ custom agents may override this method in case greater flexibility is desired.
A socket/stream can be supplied in one of two ways: by returning the
socket/stream from this function, or by passing the socket/stream to `callback`.
-This method is guaranteed to return an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This method is guaranteed to return 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
+type other than [`net.Socket`](/api/v18/net#netsocket).
`callback` has a signature of `(err, stream)`.
#### `agent.keepSocketAlive(socket)`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex)
Called when `socket` is detached from a request and could be persisted by the
`Agent`. Default behavior is to:
@@ -216,15 +220,15 @@ This method can be overridden by a particular `Agent` subclass. If this
method returns a falsy value, the socket will be destroyed instead of persisting
it for use with the next request.
-The `socket` argument can be an instance of [`net.Socket`](/api/net#netsocket), a subclass of
-[`stream.Duplex`](/api/stream#streamduplex).
+The `socket` argument can be an instance of [`net.Socket`](/api/v18/net#netsocket), a subclass of
+[`stream.Duplex`](/api/v18/stream#streamduplex).
#### `agent.reuseSocket(socket, request)`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
-* `request` [`http.ClientRequest`](/api/http#httpclientrequest)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex)
+* `request` [`http.ClientRequest`](/api/v18/http#httpclientrequest)
Called when `socket` is attached to `request` after being persisted because of
the keep-alive options. Default behavior is to:
@@ -235,12 +239,12 @@ socket.ref();
This method can be overridden by a particular `Agent` subclass.
-The `socket` argument can be an instance of [`net.Socket`](/api/net#netsocket), a subclass of
-[`stream.Duplex`](/api/stream#streamduplex).
+The `socket` argument can be an instance of [`net.Socket`](/api/v18/net#netsocket), a subclass of
+[`stream.Duplex`](/api/v18/stream#streamduplex).
#### `agent.destroy()`
-
+
Destroy any sockets that are currently in use by the agent.
@@ -252,7 +256,7 @@ terminates them.
#### `agent.freeSockets`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -264,7 +268,7 @@ removed from the array on `'timeout'`.
#### `agent.getName([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A set of options providing information for name generation
* `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A domain name or IP address of the server to issue the
@@ -283,7 +287,7 @@ that determine socket reusability.
#### `agent.maxFreeSockets`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -293,7 +297,7 @@ state.
#### `agent.maxSockets`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -302,7 +306,7 @@ can have open per origin. Origin is the returned value of [`agent.getName()`][].
#### `agent.maxTotalSockets`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -311,7 +315,7 @@ can have open. Unlike `maxSockets`, this parameter applies across all origins.
#### `agent.requests`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -320,7 +324,7 @@ sockets. Do not modify.
#### `agent.sockets`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -329,9 +333,9 @@ agent. Do not modify.
### `http.ClientRequest`
-
+
-* Extends: [`http.OutgoingMessage`](/api/http#httpoutgoingmessage)
+* Extends: [`http.OutgoingMessage`](/api/v18/http#httpoutgoingmessage)
This object is created internally and returned from [`http.request()`][]. It
represents an _in-progress_ request whose header has already been queued. The
@@ -359,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
@@ -368,35 +373,39 @@ identified by `code:` [`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`][].
#### `'abort'`
-
+
+
+
-
+Deprecated. Listen for the `'close'` event instead.
+
+
Emitted when the request has been aborted by the client. This event is only
emitted on the first call to `abort()`.
#### `'close'`
-
+
Indicates that the request is completed, or its underlying connection was
terminated prematurely (before the response completion).
#### `'connect'`
-
+
-* `response` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
-* `head` [`Buffer`](/api/buffer#buffer)
+* `response` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex)
+* `head` [`Buffer`](/api/v18/buffer#buffer)
Emitted each time a server responds to a request with a `CONNECT` method. If
this event is not being listened for, clients receiving a `CONNECT` method will
have their connections closed.
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+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
+type other than [`net.Socket`](/api/v18/net#netsocket).
A client and server pair demonstrating how to listen for the `'connect'` event:
@@ -431,7 +440,7 @@ proxy.listen(1337, '127.0.0.1', () => {
port: 1337,
host: '127.0.0.1',
method: 'CONNECT',
- path: 'www.google.com:80'
+ path: 'www.google.com:80',
};
const req = http.request(options);
@@ -457,7 +466,7 @@ proxy.listen(1337, '127.0.0.1', () => {
#### `'continue'`
-
+
Emitted when the server sends a '100 Continue' HTTP response, usually because
the request contained 'Expect: 100-continue'. This is an instruction that
@@ -465,7 +474,7 @@ the client should send the request body.
#### `'finish'`
-
+
Emitted when the request has been sent. More specifically, this event is emitted
when the last segment of the response headers and body have been handed off to
@@ -474,7 +483,7 @@ the server has received anything yet.
#### `'information'`
-
+
* `info` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `httpVersion` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -496,7 +505,7 @@ const http = require('node:http');
const options = {
host: '127.0.0.1',
port: 8080,
- path: '/length_request'
+ path: '/length_request',
};
// Make a request
@@ -515,26 +524,26 @@ upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the
#### `'response'`
-
+
-* `response` [`http.IncomingMessage`](/api/http#httpincomingmessage)
+* `response` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
Emitted when a response is received to this request. This event is emitted only
once.
#### `'socket'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex)
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+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
+type other than [`net.Socket`](/api/v18/net#netsocket).
#### `'timeout'`
-
+
Emitted when the underlying socket times out from inactivity. This only notifies
that the socket has been idle. The request must be destroyed manually.
@@ -543,20 +552,20 @@ See also: [`request.setTimeout()`][].
#### `'upgrade'`
-
+
-* `response` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
-* `head` [`Buffer`](/api/buffer#buffer)
+* `response` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex)
+* `head` [`Buffer`](/api/v18/buffer#buffer)
Emitted each time a server responds to a request with an upgrade. If this
event is not being listened for and the response status code is 101 Switching
Protocols, clients receiving an upgrade header will have their connections
closed.
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+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
+type other than [`net.Socket`](/api/v18/net#netsocket).
A client server pair demonstrating how to listen for the `'upgrade'` event.
@@ -586,8 +595,8 @@ server.listen(1337, '127.0.0.1', () => {
host: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
- 'Upgrade': 'websocket'
- }
+ 'Upgrade': 'websocket',
+ },
};
const req = http.request(options);
@@ -603,18 +612,26 @@ server.listen(1337, '127.0.0.1', () => {
#### `request.abort()`
-
+
+
+
-
+Deprecated: Use [`request.destroy()`][] instead.
+
+
Marks the request as aborting. Calling this will cause remaining data
in the response to be dropped and the socket to be destroyed.
#### `request.aborted`
-
+
+
+
+
+Deprecated. Check [`request.destroyed`][] instead.
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -623,25 +640,29 @@ been aborted.
#### `request.connection`
-
+
+
+
+
+Deprecated. Use [`request.socket`][].
-
+
-* [`stream.Duplex`](/api/stream#streamduplex)
+* [`stream.Duplex`](/api/v18/stream#streamduplex)
See [`request.socket`][].
#### `request.cork()`
-
+
See [`writable.cork()`][].
#### `request.end([data[, encoding]][, callback])`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -658,7 +679,7 @@ is finished.
#### `request.destroy([error])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Optional, an error to emit with `'error'` event.
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -671,7 +692,7 @@ See [`writable.destroy()`][] for further details.
##### `request.destroyed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -681,9 +702,13 @@ See [`writable.destroyed`][] for further details.
#### `request.finished`
-
+
-
+
+
+Deprecated. Use [`request.writableEnded`][].
+
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -693,7 +718,7 @@ request was initiated via [`http.get()`][].
#### `request.flushHeaders()`
-
+
Flushes the request headers.
@@ -707,7 +732,7 @@ the optimization and kickstarts the request.
#### `request.getHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -730,7 +755,7 @@ const cookie = request.getHeader('Cookie');
#### `request.getHeaderNames()`
-
+
* Returns: string\[]
@@ -747,7 +772,7 @@ const headerNames = request.getHeaderNames();
#### `request.getHeaders()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -772,7 +797,7 @@ const headers = request.getHeaders();
#### `request.getRawHeaderNames()`
-
+
* Returns: string\[]
@@ -789,7 +814,7 @@ const headerNames = request.getRawHeaderNames();
#### `request.hasHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -809,31 +834,31 @@ Limits maximum response headers count. If set to 0, no limit will be applied.
#### `request.path`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request path.
#### `request.method`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request method.
#### `request.host`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request host.
#### `request.protocol`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request protocol.
#### `request.removeHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -845,7 +870,7 @@ request.removeHeader('Content-Type');
#### `request.reusedSocket`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the request is send through a reused socket.
@@ -899,7 +924,7 @@ retriableRequest();
#### `request.setHeader(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -934,7 +959,7 @@ request.setHeader('Content-Disposition', `attachment; filename*=utf-8''${encodeU
#### `request.setNoDelay([noDelay])`
-
+
* `noDelay` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -943,7 +968,7 @@ Once a socket is assigned to this request and is connected
#### `request.setSocketKeepAlive([enable][, initialDelay])`
-
+
* `enable` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `initialDelay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -953,21 +978,21 @@ Once a socket is assigned to this request and is connected
#### `request.setTimeout(timeout[, callback])`
-
+
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Milliseconds before a request times out.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional function to be called when a timeout occurs.
Same as binding to the `'timeout'` event.
-* Returns: [`http.ClientRequest`](/api/http#httpclientrequest)
+* Returns: [`http.ClientRequest`](/api/v18/http#httpclientrequest)
Once a socket is assigned to this request and is connected
[`socket.setTimeout()`][] will be called.
#### `request.socket`
-
+
-* [`stream.Duplex`](/api/stream#streamduplex)
+* [`stream.Duplex`](/api/v18/stream#streamduplex)
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit `'readable'` events
@@ -988,19 +1013,19 @@ req.once('response', (res) => {
});
```
-This property is guaranteed to be an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specified a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This property is guaranteed to be an instance of the [`net.Socket`](/api/v18/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v18/stream#streamduplex), unless the user specified a socket
+type other than [`net.Socket`](/api/v18/net#netsocket).
#### `request.uncork()`
-
+
See [`writable.uncork()`][].
#### `request.writableEnded`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1010,7 +1035,7 @@ does not indicate whether the data has been flushed, for this use
#### `request.writableFinished`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1019,9 +1044,9 @@ before the [`'finish'`][] event is emitted.
#### `request.write(chunk[, encoding][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1047,16 +1072,16 @@ nothing and waits for more input.
### `http.Server`
-
+
-* Extends: [`net.Server`](/api/net#netserver)
+* Extends: [`net.Server`](/api/v18/net#netserver)
#### `'checkContinue'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `response` [`http.ServerResponse`](/api/http#httpserverresponse)
+* `request` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
+* `response` [`http.ServerResponse`](/api/v18/http#httpserverresponse)
Emitted each time a request with an HTTP `Expect: 100-continue` is received.
If this event is not listened for, the server will automatically respond
@@ -1072,10 +1097,10 @@ not be emitted.
#### `'checkExpectation'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `response` [`http.ServerResponse`](/api/http#httpserverresponse)
+* `request` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
+* `response` [`http.ServerResponse`](/api/v18/http#httpserverresponse)
Emitted each time a request with an HTTP `Expect` header is received, where the
value is not `100-continue`. If this event is not listened for, the server will
@@ -1086,19 +1111,20 @@ not be emitted.
#### `'clientError'`
-
+
* `exception` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex)
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/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+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
+type other than [`net.Socket`](/api/v18/net#netsocket).
Default behavior is to try close the socket with a HTTP '400 Bad Request',
or a HTTP '431 Request Header Fields Too Large' in the case of a
@@ -1148,26 +1174,26 @@ server.on('clientError', (err, socket) => {
#### `'close'`
-
+
Emitted when the server closes.
#### `'connect'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) Arguments for the HTTP request, as it is in
+* `request` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage) Arguments for the HTTP request, as it is in
the [`'request'`][] event
-* `socket` [`stream.Duplex`](/api/stream#streamduplex) Network socket between the server and client
-* `head` [`Buffer`](/api/buffer#buffer) The first packet of the tunneling stream (may be empty)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex) Network socket between the server and client
+* `head` [`Buffer`](/api/v18/buffer#buffer) The first packet of the tunneling stream (may be empty)
Emitted each time a client requests an HTTP `CONNECT` method. If this event is
not listened for, then clients requesting a `CONNECT` method will have their
connections closed.
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+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
+type other than [`net.Socket`](/api/v18/net#netsocket).
After this event is emitted, the request's socket will not have a `'data'`
event listener, meaning it will need to be bound in order to handle data
@@ -1175,9 +1201,9 @@ sent to the server on that socket.
#### `'connection'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex)
This event is emitted when a new TCP stream is established. `socket` is
typically an object of type [`net.Socket`][]. Usually users will not want to
@@ -1192,17 +1218,17 @@ If `socket.setTimeout()` is called here, the timeout will be replaced with
`server.keepAliveTimeout` when the socket has served a request (if
`server.keepAliveTimeout` is non-zero).
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+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
+type other than [`net.Socket`](/api/v18/net#netsocket).
#### `'dropRequest'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) Arguments for the HTTP request, as it is in
+* `request` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage) Arguments for the HTTP request, as it is in
the [`'request'`][] event
-* `socket` [`stream.Duplex`](/api/stream#streamduplex) Network socket between the server and client
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex) Network socket between the server and client
When the number of requests on a socket reaches the threshold of
`server.maxRequestsPerSocket`, the server will drop new requests
@@ -1210,22 +1236,22 @@ and emit `'dropRequest'` event instead, then send `503` to client.
#### `'request'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `response` [`http.ServerResponse`](/api/http#httpserverresponse)
+* `request` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
+* `response` [`http.ServerResponse`](/api/v18/http#httpserverresponse)
Emitted each time there is a request. There may be multiple requests
per connection (in the case of HTTP Keep-Alive connections).
#### `'upgrade'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) Arguments for the HTTP request, as it is in
+* `request` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage) Arguments for the HTTP request, as it is in
the [`'request'`][] event
-* `socket` [`stream.Duplex`](/api/stream#streamduplex) Network socket between the server and client
-* `head` [`Buffer`](/api/buffer#buffer) The first packet of the upgraded stream (may be empty)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex) Network socket between the server and client
+* `head` [`Buffer`](/api/v18/buffer#buffer) The first packet of the upgraded stream (may be empty)
Emitted each time a client requests an HTTP upgrade. Listening to this event
is optional and clients cannot insist on a protocol change.
@@ -1234,13 +1260,13 @@ After this event is emitted, the request's socket will not have a `'data'`
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+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
+type other than [`net.Socket`](/api/v18/net#netsocket).
#### `server.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1248,22 +1274,22 @@ Stops the server from accepting new connections. See [`net.Server.close()`][].
#### `server.closeAllConnections()`
-
+
Closes all connections connected to this server.
#### `server.closeIdleConnections()`
-
+
Closes all connections connected to this server which are not sending a request
or waiting for a response.
#### `server.headersTimeout`
-
+
-* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `60000`
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** The minimum between [`server.requestTimeout`][] or `60000`.
Limit the amount of time the parser will wait to receive the complete HTTP
headers.
@@ -1282,13 +1308,13 @@ This method is identical to [`server.listen()`][] from [`net.Server`][].
#### `server.listening`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates whether or not the server is listening for connections.
#### `server.maxHeadersCount`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `2000`
@@ -1296,7 +1322,7 @@ Limits maximum incoming headers count. If set to 0, no limit will be applied.
#### `server.requestTimeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `300000`
@@ -1312,11 +1338,11 @@ reverse proxy in front.
#### `server.setTimeout([msecs][, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** 0 (no timeout)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.Server`](/api/http#httpserver)
+* Returns: [`http.Server`](/api/v18/http#httpserver)
Sets the timeout value for sockets, and emits a `'timeout'` event on
the Server object, passing the socket as an argument, if a timeout
@@ -1331,7 +1357,7 @@ explicitly.
#### `server.maxRequestsPerSocket`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Requests per socket. **Default:** 0 (no limit)
@@ -1346,7 +1372,7 @@ after the limit is reached will get `503 Service Unavailable` as a response.
#### `server.timeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** 0 (no timeout)
@@ -1360,7 +1386,7 @@ value only affects new connections to the server, not any existing connections.
#### `server.keepAliveTimeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** `5000` (5 seconds).
@@ -1380,23 +1406,23 @@ affects new connections to the server, not any existing connections.
### `http.ServerResponse`
-
+
-* Extends: [`http.OutgoingMessage`](/api/http#httpoutgoingmessage)
+* Extends: [`http.OutgoingMessage`](/api/v18/http#httpoutgoingmessage)
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the [`'request'`][] event.
#### `'close'`
-
+
Indicates that the response is completed, or its underlying connection was
terminated prematurely (before the response completion).
#### `'finish'`
-
+
Emitted when the response has been sent. More specifically, this event is
emitted when the last segment of the response headers and body have been
@@ -1405,7 +1431,7 @@ does not imply that the client has received anything yet.
#### `response.addTrailers(headers)`
-
+
* `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1432,25 +1458,29 @@ will result in a [`TypeError`][] being thrown.
#### `response.connection`
-
+
+
+
-
+Deprecated. Use [`response.socket`][].
-* [`stream.Duplex`](/api/stream#streamduplex)
+
+
+* [`stream.Duplex`](/api/v18/stream#streamduplex)
See [`response.socket`][].
#### `response.cork()`
-
+
See [`writable.cork()`][].
#### `response.end([data[, encoding]][, callback])`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -1467,9 +1497,13 @@ is finished.
#### `response.finished`
-
+
+
+
+
+Deprecated. Use [`response.writableEnded`][].
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1478,13 +1512,13 @@ has been called.
#### `response.flushHeaders()`
-
+
Flushes the response headers. See also: [`request.flushHeaders()`][].
#### `response.getHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -1507,7 +1541,7 @@ const setCookie = response.getHeader('set-cookie');
#### `response.getHeaderNames()`
-
+
* Returns: string\[]
@@ -1524,7 +1558,7 @@ const headerNames = response.getHeaderNames();
#### `response.getHeaders()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1549,7 +1583,7 @@ const headers = response.getHeaders();
#### `response.hasHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1563,7 +1597,7 @@ const hasContentType = response.hasHeader('content-type');
#### `response.headersSent`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1571,7 +1605,7 @@ Boolean (read-only). True if headers were sent, false otherwise.
#### `response.removeHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1583,15 +1617,15 @@ response.removeHeader('Content-Encoding');
#### `response.req`
-
+
-* [`http.IncomingMessage`](/api/http#httpincomingmessage)
+* [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
A reference to the original HTTP `request` object.
#### `response.sendDate`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1603,11 +1637,11 @@ in responses.
#### `response.setHeader(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
-* Returns: [`http.ServerResponse`](/api/http#httpserverresponse)
+* Returns: [`http.ServerResponse`](/api/v18/http#httpserverresponse)
Returns the response object.
@@ -1655,11 +1689,11 @@ is desired with potential future retrieval and modification, use
#### `response.setTimeout(msecs[, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.ServerResponse`](/api/http#httpserverresponse)
+* Returns: [`http.ServerResponse`](/api/v18/http#httpserverresponse)
Sets the Socket's timeout value to `msecs`. If a callback is
provided, then it is added as a listener on the `'timeout'` event on
@@ -1672,9 +1706,9 @@ timed out sockets must be handled explicitly.
#### `response.socket`
-
+
-* [`stream.Duplex`](/api/stream#streamduplex)
+* [`stream.Duplex`](/api/v18/stream#streamduplex)
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit `'readable'` events
@@ -1690,13 +1724,13 @@ const server = http.createServer((req, res) => {
}).listen(3000);
```
-This property is guaranteed to be an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specified a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This property is guaranteed to be an instance of the [`net.Socket`](/api/v18/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v18/stream#streamduplex), unless the user specified a socket
+type other than [`net.Socket`](/api/v18/net#netsocket).
#### `response.statusCode`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `200`
@@ -1713,7 +1747,7 @@ status code which was sent out.
#### `response.statusMessage`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1729,15 +1763,26 @@ 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()`
-
+
See [`writable.uncork()`][].
#### `response.writableEnded`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1747,7 +1792,7 @@ does not indicate whether the data has been flushed, for this use
#### `response.writableFinished`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1756,9 +1801,9 @@ before the [`'finish'`][] event is emitted.
#### `response.write(chunk[, encoding][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1792,7 +1837,7 @@ buffer. Returns `false` if all or part of the data was queued in user memory.
#### `response.writeContinue()`
-
+
Sends an HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the [`'checkContinue'`][] event on
@@ -1800,7 +1845,7 @@ the request body should be sent. See the [`'checkContinue'`][] event on
#### `response.writeEarlyHints(hints[, callback])`
-
+
* `hints` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1825,21 +1870,23 @@ const earlyHintsLinks = [
];
response.writeEarlyHints({
'link': earlyHintsLinks,
- 'x-trace-id': 'id for diagnostics'
+ 'x-trace-id': 'id for diagnostics',
});
const earlyHintsCallback = () => console.log('early hints message sent');
-response.writeEarlyHints(earlyHintsLinks, earlyHintsCallback);
+response.writeEarlyHints({
+ 'link': earlyHintsLinks,
+}, earlyHintsCallback);
```
#### `response.writeHead(statusCode[, statusMessage][, headers])`
-
+
* `statusCode` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `statusMessage` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
-* Returns: [`http.ServerResponse`](/api/http#httpserverresponse)
+* Returns: [`http.ServerResponse`](/api/v18/http#httpserverresponse)
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like `404`. The last argument, `headers`, are the response headers.
@@ -1858,7 +1905,7 @@ const body = 'hello world';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
- 'Content-Type': 'text/plain'
+ 'Content-Type': 'text/plain',
})
.end(body);
```
@@ -1900,46 +1947,54 @@ will result in a \[`Error`]\[] being thrown.
#### `response.writeProcessing()`
-
+
Sends a HTTP/1.1 102 Processing message to the client, indicating that
the request body should be sent.
### `http.IncomingMessage`
-
+
-* Extends: [`stream.Readable`](/api/stream#streamreadable)
+* Extends: [`stream.Readable`](/api/v18/stream#streamreadable)
An `IncomingMessage` object is created by [`http.Server`][] or
[`http.ClientRequest`][] and passed as the first argument to the [`'request'`][]
and [`'response'`][] event respectively. It may be used to access response
status, headers, and data.
-Different from its `socket` value which is a subclass of [`stream.Duplex`](/api/stream#streamduplex), the
-`IncomingMessage` itself extends [`stream.Readable`](/api/stream#streamreadable) and is created separately to
+Different from its `socket` value which is a subclass of [`stream.Duplex`](/api/v18/stream#streamduplex), the
+`IncomingMessage` itself extends [`stream.Readable`](/api/v18/stream#streamreadable) and is created separately to
parse and emit the incoming HTTP headers and payload, as the underlying socket
may be reused multiple times in case of keep-alive.
#### `'aborted'`
-
+
+
+
+
+Deprecated. Listen for `'close'` event instead.
-
+
Emitted when the request has been aborted.
#### `'close'`
-
+
Emitted when the request has been completed.
#### `message.aborted`
-
+
-
+
+
+Deprecated. Check `message.destroyed` from {stream.Readable}.
+
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1948,7 +2003,7 @@ been aborted.
#### `message.complete`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1962,7 +2017,7 @@ server fully transmitted a message before a connection was terminated:
const req = http.request({
host: '127.0.0.1',
port: 8080,
- method: 'POST'
+ method: 'POST',
}, (res) => {
res.resume();
res.on('end', () => {
@@ -1975,15 +2030,19 @@ const req = http.request({
#### `message.connection`
-
+
-
+
+
+Deprecated. Use [`message.socket`][].
+
+
Alias for [`message.socket`][].
#### `message.destroy([error])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -1994,7 +2053,7 @@ as an argument to any listeners on the event.
#### `message.headers`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2018,13 +2077,17 @@ header name:
`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
`last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`,
`retry-after`, `server`, or `user-agent` are discarded.
+ To allow duplicate values of the headers listed above to be joined,
+ use the option `joinDuplicateHeaders` in [`http.request()`][]
+ and [`http.createServer()`][]. See RFC 9110 Section 5.3 for more
+ information.
* `set-cookie` is always an array. Duplicates are added to the array.
* For duplicate `cookie` headers, the values are joined together with `; `.
* For all other headers, the values are joined together with `, `.
#### `message.headersDistinct`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2042,7 +2105,7 @@ console.log(request.headersDistinct);
#### `message.httpVersion`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2055,7 +2118,7 @@ Also `message.httpVersionMajor` is the first integer and
#### `message.method`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2065,7 +2128,7 @@ The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
#### `message.rawHeaders`
-
+
* string\[]
@@ -2093,7 +2156,7 @@ console.log(request.rawHeaders);
#### `message.rawTrailers`
-
+
* string\[]
@@ -2102,32 +2165,32 @@ received. Only populated at the `'end'` event.
#### `message.setTimeout(msecs[, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.IncomingMessage`](/api/http#httpincomingmessage)
+* Returns: [`http.IncomingMessage`](/api/v18/http#httpincomingmessage)
Calls `message.socket.setTimeout(msecs, callback)`.
#### `message.socket`
-
+
-* [`stream.Duplex`](/api/stream#streamduplex)
+* [`stream.Duplex`](/api/v18/stream#streamduplex)
The [`net.Socket`][] object associated with the connection.
With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the
client's authentication details.
-This property is guaranteed to be an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specified a socket
-type other than [`net.Socket`](/api/net#netsocket) or internally nulled.
+This property is guaranteed to be an instance of the [`net.Socket`](/api/v18/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v18/stream#streamduplex), unless the user specified a socket
+type other than [`net.Socket`](/api/v18/net#netsocket) or internally nulled.
#### `message.statusCode`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2137,7 +2200,7 @@ The 3-digit HTTP response status code. E.G. `404`.
#### `message.statusMessage`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2148,7 +2211,7 @@ Error`.
#### `message.trailers`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2156,7 +2219,7 @@ The request/response trailers object. Only populated at the `'end'` event.
#### `message.trailersDistinct`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2166,7 +2229,7 @@ Only populated at the `'end'` event.
#### `message.url`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2210,9 +2273,9 @@ URL {
### `http.OutgoingMessage`
-
+
-* Extends: [`Stream`](/api/stream#stream)
+* Extends: [`Stream`](/api/v18/stream#stream)
This class serves as the parent class of [`http.ClientRequest`][]
and [`http.ServerResponse`][]. It is an abstract outgoing message from
@@ -2220,19 +2283,19 @@ the perspective of the participants of an HTTP transaction.
#### `'drain'`
-
+
Emitted when the buffer of the message is free again.
#### `'finish'`
-
+
Emitted when the transmission is finished successfully.
#### `'prefinish'`
-
+
Emitted after `outgoingMessage.end()` is called.
When the event is emitted, all data has been processed but not necessarily
@@ -2240,7 +2303,7 @@ completely flushed.
#### `outgoingMessage.addTrailers(headers)`
-
+
* `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2265,7 +2328,7 @@ will result in a `TypeError` being thrown.
#### `outgoingMessage.appendHeader(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header name
* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header value
@@ -2285,21 +2348,25 @@ a single time with values joined using `; `.
#### `outgoingMessage.connection`
-
+
+
+
+
+Deprecated: Use [`outgoingMessage.socket`][] instead.
-
+
Alias of [`outgoingMessage.socket`][].
#### `outgoingMessage.cork()`
-
+
See [`writable.cork()`][].
#### `outgoingMessage.destroy([error])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Optional, an error to emit with `error` event
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -2309,9 +2376,9 @@ and is connected, that socket will be destroyed as well.
#### `outgoingMessage.end(chunk[, encoding][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Optional, **Default**: `utf8`
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -2329,7 +2396,7 @@ If `callback` is provided, it will be called when the message is finished
#### `outgoingMessage.flushHeaders()`
-
+
Flushes the message headers.
@@ -2344,7 +2411,7 @@ bypasses the optimization and kickstarts the message.
#### `outgoingMessage.getHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Name of header
* Returns [`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)
@@ -2354,7 +2421,7 @@ set, the returned value will be `undefined`.
#### `outgoingMessage.getHeaderNames()`
-
+
* Returns string\[]
@@ -2363,7 +2430,7 @@ All names are lowercase.
#### `outgoingMessage.getHeaders()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2388,7 +2455,7 @@ const headers = outgoingMessage.getHeaders();
#### `outgoingMessage.hasHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2402,7 +2469,7 @@ const hasContentType = outgoingMessage.hasHeader('content-type');
#### `outgoingMessage.headersSent`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2410,7 +2477,7 @@ Read-only. `true` if the headers were sent, otherwise `false`.
#### `outgoingMessage.pipe()`
-
+
Overrides the `stream.pipe()` method inherited from the legacy `Stream` class
which is the parent class of `http.OutgoingMessage`.
@@ -2420,7 +2487,7 @@ write-only stream.
#### `outgoingMessage.removeHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header name
@@ -2432,7 +2499,7 @@ outgoingMessage.removeHeader('Content-Encoding');
#### `outgoingMessage.setHeader(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header name
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Header value
@@ -2442,9 +2509,49 @@ 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])`
-
+
* `msesc` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional function to be called when a timeout
@@ -2456,9 +2563,9 @@ Once a socket is associated with the message and is connected,
#### `outgoingMessage.socket`
-
+
-* [`stream.Duplex`](/api/stream#streamduplex)
+* [`stream.Duplex`](/api/v18/stream#streamduplex)
Reference to the underlying socket. Usually, users will not want to access
this property.
@@ -2467,13 +2574,13 @@ After calling `outgoingMessage.end()`, this property will be nulled.
#### `outgoingMessage.uncork()`
-
+
See [`writable.uncork()`][]
#### `outgoingMessage.writableCorked`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2481,7 +2588,7 @@ The number of times `outgoingMessage.cork()` has been called.
#### `outgoingMessage.writableEnded`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2491,7 +2598,7 @@ not indicate whether the data has been flushed. For that purpose, use
#### `outgoingMessage.writableFinished`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2499,7 +2606,7 @@ Is `true` if all data has been flushed to the underlying system.
#### `outgoingMessage.writableHighWaterMark`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2508,7 +2615,7 @@ buffer level when [`writable.write()`][] starts returning false (`16384`).
#### `outgoingMessage.writableLength`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2516,7 +2623,7 @@ The number of buffered bytes.
#### `outgoingMessage.writableObjectMode`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2524,9 +2631,9 @@ Always `false`.
#### `outgoingMessage.write(chunk[, encoding][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v18/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default**: `utf8`
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2545,7 +2652,7 @@ memory. The `'drain'` event will be emitted when the buffer is free again.
### `http.METHODS`
-
+
* string\[]
@@ -2553,7 +2660,7 @@ A list of the HTTP methods that are supported by the parser.
### `http.STATUS_CODES`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2563,42 +2670,23 @@ Found'`.
### `http.createServer([options][, requestListener])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `IncomingMessage` [`http.IncomingMessage`](/api/http#httpincomingmessage) Specifies the `IncomingMessage`
- class to be used. Useful for extending the original `IncomingMessage`.
- **Default:** `IncomingMessage`.
- * `ServerResponse` [`http.ServerResponse`](/api/http#httpserverresponse) Specifies the `ServerResponse` class
- to be used. Useful for extending the original `ServerResponse`. **Default:**
- `ServerResponse`.
- * `requestTimeout`: Sets the timeout value in milliseconds for receiving
- the entire request from the client.
- See [`server.requestTimeout`][] for more information.
- **Default:** `300000`.
+ * `connectionsCheckingInterval`: Sets the interval value in milliseconds to
+ check for request and headers timeout in incomplete requests.
+ **Default:** `30000`.
* `headersTimeout`: Sets the timeout value in milliseconds for receiving
the complete HTTP headers from the client.
See [`server.headersTimeout`][] for more information.
**Default:** `60000`.
- * `keepAliveTimeout`: The number of milliseconds of inactivity a server
- needs to wait for additional incoming data, after it has finished writing
- the last response, before a socket will be destroyed.
- See [`server.keepAliveTimeout`][] for more information.
- **Default:** `5000`.
- * `connectionsCheckingInterval`: Sets the interval value in milliseconds to
- check for request and headers timeout in incomplete requests.
- **Default:** `30000`.
* `insecureHTTPParser` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Use an insecure HTTP parser that accepts
invalid HTTP headers when `true`. Using the insecure parser should be
avoided. See [`--insecure-http-parser`][] for more information.
- **Default:** `false`
- * `maxHeaderSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Optionally overrides the value of
- [`--max-http-header-size`][] for requests received by this server, i.e.
- the maximum length of request headers in bytes.
- **Default:** 16384 (16 KiB).
- * `noDelay` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to `true`, it disables the use of Nagle's
- algorithm immediately after a new incoming connection is received.
- **Default:** `true`.
+ **Default:** `false`.
+ * `IncomingMessage` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage) Specifies the `IncomingMessage`
+ class to be used. Useful for extending the original `IncomingMessage`.
+ **Default:** `IncomingMessage`.
* `keepAlive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to `true`, it enables keep-alive functionality
on the socket immediately after a new incoming connection is received,
similarly on what is done in \[`socket.setKeepAlive([enable][, initialDelay])`]\[`socket.setKeepAlive(enable, initialDelay)`].
@@ -2606,34 +2694,43 @@ Found'`.
* `keepAliveInitialDelay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If set to a positive number, it sets the
initial delay before the first keepalive probe is sent on an idle socket.
**Default:** `0`.
+ * `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.
+ **Default:** `false`.
+ * `ServerResponse` [`http.ServerResponse`](/api/v18/http#httpserverresponse) Specifies the `ServerResponse` class
+ to be used. Useful for extending the original `ServerResponse`. **Default:**
+ `ServerResponse`.
* `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 `; `.
* `requestListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.Server`](/api/http#httpserver)
+* Returns: [`http.Server`](/api/v18/http#httpserver)
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
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
- data: 'Hello World!'
+ data: 'Hello World!',
}));
});
server.listen(8000);
-```
-
-```cjs
+--------------
const http = require('node:http');
// Create a local server to receive data from
@@ -2643,7 +2740,7 @@ const server = http.createServer();
server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
- data: 'Hello World!'
+ data: 'Hello World!',
}));
});
@@ -2654,14 +2751,14 @@ server.listen(8000);
### `http.get(url[, options][, callback])`
-
+
-* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api)
+* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Accepts the same `options` as
[`http.request()`][], with the `method` always set to `GET`.
Properties that are inherited from the prototype are ignored.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.ClientRequest`](/api/http#httpclientrequest)
+* Returns: [`http.ClientRequest`](/api/v18/http#httpclientrequest)
Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and
@@ -2715,7 +2812,7 @@ http.get('http://localhost:8000/', (res) => {
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
- data: 'Hello World!'
+ data: 'Hello World!',
}));
});
@@ -2724,16 +2821,16 @@ server.listen(8000);
### `http.globalAgent`
-
+
-* [`http.Agent`](/api/http#httpagent)
+* [`http.Agent`](/api/v18/http#httpagent)
Global instance of `Agent` which is used as the default for all HTTP client
requests.
### `http.maxHeaderSize`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2748,11 +2845,11 @@ This can be overridden for servers and client requests by passing the
### `http.request(url[, options][, callback])`
-
+
-* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api)
+* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `agent` [`http.Agent`](/api/http#httpagent) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Controls [`Agent`][] behavior. Possible
+ * `agent` [`http.Agent`](/api/v18/http#httpagent) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Controls [`Agent`][] behavior. Possible
values:
* `undefined` (default): use [`http.globalAgent`][] for this host and port.
* `Agent` object: explicitly use the passed in `Agent`.
@@ -2797,7 +2894,7 @@ This can be overridden for servers and client requests by passing the
* `protocol` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Protocol to use. **Default:** `'http:'`.
* `setHost` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type): Specifies whether or not to automatically add the
`Host` header. Defaults to `true`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal): An AbortSignal that may be used to abort an ongoing
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal): An AbortSignal that may be used to abort an ongoing
request.
* `socketPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Unix domain socket. Cannot be used if one of `host`
or `port` is specified, as those specify a TCP Socket.
@@ -2806,8 +2903,12 @@ This can be overridden for servers and client requests by passing the
* `uniqueHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) A list of request headers that should be sent
only once. If the header's value is an array, the items will be joined
using `; `.
+ * `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.
+ **Default:** `false`.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.ClientRequest`](/api/http#httpclientrequest)
+* Returns: [`http.ClientRequest`](/api/v18/http#httpclientrequest)
`options` in [`socket.connect()`][] are also supported.
@@ -2832,7 +2933,7 @@ upload a file with a POST request, then write to the `ClientRequest` object.
const http = require('node:http');
const postData = JSON.stringify({
- 'msg': 'Hello World!'
+ 'msg': 'Hello World!',
});
const options = {
@@ -2842,8 +2943,8 @@ const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
- 'Content-Length': Buffer.byteLength(postData)
- }
+ 'Content-Length': Buffer.byteLength(postData),
+ },
};
const req = http.request(options, (res) => {
@@ -3007,11 +3108,12 @@ Passing an `AbortSignal` and then calling `abort` on the corresponding
`AbortController` will behave the same way as calling `.destroy()` on the
request itself.
-### `http.validateHeaderName(name)`
+### `http.validateHeaderName(name[, label])`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `label` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Label for error message. **Default:** `'Header name'`.
Performs the low-level validations on the provided `name` that are done when
`res.setHeader(name, value)` is called.
@@ -3031,15 +3133,15 @@ const { validateHeaderName } = require('node:http');
try {
validateHeaderName('');
} catch (err) {
- err instanceof TypeError; // --> true
- err.code; // --> 'ERR_INVALID_HTTP_TOKEN'
- err.message; // --> 'Header name must be a valid HTTP token [""]'
+ console.error(err instanceof TypeError); // --> true
+ console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'
+ console.error(err.message); // --> 'Header name must be a valid HTTP token [""]'
}
```
### `http.validateHeaderValue(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -3063,27 +3165,27 @@ const { validateHeaderValue } = require('node:http');
try {
validateHeaderValue('x-my-header', undefined);
} catch (err) {
- err instanceof TypeError; // --> true
- err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'; // --> true
- err.message; // --> 'Invalid value "undefined" for header "x-my-header"'
+ console.error(err instanceof TypeError); // --> true
+ console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true
+ console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"'
}
try {
validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
- err instanceof TypeError; // --> true
- err.code === 'ERR_INVALID_CHAR'; // --> true
- err.message; // --> 'Invalid character in header content ["x-my-header"]'
+ console.error(err instanceof TypeError); // --> true
+ console.error(err.code === 'ERR_INVALID_CHAR'); // --> true
+ console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]'
}
```
-### `http.setMaxIdleHTTPParsers`
+### `http.setMaxIdleHTTPParsers(max)`
-
+
-* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+* `max` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `1000`.
-Set the maximum number of idle HTTP parsers. **Default:** `1000`.
+Set the maximum number of idle HTTP parsers.
[RFC 8187]: https://www.rfc-editor.org/rfc/rfc8187.txt
[`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`]: /api/v18/errors#err_http_content_length_mismatch
@@ -3098,6 +3200,7 @@ Set the maximum number of idle HTTP parsers. **Default:** `1000`.
[`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
@@ -3111,6 +3214,7 @@ Set the maximum number of idle HTTP parsers. **Default:** `1000`.
[`http.IncomingMessage`]: #class-httpincomingmessage
[`http.ServerResponse`]: #class-httpserverresponse
[`http.Server`]: #class-httpserver
+[`http.createServer()`]: #httpcreateserveroptions-requestlistener
[`http.get()`]: #httpgetoptions-callback
[`http.globalAgent`]: #httpglobalagent
[`http.request()`]: #httprequestoptions-callback
@@ -3123,6 +3227,7 @@ Set the maximum number of idle HTTP parsers. **Default:** `1000`.
[`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
@@ -3141,6 +3246,7 @@ Set the maximum number of idle HTTP parsers. **Default:** `1000`.
[`response.getHeader()`]: #responsegetheadername
[`response.setHeader()`]: #responsesetheadername-value
[`response.socket`]: #responsesocket
+[`response.strictContentLength`]: #responsestrictcontentlength
[`response.writableEnded`]: #responsewritableended
[`response.writableFinished`]: #responsewritablefinished
[`response.write()`]: #responsewritechunk-encoding-callback
@@ -3148,7 +3254,6 @@ Set the maximum number of idle HTTP parsers. **Default:** `1000`.
[`response.writeContinue()`]: #responsewritecontinue
[`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers
[`server.headersTimeout`]: #serverheaderstimeout
-[`server.keepAliveTimeout`]: #serverkeepalivetimeout
[`server.listen()`]: /api/v18/net#serverlisten
[`server.requestTimeout`]: #serverrequesttimeout
[`server.timeout`]: #servertimeout
diff --git a/content/api/v18/http2.en.md b/content/api/v18/http2.en.md
index 08a4c5e691..5b73f08905 100644
--- a/content/api/v18/http2.en.md
+++ b/content/api/v18/http2.en.md
@@ -5,13 +5,17 @@ category: 'api'
version: 'v18'
---
-
+
-
+
-
+
-
+Stable
+
+
+
+
The `node:http2` module provides an implementation of the [HTTP/2][] protocol.
It can be accessed using:
@@ -33,7 +37,7 @@ let http2;
try {
http2 = require('node:http2');
} catch (err) {
- console.log('http2 support is disabled!');
+ console.error('http2 support is disabled!');
}
```
@@ -51,7 +55,7 @@ let http2;
try {
http2 = await import('node:http2');
} catch (err) {
- console.log('http2 support is disabled!');
+ console.error('http2 support is disabled!');
}
```
@@ -80,7 +84,7 @@ const fs = require('node:fs');
const server = http2.createSecureServer({
key: fs.readFileSync('localhost-privkey.pem'),
- cert: fs.readFileSync('localhost-cert.pem')
+ cert: fs.readFileSync('localhost-cert.pem'),
});
server.on('error', (err) => console.error(err));
@@ -88,7 +92,7 @@ server.on('stream', (stream, headers) => {
// stream is a Duplex
stream.respond({
'content-type': 'text/html; charset=utf-8',
- ':status': 200
+ ':status': 200,
});
stream.end('
Hello World
');
});
@@ -111,7 +115,7 @@ The following illustrates an HTTP/2 client:
const http2 = require('node:http2');
const fs = require('node:fs');
const client = http2.connect('https://localhost:8443', {
- ca: fs.readFileSync('localhost-cert.pem')
+ ca: fs.readFileSync('localhost-cert.pem'),
});
client.on('error', (err) => console.error(err));
@@ -135,9 +139,9 @@ req.end();
#### `Http2Session`
-
+
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v18/events#eventemitter)
Instances of the `http2.Http2Session` class represent an active communications
session between an HTTP/2 client and server. Instances of this class are _not_
@@ -173,17 +177,17 @@ solely on the API of the `Http2Session`.
##### `'close'`
-
+
The `'close'` event is emitted once the `Http2Session` has been destroyed. Its
listener does not expect any arguments.
##### `'connect'`
-
+
-* `session` [`Http2Session`](/api/http2#http2session)
-* `socket` [`net.Socket`](/api/net#netsocket)
+* `session` [`Http2Session`](/api/v18/http2#http2session)
+* `socket` [`net.Socket`](/api/v18/net#netsocket)
The `'connect'` event is emitted once the `Http2Session` has been successfully
connected to the remote peer and communication may begin.
@@ -192,7 +196,7 @@ User code will typically not listen for this event directly.
##### `'error'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -201,7 +205,7 @@ an `Http2Session`.
##### `'frameError'`
-
+
* `type` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The frame type.
* `code` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The error code.
@@ -220,12 +224,12 @@ immediately following the `'frameError'` event.
##### `'goaway'`
-
+
* `errorCode` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The HTTP/2 error code specified in the `GOAWAY` frame.
* `lastStreamID` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ID of the last stream the remote peer successfully
processed (or `0` if no ID is specified).
-* `opaqueData` [`Buffer`](/api/buffer#buffer) If additional opaque data was included in the `GOAWAY`
+* `opaqueData` [`Buffer`](/api/v18/buffer#buffer) If additional opaque data was included in the `GOAWAY`
frame, a `Buffer` instance will be passed containing that data.
The `'goaway'` event is emitted when a `GOAWAY` frame is received.
@@ -235,7 +239,7 @@ event is emitted.
##### `'localSettings'`
-
+
* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.
@@ -255,16 +259,16 @@ session.on('localSettings', (settings) => {
##### `'ping'`
-
+
-* `payload` [`Buffer`](/api/buffer#buffer) The `PING` frame 8-byte payload
+* `payload` [`Buffer`](/api/v18/buffer#buffer) The `PING` frame 8-byte payload
The `'ping'` event is emitted whenever a `PING` frame is received from the
connected peer.
##### `'remoteSettings'`
-
+
* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.
@@ -279,9 +283,9 @@ session.on('remoteSettings', (settings) => {
##### `'stream'`
-
+
-* `stream` [`Http2Stream`](/api/http2#http2stream) A reference to the stream
+* `stream` [`Http2Stream`](/api/v18/http2#http2stream) A reference to the stream
* `headers` {HTTP/2 Headers Object} An object describing the headers
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags
* `rawHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the raw header names followed by
@@ -297,7 +301,7 @@ session.on('stream', (stream, headers, flags) => {
// ...
stream.respond({
':status': 200,
- 'content-type': 'text/plain; charset=utf-8'
+ 'content-type': 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
@@ -318,13 +322,13 @@ const server = http2.createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
- ':status': 200
+ ':status': 200,
});
stream.on('error', (error) => console.error(error));
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,
@@ -333,7 +337,7 @@ stream level, as shown above.
##### `'timeout'`
-
+
After the `http2session.setTimeout()` method is used to set the timeout period
for this `Http2Session`, the `'timeout'` event is emitted if there is no
@@ -347,7 +351,7 @@ session.on('timeout', () => { /* .. */ });
##### `http2session.alpnProtocol`
-
+
* [`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)
@@ -358,7 +362,7 @@ property.
##### `http2session.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -372,7 +376,7 @@ If specified, the `callback` function is registered as a handler for the
##### `http2session.closed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -381,7 +385,7 @@ Will be `true` if this `Http2Session` instance has been closed, otherwise
##### `http2session.connecting`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -391,7 +395,7 @@ callback.
##### `http2session.destroy([error][, code])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) An `Error` object if the `Http2Session` is being destroyed
due to an error.
@@ -411,7 +415,7 @@ If there are any remaining open `Http2Streams` associated with the
##### `http2session.destroyed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -420,7 +424,7 @@ longer be used, otherwise `false`.
##### `http2session.encrypted`
-
+
* [`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)
@@ -431,11 +435,11 @@ or stream.
##### `http2session.goaway([code[, lastStreamID[, opaqueData]]])`
-
+
* `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) An HTTP/2 error code
* `lastStreamID` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The numeric ID of the last processed `Http2Stream`
-* `opaqueData` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A `TypedArray` or `DataView`
+* `opaqueData` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A `TypedArray` or `DataView`
instance containing additional data to be carried within the `GOAWAY` frame.
Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the
@@ -443,7 +447,7 @@ Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the
##### `http2session.localSettings`
-
+
* {HTTP/2 Settings Object}
@@ -452,7 +456,7 @@ A prototype-less object describing the current local settings of this
##### `http2session.originSet`
-
+
* [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
@@ -464,7 +468,7 @@ The `originSet` property is only available when using a secure TLS connection.
##### `http2session.pendingSettingsAck`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -475,9 +479,9 @@ frames have been acknowledged.
##### `http2session.ping([payload, ]callback)`
-
+
-* `payload` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Optional ping payload.
+* `payload` [`Buffer`](/api/v18/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Optional ping payload.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -512,14 +516,14 @@ If the `payload` argument is not specified, the default payload will be the
##### `http2session.ref()`
-
+
Calls [`ref()`][`net.Socket.prototype.ref()`] on this `Http2Session`
instance's underlying [`net.Socket`][].
##### `http2session.remoteSettings`
-
+
* {HTTP/2 Settings Object}
@@ -528,7 +532,7 @@ A prototype-less object describing the current remote settings of this
##### `http2session.setLocalWindowSize(windowSize)`
-
+
* `windowSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -550,7 +554,7 @@ server.on('connect', (session) => {
##### `http2session.setTimeout(msecs, callback)`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -561,9 +565,9 @@ registered as a listener on the `'timeout'` event.
##### `http2session.socket`
-
+
-* [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket)
+* [`net.Socket`](/api/v18/net#netsocket) | [`tls.TLSSocket`](/api/v18/tls#tlstlssocket)
Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but
limits available methods to ones safe to use with HTTP/2.
@@ -578,7 +582,7 @@ All other interactions will be routed directly to the socket.
##### `http2session.state`
-
+
Provides miscellaneous information about the current state of the
`Http2Session`.
@@ -607,7 +611,7 @@ An object describing the current status of this `Http2Session`.
##### `http2session.settings([settings][, callback])`
-
+
* `settings` {HTTP/2 Settings Object}
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback that is called once the session is connected or
@@ -629,7 +633,7 @@ multiple `SETTINGS` frames while acknowledgment is still pending.
##### `http2session.type`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -640,24 +644,24 @@ client.
##### `http2session.unref()`
-
+
Calls [`unref()`][`net.Socket.prototype.unref()`] on this `Http2Session`
instance's underlying [`net.Socket`][].
#### `ServerHttp2Session`
-
+
-* Extends: [`Http2Session`](/api/http2#http2session)
+* Extends: [`Http2Session`](/api/v18/http2#http2session)
##### `serverhttp2session.altsvc(alt, originOrStream)`
-
+
* `alt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A description of the alternative service configuration as
defined by [RFC 7838][].
-* `originOrStream` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Either a URL string specifying
+* `originOrStream` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v18/url#the-whatwg-url-api) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Either a URL string specifying
the origin (or an `Object` with an `origin` property) or the numeric
identifier of an active `Http2Stream` as given by the `http2stream.id`
property.
@@ -719,7 +723,7 @@ are passed through as provided by the user or received from the peer.
##### `serverhttp2session.origin(...origins)`
-
+
* `origins` { string | URL | Object } One or more URL Strings passed as
separate arguments.
@@ -768,13 +772,13 @@ server.on('stream', (stream) => {
#### `ClientHttp2Session`
-
+
-* Extends: [`Http2Session`](/api/http2#http2session)
+* Extends: [`Http2Session`](/api/v18/http2#http2session)
##### `'altsvc'`
-
+
* `alt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `origin` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -798,7 +802,7 @@ client.on('altsvc', (alt, origin, streamId) => {
##### `'origin'`
-
+
* `origins` string\[]
@@ -821,7 +825,7 @@ The `'origin'` event is only emitted when using a secure TLS connection.
##### `clienthttp2session.request(headers[, options])`
-
+
* `headers` {HTTP/2 Headers Object}
@@ -840,10 +844,10 @@ The `'origin'` event is only emitted when using a secure TLS connection.
and `256` (inclusive).
* `waitForTrailers` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, the `Http2Stream` will emit the
`'wantTrailers'` event after the final `DATA` frame has been sent.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An AbortSignal that may be used to abort an ongoing
+ * `signal` [`AbortSignal`](/api/v18/globals#abortsignal) An AbortSignal that may be used to abort an ongoing
request.
-* Returns: [`ClientHttp2Stream`](/api/http2#clienthttp2stream)
+* Returns: [`ClientHttp2Stream`](/api/v18/http2#clienthttp2stream)
For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`
creates and returns an `Http2Stream` instance that can be used to send an
@@ -863,7 +867,7 @@ const http2 = require('node:http2');
const clientSession = http2.connect('https://localhost:1234');
const {
HTTP2_HEADER_PATH,
- HTTP2_HEADER_STATUS
+ HTTP2_HEADER_STATUS,
} = http2.constants;
const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });
@@ -896,9 +900,9 @@ they respectively default to:
#### `Http2Stream`
-
+
-* Extends: [`stream.Duplex`](/api/stream#streamduplex)
+* Extends: [`stream.Duplex`](/api/v18/stream#streamduplex)
Each instance of the `Http2Stream` class represents a bidirectional HTTP/2
communications stream over an `Http2Session` instance. Any single `Http2Session`
@@ -928,7 +932,7 @@ encoding.
```js
stream.respond({
'content-type': 'text/html; charset=utf-8',
- ':status': 200
+ ':status': 200,
});
```
@@ -979,7 +983,7 @@ destroyed.
##### `'aborted'`
-
+
The `'aborted'` event is emitted whenever a `Http2Stream` instance is
abnormally aborted in mid-communication.
@@ -990,7 +994,7 @@ has not been ended.
##### `'close'`
-
+
The `'close'` event is emitted when the `Http2Stream` is destroyed. Once
this event is emitted, the `Http2Stream` instance is no longer usable.
@@ -1001,7 +1005,7 @@ the `http2stream.rstCode` property. If the code is any value other than
##### `'error'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -1010,7 +1014,7 @@ an `Http2Stream`.
##### `'frameError'`
-
+
* `type` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The frame type.
* `code` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The error code.
@@ -1025,7 +1029,7 @@ error code. The `Http2Stream` instance will be destroyed immediately after the
##### `'ready'`
-
+
The `'ready'` event is emitted when the `Http2Stream` has been opened, has
been assigned an `id`, and can be used. The listener does not expect any
@@ -1033,7 +1037,7 @@ arguments.
##### `'timeout'`
-
+
The `'timeout'` event is emitted after no activity is received for this
`Http2Stream` within the number of milliseconds set using
@@ -1042,7 +1046,7 @@ Its listener does not expect any arguments.
##### `'trailers'`
-
+
* `headers` {HTTP/2 Headers Object} An object describing the headers
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags
@@ -1063,7 +1067,7 @@ stream.on('trailers', (headers, flags) => {
##### `'wantTrailers'`
-
+
The `'wantTrailers'` event is emitted when the `Http2Stream` has queued the
final `DATA` frame to be sent on a frame and the `Http2Stream` is ready to send
@@ -1072,7 +1076,7 @@ option must be set for this event to be emitted.
##### `http2stream.aborted`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1081,7 +1085,7 @@ the `'aborted'` event will have been emitted.
##### `http2stream.bufferSize`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1090,7 +1094,7 @@ See [`net.Socket.bufferSize`][] for details.
##### `http2stream.close(code[, callback])`
-
+
* `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Unsigned 32-bit integer identifying the error code.
**Default:** `http2.constants.NGHTTP2_NO_ERROR` (`0x00`).
@@ -1102,7 +1106,7 @@ connected HTTP/2 peer.
##### `http2stream.closed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1110,7 +1114,7 @@ Set to `true` if the `Http2Stream` instance has been closed.
##### `http2stream.destroyed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1119,7 +1123,7 @@ usable.
##### `http2stream.endAfterHeaders`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1129,7 +1133,7 @@ and the readable side of the `Http2Stream` will be closed.
##### `http2stream.id`
-
+
* [`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)
@@ -1138,7 +1142,7 @@ if the stream identifier has not yet been assigned.
##### `http2stream.pending`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1147,7 +1151,7 @@ numeric stream identifier.
##### `http2stream.priority(options)`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `exclusive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true` and `parent` identifies a parent Stream,
@@ -1166,7 +1170,7 @@ Updates the priority for this `Http2Stream` instance.
##### `http2stream.rstCode`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1177,7 +1181,7 @@ calling `http2stream.close()`, or `http2stream.destroy()`. Will be
##### `http2stream.sentHeaders`
-
+
* {HTTP/2 Headers Object}
@@ -1185,7 +1189,7 @@ An object containing the outbound headers sent for this `Http2Stream`.
##### `http2stream.sentInfoHeaders`
-
+
* {HTTP/2 Headers Object\[]}
@@ -1194,7 +1198,7 @@ sent for this `Http2Stream`.
##### `http2stream.sentTrailers`
-
+
* {HTTP/2 Headers Object}
@@ -1202,16 +1206,16 @@ An object containing the outbound trailers sent for this `HttpStream`.
##### `http2stream.session`
-
+
-* [`Http2Session`](/api/http2#http2session)
+* [`Http2Session`](/api/v18/http2#http2session)
A reference to the `Http2Session` instance that owns this `Http2Stream`. The
value will be `undefined` after the `Http2Stream` instance is destroyed.
##### `http2stream.setTimeout(msecs, callback)`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1228,7 +1232,7 @@ req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));
##### `http2stream.state`
-
+
Provides miscellaneous information about the current state of the
`Http2Stream`.
@@ -1250,7 +1254,7 @@ A current state of this `Http2Stream`.
##### `http2stream.sendTrailers(headers)`
-
+
* `headers` {HTTP/2 Headers Object}
@@ -1278,9 +1282,9 @@ fields (e.g. `':method'`, `':path'`, etc).
#### `ClientHttp2Stream`
-
+
-* Extends [`Http2Stream`](/api/http2#http2stream)
+* Extends [`Http2Stream`](/api/v18/http2#http2stream)
The `ClientHttp2Stream` class is an extension of `Http2Stream` that is
used exclusively on HTTP/2 Clients. `Http2Stream` instances on the client
@@ -1289,7 +1293,7 @@ the client.
##### `'continue'`
-
+
Emitted when the server sends a `100 Continue` status, usually because
the request contained `Expect: 100-continue`. This is an instruction that
@@ -1297,7 +1301,7 @@ the client should send the request body.
##### `'headers'`
-
+
* `headers` {HTTP/2 Headers Object}
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1315,7 +1319,7 @@ stream.on('headers', (headers, flags) => {
##### `'push'`
-
+
* `headers` {HTTP/2 Headers Object}
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1332,7 +1336,7 @@ stream.on('push', (headers, flags) => {
##### `'response'`
-
+
* `headers` {HTTP/2 Headers Object}
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1353,9 +1357,9 @@ req.on('response', (headers, flags) => {
#### `ServerHttp2Stream`
-
+
-* Extends: [`Http2Stream`](/api/http2#http2stream)
+* Extends: [`Http2Stream`](/api/v18/http2#http2stream)
The `ServerHttp2Stream` class is an extension of [`Http2Stream`][] that is
used exclusively on HTTP/2 Servers. `Http2Stream` instances on the server
@@ -1364,7 +1368,7 @@ provide additional methods such as `http2stream.pushStream()` and
##### `http2stream.additionalHeaders(headers)`
-
+
* `headers` {HTTP/2 Headers Object}
@@ -1372,7 +1376,7 @@ Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer.
##### `http2stream.headersSent`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1380,7 +1384,7 @@ True if headers were sent, false otherwise (read-only).
##### `http2stream.pushAllowed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1391,7 +1395,7 @@ accepts push streams, `false` otherwise. Settings are the same for every
##### `http2stream.pushStream(headers[, options], callback)`
-
+
* `headers` {HTTP/2 Headers Object}
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1404,7 +1408,7 @@ accepts push streams, `false` otherwise. Settings are the same for every
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback that is called once the push stream has been
initiated.
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
- * `pushStream` [`ServerHttp2Stream`](/api/http2#serverhttp2stream) The returned `pushStream` object.
+ * `pushStream` [`ServerHttp2Stream`](/api/v18/http2#serverhttp2stream) The returned `pushStream` object.
* `headers` {HTTP/2 Headers Object} Headers object the `pushStream` was
initiated with.
@@ -1435,7 +1439,7 @@ and will throw an error.
##### `http2stream.respond([headers[, options]])`
-
+
* `headers` {HTTP/2 Headers Object}
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1477,9 +1481,9 @@ server.on('stream', (stream) => {
##### `http2stream.respondWithFD(fd[, headers[, options]])`
-
+
-* `fd` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/fs#filehandle) A readable file descriptor.
+* `fd` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/v18/fs#filehandle) A readable file descriptor.
* `headers` {HTTP/2 Headers Object}
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `statCheck` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1508,7 +1512,7 @@ server.on('stream', (stream) => {
const headers = {
'content-length': stat.size,
'last-modified': stat.mtime.toUTCString(),
- 'content-type': 'text/plain; charset=utf-8'
+ 'content-type': 'text/plain; charset=utf-8',
};
stream.respondWithFD(fd, headers);
stream.on('close', () => fs.closeSync(fd));
@@ -1553,7 +1557,7 @@ server.on('stream', (stream) => {
const headers = {
'content-length': stat.size,
'last-modified': stat.mtime.toUTCString(),
- 'content-type': 'text/plain; charset=utf-8'
+ 'content-type': 'text/plain; charset=utf-8',
};
stream.respondWithFD(fd, headers, { waitForTrailers: true });
stream.on('wantTrailers', () => {
@@ -1566,9 +1570,9 @@ server.on('stream', (stream) => {
##### `http2stream.respondWithFile(path[, headers[, options]])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `headers` {HTTP/2 Headers Object}
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `statCheck` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1615,7 +1619,7 @@ server.on('stream', (stream) => {
}
} catch (err) {
// Perform actual error handling.
- console.log(err);
+ console.error(err);
}
stream.end();
}
@@ -1681,9 +1685,9 @@ server.on('stream', (stream) => {
#### `Http2Server`
-
+
-* Extends: [`net.Server`](/api/net#netserver)
+* Extends: [`net.Server`](/api/v18/net#netserver)
Instances of `Http2Server` are created using the `http2.createServer()`
function. The `Http2Server` class is not exported directly by the
@@ -1691,10 +1695,10 @@ function. The `Http2Server` class is not exported directly by the
##### `'checkContinue'`
-
+
-* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest)
-* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse)
+* `request` [`http2.Http2ServerRequest`](/api/v18/http2#http2http2serverrequest)
+* `response` [`http2.Http2ServerResponse`](/api/v18/http2#http2http2serverresponse)
If a [`'request'`][] listener is registered or [`http2.createServer()`][] is
supplied a callback function, the `'checkContinue'` event is emitted each time
@@ -1712,9 +1716,9 @@ not be emitted.
##### `'connection'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex)
This event is emitted when a new TCP stream is established. `socket` is
typically an object of type [`net.Socket`][]. Usually users will not want to
@@ -1725,38 +1729,38 @@ into the HTTP server. In that case, any [`Duplex`][] stream can be passed.
##### `'request'`
-
+
-* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest)
-* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse)
+* `request` [`http2.Http2ServerRequest`](/api/v18/http2#http2http2serverrequest)
+* `response` [`http2.Http2ServerResponse`](/api/v18/http2#http2http2serverresponse)
Emitted each time there is a request. There may be multiple requests
per session. See the [Compatibility API][].
##### `'session'`
-
+
-* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session)
+* `session` [`ServerHttp2Session`](/api/v18/http2#serverhttp2session)
The `'session'` event is emitted when a new `Http2Session` is created by the
`Http2Server`.
##### `'sessionError'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
-* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session)
+* `session` [`ServerHttp2Session`](/api/v18/http2#serverhttp2session)
The `'sessionError'` event is emitted when an `'error'` event is emitted by
an `Http2Session` object associated with the `Http2Server`.
##### `'stream'`
-
+
-* `stream` [`Http2Stream`](/api/http2#http2stream) A reference to the stream
+* `stream` [`Http2Stream`](/api/v18/http2#http2stream) A reference to the stream
* `headers` {HTTP/2 Headers Object} An object describing the headers
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags
* `rawHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the raw header names followed by
@@ -1773,7 +1777,7 @@ const {
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS,
- HTTP2_HEADER_CONTENT_TYPE
+ HTTP2_HEADER_CONTENT_TYPE,
} = http2.constants;
const server = http2.createServer();
@@ -1783,7 +1787,7 @@ server.on('stream', (stream, headers, flags) => {
// ...
stream.respond({
[HTTP2_HEADER_STATUS]: 200,
- [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'
+ [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
@@ -1792,7 +1796,7 @@ server.on('stream', (stream, headers, flags) => {
##### `'timeout'`
-
+
The `'timeout'` event is emitted when there is no activity on the Server for
a given number of milliseconds set using `http2server.setTimeout()`.
@@ -1800,7 +1804,7 @@ a given number of milliseconds set using `http2server.setTimeout()`.
##### `server.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1815,11 +1819,11 @@ closed, although the server has already stopped allowing new sessions. See
##### `server.setTimeout([msecs][, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** 0 (no timeout)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`Http2Server`](/api/http2#http2server)
+* Returns: [`Http2Server`](/api/v18/http2#http2server)
Used to set the timeout value for http2 server requests,
and sets a callback function that is called when there is no activity
@@ -1832,7 +1836,7 @@ error will be thrown.
##### `server.timeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** 0 (no timeout)
@@ -1846,7 +1850,7 @@ value only affects new connections to the server, not any existing connections.
##### `server.updateSettings([settings])`
-
+
* `settings` {HTTP/2 Settings Object}
@@ -1858,9 +1862,9 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument.
#### `Http2SecureServer`
-
+
-* Extends: [`tls.Server`](/api/tls#tlsserver)
+* Extends: [`tls.Server`](/api/v18/tls#tlsserver)
Instances of `Http2SecureServer` are created using the
`http2.createSecureServer()` function. The `Http2SecureServer` class is not
@@ -1868,10 +1872,10 @@ exported directly by the `node:http2` module.
##### `'checkContinue'`
-
+
-* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest)
-* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse)
+* `request` [`http2.Http2ServerRequest`](/api/v18/http2#http2http2serverrequest)
+* `response` [`http2.Http2ServerResponse`](/api/v18/http2#http2http2serverresponse)
If a [`'request'`][] listener is registered or [`http2.createSecureServer()`][]
is supplied a callback function, the `'checkContinue'` event is emitted each
@@ -1889,9 +1893,9 @@ not be emitted.
##### `'connection'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex)
This event is emitted when a new TCP stream is established, before the TLS
handshake begins. `socket` is typically an object of type [`net.Socket`][].
@@ -1902,38 +1906,38 @@ into the HTTP server. In that case, any [`Duplex`][] stream can be passed.
##### `'request'`
-
+
-* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest)
-* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse)
+* `request` [`http2.Http2ServerRequest`](/api/v18/http2#http2http2serverrequest)
+* `response` [`http2.Http2ServerResponse`](/api/v18/http2#http2http2serverresponse)
Emitted each time there is a request. There may be multiple requests
per session. See the [Compatibility API][].
##### `'session'`
-
+
-* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session)
+* `session` [`ServerHttp2Session`](/api/v18/http2#serverhttp2session)
The `'session'` event is emitted when a new `Http2Session` is created by the
`Http2SecureServer`.
##### `'sessionError'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
-* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session)
+* `session` [`ServerHttp2Session`](/api/v18/http2#serverhttp2session)
The `'sessionError'` event is emitted when an `'error'` event is emitted by
an `Http2Session` object associated with the `Http2SecureServer`.
##### `'stream'`
-
+
-* `stream` [`Http2Stream`](/api/http2#http2stream) A reference to the stream
+* `stream` [`Http2Stream`](/api/v18/http2#http2stream) A reference to the stream
* `headers` {HTTP/2 Headers Object} An object describing the headers
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags
* `rawHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the raw header names followed by
@@ -1950,7 +1954,7 @@ const {
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS,
- HTTP2_HEADER_CONTENT_TYPE
+ HTTP2_HEADER_CONTENT_TYPE,
} = http2.constants;
const options = getOptionsSomehow();
@@ -1962,7 +1966,7 @@ server.on('stream', (stream, headers, flags) => {
// ...
stream.respond({
[HTTP2_HEADER_STATUS]: 200,
- [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'
+ [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
@@ -1971,7 +1975,7 @@ server.on('stream', (stream, headers, flags) => {
##### `'timeout'`
-
+
The `'timeout'` event is emitted when there is no activity on the Server for
a given number of milliseconds set using `http2secureServer.setTimeout()`.
@@ -1979,9 +1983,9 @@ a given number of milliseconds set using `http2secureServer.setTimeout()`.
##### `'unknownProtocol'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v18/stream#streamduplex)
The `'unknownProtocol'` event is emitted when a connecting client fails to
negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler
@@ -1992,7 +1996,7 @@ See the [Compatibility API][].
##### `server.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -2007,11 +2011,11 @@ closed, although the server has already stopped allowing new sessions. See
##### `server.setTimeout([msecs][, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `120000` (2 minutes)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`Http2SecureServer`](/api/http2#http2secureserver)
+* Returns: [`Http2SecureServer`](/api/v18/http2#http2secureserver)
Used to set the timeout value for http2 secure server requests,
and sets a callback function that is called when there is no activity
@@ -2024,7 +2028,7 @@ error will be thrown.
##### `server.timeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** 0 (no timeout)
@@ -2038,7 +2042,7 @@ value only affects new connections to the server, not any existing connections.
##### `server.updateSettings([settings])`
-
+
* `settings` {HTTP/2 Settings Object}
@@ -2050,7 +2054,7 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument.
#### `http2.createServer([options][, onRequestHandler])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `maxDeflateDynamicTableSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the maximum dynamic table size
@@ -2107,17 +2111,17 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument.
**Default:** `100`.
* `settings` {HTTP/2 Settings Object} The initial settings to send to the
remote peer upon connection.
- * `Http1IncomingMessage` [`http.IncomingMessage`](/api/http#httpincomingmessage) Specifies the
+ * `Http1IncomingMessage` [`http.IncomingMessage`](/api/v18/http#httpincomingmessage) Specifies the
`IncomingMessage` class to used for HTTP/1 fallback. Useful for extending
the original `http.IncomingMessage`. **Default:** `http.IncomingMessage`.
- * `Http1ServerResponse` [`http.ServerResponse`](/api/http#httpserverresponse) Specifies the `ServerResponse`
+ * `Http1ServerResponse` [`http.ServerResponse`](/api/v18/http#httpserverresponse) Specifies the `ServerResponse`
class to used for HTTP/1 fallback. Useful for extending the original
`http.ServerResponse`. **Default:** `http.ServerResponse`.
- * `Http2ServerRequest` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest) Specifies the
+ * `Http2ServerRequest` [`http2.Http2ServerRequest`](/api/v18/http2#http2http2serverrequest) Specifies the
`Http2ServerRequest` class to use.
Useful for extending the original `Http2ServerRequest`.
**Default:** `Http2ServerRequest`.
- * `Http2ServerResponse` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) Specifies the
+ * `Http2ServerResponse` [`http2.Http2ServerResponse`](/api/v18/http2#http2http2serverresponse) Specifies the
`Http2ServerResponse` class to use.
Useful for extending the original `Http2ServerResponse`.
**Default:** `Http2ServerResponse`.
@@ -2127,7 +2131,7 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument.
**Default:** `10000`.
* ...: Any [`net.createServer()`][] option can be provided.
* `onRequestHandler` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) See [Compatibility API][]
-* Returns: [`Http2Server`](/api/http2#http2server)
+* Returns: [`Http2Server`](/api/v18/http2#http2server)
Returns a `net.Server` instance that creates and manages `Http2Session`
instances.
@@ -2149,17 +2153,17 @@ const server = http2.createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
- ':status': 200
+ ':status': 200,
});
stream.end('
Hello World
');
});
-server.listen(80);
+server.listen(8000);
```
#### `http2.createSecureServer(options[, onRequestHandler])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `allowHTTP1` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Incoming client connections that do not support
@@ -2226,7 +2230,7 @@ server.listen(80);
the socket has not been destroyed by that time the server will destroy it.
**Default:** `10000`.
* `onRequestHandler` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) See [Compatibility API][]
-* Returns: [`Http2SecureServer`](/api/http2#http2secureserver)
+* Returns: [`Http2SecureServer`](/api/v18/http2#http2secureserver)
Returns a `tls.Server` instance that creates and manages `Http2Session`
instances.
@@ -2237,7 +2241,7 @@ const fs = require('node:fs');
const options = {
key: fs.readFileSync('server-key.pem'),
- cert: fs.readFileSync('server-cert.pem')
+ cert: fs.readFileSync('server-cert.pem'),
};
// Create a secure HTTP/2 server
@@ -2246,19 +2250,19 @@ const server = http2.createSecureServer(options);
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
- ':status': 200
+ ':status': 200,
});
stream.end('
@@ -4890,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.
@@ -4977,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
@@ -4993,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 d9df67e811..c34a977b1b 100644
--- a/content/api/v19/debugger.en.md
+++ b/content/api/v19/debugger.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
Node.js includes a command-line debugging utility. The Node.js debugger client
is not a full-featured debugger, but simple stepping and inspection are
@@ -23,6 +27,7 @@ $ node inspect myscript.js
< Debugger listening on ws://127.0.0.1:9229/621111f9-ffcb-4e82-b718-48a145fa5db8
< For help, see: https://nodejs.org/en/docs/inspector
<
+connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
<
ok
@@ -137,9 +142,9 @@ $ node inspect main.js
< Debugger listening on ws://127.0.0.1:9229/48a5b28a-550c-471b-b5e1-d13dd7165df9
< For help, see: https://nodejs.org/en/docs/inspector
<
+connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
<
- ok
Break on start in main.js:1
> 1 const mod = require('./mod.js');
2 mod.hello();
@@ -163,6 +168,8 @@ given expression evaluates to `true`:
$ node inspect main.js
< Debugger listening on ws://127.0.0.1:9229/ce24daa8-3816-44d4-b8ab-8273c8a66d35
< For help, see: https://nodejs.org/en/docs/inspector
+<
+connecting to 127.0.0.1:9229 ... ok
< Debugger attached.
Break on start in main.js:7
5 }
@@ -199,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 43b2cb464a..948cb7d948 100644
--- a/content/api/v19/deprecations.en.md
+++ b/content/api/v19/deprecations.en.md
@@ -5,9 +5,9 @@ category: 'api'
version: 'v19'
---
-
+
-
+
Node.js APIs might be deprecated for any of the following reasons:
@@ -48,7 +48,7 @@ However, the deprecation identifier will not be modified.
#### DEP0001: `http.OutgoingMessage.prototype.flush`
-
+
Type: End-of-Life
@@ -57,7 +57,7 @@ Type: End-of-Life
#### DEP0002: `require('_linklist')`
-
+
Type: End-of-Life
@@ -65,7 +65,7 @@ The `_linklist` module is deprecated. Please use a userland alternative.
#### DEP0003: `_writableState.buffer`
-
+
Type: End-of-Life
@@ -74,7 +74,7 @@ instead.
#### DEP0004: `CryptoStream.prototype.readyState`
-
+
Type: End-of-Life
@@ -82,7 +82,7 @@ The `CryptoStream.prototype.readyState` property was removed.
#### DEP0005: `Buffer()` constructor
-
+
Type: Runtime (supports [`--pending-deprecation`][])
@@ -112,7 +112,7 @@ warning results no matter where the `Buffer()` usage occurs.
#### DEP0006: `child_process` `options.customFds`
-
+
Type: End-of-Life
@@ -122,7 +122,7 @@ option should be used instead.
#### DEP0007: Replace `cluster` `worker.suicide` with `worker.exitedAfterDisconnect`
-
+
Type: End-of-Life
@@ -135,7 +135,7 @@ precisely describe the actual semantics and was unnecessarily emotion-laden.
#### DEP0008: `require('node:constants')`
-
+
Type: Documentation-only
@@ -146,7 +146,7 @@ to the `constants` property exposed by the relevant module. For instance,
#### DEP0009: `crypto.pbkdf2` without digest
-
+
Type: End-of-Life
@@ -164,7 +164,7 @@ Now, however, passing either `undefined` or `null` will throw a `TypeError`.
#### DEP0010: `crypto.createCredentials`
-
+
Type: End-of-Life
@@ -173,7 +173,7 @@ The `crypto.createCredentials()` API was removed. Please use
#### DEP0011: `crypto.Credentials`
-
+
Type: End-of-Life
@@ -182,7 +182,7 @@ instead.
#### DEP0012: `Domain.dispose`
-
+
Type: End-of-Life
@@ -191,7 +191,7 @@ explicitly via error event handlers set on the domain instead.
#### DEP0013: `fs` asynchronous function without callback
-
+
Type: End-of-Life
@@ -200,7 +200,7 @@ in Node.js 10.0.0 onwards. See [https://github.com/nodejs/node/pull/12562](https
#### DEP0014: `fs.read` legacy String interface
-
+
Type: End-of-Life
@@ -209,7 +209,7 @@ API as mentioned in the documentation instead.
#### DEP0015: `fs.readSync` legacy String interface
-
+
Type: End-of-Life
@@ -218,7 +218,7 @@ The [`fs.readSync()`][] legacy `String` interface is deprecated. Use the
#### DEP0016: `GLOBAL`/`root`
-
+
Type: End-of-Life
@@ -227,7 +227,7 @@ in Node.js 6.0.0 and have since been removed.
#### DEP0017: `Intl.v8BreakIterator`
-
+
Type: End-of-Life
@@ -236,7 +236,7 @@ See [`Intl.Segmenter`](https://github.com/tc39/proposal-intl-segmenter).
#### DEP0018: Unhandled promise rejections
-
+
Type: End-of-Life
@@ -247,7 +247,7 @@ code. To change the way Node.js treats unhandled rejections, use the
#### DEP0019: `require('.')` resolved outside directory
-
+
Type: End-of-Life
@@ -256,7 +256,7 @@ This behavior has been removed.
#### DEP0020: `Server.connections`
-
+
Type: End-of-Life
@@ -265,7 +265,7 @@ been removed. Please use the [`Server.getConnections()`][] method instead.
#### DEP0021: `Server.listenFD`
-
+
Type: End-of-Life
@@ -274,7 +274,7 @@ The `Server.listenFD()` method was deprecated and removed. Please use
#### DEP0022: `os.tmpDir()`
-
+
Type: End-of-Life
@@ -283,7 +283,7 @@ removed. Please use [`os.tmpdir()`][] instead.
#### DEP0023: `os.getNetworkInterfaces()`
-
+
Type: End-of-Life
@@ -292,7 +292,7 @@ The `os.getNetworkInterfaces()` method is deprecated. Please use the
#### DEP0024: `REPLServer.prototype.convertToContext()`
-
+
Type: End-of-Life
@@ -300,7 +300,7 @@ The `REPLServer.prototype.convertToContext()` API has been removed.
#### DEP0025: `require('node:sys')`
-
+
Type: Runtime
@@ -308,7 +308,7 @@ The `node:sys` module is deprecated. Please use the [`util`][] module instead.
#### DEP0026: `util.print()`
-
+
Type: End-of-Life
@@ -316,7 +316,7 @@ Type: End-of-Life
#### DEP0027: `util.puts()`
-
+
Type: End-of-Life
@@ -324,7 +324,7 @@ Type: End-of-Life
#### DEP0028: `util.debug()`
-
+
Type: End-of-Life
@@ -332,7 +332,7 @@ Type: End-of-Life
#### DEP0029: `util.error()`
-
+
Type: End-of-Life
@@ -340,7 +340,7 @@ Type: End-of-Life
#### DEP0030: `SlowBuffer`
-
+
Type: Documentation-only
@@ -349,7 +349,7 @@ The [`SlowBuffer`][] class is deprecated. Please use
#### DEP0031: `ecdh.setPublicKey()`
-
+
Type: Documentation-only
@@ -358,7 +358,7 @@ API is not useful.
#### DEP0032: `node:domain` module
-
+
Type: Documentation-only
@@ -366,7 +366,7 @@ The [`domain`][] module is deprecated and should not be used.
#### DEP0033: `EventEmitter.listenerCount()`
-
+
Type: Documentation-only
@@ -375,7 +375,7 @@ deprecated. Please use [`emitter.listenerCount(eventName)`][] instead.
#### DEP0034: `fs.exists(path, callback)`
-
+
Type: Documentation-only
@@ -384,7 +384,7 @@ The [`fs.exists(path, callback)`][] API is deprecated. Please use
#### DEP0035: `fs.lchmod(path, mode, callback)`
-
+
Type: Documentation-only
@@ -392,7 +392,7 @@ The [`fs.lchmod(path, mode, callback)`][] API is deprecated.
#### DEP0036: `fs.lchmodSync(path, mode)`
-
+
Type: Documentation-only
@@ -400,7 +400,7 @@ The [`fs.lchmodSync(path, mode)`][] API is deprecated.
#### DEP0037: `fs.lchown(path, uid, gid, callback)`
-
+
Type: Deprecation revoked
@@ -410,7 +410,7 @@ libuv.
#### DEP0038: `fs.lchownSync(path, uid, gid)`
-
+
Type: Deprecation revoked
@@ -419,7 +419,7 @@ revoked because the requisite supporting APIs were added in libuv.
#### DEP0039: `require.extensions`
-
+
Type: Documentation-only
@@ -427,7 +427,7 @@ The [`require.extensions`][] property is deprecated.
#### DEP0040: `node:punycode` module
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -436,7 +436,7 @@ instead.
#### DEP0041: `NODE_REPL_HISTORY_FILE` environment variable
-
+
Type: End-of-Life
@@ -445,7 +445,7 @@ The `NODE_REPL_HISTORY_FILE` environment variable was removed. Please use
#### DEP0042: `tls.CryptoStream`
-
+
Type: End-of-Life
@@ -454,7 +454,7 @@ The [`tls.CryptoStream`][] class was removed. Please use
#### DEP0043: `tls.SecurePair`
-
+
Type: Documentation-only
@@ -463,7 +463,7 @@ The [`tls.SecurePair`][] class is deprecated. Please use
#### DEP0044: `util.isArray()`
-
+
Type: Documentation-only
@@ -472,7 +472,7 @@ instead.
#### DEP0045: `util.isBoolean()`
-
+
Type: Documentation-only
@@ -480,7 +480,7 @@ The [`util.isBoolean()`][] API is deprecated.
#### DEP0046: `util.isBuffer()`
-
+
Type: Documentation-only
@@ -489,7 +489,7 @@ The [`util.isBuffer()`][] API is deprecated. Please use
#### DEP0047: `util.isDate()`
-
+
Type: Documentation-only
@@ -497,7 +497,7 @@ The [`util.isDate()`][] API is deprecated.
#### DEP0048: `util.isError()`
-
+
Type: Documentation-only
@@ -505,7 +505,7 @@ The [`util.isError()`][] API is deprecated.
#### DEP0049: `util.isFunction()`
-
+
Type: Documentation-only
@@ -513,7 +513,7 @@ The [`util.isFunction()`][] API is deprecated.
#### DEP0050: `util.isNull()`
-
+
Type: Documentation-only
@@ -521,7 +521,7 @@ The [`util.isNull()`][] API is deprecated.
#### DEP0051: `util.isNullOrUndefined()`
-
+
Type: Documentation-only
@@ -529,7 +529,7 @@ The [`util.isNullOrUndefined()`][] API is deprecated.
#### DEP0052: `util.isNumber()`
-
+
Type: Documentation-only
@@ -537,7 +537,7 @@ The [`util.isNumber()`][] API is deprecated.
#### DEP0053: `util.isObject()`
-
+
Type: Documentation-only
@@ -545,7 +545,7 @@ The [`util.isObject()`][] API is deprecated.
#### DEP0054: `util.isPrimitive()`
-
+
Type: Documentation-only
@@ -553,7 +553,7 @@ The [`util.isPrimitive()`][] API is deprecated.
#### DEP0055: `util.isRegExp()`
-
+
Type: Documentation-only
@@ -561,7 +561,7 @@ The [`util.isRegExp()`][] API is deprecated.
#### DEP0056: `util.isString()`
-
+
Type: Documentation-only
@@ -569,7 +569,7 @@ The [`util.isString()`][] API is deprecated.
#### DEP0057: `util.isSymbol()`
-
+
Type: Documentation-only
@@ -577,7 +577,7 @@ The [`util.isSymbol()`][] API is deprecated.
#### DEP0058: `util.isUndefined()`
-
+
Type: Documentation-only
@@ -585,7 +585,7 @@ The [`util.isUndefined()`][] API is deprecated.
#### DEP0059: `util.log()`
-
+
Type: Documentation-only
@@ -593,7 +593,7 @@ The [`util.log()`][] API is deprecated.
#### DEP0060: `util._extend()`
-
+
Type: Documentation-only
@@ -601,7 +601,7 @@ The [`util._extend()`][] API is deprecated.
#### DEP0061: `fs.SyncWriteStream`
-
+
Type: End-of-Life
@@ -611,7 +611,7 @@ alternative.
#### DEP0062: `node --debug`
-
+
Type: End-of-Life
@@ -621,7 +621,7 @@ instead.
#### DEP0063: `ServerResponse.prototype.writeHeader()`
-
+
Type: Documentation-only
@@ -633,7 +633,7 @@ officially supported API.
#### DEP0064: `tls.createSecurePair()`
-
+
Type: Runtime
@@ -642,7 +642,7 @@ The `tls.createSecurePair()` API was deprecated in documentation in Node.js
#### DEP0065: `repl.REPL_MODE_MAGIC` and `NODE_REPL_MODE=magic`
-
+
Type: End-of-Life
@@ -657,7 +657,7 @@ removed. Please use `sloppy` instead.
#### DEP0066: `OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames`
-
+
Type: Runtime
@@ -677,7 +677,7 @@ officially supported properties.
#### DEP0067: `OutgoingMessage.prototype._renderHeaders`
-
+
Type: Documentation-only
@@ -689,7 +689,7 @@ an officially supported API.
#### DEP0068: `node debug`
-
+
Type: End-of-Life
@@ -698,7 +698,7 @@ a V8-inspector based CLI debugger available through `node inspect`.
#### DEP0069: `vm.runInDebugContext(string)`
-
+
Type: End-of-Life
@@ -708,7 +708,7 @@ DebugContext was an experimental API.
#### DEP0070: `async_hooks.currentId()`
-
+
Type: End-of-Life
@@ -719,7 +719,7 @@ This change was made while `async_hooks` was an experimental API.
#### DEP0071: `async_hooks.triggerId()`
-
+
Type: End-of-Life
@@ -730,7 +730,7 @@ This change was made while `async_hooks` was an experimental API.
#### DEP0072: `async_hooks.AsyncResource.triggerId()`
-
+
Type: End-of-Life
@@ -741,7 +741,7 @@ This change was made while `async_hooks` was an experimental API.
#### DEP0073: Several internal properties of `net.Server`
-
+
Type: End-of-Life
@@ -753,7 +753,7 @@ code, no replacement API is provided.
#### DEP0074: `REPLServer.bufferedCommand`
-
+
Type: End-of-Life
@@ -762,7 +762,7 @@ The `REPLServer.bufferedCommand` property was deprecated in favor of
#### DEP0075: `REPLServer.parseREPLKeyword()`
-
+
Type: End-of-Life
@@ -770,7 +770,7 @@ Type: End-of-Life
#### DEP0076: `tls.parseCertString()`
-
+
Type: End-of-Life
@@ -784,7 +784,7 @@ not handle all certificate subjects correctly and should not be used.
#### DEP0077: `Module._debug()`
-
+
Type: Runtime
@@ -795,7 +795,7 @@ supported API.
#### DEP0078: `REPLServer.turnOffEditorMode()`
-
+
Type: End-of-Life
@@ -803,7 +803,7 @@ Type: End-of-Life
#### DEP0079: Custom inspection function on objects via `.inspect()`
-
+
Type: End-of-Life
@@ -814,7 +814,7 @@ can be specified.
#### DEP0080: `path._makeLong()`
-
+
Type: Documentation-only
@@ -824,7 +824,7 @@ and replaced with an identical, public `path.toNamespacedPath()` method.
#### DEP0081: `fs.truncate()` using a file descriptor
-
+
Type: Runtime
@@ -834,7 +834,7 @@ file descriptors.
#### DEP0082: `REPLServer.prototype.memory()`
-
+
Type: End-of-Life
@@ -843,7 +843,7 @@ the `REPLServer` itself. Do not use this function.
#### DEP0083: Disabling ECDH by setting `ecdhCurve` to `false`
-
+
Type: End-of-Life.
@@ -854,7 +854,7 @@ the client and is now unsupported. Use the `ciphers` parameter instead.
#### DEP0084: requiring bundled internal dependencies
-
+
Type: End-of-Life
@@ -886,7 +886,7 @@ code modification is necessary if that is done.
#### DEP0085: AsyncHooks sensitive API
-
+
Type: End-of-Life
@@ -896,7 +896,7 @@ Use the `AsyncResource` API instead. See
#### DEP0086: Remove `runInAsyncIdScope`
-
+
Type: End-of-Life
@@ -905,7 +905,7 @@ cause a lot of issues. See [https://github.com/nodejs/node/issues/14328](https:/
#### DEP0089: `require('node:assert')`
-
+
Type: Deprecation revoked
@@ -916,7 +916,7 @@ confusion.
#### DEP0090: Invalid GCM authentication tag lengths
-
+
Type: End-of-Life
@@ -928,7 +928,7 @@ bits are allowed. Authentication tags of other lengths are invalid per
#### DEP0091: `crypto.DEFAULT_ENCODING`
-
+
Type: Runtime
@@ -936,7 +936,7 @@ The [`crypto.DEFAULT_ENCODING`][] property is deprecated.
#### DEP0092: Top-level `this` bound to `module.exports`
-
+
Type: Documentation-only
@@ -946,7 +946,7 @@ or `module.exports` instead.
#### DEP0093: `crypto.fips` is deprecated and replaced
-
+
Type: Documentation-only
@@ -955,7 +955,7 @@ and `crypto.getFips()` instead.
#### DEP0094: Using `assert.fail()` with more than one argument
-
+
Type: Runtime
@@ -965,7 +965,7 @@ method.
#### DEP0095: `timers.enroll()`
-
+
Type: Runtime
@@ -974,7 +974,7 @@ Type: Runtime
#### DEP0096: `timers.unenroll()`
-
+
Type: Runtime
@@ -983,7 +983,7 @@ Type: Runtime
#### DEP0097: `MakeCallback` with `domain` property
-
+
Type: Runtime
@@ -993,7 +993,7 @@ should start using the `async_context` variant of `MakeCallback` or
#### DEP0098: AsyncHooks embedder `AsyncResource.emitBefore` and `AsyncResource.emitAfter` APIs
-
+
Type: End-of-Life
@@ -1007,7 +1007,7 @@ safer, and more convenient, alternative. See
#### DEP0099: Async context-unaware `node::MakeCallback` C++ APIs
-
+
Type: Compile-time
@@ -1017,7 +1017,7 @@ parameter.
#### DEP0100: `process.assert()`
-
+
Type: Runtime
@@ -1027,7 +1027,7 @@ This was never a documented feature.
#### DEP0101: `--with-lttng`
-
+
Type: End-of-Life
@@ -1035,7 +1035,7 @@ The `--with-lttng` compile-time option has been removed.
#### DEP0102: Using `noAssert` in `Buffer#(read|write)` operations
-
+
Type: End-of-Life
@@ -1045,7 +1045,7 @@ could lead to hard-to-find errors and crashes.
#### DEP0103: `process.binding('util').is[...]` typechecks
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1057,7 +1057,7 @@ This deprecation has been superseded by the deprecation of the
#### DEP0104: `process.env` string coercion
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1069,7 +1069,7 @@ assigning it to `process.env`.
#### DEP0105: `decipher.finaltol`
-
+
Type: End-of-Life
@@ -1079,7 +1079,7 @@ Type: End-of-Life
#### DEP0106: `crypto.createCipher` and `crypto.createDecipher`
-
+
Type: Runtime
@@ -1092,7 +1092,7 @@ initialization vectors. It is recommended to derive a key using
#### DEP0107: `tls.convertNPNProtocols()`
-
+
Type: End-of-Life
@@ -1101,7 +1101,7 @@ core and obsoleted by the removal of NPN (Next Protocol Negotiation) support.
#### DEP0108: `zlib.bytesRead`
-
+
Type: Runtime
@@ -1112,7 +1112,7 @@ expose values under these names.
#### DEP0109: `http`, `https`, and `tls` support for invalid URLs
-
+
Type: End-of-Life
@@ -1125,7 +1125,7 @@ deprecated and support will be removed in the future.
#### DEP0110: `vm.Script` cached data
-
+
Type: Documentation-only
@@ -1134,7 +1134,7 @@ The `produceCachedData` option is deprecated. Use
#### DEP0111: `process.binding()`
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1142,7 +1142,7 @@ Type: Documentation-only (supports [`--pending-deprecation`][])
#### DEP0112: `dgram` private APIs
-
+
Type: Runtime
@@ -1155,7 +1155,7 @@ to accessed outside of Node.js core: `Socket.prototype._handle`,
#### DEP0113: `Cipher.setAuthTag()`, `Decipher.getAuthTag()`
-
+
Type: End-of-Life
@@ -1164,7 +1164,7 @@ were never documented and would throw when called.
#### DEP0114: `crypto._toBuf()`
-
+
Type: End-of-Life
@@ -1173,7 +1173,7 @@ of Node.js core and was removed.
#### DEP0115: `crypto.prng()`, `crypto.pseudoRandomBytes()`, `crypto.rng()`
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1185,7 +1185,7 @@ future release.
#### DEP0116: Legacy URL API
-
+
Type: Deprecation revoked
@@ -1195,7 +1195,7 @@ use the [WHATWG URL API][] instead.
#### DEP0117: Native crypto handles
-
+
Type: End-of-Life
@@ -1207,7 +1207,7 @@ object can lead to crashing the application.
#### DEP0118: `dns.lookup()` support for a falsy host name
-
+
Type: Runtime
@@ -1218,7 +1218,7 @@ It will become an error in future versions of Node.js.
#### DEP0119: `process.binding('uv').errname()` private API
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1227,7 +1227,7 @@ Type: Documentation-only (supports [`--pending-deprecation`][])
#### DEP0120: Windows Performance Counter support
-
+
Type: End-of-Life
@@ -1239,7 +1239,7 @@ undocumented `COUNTER_NET_SERVER_CONNECTION()`,
#### DEP0121: `net._setSimultaneousAccepts()`
-
+
Type: Runtime
@@ -1251,7 +1251,7 @@ generally useful and is being removed. See discussion here:
#### DEP0122: `tls` `Server.prototype.setOptions()`
-
+
Type: Runtime
@@ -1259,7 +1259,7 @@ Please use `Server.prototype.setSecureContext()` instead.
#### DEP0123: setting the TLS ServerName to an IP address
-
+
Type: Runtime
@@ -1268,7 +1268,7 @@ Setting the TLS ServerName to an IP address is not permitted by
#### DEP0124: using `REPLServer.rli`
-
+
Type: End-of-Life
@@ -1276,7 +1276,7 @@ This property is a reference to the instance itself.
#### DEP0125: `require('node:_stream_wrap')`
-
+
Type: Runtime
@@ -1284,7 +1284,7 @@ The `node:_stream_wrap` module is deprecated.
#### DEP0126: `timers.active()`
-
+
Type: Runtime
@@ -1295,7 +1295,7 @@ with no performance impact since Node.js 10.
#### DEP0127: `timers._unrefActive()`
-
+
Type: Runtime
@@ -1306,7 +1306,7 @@ with no performance impact since Node.js 10.
#### DEP0128: modules with an invalid `main` entry and an `index.js` file
-
+
Type: Runtime
@@ -1317,7 +1317,7 @@ Node.js versions.
#### DEP0129: `ChildProcess._channel`
-
+
Type: Runtime
@@ -1327,7 +1327,7 @@ instead.
#### DEP0130: `Module.createRequireFromPath()`
-
+
Type: End-of-Life
@@ -1335,7 +1335,7 @@ Use [`module.createRequire()`][] instead.
#### DEP0131: Legacy HTTP parser
-
+
Type: End-of-Life
@@ -1346,7 +1346,7 @@ legacy parser.
#### DEP0132: `worker.terminate()` with callback
-
+
Type: Runtime
@@ -1355,7 +1355,7 @@ Passing a callback to [`worker.terminate()`][] is deprecated. Use the returned
#### DEP0133: `http` `connection`
-
+
Type: Documentation-only
@@ -1364,7 +1364,7 @@ Prefer [`response.socket`][] over [`response.connection`][] and
#### DEP0134: `process._tickCallback`
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1373,7 +1373,7 @@ an officially supported API.
#### DEP0135: `WriteStream.open()` and `ReadStream.open()` are internal
-
+
Type: Runtime
@@ -1384,7 +1384,7 @@ and [`fs.createReadStream()`][]) or by passing a file descriptor in options.
#### DEP0136: `http` `finished`
-
+
Type: Documentation-only
@@ -1400,7 +1400,7 @@ To maintain existing behavior `response.finished` should be replaced with
#### DEP0137: Closing fs.FileHandle on garbage collection
-
+
Type: Runtime
@@ -1426,7 +1426,7 @@ async function openAndClose() {
#### DEP0138: `process.mainModule`
-
+
Type: Documentation-only
@@ -1439,7 +1439,7 @@ purpose and is only available on CommonJS environment.
#### DEP0139: `process.umask()` with no arguments
-
+
Type: Documentation-only
@@ -1450,7 +1450,7 @@ API.
#### DEP0140: Use `request.destroy()` instead of `request.abort()`
-
+
Type: Documentation-only
@@ -1458,7 +1458,7 @@ Use [`request.destroy()`][] instead of [`request.abort()`][].
#### DEP0141: `repl.inputStream` and `repl.outputStream`
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1467,7 +1467,7 @@ instead of `.inputStream` and `.output` instead of `.outputStream`.
#### DEP0142: `repl._builtinLibs`
-
+
Type: Documentation-only
@@ -1477,7 +1477,7 @@ upon `require('node:module').builtinModules`.
#### DEP0143: `Transform._transformState`
-
+
Type: Runtime
`Transform._transformState` will be removed in future versions where it is
@@ -1485,7 +1485,7 @@ no longer required due to simplification of the implementation.
#### DEP0144: `module.parent`
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1513,7 +1513,7 @@ const moduleParents = Object.values(require.cache)
#### DEP0145: `socket.bufferSize`
-
+
Type: Documentation-only
@@ -1521,7 +1521,7 @@ Type: Documentation-only
#### DEP0146: `new crypto.Certificate()`
-
+
Type: Documentation-only
@@ -1530,7 +1530,7 @@ The [`crypto.Certificate()` constructor][] is deprecated. Use
#### DEP0147: `fs.rmdir(path, { recursive: true })`
-
+
Type: Runtime
@@ -1543,7 +1543,7 @@ Use `fs.rm(path, { recursive: true, force: true })`,
#### DEP0148: Folder mappings in `"exports"` (trailing `"/"`)
-
+
Type: Runtime
@@ -1553,7 +1553,7 @@ Using a trailing `"/"` to define subpath folder mappings in the
#### DEP0149: `http.IncomingMessage#connection`
-
+
Type: Documentation-only.
@@ -1561,7 +1561,7 @@ Prefer [`message.socket`][] over [`message.connection`][].
#### DEP0150: Changing the value of `process.config`
-
+
Type: End-of-Life
@@ -1571,7 +1571,7 @@ to change the value will be removed in a future version of Node.js.
#### DEP0151: Main index lookup and extension searching
-
+
Type: Runtime
@@ -1583,11 +1583,11 @@ an explicit [`"exports"` or `"main"` entry][] with the exact file extension.
#### DEP0152: Extension PerformanceEntry properties
-
+
Type: Runtime
-The `'gc'`, `'http2'`, and `'http'` [`PerformanceEntry`](/api/perf_hooks#performanceentry) object types have
+The `'gc'`, `'http2'`, and `'http'` [`PerformanceEntry`](/api/v19/perf_hooks#performanceentry) object types have
additional properties assigned to them that provide additional information.
These properties are now available within the standard `detail` property
of the `PerformanceEntry` object. The existing accessors have been
@@ -1595,7 +1595,7 @@ deprecated and should no longer be used.
#### DEP0153: `dns.lookup` and `dnsPromises.lookup` options type coercion
-
+
Type: End-of-Life
@@ -1607,7 +1607,7 @@ option, or a non-nullish non-boolean value for `verbatim` option in
#### DEP0154: RSA-PSS generate key pair options
-
+
Type: Documentation-only (supports [`--pending-deprecation`][])
@@ -1616,7 +1616,7 @@ and `'mgf1HashAlgorithm'`.
#### DEP0155: Trailing slashes in pattern specifier resolutions
-
+
Type: Runtime
@@ -1625,11 +1625,11 @@ for package `"exports"` and `"imports"` pattern resolutions.
#### DEP0156: `.aborted` property and `'abort'`, `'aborted'` event in `http`
-
+
Type: Documentation-only
-Move to [`Stream`](/api/stream#stream) API instead, as the [`http.ClientRequest`][],
+Move to [`Stream`](/api/v19/stream#stream) API instead, as the [`http.ClientRequest`][],
[`http.ServerResponse`][], and [`http.IncomingMessage`][] are all stream-based.
Check `stream.destroyed` instead of the `.aborted` property, and listen for
`'close'` instead of `'abort'`, `'aborted'` event.
@@ -1643,7 +1643,7 @@ it was an aborted or graceful destroy.
#### DEP0157: Thenable support in streams
-
+
Type: End-of-Life
@@ -1660,13 +1660,13 @@ const w = new Writable({
async final(callback) {
await someOp();
callback();
- }
+ },
});
```
#### DEP0158: `buffer.slice(start, end)`
-
+
Type: Documentation-only
@@ -1677,7 +1677,7 @@ Use [`buffer.subarray`][] which does the same thing instead.
#### DEP0159: `ERR_INVALID_CALLBACK`
-
+
Type: End-of-Life
@@ -1686,7 +1686,7 @@ the errors used for value type validation.
#### DEP0160: `process.on('multipleResolves', handler)`
-
+
Type: Runtime.
@@ -1695,7 +1695,7 @@ which diminished its usefulness.
#### DEP0161: `process._getActiveRequests()` and `process._getActiveHandles()`
-
+
Type: Documentation-only
@@ -1708,7 +1708,7 @@ resources and not the actual references.
#### DEP0162: `fs.write()`, `fs.writeFileSync()` coercion to string
-
+
Type: End-of-Life
@@ -1719,7 +1719,7 @@ Convert them to primitive strings.
#### DEP0163: `channel.subscribe(onMessage)`, `channel.unsubscribe(onMessage)`
-
+
Type: Documentation-only
@@ -1732,7 +1732,7 @@ thing instead.
#### DEP0164: `process.exit(code)`, `process.exitCode` coercion to integer
-
+
Type: Runtime
@@ -1742,7 +1742,7 @@ Values other than `undefined`, `null`, integer numbers, and integer strings
#### DEP0165: `--trace-atomics-wait`
-
+
Type: Documentation-only
@@ -1750,7 +1750,7 @@ The [`--trace-atomics-wait`][] flag is deprecated.
#### DEP0166: Double slashes in imports and exports targets
-
+
Type: Runtime
@@ -1761,7 +1761,7 @@ starting or ending in a slash.
#### DEP0167: Weak `DiffieHellmanGroup` instances (`modp1`, `modp2`, `modp5`)
-
+
Type: Documentation-only
@@ -1774,7 +1774,7 @@ rely on these groups should evaluate using stronger MODP groups instead.
#### DEP0168: Unhandled exception in Node-API callbacks
-
+
Type: Runtime
@@ -1787,7 +1787,7 @@ Node-API callbacks.
#### DEP0169: Insecure url.parse()
-
+
Type: Documentation-only
@@ -1795,6 +1795,26 @@ Type: Documentation-only
have security implications. Use the [WHATWG URL API][] instead. CVEs are not
issued for `url.parse()` vulnerabilities.
+#### DEP0170: Invalid port when using `url.parse()`
+
+
+
+Type: Documentation-only
+
+[`url.parse()`][] accepts URLs with ports that are not numbers. This behavior
+might result in host name spoofing with unexpected input. These URLs will throw
+an error in future versions of Node.js, as the [WHATWG URL API][] does already.
+
+#### DEP0171: Setters for `http.IncomingMessage` headers and trailers
+
+
+
+Type: Documentation-only
+
+In a future version of Node.js, [`message.headers`][],
+[`message.headersDistinct`][], [`message.trailers`][], and
+[`message.trailersDistinct`][] will be read-only.
+
[NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
[RFC 6066]: https://tools.ietf.org/html/rfc6066#section-3
[RFC 8247 Section 2.4]: https://www.rfc-editor.org/rfc/rfc8247#section-2.4
@@ -1844,7 +1864,7 @@ issued for `url.parse()` vulnerabilities.
[`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
@@ -1871,7 +1891,11 @@ issued for `url.parse()` vulnerabilities.
[`https.get()`]: /api/v19/https#httpsgetoptions-callback
[`https.request()`]: /api/v19/https#httpsrequestoptions-callback
[`message.connection`]: /api/v19/http#messageconnection
+[`message.headersDistinct`]: /api/v19/http#messageheadersdistinct
+[`message.headers`]: /api/v19/http#messageheaders
[`message.socket`]: /api/v19/http#messagesocket
+[`message.trailersDistinct`]: /api/v19/http#messagetrailersdistinct
+[`message.trailers`]: /api/v19/http#messagetrailers
[`module.createRequire()`]: /api/v19/module#modulecreaterequirefilename
[`os.networkInterfaces()`]: /api/v19/os#osnetworkinterfaces
[`os.tmpdir()`]: /api/v19/os#ostmpdir
diff --git a/content/api/v19/dgram.en.md b/content/api/v19/dgram.en.md
index 683c3d7698..cfddeef29b 100644
--- a/content/api/v19/dgram.en.md
+++ b/content/api/v19/dgram.en.md
@@ -5,23 +5,27 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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');
server.on('error', (err) => {
- console.log(`server error:\n${err.stack}`);
+ console.error(`server error:\n${err.stack}`);
server.close();
});
@@ -36,14 +40,12 @@ 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');
server.on('error', (err) => {
- console.log(`server error:\n${err.stack}`);
+ console.error(`server error:\n${err.stack}`);
server.close();
});
@@ -62,9 +64,9 @@ server.bind(41234);
### `dgram.Socket`
-
+
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v19/events#eventemitter)
Encapsulates the datagram functionality.
@@ -73,21 +75,21 @@ The `new` keyword is not to be used to create `dgram.Socket` instances.
#### `'close'`
-
+
The `'close'` event is emitted after a socket is closed with [`close()`][].
Once triggered, no new `'message'` events will be emitted on this socket.
#### `'connect'`
-
+
The `'connect'` event is emitted after a socket is associated to a remote
address as a result of a successful [`connect()`][] call.
#### `'error'`
-
+
* `exception` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -96,7 +98,7 @@ function is passed a single `Error` object.
#### `'listening'`
-
+
The `'listening'` event is emitted once the `dgram.Socket` is addressable and
can receive data. This happens either explicitly with `socket.bind()` or
@@ -106,12 +108,12 @@ exist and calls such as `socket.address()` and `socket.setTTL()` will fail.
#### `'message'`
-
+
The `'message'` event is emitted when a new datagram is available on a socket.
The event handler function is passed two arguments: `msg` and `rinfo`.
-* `msg` [`Buffer`](/api/buffer#buffer) The message.
+* `msg` [`Buffer`](/api/v19/buffer#buffer) The message.
* `rinfo` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Remote address information.
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The sender address.
* `family` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The address family (`'IPv4'` or `'IPv6'`).
@@ -126,7 +128,7 @@ is the interface name as a zone ID suffix.
#### `socket.addMembership(multicastAddress[, multicastInterface])`
-
+
* `multicastAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `multicastInterface` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -144,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';
@@ -157,9 +159,7 @@ if (cluster.isPrimary) {
s.addMembership('224.0.0.114');
});
}
-```
-
-```cjs
+--------------
const cluster = require('node:cluster');
const dgram = require('node:dgram');
@@ -176,7 +176,7 @@ if (cluster.isPrimary) {
#### `socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`
-
+
* `sourceAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `groupAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -194,7 +194,7 @@ port, listening on all interfaces.
#### `socket.address()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -206,7 +206,7 @@ This method throws `EBADF` if called on an unbound socket.
#### `socket.bind([port][, address][, callback])`
-
+
* `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -232,13 +232,13 @@ 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');
server.on('error', (err) => {
- console.log(`server error:\n${err.stack}`);
+ console.error(`server error:\n${err.stack}`);
server.close();
});
@@ -253,14 +253,12 @@ 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');
server.on('error', (err) => {
- console.log(`server error:\n${err.stack}`);
+ console.error(`server error:\n${err.stack}`);
server.close();
});
@@ -279,7 +277,7 @@ server.bind(41234);
#### `socket.bind(options[, callback])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Required. Supports the following properties:
* `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -325,13 +323,13 @@ An example socket listening on an exclusive port is shown below.
socket.bind({
address: 'localhost',
port: 8000,
- exclusive: true
+ exclusive: true,
});
```
#### `socket.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called when the socket has been closed.
@@ -340,7 +338,7 @@ provided, it is added as a listener for the [`'close'`][] event.
#### `socket.connect(port[, address][, callback])`
-
+
* `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -358,7 +356,7 @@ the `callback` is called or, failing this, an `'error'` event is emitted.
#### `socket.disconnect()`
-
+
A synchronous function that disassociates a connected `dgram.Socket` from
its remote address. Trying to call `disconnect()` on an unbound or already
@@ -367,7 +365,7 @@ exception.
#### `socket.dropMembership(multicastAddress[, multicastInterface])`
-
+
* `multicastAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `multicastInterface` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -382,7 +380,7 @@ drop membership on all valid interfaces.
#### `socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`
-
+
* `sourceAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `groupAddress` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -399,7 +397,7 @@ drop membership on all valid interfaces.
#### `socket.getRecvBufferSize()`
-
+
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the `SO_RCVBUF` socket receive buffer size in bytes.
@@ -407,7 +405,7 @@ This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
#### `socket.getSendBufferSize()`
-
+
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the `SO_SNDBUF` socket send buffer size in bytes.
@@ -415,22 +413,22 @@ This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
#### `socket.getSendQueueSize()`
-
+
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes queued for sending.
#### `socket.getSendQueueCount()`
-
+
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of send requests currently in the queue awaiting
to be processed.
#### `socket.ref()`
-
+
-* Returns: [`dgram.Socket`](/api/dgram#dgramsocket)
+* Returns: [`dgram.Socket`](/api/v19/dgram#dgramsocket)
By default, binding a socket will cause it to block the Node.js process from
exiting as long as the socket is open. The `socket.unref()` method can be used
@@ -445,7 +443,7 @@ chained.
#### `socket.remoteAddress()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -455,9 +453,9 @@ if the socket is not connected.
#### `socket.send(msg[, offset, length][, port][, address][, callback])`
-
+
-* `msg` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Message to be sent.
+* `msg` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) Message to be sent.
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Offset in the buffer where the message starts.
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes in the message.
* `port` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Destination port.
@@ -507,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';
@@ -516,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');
@@ -532,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';
@@ -542,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');
@@ -564,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';
@@ -575,9 +569,7 @@ client.connect(41234, 'localhost', (err) => {
client.close();
});
});
-```
-
-```cjs
+--------------
const dgram = require('node:dgram');
const { Buffer } = require('node:buffer');
@@ -619,7 +611,7 @@ source that the data did not reach its intended recipient.
#### `socket.setBroadcast(flag)`
-
+
* `flag` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -630,7 +622,7 @@ This method throws `EBADF` if called on an unbound socket.
#### `socket.setMulticastInterface(multicastInterface)`
-
+
* `multicastInterface` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -710,7 +702,7 @@ for future multicast packets.
#### `socket.setMulticastLoopback(flag)`
-
+
* `flag` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -721,7 +713,7 @@ This method throws `EBADF` if called on an unbound socket.
#### `socket.setMulticastTTL(ttl)`
-
+
* `ttl` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -737,7 +729,7 @@ This method throws `EBADF` if called on an unbound socket.
#### `socket.setRecvBufferSize(size)`
-
+
* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -748,7 +740,7 @@ This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
#### `socket.setSendBufferSize(size)`
-
+
* `size` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -759,7 +751,7 @@ This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
#### `socket.setTTL(ttl)`
-
+
* `ttl` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -776,9 +768,9 @@ This method throws `EBADF` if called on an unbound socket.
#### `socket.unref()`
-
+
-* Returns: [`dgram.Socket`](/api/dgram#dgramsocket)
+* Returns: [`dgram.Socket`](/api/v19/dgram#dgramsocket)
By default, binding a socket will cause it to block the Node.js process from
exiting as long as the socket is open. The `socket.unref()` method can be used
@@ -795,7 +787,7 @@ chained.
#### `dgram.createSocket(options[, callback])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Available options are:
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The family of socket. Must be either `'udp4'` or `'udp6'`.
@@ -809,9 +801,9 @@ chained.
* `recvBufferSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the `SO_RCVBUF` socket value.
* `sendBufferSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the `SO_SNDBUF` socket value.
* `lookup` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Custom lookup function. **Default:** [`dns.lookup()`][].
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An AbortSignal that may be used to close a socket.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) An AbortSignal that may be used to close a socket.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Attached as a listener for `'message'` events. Optional.
-* Returns: [`dgram.Socket`](/api/dgram#dgramsocket)
+* Returns: [`dgram.Socket`](/api/v19/dgram#dgramsocket)
Creates a `dgram.Socket` object. Once the socket is created, calling
[`socket.bind()`][] will instruct the socket to begin listening for datagram
@@ -837,11 +829,11 @@ controller.abort();
#### `dgram.createSocket(type[, callback])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Either `'udp4'` or `'udp6'`.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Attached as a listener to `'message'` events.
-* Returns: [`dgram.Socket`](/api/dgram#dgramsocket)
+* Returns: [`dgram.Socket`](/api/v19/dgram#dgramsocket)
Creates a `dgram.Socket` object of the specified `type`.
diff --git a/content/api/v19/diagnostics_channel.en.md b/content/api/v19/diagnostics_channel.en.md
index e1f771ade7..710ad0f864 100644
--- a/content/api/v19/diagnostics_channel.en.md
+++ b/content/api/v19/diagnostics_channel.en.md
@@ -5,22 +5,26 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
+
+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');
```
@@ -42,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
@@ -59,15 +63,13 @@ diagnostics_channel.subscribe('my-channel', onMessage);
if (channel.hasSubscribers) {
// Publish data to the channel
channel.publish({
- some: 'data'
+ some: 'data',
});
}
// Unsubscribe from the channel
diagnostics_channel.unsubscribe('my-channel', onMessage);
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
// Get a reusable channel object
@@ -84,7 +86,7 @@ diagnostics_channel.subscribe('my-channel', onMessage);
if (channel.hasSubscribers) {
// Publish data to the channel
channel.publish({
- some: 'data'
+ some: 'data',
});
}
@@ -94,7 +96,7 @@ diagnostics_channel.unsubscribe('my-channel', onMessage);
##### `diagnostics_channel.hasSubscribers(name)`
-
+
* `name` [`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 channel name
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If there are active subscribers
@@ -105,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')) {
@@ -123,22 +123,20 @@ if (diagnostics_channel.hasSubscribers('my-channel')) {
##### `diagnostics_channel.channel(name)`
-
+
* `name` [`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 channel name
-* Returns: [`Channel`](/api/diagnostics_channel#channel) The named channel object
+* Returns: [`Channel`](/api/v19/diagnostics_channel#channel) The named channel object
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');
@@ -146,7 +144,7 @@ const channel = diagnostics_channel.channel('my-channel');
##### `diagnostics_channel.subscribe(name, onMessage)`
-
+
* `name` [`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 channel name
* `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The handler to receive channel messages
@@ -157,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) => {
@@ -175,7 +171,7 @@ diagnostics_channel.subscribe('my-channel', (message, name) => {
##### `diagnostics_channel.unsubscribe(name, onMessage)`
-
+
* `name` [`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 channel name
* `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The previous subscribed handler to remove
@@ -184,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) {
@@ -194,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) {
@@ -210,7 +204,7 @@ diagnostics_channel.unsubscribe('my-channel', onMessage);
#### `Channel`
-
+
The class `Channel` represents an individual named channel within the data
pipeline. It is used to track subscribers and to publish messages when there
@@ -222,7 +216,7 @@ with `new Channel(name)` is not supported.
##### `channel.hasSubscribers`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If there are active subscribers
@@ -232,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');
@@ -240,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');
@@ -254,38 +246,40 @@ if (channel.hasSubscribers) {
##### `channel.publish(message)`
-
+
* `message` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The message to send to the channel subscribers
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');
channel.publish({
- some: 'message'
+ some: 'message',
});
-```
-
-```cjs
+--------------
const diagnostics_channel = require('node:diagnostics_channel');
const channel = diagnostics_channel.channel('my-channel');
channel.publish({
- some: 'message'
+ some: 'message',
});
```
##### `channel.subscribe(onMessage)`
-
+
+
+
-
+Deprecated: Use [`diagnostics_channel.subscribe(name, onMessage)`][]
+
+
* `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The handler to receive channel messages
* `message` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The message data
@@ -295,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');
@@ -303,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');
@@ -317,9 +309,13 @@ channel.subscribe((message, name) => {
##### `channel.unsubscribe(onMessage)`
-
+
+
+
-
+Deprecated: Use [`diagnostics_channel.unsubscribe(name, onMessage)`][]
+
+
* `onMessage` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The previous subscribed handler to remove
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the handler was found, `false` otherwise.
@@ -327,7 +323,7 @@ channel.subscribe((message, name) => {
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');
@@ -339,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');
@@ -357,36 +351,46 @@ channel.unsubscribe(onMessage);
#### Built-in Channels
+
+
+Experimental
+
+
+
+While the diagnostics\_channel API is now considered stable, the built-in
+channels currently available are not. Each channel must be declared stable
+independently.
+
##### HTTP
`http.client.request.start`
-* `request` [`http.ClientRequest`](/api/http#httpclientrequest)
+* `request` [`http.ClientRequest`](/api/v19/http#httpclientrequest)
Emitted when client starts a request.
`http.client.response.finish`
-* `request` [`http.ClientRequest`](/api/http#httpclientrequest)
-* `response` [`http.IncomingMessage`](/api/http#httpincomingmessage)
+* `request` [`http.ClientRequest`](/api/v19/http#httpclientrequest)
+* `response` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
Emitted when client receives a response.
`http.server.request.start`
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `response` [`http.ServerResponse`](/api/http#httpserverresponse)
-* `socket` [`net.Socket`](/api/net#netsocket)
-* `server` [`http.Server`](/api/http#httpserver)
+* `request` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
+* `response` [`http.ServerResponse`](/api/v19/http#httpserverresponse)
+* `socket` [`net.Socket`](/api/v19/net#netsocket)
+* `server` [`http.Server`](/api/v19/http#httpserver)
Emitted when server receives a request.
`http.server.response.finish`
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `response` [`http.ServerResponse`](/api/http#httpserverresponse)
-* `socket` [`net.Socket`](/api/net#netsocket)
-* `server` [`http.Server`](/api/http#httpserver)
+* `request` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
+* `response` [`http.ServerResponse`](/api/v19/http#httpserverresponse)
+* `socket` [`net.Socket`](/api/v19/net#netsocket)
+* `server` [`http.Server`](/api/v19/http#httpserver)
Emitted when server sends a response.
@@ -394,13 +398,13 @@ Emitted when server sends a response.
`net.client.socket`
-* `socket` [`net.Socket`](/api/net#netsocket)
+* `socket` [`net.Socket`](/api/v19/net#netsocket)
Emitted when a new TCP or pipe client socket is created.
`net.server.socket`
-* `socket` [`net.Socket`](/api/net#netsocket)
+* `socket` [`net.Socket`](/api/v19/net#netsocket)
Emitted when a new TCP or pipe connection is received.
@@ -408,23 +412,23 @@ Emitted when a new TCP or pipe connection is received.
`udp.socket`
-* `socket` [`dgram.Socket`](/api/dgram#dgramsocket)
+* `socket` [`dgram.Socket`](/api/v19/dgram#dgramsocket)
Emitted when a new UDP socket is created.
##### Process
-
+
`child_process`
-* `process` [`ChildProcess`](/api/child_process#childprocess)
+* `process` [`ChildProcess`](/api/v19/child_process#childprocess)
Emitted when a new process is created.
##### Worker Thread
-
+
`worker_threads`
diff --git a/content/api/v19/dns.en.md b/content/api/v19/dns.en.md
index 0f202d78b0..be3a739b75 100644
--- a/content/api/v19/dns.en.md
+++ b/content/api/v19/dns.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
The `node:dns` module enables name resolution. For example, use it to look up IP
addresses of host names.
@@ -58,7 +62,7 @@ See the [Implementation considerations section][] for more information.
### `dns.Resolver`
-
+
An independent resolver for DNS requests.
@@ -99,7 +103,7 @@ The following methods from the `node:dns` module are available:
#### `Resolver([options])`
-
+
Create a new resolver.
@@ -111,14 +115,14 @@ Create a new resolver.
#### `resolver.cancel()`
-
+
Cancel all outstanding DNS queries made by this resolver. The corresponding
callbacks will be called with an error with code `ECANCELLED`.
#### `resolver.setLocalAddress([ipv4][, ipv6])`
-
+
* `ipv4` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string representation of an IPv4 address.
**Default:** `'0.0.0.0'`
@@ -138,7 +142,7 @@ The `rrtype` of resolution requests has no impact on the local address used.
### `dns.getServers()`
-
+
* Returns: string\[]
@@ -157,7 +161,7 @@ section if a custom port is used.
### `dns.lookup(hostname[, options], callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -228,7 +232,7 @@ is not set to `true`, it returns a `Promise` for an `Object` with `address` and
#### Supported getaddrinfo flags
-
+
The following flags can be passed as hints to [`dns.lookup()`][].
@@ -243,7 +247,7 @@ The following flags can be passed as hints to [`dns.lookup()`][].
### `dns.lookupService(address, port, callback)`
-
+
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -274,7 +278,7 @@ If this method is invoked as its [`util.promisify()`][]ed version, it returns a
### `dns.resolve(hostname[, rrtype], callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `rrtype` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Resource record type. **Default:** `'A'`.
@@ -307,7 +311,7 @@ On error, `err` is an [`Error`][] object, where `err.code` is one of the
### `dns.resolve4(hostname[, options], callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -326,7 +330,7 @@ will contain an array of IPv4 addresses (e.g.
### `dns.resolve6(hostname[, options], callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -344,7 +348,7 @@ will contain an array of IPv6 addresses.
### `dns.resolveAny(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -394,7 +398,7 @@ queries. It may be better to call individual methods like [`dns.resolve4()`][],
### `dns.resolveCname(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -408,7 +412,7 @@ will contain an array of canonical name records available for the `hostname`
### `dns.resolveCaa(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -423,7 +427,7 @@ available for the `hostname` (e.g. `[{critical: 0, iodef:
### `dns.resolveMx(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -437,7 +441,7 @@ property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
### `dns.resolveNaptr(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -468,7 +472,7 @@ function will contain an array of objects with the following properties:
### `dns.resolveNs(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -482,7 +486,7 @@ contain an array of name server records available for `hostname`
### `dns.resolvePtr(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -495,7 +499,7 @@ be an array of strings containing the reply records.
### `dns.resolveSoa(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -528,7 +532,7 @@ be an object with the following properties:
### `dns.resolveSrv(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -555,7 +559,7 @@ be an array of objects with the following properties:
### `dns.resolveTxt(hostname, callback)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -571,7 +575,7 @@ treated separately.
### `dns.reverse(ip, callback)`
-
+
* `ip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -586,7 +590,7 @@ one of the [DNS error codes][].
### `dns.setDefaultResultOrder(order)`
-
+
* `order` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) must be `'ipv4first'` or `'verbatim'`.
@@ -596,14 +600,14 @@ Set the default value of `verbatim` in [`dns.lookup()`][] and
* `ipv4first`: sets default `verbatim` `false`.
* `verbatim`: sets default `verbatim` `true`.
-The default is `ipv4first` and [`dns.setDefaultResultOrder()`][] have higher
+The default is `verbatim` and [`dns.setDefaultResultOrder()`][] have higher
priority than [`--dns-result-order`][]. When using [worker threads][],
[`dns.setDefaultResultOrder()`][] from the main thread won't affect the default
dns orders in workers.
### `dns.setServers(servers)`
-
+
* `servers` string\[] array of [RFC 5952][] formatted addresses
@@ -638,7 +642,7 @@ earlier ones time out or result in some other error.
### DNS promises API
-
+
The `dns.promises` API provides an alternative set of asynchronous DNS methods
that return `Promise` objects rather than using callbacks. The API is accessible
@@ -646,7 +650,7 @@ via `require('node:dns').promises` or `require('node:dns/promises')`.
#### `dnsPromises.Resolver`
-
+
An independent resolver for DNS requests.
@@ -692,14 +696,14 @@ The following methods from the `dnsPromises` API are available:
#### `resolver.cancel()`
-
+
Cancel all outstanding DNS queries made by this resolver. The corresponding
promises will be rejected with an error with the code `ECANCELLED`.
#### `dnsPromises.getServers()`
-
+
* Returns: string\[]
@@ -718,7 +722,7 @@ section if a custom port is used.
#### `dnsPromises.lookup(hostname[, options])`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -783,7 +787,7 @@ dnsPromises.lookup('example.com', options).then((result) => {
#### `dnsPromises.lookupService(address, port)`
-
+
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -808,7 +812,7 @@ dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
#### `dnsPromises.resolve(hostname[, rrtype])`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `rrtype` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Resource record type. **Default:** `'A'`.
@@ -838,7 +842,7 @@ is one of the [DNS error codes][].
#### `dnsPromises.resolve4(hostname[, options])`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -853,7 +857,7 @@ addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
#### `dnsPromises.resolve6(hostname[, options])`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host name to resolve.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -868,7 +872,7 @@ addresses.
#### `dnsPromises.resolveAny(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -911,7 +915,7 @@ Here is an example of the result object:
#### `dnsPromises.resolveCaa(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -923,7 +927,7 @@ certification authority authorization records available for the `hostname`
#### `dnsPromises.resolveCname(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -933,7 +937,7 @@ the `hostname` (e.g. `['bar.example.com']`).
#### `dnsPromises.resolveMx(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -944,7 +948,7 @@ containing both a `priority` and `exchange` property (e.g.
#### `dnsPromises.resolveNaptr(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -972,7 +976,7 @@ of objects with the following properties:
#### `dnsPromises.resolveNs(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -983,7 +987,7 @@ records available for `hostname` (e.g.
#### `dnsPromises.resolvePtr(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -993,7 +997,7 @@ containing the reply records.
#### `dnsPromises.resolveSoa(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1023,7 +1027,7 @@ following properties:
#### `dnsPromises.resolveSrv(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1047,7 +1051,7 @@ the following properties:
#### `dnsPromises.resolveTxt(hostname)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1060,7 +1064,7 @@ treated separately.
#### `dnsPromises.reverse(ip)`
-
+
* `ip` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1072,7 +1076,7 @@ is one of the [DNS error codes][].
#### `dnsPromises.setDefaultResultOrder(order)`
-
+
* `order` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) must be `'ipv4first'` or `'verbatim'`.
@@ -1082,14 +1086,14 @@ Set the default value of `verbatim` in [`dns.lookup()`][] and
* `ipv4first`: sets default `verbatim` `false`.
* `verbatim`: sets default `verbatim` `true`.
-The default is `ipv4first` and [`dnsPromises.setDefaultResultOrder()`][] have
+The default is `verbatim` and [`dnsPromises.setDefaultResultOrder()`][] have
higher priority than [`--dns-result-order`][]. When using [worker threads][],
[`dnsPromises.setDefaultResultOrder()`][] from the main thread won't affect the
default dns orders in workers.
#### `dnsPromises.setServers(servers)`
-
+
* `servers` string\[] array of [RFC 5952][] formatted addresses
diff --git a/content/api/v19/documentation.en.md b/content/api/v19/documentation.en.md
index 5eb18dae06..4acc98a915 100644
--- a/content/api/v19/documentation.en.md
+++ b/content/api/v19/documentation.en.md
@@ -5,9 +5,9 @@ category: 'api'
version: 'v19'
---
-
+
-
+
Welcome to the official API reference documentation for Node.js!
@@ -20,7 +20,7 @@ Report errors in this documentation in [the issue tracker][]. See
### Stability index
-
+
Throughout the documentation are indications of a section's stability. Some APIs
are so proven and so relied upon that they are unlikely to ever change at all.
@@ -28,13 +28,29 @@ Others are brand new and experimental, or known to be hazardous.
The stability indices are as follows:
-
+
- occur in any future release. Use of the feature is not recommended in\n> production environments."}}} />
+Deprecated. The feature may emit warnings. Backward compatibility is not guaranteed.
-
+
- maintained, and other alternatives are available."}}} />
+
+
+Experimental. The feature is not subject to [semantic versioning][] rules. Non-backward compatible changes or removal may occur in any future release. Use of the feature is not recommended in production environments.
+
+
+
+
+
+Stable. Compatibility with the npm ecosystem is a high priority.
+
+
+
+
+
+Legacy. Although this feature is unlikely to be removed and is still covered by semantic versioning guarantees, it is no longer actively maintained, and other alternatives are available.
+
+
Features are marked as legacy rather than being deprecated if their use does no
harm, and they are widely relied upon within the npm ecosystem. Bugs found in
@@ -50,7 +66,7 @@ a command-line flag. Experimental features may also emit a [warning][].
### JSON output
-
+
Every `.html` document has a corresponding `.json` document. This is for IDEs
and other utilities that consume the documentation.
diff --git a/content/api/v19/domain.en.md b/content/api/v19/domain.en.md
index 43b65e1166..45d07cecd3 100644
--- a/content/api/v19/domain.en.md
+++ b/content/api/v19/domain.en.md
@@ -5,13 +5,17 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
-
+Deprecated
+
+
+
+
**This module is pending deprecation.** Once a replacement API has been
finalized, this module will be fully deprecated. Most developers should
@@ -29,7 +33,7 @@ exit immediately with an error code.
### Warning: Don't ignore errors!
-
+
Domain error handlers are not a substitute for closing down a
process when an error occurs.
@@ -183,7 +187,7 @@ function handleRequest(req, res) {
### Additions to `Error` objects
-
+
Any time an `Error` object is routed through a domain, a few extra fields
are added to it.
@@ -198,7 +202,7 @@ are added to it.
### Implicit binding
-
+
If domains are in use, then all **new** `EventEmitter` objects (including
Stream objects, requests, responses, etc.) will be implicitly bound to
@@ -224,7 +228,7 @@ Implicit binding only takes care of thrown errors and `'error'` events.
### Explicit binding
-
+
Sometimes, the domain in use is not the one that ought to be used for a
specific event emitter. Or, the event emitter could have been created
@@ -266,11 +270,11 @@ serverDomain.run(() => {
### `domain.create()`
-* Returns: [`Domain`](/api/domain#domain)
+* Returns: [`Domain`](/api/v19/domain#domain)
### `Domain`
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v19/events#eventemitter)
The `Domain` class encapsulates the functionality of routing errors and
uncaught exceptions to the active `Domain` object.
@@ -286,7 +290,7 @@ to the domain.
#### `domain.add(emitter)`
-* `emitter` [`EventEmitter`](/api/events#eventemitter) | [`Timer`](/api/timers#timers) emitter or timer to be added to the domain
+* `emitter` [`EventEmitter`](/api/v19/events#eventemitter) | [`Timer`](/api/v19/timers#timers) emitter or timer to be added to the domain
Explicitly adds an emitter to the domain. If any event handlers called by
the emitter throw an error, or if the emitter emits an `'error'` event, it
@@ -390,7 +394,7 @@ d.on('error', (er) => {
#### `domain.remove(emitter)`
-* `emitter` [`EventEmitter`](/api/events#eventemitter) | [`Timer`](/api/timers#timers) emitter or timer to be removed from the domain
+* `emitter` [`EventEmitter`](/api/v19/events#eventemitter) | [`Timer`](/api/v19/timers#timers) emitter or timer to be removed from the domain
The opposite of [`domain.add(emitter)`][]. Removes domain handling from the
specified emitter.
diff --git a/content/api/v19/embedding.en.md b/content/api/v19/embedding.en.md
index a92e886a52..96071de2f1 100644
--- a/content/api/v19/embedding.en.md
+++ b/content/api/v19/embedding.en.md
@@ -5,7 +5,7 @@ category: 'api'
version: 'v19'
---
-
+
Node.js provides a number of C++ APIs that can be used to execute JavaScript
in a Node.js environment from other C++ software.
@@ -79,7 +79,7 @@ int main(int argc, char** argv) {
#### Per-instance state
-
+
Node.js has a concept of a “Node.js instance”, that is commonly being referred
to as `node::Environment`. Each `node::Environment` is associated with:
diff --git a/content/api/v19/errors.en.md b/content/api/v19/errors.en.md
index bd7aabd3d9..357b43e489 100644
--- a/content/api/v19/errors.en.md
+++ b/content/api/v19/errors.en.md
@@ -5,9 +5,9 @@ category: 'api'
version: 'v19'
---
-
+
-
+
Applications running in Node.js will generally experience four categories of
errors:
@@ -28,7 +28,7 @@ to provide _at least_ the properties available on that class.
### Error propagation and interception
-
+
Node.js supports several mechanisms for propagating and handling errors that
occur while an application is running. How these errors are reported and
@@ -132,7 +132,7 @@ exactly how errors raised by those methods are propagated.
#### Error-first callbacks
-
+
Most asynchronous methods exposed by the Node.js core API follow an idiomatic
pattern referred to as an _error-first callback_. With this pattern, a callback
@@ -186,7 +186,7 @@ cases. If [domains][] are enabled, or a handler has been registered with
### `Error`
-
+
A generic JavaScript [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object that does not denote any specific
circumstance of why the error occurred. `Error` objects capture a "stack trace"
@@ -263,7 +263,7 @@ not capture any frames.
#### `error.cause`
-
+
* [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -407,14 +407,14 @@ loop tick.
### `AssertionError`
-* Extends: [`errors.Error`](/api/errors#error)
+* Extends: [`errors.Error`](/api/v19/errors#error)
Indicates the failure of an assertion. For details, see
[`Class: assert.AssertionError`][].
### `RangeError`
-* Extends: [`errors.Error`](/api/errors#error)
+* Extends: [`errors.Error`](/api/v19/errors#error)
Indicates that a provided argument was not within the set or range of
acceptable values for a function; whether that is a numeric range, or
@@ -430,7 +430,7 @@ of argument validation.
### `ReferenceError`
-* Extends: [`errors.Error`](/api/errors#error)
+* Extends: [`errors.Error`](/api/v19/errors#error)
Indicates that an attempt is being made to access a variable that is not
defined. Such errors commonly indicate typos in code, or an otherwise broken
@@ -449,7 +449,7 @@ Unless an application is dynamically generating and running code,
### `SyntaxError`
-* Extends: [`errors.Error`](/api/errors#error)
+* Extends: [`errors.Error`](/api/v19/errors#error)
Indicates that a program is not valid JavaScript. These errors may only be
generated and propagated as a result of code evaluation. Code evaluation may
@@ -469,7 +469,7 @@ they may only be caught by other contexts.
### `SystemError`
-* Extends: [`errors.Error`](/api/errors#error)
+* Extends: [`errors.Error`](/api/v19/errors#error)
Node.js generates system errors when exceptions occur within its runtime
environment. These usually occur when an application violates an operating
@@ -613,7 +613,7 @@ program. For a comprehensive list, see the [`errno`(3) man page][].
### `TypeError`
-* Extends [`errors.Error`](/api/errors#error)
+* Extends [`errors.Error`](/api/v19/errors#error)
Indicates that a provided argument is not an allowable type. For example,
passing a function to a parameter which expects a string would be a `TypeError`.
@@ -628,7 +628,7 @@ of argument validation.
### Exceptions vs. errors
-
+
A JavaScript exception is a value that is thrown as a result of an invalid
operation or as the target of a `throw` statement. While it is not required
@@ -671,7 +671,7 @@ A human-readable string describing the reason for the error.
#### `ABORT_ERR`
-
+
Used when an operation has been aborted (typically using an `AbortController`).
@@ -706,13 +706,6 @@ A special type of error that can be triggered whenever Node.js detects an
exceptional logic violation that should never occur. These are raised typically
by the `node:assert` module.
-
-
-#### `ERR_ASSERT_SNAPSHOT_NOT_SUPPORTED`
-
-An attempt was made to use `assert.snapshot()` in an environment that
-does not support snapshots, such as the REPL, or when using `node --eval`.
-
#### `ERR_ASYNC_CALLBACK`
@@ -795,7 +788,7 @@ STDERR/STDOUT, and the data's length is longer than the `maxBuffer` option.
#### `ERR_CLOSED_MESSAGE_PORT`
-
+
There was an attempt to use a `MessagePort` instance in a closed
state, usually after `.close()` has been called.
@@ -811,7 +804,7 @@ non-writable `stdout` or `stderr` stream.
#### `ERR_CONSTRUCT_CALL_INVALID`
-
+
A class constructor was called that is not callable.
@@ -902,7 +895,7 @@ The selected public or private key encoding is incompatible with other options.
#### `ERR_CRYPTO_INITIALIZATION_FAILED`
-
+
Initialization of the crypto subsystem failed.
@@ -910,7 +903,7 @@ Initialization of the crypto subsystem failed.
#### `ERR_CRYPTO_INVALID_AUTH_TAG`
-
+
An invalid authentication tag was provided.
@@ -918,7 +911,7 @@ An invalid authentication tag was provided.
#### `ERR_CRYPTO_INVALID_COUNTER`
-
+
An invalid counter was provided for a counter-mode cipher.
@@ -926,7 +919,7 @@ An invalid counter was provided for a counter-mode cipher.
#### `ERR_CRYPTO_INVALID_CURVE`
-
+
An invalid elliptic-curve was provided.
@@ -940,7 +933,7 @@ An invalid [crypto digest algorithm][] was specified.
#### `ERR_CRYPTO_INVALID_IV`
-
+
An invalid initialization vector was provided.
@@ -948,7 +941,7 @@ An invalid initialization vector was provided.
#### `ERR_CRYPTO_INVALID_JWK`
-
+
An invalid JSON Web Key was provided.
@@ -962,7 +955,7 @@ The given crypto key object's type is invalid for the attempted operation.
#### `ERR_CRYPTO_INVALID_KEYLEN`
-
+
An invalid key length was provided.
@@ -970,7 +963,7 @@ An invalid key length was provided.
#### `ERR_CRYPTO_INVALID_KEYPAIR`
-
+
An invalid key pair was provided.
@@ -978,7 +971,7 @@ An invalid key pair was provided.
#### `ERR_CRYPTO_INVALID_KEYTYPE`
-
+
An invalid key type was provided.
@@ -986,7 +979,7 @@ An invalid key type was provided.
#### `ERR_CRYPTO_INVALID_MESSAGELEN`
-
+
An invalid message length was provided.
@@ -994,7 +987,7 @@ An invalid message length was provided.
#### `ERR_CRYPTO_INVALID_SCRYPT_PARAMS`
-
+
Invalid scrypt algorithm parameters were provided.
@@ -1009,7 +1002,7 @@ instance, calling [`cipher.getAuthTag()`][] before calling `cipher.final()`.
#### `ERR_CRYPTO_INVALID_TAG_LENGTH`
-
+
An invalid authentication tag length was provided.
@@ -1017,7 +1010,7 @@ An invalid authentication tag length was provided.
#### `ERR_CRYPTO_JOB_INIT_FAILED`
-
+
Initialization of an asynchronous crypto operation failed.
@@ -1039,7 +1032,7 @@ Key's Asymmetric Key Type is not registered for use in the
#### `ERR_CRYPTO_OPERATION_FAILED`
-
+
A crypto operation failed for an otherwise unspecified reason.
@@ -1094,7 +1087,7 @@ An unknown Diffie-Hellman group name was given. See
#### `ERR_CRYPTO_UNSUPPORTED_OPERATION`
-
+
An attempt to invoke an unsupported crypto operation was made.
@@ -1102,7 +1095,7 @@ An attempt to invoke an unsupported crypto operation was made.
#### `ERR_DEBUGGER_ERROR`
-
+
An error occurred with the [debugger][].
@@ -1110,7 +1103,7 @@ An error occurred with the [debugger][].
#### `ERR_DEBUGGER_STARTUP_ERROR`
-
+
The [debugger][] timed out waiting for the required host/port to be free.
@@ -1118,7 +1111,7 @@ The [debugger][] timed out waiting for the required host/port to be free.
#### `ERR_DLOPEN_DISABLED`
-
+
Loading native addons has been disabled using [`--no-addons`][].
@@ -1126,7 +1119,7 @@ Loading native addons has been disabled using [`--no-addons`][].
#### `ERR_DLOPEN_FAILED`
-
+
A call to `process.dlopen()` failed.
@@ -1140,7 +1133,7 @@ The [`fs.Dir`][] was previously closed.
#### `ERR_DIR_CONCURRENT_OPERATION`
-
+
A synchronous read or close call was attempted on an [`fs.Dir`][] which has
ongoing asynchronous operations.
@@ -1222,7 +1215,7 @@ falsy value.
#### `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`
-
+
Used when a feature that is not available
to the current platform which is running Node.js is used.
@@ -1231,7 +1224,7 @@ to the current platform which is running Node.js is used.
#### `ERR_FS_CP_DIR_TO_NON_DIR`
-
+
An attempt was made to copy a directory to a non-directory (file, symlink,
etc.) using [`fs.cp()`][].
@@ -1240,7 +1233,7 @@ etc.) using [`fs.cp()`][].
#### `ERR_FS_CP_EEXIST`
-
+
An attempt was made to copy over a file that already existed with
[`fs.cp()`][], with the `force` and `errorOnExist` set to `true`.
@@ -1249,7 +1242,7 @@ An attempt was made to copy over a file that already existed with
#### `ERR_FS_CP_EINVAL`
-
+
When using [`fs.cp()`][], `src` or `dest` pointed to an invalid path.
@@ -1263,7 +1256,7 @@ Response body size doesn't match with the specified content-length header value.
#### `ERR_FS_CP_FIFO_PIPE`
-
+
An attempt was made to copy a named pipe with [`fs.cp()`][].
@@ -1271,7 +1264,7 @@ An attempt was made to copy a named pipe with [`fs.cp()`][].
#### `ERR_FS_CP_NON_DIR_TO_DIR`
-
+
An attempt was made to copy a non-directory (file, symlink, etc.) to a directory
using [`fs.cp()`][].
@@ -1280,7 +1273,7 @@ using [`fs.cp()`][].
#### `ERR_FS_CP_SOCKET`
-
+
An attempt was made to copy to a socket with [`fs.cp()`][].
@@ -1288,7 +1281,7 @@ An attempt was made to copy to a socket with [`fs.cp()`][].
#### `ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY`
-
+
When using [`fs.cp()`][], a symlink in `dest` pointed to a subdirectory
of `src`.
@@ -1297,7 +1290,7 @@ of `src`.
#### `ERR_FS_CP_UNKNOWN`
-
+
An attempt was made to copy to an unknown file type with [`fs.cp()`][].
@@ -1645,7 +1638,7 @@ made to mark a stream and dependent of itself.
#### `ERR_HTTP2_TOO_MANY_INVALID_FRAMES`
-
+
The limit of acceptable invalid HTTP/2 protocol frames sent by the peer,
as specified through the `maxSessionInvalidFrames` option, has been exceeded.
@@ -1682,7 +1675,7 @@ An attempt was made to construct an object using a non-public constructor.
#### `ERR_IMPORT_ASSERTION_TYPE_FAILED`
-
+
An import assertion has failed, preventing the specified module to be imported.
@@ -1690,7 +1683,7 @@ An import assertion has failed, preventing the specified module to be imported.
#### `ERR_IMPORT_ASSERTION_TYPE_MISSING`
-
+
An import assertion is missing, preventing the specified module to be imported.
@@ -1698,7 +1691,7 @@ An import assertion is missing, preventing the specified module to be imported.
#### `ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED`
-
+
An import assertion is not supported by this version of Node.js.
@@ -1713,7 +1706,11 @@ time.
#### `ERR_INPUT_TYPE_NOT_ALLOWED`
-
+
+
+Experimental
+
+
The `--input-type` flag was used to attempt to execute a file. This flag can
only be used with input via `--eval`, `--print`, or `STDIN`.
@@ -1883,7 +1880,7 @@ The syntax of a MIME is not valid.
#### `ERR_INVALID_MODULE`
-
+
An attempt was made to load a module that does not exist or was otherwise not
valid.
@@ -1967,7 +1964,7 @@ type on execution, such as when a function is expected to return a promise.
#### `ERR_INVALID_STATE`
-
+
Indicates that an operation cannot be completed due to an invalid state.
For instance, an object may have already been destroyed, or may be
@@ -2068,7 +2065,7 @@ for more information.
#### `ERR_LOADER_CHAIN_INCOMPLETE`
-
+
An ESM loader hook returned without calling `next()` and without explicitly
signaling a short circuit.
@@ -2146,7 +2143,7 @@ failed.
#### `ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE`
-
+
A message posted to a [`MessagePort`][] could not be deserialized in the target
[vm][] `Context`. Not all Node.js objects can be successfully instantiated in
@@ -2194,7 +2191,7 @@ this error will not occur with standard builds of Node.js.
#### `ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST`
-
+
An object that needs to be explicitly listed in the `transferList` argument
is in the object passed to a [`postMessage()`][] call, but is not provided
@@ -2330,7 +2327,7 @@ cannot be imported through the package resolution, unless using an absolute URL.
#### `ERR_PARSE_ARGS_INVALID_OPTION_VALUE`
-
+
When `strict` set to `true`, thrown by [`util.parseArgs()`][] if a [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
value is provided for an option of type [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type), or if a [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2340,7 +2337,7 @@ value is provided for an option of type [`boolean`](https://developer.mozilla.or
#### `ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL`
-
+
Thrown by [`util.parseArgs()`][], when a positional argument is provided and
`allowPositionals` is set to `false`.
@@ -2349,7 +2346,7 @@ Thrown by [`util.parseArgs()`][], when a positional argument is provided and
#### `ERR_PARSE_ARGS_UNKNOWN_OPTION`
-
+
When `strict` set to `true`, thrown by [`util.parseArgs()`][] if an argument
is not configured in `options`.
@@ -2379,7 +2376,11 @@ object.
#### `ERR_REQUIRE_ESM`
-
+
+
+Experimental
+
+
An attempt was made to `require()` an [ES Module][].
@@ -2451,6 +2452,13 @@ could not be determined.
An attempt was made to operate on an already closed socket.
+
+
+#### `ERR_SOCKET_CLOSED_BEFORE_CONNECTION`
+
+When calling [`net.Socket.write()`][] on a connecting socket and the socket was
+closed before the connection was established.
+
#### `ERR_SOCKET_DGRAM_IS_CONNECTED`
@@ -2568,6 +2576,25 @@ An unspecified or non-specific system error has occurred within the Node.js
process. The error object will have an `err.info` object property with
additional details.
+
+
+#### `ERR_TAP_LEXER_ERROR`
+
+An error representing a failing lexer state.
+
+
+
+#### `ERR_TAP_PARSER_ERROR`
+
+An error representing a failing parser state. Additional information about
+the token causing the error is available via the `cause` property.
+
+
+
+#### `ERR_TAP_VALIDATION_ERROR`
+
+This error represents a failed TAP validation.
+
#### `ERR_TEST_FAILURE`
@@ -2612,7 +2639,7 @@ connection.
#### `ERR_TLS_INVALID_CONTEXT`
-
+
The context must be a `SecureContext`.
@@ -2633,7 +2660,7 @@ Valid TLS protocol versions are `'TLSv1'`, `'TLSv1.1'`, or `'TLSv1.2'`.
#### `ERR_TLS_INVALID_STATE`
-
+
The TLS socket must be connected and securely established. Ensure the 'secure'
event is emitted before continuing.
@@ -2655,7 +2682,8 @@ Failed to set PSK identity hint. Hint may be too long.
#### `ERR_TLS_RENEGOTIATION_DISABLED`
-An attempt was made to renegotiate TLS on a socket instance with TLS disabled.
+An attempt was made to renegotiate TLS on a socket instance with renegotiation
+disabled.
@@ -2764,7 +2792,11 @@ An invalid or unknown encoding option was passed to an API.
#### `ERR_UNKNOWN_FILE_EXTENSION`
-
+
+
+Experimental
+
+
An attempt was made to load a module with an unknown or unsupported file
extension.
@@ -2773,7 +2805,11 @@ extension.
#### `ERR_UNKNOWN_MODULE_FORMAT`
-
+
+
+Experimental
+
+
An attempt was made to load a module with an unknown or unsupported format.
@@ -2808,7 +2844,11 @@ import 'package-name'; // supported
#### `ERR_USE_AFTER_CLOSE`
-
+
+
+Experimental
+
+
An attempt was made to use something that was already closed.
@@ -2890,7 +2930,7 @@ The WASI instance has not been started.
#### `ERR_WEBASSEMBLY_RESPONSE`
-
+
The `Response` that has been passed to `WebAssembly.compileStreaming` or to
`WebAssembly.instantiateStreaming` is not a valid WebAssembly response.
@@ -2949,7 +2989,7 @@ Creation of a [`zlib`][] object failed due to incorrect configuration.
#### `HPE_HEADER_OVERFLOW`
-
+
Too much HTTP header data was received. In order to protect against malicious or
malconfigured clients, if more than 8 KiB of HTTP header data is received then
@@ -2972,20 +3012,24 @@ Use `Content-Length` or `Transfer-Encoding: chunked`.
#### `MODULE_NOT_FOUND`
-
+
A module file could not be resolved by the CommonJS modules loader while
attempting a [`require()`][] operation or when loading the program entry point.
### Legacy Node.js error codes
-
+
+
+Deprecated. These error codes are either inconsistent, or have been removed.
+
+
#### `ERR_CANNOT_TRANSFER_OBJECT`
-
+
The value passed to `postMessage()` contained an object that is not supported
for transferring.
@@ -2994,7 +3038,7 @@ for transferring.
#### `ERR_CRYPTO_HASH_DIGEST_NO_UTF16`
-
+
The UTF-16 encoding was used with [`hash.digest()`][]. While the
`hash.digest()` method does allow an `encoding` argument to be passed in,
@@ -3005,7 +3049,7 @@ encoding (e.g. `ucs` or `utf16le`) is not supported.
#### `ERR_HTTP2_FRAME_ERROR`
-
+
Used when a failure occurs sending an individual frame on the HTTP/2
session.
@@ -3014,7 +3058,7 @@ session.
#### `ERR_HTTP2_HEADERS_OBJECT`
-
+
Used when an HTTP/2 Headers Object is expected.
@@ -3022,7 +3066,7 @@ Used when an HTTP/2 Headers Object is expected.
#### `ERR_HTTP2_HEADER_REQUIRED`
-
+
Used when a required header is missing in an HTTP/2 message.
@@ -3030,7 +3074,7 @@ Used when a required header is missing in an HTTP/2 message.
#### `ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND`
-
+
HTTP/2 informational headers must only be sent _prior_ to calling the
`Http2Stream.prototype.respond()` method.
@@ -3039,7 +3083,7 @@ HTTP/2 informational headers must only be sent _prior_ to calling the
#### `ERR_HTTP2_STREAM_CLOSED`
-
+
Used when an action has been performed on an HTTP/2 Stream that has already
been closed.
@@ -3048,7 +3092,7 @@ been closed.
#### `ERR_HTTP_INVALID_CHAR`
-
+
Used when an invalid character is found in an HTTP response status message
(reason phrase).
@@ -3057,7 +3101,7 @@ Used when an invalid character is found in an HTTP response status message
#### `ERR_INDEX_OUT_OF_RANGE`
-
+
A given index was out of the accepted range (e.g. negative offsets).
@@ -3065,7 +3109,7 @@ A given index was out of the accepted range (e.g. negative offsets).
#### `ERR_INVALID_OPT_VALUE`
-
+
An invalid or unexpected value was passed in an options object.
@@ -3073,7 +3117,7 @@ An invalid or unexpected value was passed in an options object.
#### `ERR_INVALID_OPT_VALUE_ENCODING`
-
+
An invalid or unknown file encoding was passed.
@@ -3081,7 +3125,7 @@ An invalid or unknown file encoding was passed.
#### `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`
-
+
This error code was replaced by [`ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST`][]
in Node.js v15.0.0, because it is no longer accurate as other types of
@@ -3091,7 +3135,7 @@ transferable objects also exist now.
#### `ERR_NAPI_CONS_PROTOTYPE_OBJECT`
-
+
Used by the `Node-API` when `Constructor.prototype` is not an object.
@@ -3099,7 +3143,11 @@ Used by the `Node-API` when `Constructor.prototype` is not an object.
#### `ERR_NETWORK_IMPORT_BAD_RESPONSE`
-
+
+
+Experimental
+
+
Response was received but was invalid when importing a module over the network.
@@ -3107,7 +3155,11 @@ Response was received but was invalid when importing a module over the network.
#### `ERR_NETWORK_IMPORT_DISALLOWED`
-
+
+
+Experimental
+
+
A network module attempted to load another module that it is not allowed to
load. Likely this restriction is for security reasons.
@@ -3123,7 +3175,7 @@ A Node.js API was called in an unsupported manner, such as
#### `ERR_OPERATION_FAILED`
-
+
An operation failed. This is typically used to signal the general failure
of an asynchronous operation.
@@ -3132,7 +3184,7 @@ of an asynchronous operation.
#### `ERR_OUTOFMEMORY`
-
+
Used generically to identify that an operation caused an out of memory
condition.
@@ -3141,7 +3193,7 @@ condition.
#### `ERR_PARSE_HISTORY_DATA`
-
+
The `node:repl` module was unable to parse data from the REPL history file.
@@ -3149,7 +3201,7 @@ The `node:repl` module was unable to parse data from the REPL history file.
#### `ERR_SOCKET_CANNOT_SEND`
-
+
Data could not be sent on a socket.
@@ -3157,7 +3209,7 @@ Data could not be sent on a socket.
#### `ERR_STDERR_CLOSE`
-
+
An attempt was made to close the `process.stderr` stream. By design, Node.js
does not allow `stdout` or `stderr` streams to be closed by user code.
@@ -3166,7 +3218,7 @@ does not allow `stdout` or `stderr` streams to be closed by user code.
#### `ERR_STDOUT_CLOSE`
-
+
An attempt was made to close the `process.stdout` stream. By design, Node.js
does not allow `stdout` or `stderr` streams to be closed by user code.
@@ -3175,7 +3227,7 @@ does not allow `stdout` or `stderr` streams to be closed by user code.
#### `ERR_STREAM_READ_NOT_IMPLEMENTED`
-
+
Used when an attempt is made to use a readable stream that has not implemented
[`readable._read()`][].
@@ -3184,7 +3236,7 @@ Used when an attempt is made to use a readable stream that has not implemented
#### `ERR_TLS_RENEGOTIATION_FAILED`
-
+
Used when a TLS renegotiation request has failed in a non-specific way.
@@ -3192,7 +3244,7 @@ Used when a TLS renegotiation request has failed in a non-specific way.
#### `ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER`
-
+
A `SharedArrayBuffer` whose memory is not managed by the JavaScript engine
or by Node.js was encountered during serialization. Such a `SharedArrayBuffer`
@@ -3205,7 +3257,7 @@ This can only happen when native addons create `SharedArrayBuffer`s in
#### `ERR_UNKNOWN_STDIN_TYPE`
-
+
An attempt was made to launch a Node.js process with an unknown `stdin` file
type. This error is usually an indication of a bug within Node.js itself,
@@ -3215,7 +3267,7 @@ although it is possible for user code to trigger it.
#### `ERR_UNKNOWN_STREAM_TYPE`
-
+
An attempt was made to launch a Node.js process with an unknown `stdout` or
`stderr` file type. This error is usually an indication of a bug within Node.js
@@ -3231,7 +3283,7 @@ The V8 `BreakIterator` API was used but the full ICU data set is not installed.
#### `ERR_VALUE_OUT_OF_RANGE`
-
+
Used when a given value is out of the accepted range.
@@ -3245,7 +3297,7 @@ The module must be successfully linked before instantiation.
#### `ERR_VM_MODULE_LINKING_ERRORED`
-
+
The linker function returned a module for which linking has failed.
@@ -3253,7 +3305,7 @@ The linker function returned a module for which linking has failed.
#### `ERR_WORKER_UNSUPPORTED_EXTENSION`
-
+
The pathname used for the main script of a worker has an
unknown file extension.
@@ -3262,7 +3314,7 @@ unknown file extension.
#### `ERR_ZLIB_BINDING_CLOSED`
-
+
Used when an attempt is made to use a `zlib` object after it has already been
closed.
@@ -3271,7 +3323,7 @@ closed.
#### `ERR_CPU_USAGE`
-
+
The native call from `process.cpuUsage` could not be processed.
@@ -3325,6 +3377,7 @@ The native call from `process.cpuUsage` could not be processed.
[`http`]: /api/v19/http
[`https`]: /api/v19/https
[`libuv Error handling`]: https://docs.libuv.org/en/v1.x/errors.html
+[`net.Socket.write()`]: /api/v19/net#socketwritedata-encoding-callback
[`net`]: /api/v19/net
[`new URL(input)`]: /api/v19/url#new-urlinput-base
[`new URLSearchParams(iterable)`]: /api/v19/url#new-urlsearchparamsiterable
diff --git a/content/api/v19/esm.en.md b/content/api/v19/esm.en.md
index a0c772b0e9..d759da372f 100644
--- a/content/api/v19/esm.en.md
+++ b/content/api/v19/esm.en.md
@@ -5,17 +5,21 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
-
+
+
+Stable
+
+
### Introduction
-
+
ECMAScript modules are [the official standard format][] to package JavaScript
code for reuse. Modules are defined using a variety of [`import`][] and
@@ -50,7 +54,7 @@ provides interoperability between them and its original module format,
### Enabling
-
+
Node.js has two module systems: [CommonJS][] modules and ECMAScript modules.
@@ -135,7 +139,7 @@ details), it is recommended to use [url.pathToFileURL][] when importing a path.
##### `data:` imports
-
+
[`data:` URLs][] are supported for importing with the following MIME types:
@@ -157,7 +161,7 @@ is no concept of relative resolution for `data:` URLs.
##### `node:` imports
-
+
`node:` URLs are supported as an alternative means to load Node.js builtin
modules. This URL scheme allows for builtin modules to be referenced by valid
@@ -169,9 +173,13 @@ import fs from 'node:fs/promises';
### Import assertions
-
+
+
+
-
+Experimental
+
+
The [Import Assertions proposal][] adds an inline syntax for module import
statements to pass on more information alongside the module specifier.
@@ -198,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) {
@@ -253,15 +259,19 @@ const buffer = readFileSync(new URL('./data.proto', import.meta.url));
#### `import.meta.resolve(specifier[, parent])`
-
+
+
+
-
+Experimental
+
+
This feature is only available with the `--experimental-import-meta-resolve`
command flag enabled.
* `specifier` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The module specifier to resolve relative to `parent`.
-* `parent` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) The absolute parent module URL to resolve from. If none
+* `parent` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) The absolute parent module URL to resolve from. If none
is specified, the value of `import.meta.url` is used as the default.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
@@ -399,9 +409,9 @@ These CommonJS variables are not available in ES modules.
`__filename` and `__dirname` use cases can be replicated via
[`import.meta.url`][].
-##### No Native Module Loading
+##### No Addon Loading
-Native modules are not currently supported with ES module imports.
+[Addons][] are not currently supported with ES module imports.
They can instead be loaded with [`module.createRequire()`][] or
[`process.dlopen`][].
@@ -434,7 +444,11 @@ separate cache.
### JSON modules
-
+
+
+Experimental
+
+
JSON files can be referenced by `import`:
@@ -453,7 +467,11 @@ imported from the same path.
### Wasm modules
-
+
+
+Experimental
+
+
Importing WebAssembly modules is supported under the
`--experimental-wasm-modules` flag, allowing any `.wasm` files to be
@@ -481,7 +499,7 @@ would provide the exports interface for the instantiation of `module.wasm`.
### Top-level `await`
-
+
The `await` keyword may be used in the top level body of an ECMAScript module.
@@ -493,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
```
@@ -522,7 +538,11 @@ spawn(execPath, [
### HTTPS and HTTP imports
-
+
+
+Experimental
+
+
Importing network based modules using `https:` and `http:` is supported under
the `--experimental-network-imports` flag. This allows web browser-like imports
@@ -559,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) {
@@ -589,19 +607,24 @@ of Node.js applications.
### Loaders
-
+
+
+
-
+Experimental
+
+
> This API is currently being redesigned and will still change.
-
+
To customize the default module resolution, loader hooks can optionally be
provided via a `--experimental-loader ./loader-name.mjs` argument to Node.js.
-When hooks are used they apply to the entry point and all `import` calls. They
-won't apply to `require` calls; those still follow [CommonJS][] rules.
+When hooks are used they apply to each subsequent loader, the entry point, and
+all `import` calls. They won't apply to `require` calls; those still follow
+[CommonJS][] rules.
Loaders follow the pattern of `--require`:
@@ -630,7 +653,7 @@ prevent unintentional breaks in the chain.
##### `resolve(specifier, context, nextResolve)`
-
+
> The loaders API is being redesigned. This hook may disappear or its
> signature may change. Do not rely on the API described below.
@@ -638,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
@@ -649,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 `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 module specifier is the string in an `import` statement or
-`import()` expression.
-
-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
@@ -710,7 +735,7 @@ export async function resolve(specifier, context, nextResolve) {
##### `load(url, context, nextLoad)`
-
+
> The loaders API is being redesigned. This hook may disappear or its
> signature may change. Do not rely on the API described below.
@@ -801,7 +826,7 @@ source to a supported one (see [Examples](#examples) below).
##### `globalPreload()`
-
+
> The loaders API is being redesigned. This hook may disappear or its
> signature may change. Do not rely on the API described below.
@@ -810,7 +835,7 @@ source to a supported one (see [Examples](#examples) below).
> `getGlobalPreloadCode`.
* `context` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Information to assist the preload code
- * `port` [`MessagePort`](/api/worker_threads#messageport)
+ * `port` [`MessagePort`](/api/v19/worker_threads#messageport)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Code to run before application startup
Sometimes it might be necessary to run some code inside of the same global
@@ -880,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';
@@ -893,7 +918,7 @@ export function resolve(specifier, context, nextResolve) {
if (specifier.startsWith('https://')) {
return {
shortCircuit: true,
- url: specifier
+ url: specifier,
};
} else if (parentURL && parentURL.startsWith('https://')) {
return {
@@ -928,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';
@@ -953,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';
@@ -974,7 +997,7 @@ export async function resolve(specifier, context, nextResolve) {
// specifiers ending in the CoffeeScript file extensions.
return {
shortCircuit: true,
- url: new URL(specifier, parentURL).href
+ url: new URL(specifier, parentURL).href,
};
}
@@ -995,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
@@ -1051,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'
@@ -1391,9 +1412,10 @@ The [Loaders API][] provides a mechanism for customizing the ESM specifier
resolution algorithm. An example loader that provides CommonJS-style resolution
for ESM specifiers is [commonjs-extension-resolution-loader][].
-
+
[6.1.7 Array Index]: https://tc39.es/ecma262/#integer-index
+[Addons]: /api/v19/addons
[CommonJS]: /api/v19/modules
[Conditional exports]: /api/v19/packages#conditional-exports
[Core modules]: /api/v19/modules#core-modules
diff --git a/content/api/v19/events.en.md b/content/api/v19/events.en.md
index 1d05331712..046f747af5 100644
--- a/content/api/v19/events.en.md
+++ b/content/api/v19/events.en.md
@@ -5,13 +5,17 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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")
@@ -35,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 {}
@@ -45,9 +49,7 @@ myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
-```
-
-```cjs
+--------------
const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
@@ -67,16 +69,34 @@ an ordinary listener function is called, the standard `this` keyword
is intentionally set to reference the `EventEmitter` instance to which the
listener is attached.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+myEmitter.on('event', function(a, b) {
+ console.log(a, b, this, this === myEmitter);
+ // Prints:
+ // a b MyEmitter {
+ // _events: [Object: null prototype] { event: [Function (anonymous)] },
+ // _eventsCount: 1,
+ // _maxListeners: undefined,
+ // [Symbol(kCapture)]: false
+ // } true
+});
+myEmitter.emit('event', 'a', 'b');
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
console.log(a, b, this, this === myEmitter);
// Prints:
// a b MyEmitter {
- // domain: null,
- // _events: { event: [Function] },
+ // _events: [Object: null prototype] { event: [Function (anonymous)] },
// _eventsCount: 1,
- // _maxListeners: undefined } true
+ // _maxListeners: undefined,
+ // [Symbol(kCapture)]: false
+ // } true
});
myEmitter.emit('event', 'a', 'b');
```
@@ -84,7 +104,18 @@ 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:
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+myEmitter.on('event', (a, b) => {
+ console.log(a, b, this);
+ // Prints: a b {}
+});
+myEmitter.emit('event', 'a', 'b');
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
console.log(a, b, this);
@@ -101,7 +132,19 @@ 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:
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+myEmitter.on('event', (a, b) => {
+ setImmediate(() => {
+ console.log('this happens asynchronously');
+ });
+});
+myEmitter.emit('event', 'a', 'b');
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
setImmediate(() => {
@@ -116,7 +159,21 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+let m = 0;
+myEmitter.on('event', () => {
+ console.log(++m);
+});
+myEmitter.emit('event');
+// Prints: 1
+myEmitter.emit('event');
+// Prints: 2
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
let m = 0;
myEmitter.on('event', () => {
@@ -132,7 +189,21 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+let m = 0;
+myEmitter.once('event', () => {
+ console.log(++m);
+});
+myEmitter.emit('event');
+// Prints: 1
+myEmitter.emit('event');
+// Ignored
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
let m = 0;
myEmitter.once('event', () => {
@@ -154,7 +225,15 @@ 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.
-```js
+```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
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// Throws and crashes Node.js
@@ -165,7 +244,18 @@ used. (Note, however, that the `node:domain` module is deprecated.)
As a best practice, listeners should always be added for the `'error'` events.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+myEmitter.on('error', (err) => {
+ console.error('whoops! there was an error');
+});
+myEmitter.emit('error', new Error('whoops!'));
+// Prints: whoops! there was an error
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('error', (err) => {
console.error('whoops! there was an error');
@@ -177,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();
@@ -186,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();
@@ -204,7 +292,14 @@ 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:
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const ee = new EventEmitter();
+ee.on('something', async (value) => {
+ throw new Error('kaboom');
+});
+--------------
+const EventEmitter = require('node:events');
const ee = new EventEmitter();
ee.on('something', async (value) => {
throw new Error('kaboom');
@@ -217,7 +312,23 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const ee1 = new EventEmitter({ captureRejections: true });
+ee1.on('something', async (value) => {
+ throw new Error('kaboom');
+});
+
+ee1.on('error', console.log);
+
+const ee2 = new EventEmitter({ captureRejections: true });
+ee2.on('something', async (value) => {
+ throw new Error('kaboom');
+});
+
+ee2[Symbol.for('nodejs.rejection')] = console.log;
+--------------
+const EventEmitter = require('node:events');
const ee1 = new EventEmitter({ captureRejections: true });
ee1.on('something', async (value) => {
throw new Error('kaboom');
@@ -236,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;
@@ -246,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();
@@ -265,15 +374,13 @@ recommendation is to **not use `async` functions as `'error'` event handlers**.
### `EventEmitter`
-
+
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');
```
@@ -288,7 +395,7 @@ It supports the following option:
#### `'newListener'`
-
+
* `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
@@ -304,7 +411,29 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+
+const myEmitter = new MyEmitter();
+// Only do this once so we don't loop forever
+myEmitter.once('newListener', (event, listener) => {
+ if (event === 'event') {
+ // Insert a new listener in front
+ myEmitter.on('event', () => {
+ console.log('B');
+ });
+ }
+});
+myEmitter.on('event', () => {
+ console.log('A');
+});
+myEmitter.emit('event');
+// Prints:
+// B
+// A
+--------------
+const EventEmitter = require('node:events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
@@ -328,7 +457,7 @@ myEmitter.emit('event');
#### `'removeListener'`
-
+
* `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 event name
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The event handler function
@@ -337,7 +466,7 @@ The `'removeListener'` event is emitted _after_ the `listener` is removed.
#### `emitter.addListener(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)
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -346,7 +475,7 @@ Alias for `emitter.on(eventName, listener)`.
#### `emitter.emit(eventName[, ...args])`
-
+
* `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)
* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -358,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();
@@ -389,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();
@@ -426,14 +553,14 @@ myEmitter.emit('event', 1, 2, 3, 4, 5);
#### `emitter.eventNames()`
-
+
* Returns: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
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();
@@ -445,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();
@@ -463,7 +588,7 @@ console.log(myEE.eventNames());
#### `emitter.getMaxListeners()`
-
+
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -471,18 +596,21 @@ 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)`
-
+
* `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)
* Returns: Function\[]
@@ -499,21 +627,21 @@ console.log(util.inspect(server.listeners('connection')));
#### `emitter.off(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)
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v19/events#eventemitter)
Alias for [`emitter.removeListener()`][].
#### `emitter.on(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.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v19/events#eventemitter)
Adds the `listener` function to the end of the listeners array for the
event named `eventName`. No checks are made to see if the `listener` has
@@ -533,7 +661,17 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const myEE = new EventEmitter();
+myEE.on('foo', () => console.log('a'));
+myEE.prependListener('foo', () => console.log('b'));
+myEE.emit('foo');
+// Prints:
+// b
+// a
+--------------
+const EventEmitter = require('node:events');
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
@@ -545,11 +683,11 @@ myEE.emit('foo');
#### `emitter.once(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.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v19/events#eventemitter)
Adds a **one-time** `listener` function for the event named `eventName`. The
next time `eventName` is triggered, this listener is removed and then invoked.
@@ -566,7 +704,17 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const myEE = new EventEmitter();
+myEE.once('foo', () => console.log('a'));
+myEE.prependOnceListener('foo', () => console.log('b'));
+myEE.emit('foo');
+// Prints:
+// b
+// a
+--------------
+const EventEmitter = require('node:events');
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
@@ -578,11 +726,11 @@ myEE.emit('foo');
#### `emitter.prependListener(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.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v19/events#eventemitter)
Adds the `listener` function to the _beginning_ of the listeners array for the
event named `eventName`. No checks are made to see if the `listener` has
@@ -600,11 +748,11 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
#### `emitter.prependOnceListener(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.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The callback function
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v19/events#eventemitter)
Adds a **one-time** `listener` function for the event named `eventName` to the
_beginning_ of the listeners array. The next time `eventName` is triggered, this
@@ -620,10 +768,10 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
#### `emitter.removeAllListeners([eventName])`
-
+
* `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)
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v19/events#eventemitter)
Removes all listeners, or those of the specified `eventName`.
@@ -635,11 +783,11 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
#### `emitter.removeListener(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)
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v19/events#eventemitter)
Removes the specified `listener` from the listener array for the event named
`eventName`.
@@ -664,7 +812,39 @@ 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.
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+class MyEmitter extends EventEmitter {}
+const myEmitter = new MyEmitter();
+
+const callbackA = () => {
+ console.log('A');
+ myEmitter.removeListener('event', callbackB);
+};
+
+const callbackB = () => {
+ console.log('B');
+};
+
+myEmitter.on('event', callbackA);
+
+myEmitter.on('event', callbackB);
+
+// callbackA removes listener callbackB but it will still be called.
+// Internal listener array at time of emit [callbackA, callbackB]
+myEmitter.emit('event');
+// Prints:
+// A
+// B
+
+// callbackB is now removed.
+// Internal listener array [callbackA]
+myEmitter.emit('event');
+// Prints:
+// A
+--------------
+const EventEmitter = require('node:events');
+class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
const callbackA = () => {
@@ -705,7 +885,22 @@ event (as in the example below), `removeListener()` will remove the most
recently added instance. In the example the `once('ping')`
listener is removed:
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const ee = new EventEmitter();
+
+function pong() {
+ console.log('pong');
+}
+
+ee.on('ping', pong);
+ee.once('ping', pong);
+ee.removeListener('ping', pong);
+
+ee.emit('ping');
+ee.emit('ping');
+--------------
+const EventEmitter = require('node:events');
const ee = new EventEmitter();
function pong() {
@@ -724,10 +919,10 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
#### `emitter.setMaxListeners(n)`
-
+
* `n` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* Returns: [`EventEmitter`](/api/events#eventemitter)
+* Returns: [`EventEmitter`](/api/v19/events#eventemitter)
By default `EventEmitter`s will print a warning if more than `10` listeners are
added for a particular event. This is a useful default that helps finding
@@ -739,7 +934,7 @@ Returns a reference to the `EventEmitter`, so that calls can be chained.
#### `emitter.rawListeners(eventName)`
-
+
* `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)
* Returns: Function\[]
@@ -747,7 +942,31 @@ 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()`).
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const emitter = new EventEmitter();
+emitter.once('log', () => console.log('log once'));
+
+// Returns a new Array with a function `onceWrapper` which has a property
+// `listener` which contains the original listener bound above
+const listeners = emitter.rawListeners('log');
+const logFnWrapper = listeners[0];
+
+// Logs "log once" to the console and does not unbind the `once` event
+logFnWrapper.listener();
+
+// Logs "log once" to the console and removes the listener
+logFnWrapper();
+
+emitter.on('log', () => console.log('log persistently'));
+// Will return a new Array with a single function bound by `.on()` above
+const newListeners = emitter.rawListeners('log');
+
+// Logs "log persistently" twice
+newListeners[0]();
+emitter.emit('log');
+--------------
+const EventEmitter = require('node:events');
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
@@ -773,7 +992,7 @@ emitter.emit('log');
#### `emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])`
-
+
* `err` Error
* `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)
@@ -785,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 {
@@ -802,9 +1021,7 @@ class MyClass extends EventEmitter {
// Tear the resource down here.
}
}
-```
-
-```cjs
+--------------
const { EventEmitter, captureRejectionSymbol } = require('node:events');
class MyClass extends EventEmitter {
@@ -825,7 +1042,7 @@ class MyClass extends EventEmitter {
### `events.defaultMaxListeners`
-
+
By default, a maximum of `10` listeners can be registered for any single
event. This limit can be changed for individual `EventEmitter` instances
@@ -845,7 +1062,17 @@ 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:
-```js
+```mjs|cjs
+import { EventEmitter } from 'node:events';
+const emitter = new EventEmitter();
+emitter.setMaxListeners(emitter.getMaxListeners() + 1);
+emitter.once('event', () => {
+ // do stuff
+ emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
+});
+--------------
+const EventEmitter = require('node:events');
+const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
@@ -864,7 +1091,7 @@ Its `name` property is set to `'MaxListenersExceededWarning'`.
### `events.errorMonitor`
-
+
This symbol shall be used to install a listener for only monitoring `'error'`
events. Listeners installed using this symbol are called before the regular
@@ -876,9 +1103,9 @@ regular `'error'` listener is installed.
### `events.getEventListeners(emitterOrTarget, eventName)`
-
+
-* `emitterOrTarget` [`EventEmitter`](/api/events#eventemitter) | [`EventTarget`](/api/events#eventtarget)
+* `emitterOrTarget` [`EventEmitter`](/api/v19/events#eventemitter) | [`EventTarget`](/api/v19/events#eventtarget)
* `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)
* Returns: Function\[]
@@ -890,48 +1117,46 @@ 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] ]
}
```
### `events.once(emitter, name[, options])`
-
+
-* `emitter` [`EventEmitter`](/api/events#eventemitter)
+* `emitter` [`EventEmitter`](/api/v19/events#eventemitter)
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Can be used to cancel waiting for the event.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Can be used to cancel waiting for the event.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
@@ -943,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';
@@ -964,11 +1189,9 @@ process.nextTick(() => {
try {
await once(ee, 'myevent');
} catch (err) {
- console.log('error happened', err);
+ console.error('error happened', err);
}
-```
-
-```cjs
+--------------
const { once, EventEmitter } = require('node:events');
async function run() {
@@ -989,7 +1212,7 @@ async function run() {
try {
await once(ee, 'myevent');
} catch (err) {
- console.log('error happened', err);
+ console.error('error happened', err);
}
}
@@ -1001,37 +1224,35 @@ 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();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
- .catch((err) => console.log('error', err.message));
+ .catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
- .catch((err) => console.log('error', err.message));
+ .catch((err) => console.error('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
```
-An [`AbortSignal`](/api/globals#abortsignal) can be used to cancel waiting for the event:
+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();
@@ -1053,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();
@@ -1088,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';
@@ -1110,9 +1329,7 @@ process.nextTick(() => {
});
foo().then(() => console.log('done'));
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const myEE = new EventEmitter();
@@ -1139,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';
@@ -1156,9 +1373,7 @@ process.nextTick(() => {
});
foo().then(() => console.log('done'));
-```
-
-```cjs
+--------------
const { EventEmitter, once } = require('node:events');
const myEE = new EventEmitter();
@@ -1178,7 +1393,7 @@ foo().then(() => console.log('done'));
### `events.captureRejections`
-
+
Value: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1186,7 +1401,7 @@ Change the default `captureRejections` option on all new `EventEmitter` objects.
### `events.captureRejectionSymbol`
-
+
Value: `Symbol.for('nodejs.rejection')`
@@ -1194,17 +1409,21 @@ See how to write a custom [rejection handler][rejection].
### `events.listenerCount(emitter, eventName)`
-
+
+
+
+
+Deprecated: Use [`emitter.listenerCount()`][] instead.
-
+
-* `emitter` [`EventEmitter`](/api/events#eventemitter) The emitter to query
+* `emitter` [`EventEmitter`](/api/v19/events#eventemitter) The emitter to query
* `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 event name
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();
@@ -1212,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();
@@ -1226,15 +1443,15 @@ console.log(listenerCount(myEmitter, 'event'));
### `events.on(emitter, eventName[, options])`
-
+
-* `emitter` [`EventEmitter`](/api/events#eventemitter)
+* `emitter` [`EventEmitter`](/api/v19/events#eventemitter)
* `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
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Can be used to cancel awaiting events.
+ * `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';
@@ -1253,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 () => {
@@ -1282,9 +1497,9 @@ if the `EventEmitter` emits `'error'`. It removes all listeners when
exiting the loop. The `value` returned by each iteration is an array
composed of the emitted event arguments.
-An [`AbortSignal`](/api/globals#abortsignal) can be used to cancel waiting on events:
+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';
@@ -1309,9 +1524,7 @@ const ac = new AbortController();
})();
process.nextTick(() => ac.abort());
-```
-
-```cjs
+--------------
const { on, EventEmitter } = require('node:events');
const ac = new AbortController();
@@ -1339,27 +1552,25 @@ process.nextTick(() => ac.abort());
### `events.setMaxListeners(n[, ...eventTargets])`
-
+
* `n` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A non-negative number. The maximum number of listeners per
`EventTarget` event.
-* `...eventsTargets` EventTarget\[]|EventEmitter\[] Zero or more [`EventTarget`](/api/events#eventtarget)
- or [`EventEmitter`](/api/events#eventemitter) instances. If none are specified, `n` is set as the default
- max for all newly created [`EventTarget`](/api/events#eventtarget) and [`EventEmitter`](/api/events#eventemitter) objects.
+* `...eventsTargets` EventTarget\[]|EventEmitter\[] Zero or more [`EventTarget`](/api/v19/events#eventtarget)
+ 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
+ EventEmitter,
} = require('node:events');
const target = new EventTarget();
@@ -1370,13 +1581,13 @@ setMaxListeners(5, target, emitter);
### `events.EventEmitterAsyncResource extends EventEmitter`
-
+
-Integrates `EventEmitter` with [`AsyncResource`](/api/async_hooks#asyncresource) for `EventEmitter`s that
+Integrates `EventEmitter` with [`AsyncResource`](/api/v19/async_hooks#asyncresource) for `EventEmitter`s that
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';
@@ -1403,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');
@@ -1437,7 +1646,7 @@ Promise.resolve().then(() => {
The `EventEmitterAsyncResource` class has the same methods and takes the
same options as `EventEmitter` and `AsyncResource` themselves.
-#### `new events.EventEmitterAsyncResource(options)`
+#### `new events.EventEmitterAsyncResource([options])`
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `captureRejections` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) It enables
@@ -1461,7 +1670,7 @@ same options as `EventEmitter` and `AsyncResource` themselves.
#### `eventemitterasyncresource.asyncResource`
-* Type: The underlying [`AsyncResource`](/api/async_hooks#asyncresource).
+* Type: The underlying [`AsyncResource`](/api/v19/async_hooks#asyncresource).
The returned `AsyncResource` object has an additional `eventEmitter` property
that provides a reference to this `EventEmitterAsyncResource`.
@@ -1482,7 +1691,7 @@ never be called.
### `EventTarget` and `Event` API
-
+
The `EventTarget` and `Event` objects are a Node.js-specific implementation
of the [`EventTarget` Web API][] that are exposed by some Node.js core APIs.
@@ -1522,9 +1731,8 @@ and cannot be used in place of an `EventEmitter` in most cases.
ignored.
2. The `NodeEventTarget` does not emulate the full `EventEmitter` API.
Specifically the `prependListener()`, `prependOnceListener()`,
- `rawListeners()`, `setMaxListeners()`, `getMaxListeners()`, and
- `errorMonitor` APIs are not emulated. The `'newListener'` and
- `'removeListener'` events will also not be emitted.
+ `rawListeners()`, and `errorMonitor` APIs are not emulated.
+ The `'newListener'` and `'removeListener'` events will also not be emitted.
3. The `NodeEventTarget` does not implement any special default behavior
for events with type `'error'`.
4. The `NodeEventTarget` supports `EventListener` objects as well as
@@ -1565,13 +1773,13 @@ async function handler2(event) {
const handler3 = {
handleEvent(event) {
console.log(event.type); // Prints 'foo'
- }
+ },
};
const handler4 = {
async handleEvent(event) {
console.log(event.type); // Prints 'foo'
- }
+ },
};
const target = new EventTarget();
@@ -1603,35 +1811,43 @@ be aligned with the new behavior.
#### `Event`
-
+
The `Event` object is an adaptation of the [`Event` Web API][]. Instances
are created internally by Node.js.
##### `event.bubbles`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Always returns `false`.
This is not used in Node.js and is provided purely for completeness.
-##### `event.cancelBubble()`
+##### `event.cancelBubble`
+
+
+
+
+
+Legacy: Use [`event.stopPropagation()`][] instead.
-
+
-Alias for `event.stopPropagation()`. This is not used in Node.js and is
-provided purely for completeness.
+* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+Alias for `event.stopPropagation()` if set to `true`. This is not used
+in Node.js and is provided purely for completeness.
##### `event.cancelable`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True if the event was created with the `cancelable` option.
##### `event.composed`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Always returns `false`.
@@ -1639,7 +1855,7 @@ This is not used in Node.js and is provided purely for completeness.
##### `event.composedPath()`
-
+
Returns an array containing the current `EventTarget` as the only entry or
empty if the event is not being dispatched. This is not used in
@@ -1647,15 +1863,15 @@ Node.js and is provided purely for completeness.
##### `event.currentTarget`
-
+
-* Type: [`EventTarget`](/api/events#eventtarget) The `EventTarget` dispatching the event.
+* Type: [`EventTarget`](/api/v19/events#eventtarget) The `EventTarget` dispatching the event.
Alias for `event.target`.
##### `event.defaultPrevented`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1664,65 +1880,95 @@ called.
##### `event.eventPhase`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Returns `0` while an event is not being dispatched, `2` while
it is being dispatched.
This is not used in Node.js and is provided purely for completeness.
+##### `event.initEvent(type[, bubbles[, cancelable]])`
+
+
+
+
+
+Legacy: The WHATWG spec considers it deprecated and users shouldn't use it at all.
+
+
+
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `bubbles` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+* `cancelable` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+
+Redundant with event constructors and incapable of setting `composed`.
+This is not used in Node.js and is provided purely for completeness.
+
##### `event.isTrusted`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-The [`AbortSignal`](/api/globals#abortsignal) `"abort"` event is emitted with `isTrusted` set to `true`. The
+The [`AbortSignal`](/api/v19/globals#abortsignal) `"abort"` event is emitted with `isTrusted` set to `true`. The
value is `false` in all other cases.
##### `event.preventDefault()`
-
+
Sets the `defaultPrevented` property to `true` if `cancelable` is `true`.
##### `event.returnValue`
-
+
+
+
+
+Legacy: Use [`event.defaultPrevented`][] instead.
+
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True if the event has not been canceled.
+The value of `event.returnValue` is always the opposite of `event.defaultPrevented`.
This is not used in Node.js and is provided purely for completeness.
##### `event.srcElement`
-
+
+
+
-* Type: [`EventTarget`](/api/events#eventtarget) The `EventTarget` dispatching the event.
+Legacy: Use [`event.target`][] instead.
+
+
+
+* Type: [`EventTarget`](/api/v19/events#eventtarget) The `EventTarget` dispatching the event.
Alias for `event.target`.
##### `event.stopImmediatePropagation()`
-
+
Stops the invocation of event listeners after the current one completes.
##### `event.stopPropagation()`
-
+
This is not used in Node.js and is provided purely for completeness.
##### `event.target`
-
+
-* Type: [`EventTarget`](/api/events#eventtarget) The `EventTarget` dispatching the event.
+* Type: [`EventTarget`](/api/v19/events#eventtarget) The `EventTarget` dispatching the event.
##### `event.timeStamp`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1730,7 +1976,7 @@ The millisecond timestamp when the `Event` object was created.
##### `event.type`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1738,14 +1984,14 @@ The event type identifier.
#### `EventTarget`
-
+
##### `eventTarget.addEventListener(type, listener[, options])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v19/events#listener)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `once` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, the listener is automatically removed
when it is first invoked. **Default:** `false`.
@@ -1754,7 +2000,7 @@ The event type identifier.
**Default:** `false`.
* `capture` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Not directly used by Node.js. Added for API
completeness. **Default:** `false`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) The listener will be removed when the given
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) The listener will be removed when the given
AbortSignal object's `abort()` method is called.
Adds a new handler for the `type` event. Any given `listener` is added
@@ -1785,9 +2031,9 @@ target.removeEventListener('foo', handler, { capture: true });
##### `eventTarget.dispatchEvent(event)`
-
+
-* `event` [`Event`](/api/events#event)
+* `event` [`Event`](/api/v19/events#event)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if either event's `cancelable` attribute value is
false or its `preventDefault()` method was not invoked, otherwise `false`.
@@ -1796,12 +2042,12 @@ Dispatches the `event` to the list of handlers for `event.type`.
The registered event listeners is synchronously invoked in the order they
were registered.
-##### `eventTarget.removeEventListener(type, listener)`
+##### `eventTarget.removeEventListener(type, listener[, options])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v19/events#listener)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `capture` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1809,20 +2055,28 @@ Removes the `listener` from the list of handlers for event `type`.
#### `CustomEvent`
-
+
+
+
-
+Experimental.
-* Extends: [`Event`](/api/events#event)
+
+
+* Extends: [`Event`](/api/v19/events#event)
The `CustomEvent` object is an adaptation of the [`CustomEvent` Web API][].
Instances are created internally by Node.js.
##### `event.detail`
-
+
+
+
-
+Experimental.
+
+
* Type: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Returns custom data passed when initializing.
@@ -1830,34 +2084,43 @@ Read-only.
#### `NodeEventTarget`
-
+
-* Extends: [`EventTarget`](/api/events#eventtarget)
+* Extends: [`EventTarget`](/api/v19/events#eventtarget)
The `NodeEventTarget` is a Node.js-specific extension to `EventTarget`
that emulates a subset of the `EventEmitter` API.
-##### `nodeEventTarget.addListener(type, listener[, options])`
+##### `nodeEventTarget.addListener(type, listener)`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
-
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `once` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v19/events#listener)
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+* Returns: [`EventTarget`](/api/v19/events#eventtarget) this
Node.js-specific extension to the `EventTarget` class that emulates the
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()`
-
+
* Returns: string\[]
@@ -1866,7 +2129,7 @@ of event `type` names for which event listeners are registered.
##### `nodeEventTarget.listenerCount(type)`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1875,44 +2138,60 @@ of event `type` names for which event listeners are registered.
Node.js-specific extension to the `EventTarget` class that returns the number
of event listeners registered for the `type`.
-##### `nodeEventTarget.off(type, listener)`
+##### `nodeEventTarget.setMaxListeners(n)`
-
+
-* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `n` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Node.js-specific extension to the `EventTarget` class that sets the number
+of max event listeners as `n`.
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+##### `nodeEventTarget.getMaxListeners()`
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+
-Node.js-specific alias for `eventTarget.removeListener()`.
+* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Node.js-specific extension to the `EventTarget` class that returns the number
+of max event listeners.
-##### `nodeEventTarget.on(type, listener[, options])`
+##### `nodeEventTarget.off(type, listener[, options])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v19/events#listener)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `once` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
+ * `capture` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+* Returns: [`EventTarget`](/api/v19/events#eventtarget) this
-Node.js-specific alias for `eventTarget.addListener()`.
+Node.js-specific alias for `eventTarget.removeEventListener()`.
-##### `nodeEventTarget.once(type, listener[, options])`
+##### `nodeEventTarget.on(type, listener)`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v19/events#listener)
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+* Returns: [`EventTarget`](/api/v19/events#eventtarget) this
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+Node.js-specific alias for `eventTarget.addEventListener()`.
+
+##### `nodeEventTarget.once(type, listener)`
+
+
+
+* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v19/events#listener)
+
+* Returns: [`EventTarget`](/api/v19/events#eventtarget) this
Node.js-specific extension to the `EventTarget` class that adds a `once`
listener for the given event `type`. This is equivalent to calling `on`
@@ -1920,25 +2199,28 @@ with the `once` option set to `true`.
##### `nodeEventTarget.removeAllListeners([type])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+* Returns: [`EventTarget`](/api/v19/events#eventtarget) this
Node.js-specific extension to the `EventTarget` class. If `type` is specified,
removes all registered listeners for `type`, otherwise removes all registered
listeners.
-##### `nodeEventTarget.removeListener(type, listener)`
+##### `nodeEventTarget.removeListener(type, listener[, options])`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/events#listener)
+* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`EventListener`](/api/v19/events#listener)
+
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `capture` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-* Returns: [`EventTarget`](/api/events#eventtarget) this
+* Returns: [`EventTarget`](/api/v19/events#eventtarget) this
Node.js-specific extension to the `EventTarget` class that removes the
`listener` for the given `type`. The only difference between `removeListener()`
@@ -1952,9 +2234,12 @@ 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
+[`event.stopPropagation()`]: #eventstoppropagation
+[`event.target`]: #eventtarget
[`events.defaultMaxListeners`]: #eventsdefaultmaxlisteners
[`fs.ReadStream`]: /api/v19/fs#class-fsreadstream
[`net.Server`]: /api/v19/net#class-netserver
diff --git a/content/api/v19/fs.en.md b/content/api/v19/fs.en.md
index f4e04f440c..a204a260cc 100644
--- a/content/api/v19/fs.en.md
+++ b/content/api/v19/fs.en.md
@@ -5,34 +5,34 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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');
```
@@ -44,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 {
@@ -53,9 +53,7 @@ try {
} catch (error) {
console.error('there was an error:', error.message);
}
-```
-
-```cjs
+--------------
const { unlink } = require('node:fs/promises');
(async function(path) {
@@ -76,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) => {
@@ -104,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 {
@@ -113,9 +109,7 @@ try {
} catch (err) {
// handle the error
}
-```
-
-```cjs
+--------------
const { unlinkSync } = require('node:fs');
try {
@@ -128,7 +122,7 @@ try {
### Promises API
-
+
The `fs/promises` API provides asynchronous file system methods that return
promises.
@@ -140,33 +134,33 @@ concurrent modifications on the same file or data corruption may occur.
#### `FileHandle`
-
+
-A [`FileHandle`](/api/fs#filehandle) object is an object wrapper for a numeric file descriptor.
+A [`FileHandle`](/api/v19/fs#filehandle) object is an object wrapper for a numeric file descriptor.
-Instances of the [`FileHandle`](/api/fs#filehandle) object are created by the `fsPromises.open()`
+Instances of the [`FileHandle`](/api/v19/fs#filehandle) object are created by the `fsPromises.open()`
method.
-All [`FileHandle`](/api/fs#filehandle) objects are [`EventEmitter`](/api/events#eventemitter)s.
+All [`FileHandle`](/api/v19/fs#filehandle) objects are [`EventEmitter`](/api/v19/events#eventemitter)s.
-If a [`FileHandle`](/api/fs#filehandle) is not closed using the `filehandle.close()` method, it will
+If a [`FileHandle`](/api/v19/fs#filehandle) is not closed using the `filehandle.close()` method, it will
try to automatically close the file descriptor and emit a process warning,
helping to prevent memory leaks. Please do not rely on this behavior because
it can be unreliable and the file may not be closed. Instead, always explicitly
-close [`FileHandle`](/api/fs#filehandle)s. Node.js may change this behavior in the future.
+close [`FileHandle`](/api/v19/fs#filehandle)s. Node.js may change this behavior in the future.
##### `'close'`
-
+
-The `'close'` event is emitted when the [`FileHandle`](/api/fs#filehandle) has been closed and can no
+The `'close'` event is emitted when the [`FileHandle`](/api/v19/fs#filehandle) has been closed and can no
longer be used.
##### `filehandle.appendFile(data[, options])`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/stream#stream)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/v19/stream#stream)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -179,7 +173,7 @@ to with [`fsPromises.open()`][]. Therefore, this is equivalent to
##### `filehandle.chmod(mode)`
-
+
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the file mode bit mask.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -188,7 +182,7 @@ Modifies the permissions on the file. See chmod(2).
##### `filehandle.chown(uid, gid)`
-
+
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new owner's user id.
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new group's group id.
@@ -198,7 +192,7 @@ Changes the ownership of the file. A wrapper for chown(2).
##### `filehandle.close()`
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -218,7 +212,7 @@ try {
##### `filehandle.createReadStream([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `null`
@@ -227,9 +221,9 @@ try {
* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `Infinity`
* `highWaterMark` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `64 * 1024`
-* Returns: [`fs.ReadStream`](/api/fs#fsreadstream)
+* Returns: [`fs.ReadStream`](/api/v19/fs#fsreadstream)
-Unlike the 16 KiB default `highWaterMark` for a [`stream.Readable`](/api/stream#streamreadable), the stream
+Unlike the 16 KiB default `highWaterMark` for a [`stream.Readable`](/api/v19/stream#streamreadable), the stream
returned by this method has a default `highWaterMark` of 64 KiB.
`options` can include `start` and `end` values to read a range of bytes from
@@ -238,7 +232,7 @@ start counting at 0, allowed values are in the
\[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `start` is
omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from
the current file position. The `encoding` can be any one of those accepted by
-[`Buffer`](/api/buffer#buffer).
+[`Buffer`](/api/v19/buffer#buffer).
If the `FileHandle` points to a character device that only supports blocking
reads (such as keyboard or sound card), read operations do not finish until data
@@ -283,20 +277,20 @@ fd.createReadStream({ start: 90, end: 99 });
##### `filehandle.createWriteStream([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `autoClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `emitClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* Returns: [`fs.WriteStream`](/api/fs#fswritestream)
+* Returns: [`fs.WriteStream`](/api/v19/fs#fswritestream)
`options` may also include a `start` option to allow writing data at some
position past the beginning of the file, allowed values are in the
\[0, [`Number.MAX_SAFE_INTEGER`][]] range. Modifying a file rather than
replacing it may require the `flags` `open` option to be set to `r+` rather than
-the default `r`. The `encoding` can be any one of those accepted by [`Buffer`](/api/buffer#buffer).
+the default `r`. The `encoding` can be any one of those accepted by [`Buffer`](/api/v19/buffer#buffer).
If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`
the file descriptor will be closed automatically. If `autoClose` is false,
@@ -309,7 +303,7 @@ destroyed. Set the `emitClose` option to `false` to change this behavior.
##### `filehandle.datasync()`
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -321,15 +315,15 @@ Unlike `filehandle.sync` this method does not flush modified metadata.
##### `filehandle.fd`
-
+
-* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The numeric file descriptor managed by the [`FileHandle`](/api/fs#filehandle) object.
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The numeric file descriptor managed by the [`FileHandle`](/api/v19/fs#filehandle) object.
##### `filehandle.read(buffer, offset, length, position)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
file data read.
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The location in the buffer at which to start filling.
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes to read.
@@ -339,7 +333,7 @@ Unlike `filehandle.sync` this method does not flush modified metadata.
file position will remain unchanged.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills upon success with an object with two properties:
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes read
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
argument.
Reads data from the file and stores that in the given buffer.
@@ -349,10 +343,10 @@ number of bytes read is zero.
##### `filehandle.read([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
file data read. **Default:** `Buffer.alloc(16384)`
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The location in the buffer at which to start filling.
**Default:** `0`
@@ -364,7 +358,7 @@ number of bytes read is zero.
file position will remain unchanged. **Default:**: `null`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills upon success with an object with two properties:
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes read
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
argument.
Reads data from the file and stores that in the given buffer.
@@ -374,9 +368,9 @@ number of bytes read is zero.
##### `filehandle.read(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer that will be filled with the
file data read.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The location in the buffer at which to start filling.
@@ -389,7 +383,7 @@ number of bytes read is zero.
file position will remain unchanged. **Default:**: `null`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills upon success with an object with two properties:
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes read
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A reference to the passed in `buffer`
argument.
Reads data from the file and stores that in the given buffer.
@@ -399,18 +393,22 @@ number of bytes read is zero.
##### `filehandle.readableWebStream()`
-
+
+
+
-
+Experimental
-* Returns: [`ReadableStream`](/api/webstreams#readablestream)
+
+
+* Returns: [`ReadableStream`](/api/v19/webstreams#readablestream)
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';
@@ -421,9 +419,7 @@ for await (const chunk of file.readableWebStream())
console.log(chunk);
await file.close();
-```
-
-```cjs
+--------------
const {
open,
} = require('node:fs/promises');
@@ -444,20 +440,20 @@ close the `FileHandle` automatically. User code must still call the
##### `filehandle.readFile(options)`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `null`
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting an in-progress readFile
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows aborting an in-progress readFile
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills upon a successful read with the contents of the
file. If no encoding is specified (using `options.encoding`), the data is
- returned as a [`Buffer`](/api/buffer#buffer) object. Otherwise, the data will be a string.
+ returned as a [`Buffer`](/api/v19/buffer#buffer) object. Otherwise, the data will be a string.
Asynchronously reads the entire contents of a file.
If `options` is a string, then it specifies the `encoding`.
-The [`FileHandle`](/api/fs#filehandle) has to support reading.
+The [`FileHandle`](/api/v19/fs#filehandle) has to support reading.
If one or more `filehandle.read()` calls are made on a file handle and then a
`filehandle.readFile()` call is made, the data will be read from the current
@@ -466,7 +462,7 @@ of the file.
##### `filehandle.readLines([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `null`
@@ -475,12 +471,12 @@ of the file.
* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `Infinity`
* `highWaterMark` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `64 * 1024`
-* Returns: [`readline.InterfaceConstructor`](/api/readline#interfaceconstructor)
+* Returns: [`readline.InterfaceConstructor`](/api/v19/readline#interfaceconstructor)
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');
@@ -488,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 () => {
@@ -504,7 +498,7 @@ const { open } = require('node:fs/promises');
##### `filehandle.readv(buffers[, position])`
-
+
* `buffers` Buffer\[]|TypedArray\[]|DataView\[]
* `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The offset from the beginning of the file where
@@ -519,16 +513,16 @@ Read from a file and write to an array of [`ArrayBufferView`](https://developer.
##### `filehandle.stat([options])`
-
+
* `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.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an [`fs.Stats`](/api/fs#fsstats) for the file.
+ [`fs.Stats`](/api/v19/fs#fsstats) object should be `bigint`. **Default:** `false`.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an [`fs.Stats`](/api/v19/fs#fsstats) for the file.
##### `filehandle.sync()`
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -538,7 +532,7 @@ Refer to the POSIX fsync(2) documentation for more detail.
##### `filehandle.truncate(len)`
-
+
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -569,20 +563,20 @@ If `len` is negative then `0` will be used.
##### `filehandle.utimes(atime, mtime)`
-
+
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
-Change the file system timestamps of the object referenced by the [`FileHandle`](/api/fs#filehandle)
+Change the file system timestamps of the object referenced by the [`FileHandle`](/api/v19/fs#filehandle)
then resolves the promise with no arguments upon success.
##### `filehandle.write(buffer, offset[, length[, position]])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The start position from within `buffer` where the data
to write begins.
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes from `buffer` to write. **Default:**
@@ -598,7 +592,7 @@ Write `buffer` to the file.
The promise is resolved with an object containing two properties:
* `bytesWritten` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the number of bytes written
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) a reference to the
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) a reference to the
`buffer` written.
It is unsafe to use `filehandle.write()` multiple times on the same file
@@ -611,9 +605,9 @@ the end of the file.
##### `filehandle.write(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
@@ -628,7 +622,7 @@ default with the above values.
##### `filehandle.write(string[, position[, encoding]])`
-
+
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The offset from the beginning of the file where the
@@ -656,9 +650,9 @@ the end of the file.
##### `filehandle.writeFile(data, options)`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/stream#stream)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/v19/stream#stream)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The expected character encoding when `data` is a
string. **Default:** `'utf8'`
@@ -670,7 +664,7 @@ The promise is resolved with no arguments upon success.
If `options` is a string, then it specifies the `encoding`.
-The [`FileHandle`](/api/fs#filehandle) has to support writing.
+The [`FileHandle`](/api/v19/fs#filehandle) has to support writing.
It is unsafe to use `filehandle.writeFile()` multiple times on the same file
without waiting for the promise to be resolved (or rejected).
@@ -682,7 +676,7 @@ beginning of the file.
##### `filehandle.writev(buffers[, position])`
-
+
* `buffers` Buffer\[]|TypedArray\[]|DataView\[]
* `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) The offset from the beginning of the file where the
@@ -707,9 +701,9 @@ the end of the file.
#### `fsPromises.access(path[, mode])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `fs.constants.F_OK`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -745,10 +739,10 @@ the error raised if the file is not accessible.
#### `fsPromises.appendFile(path, data[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`FileHandle`](/api/fs#filehandle) filename or [`FileHandle`](/api/fs#filehandle)
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `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) | [`FileHandle`](/api/v19/fs#filehandle) filename or [`FileHandle`](/api/v19/fs#filehandle)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
@@ -756,21 +750,21 @@ the error raised if the file is not accessible.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
Asynchronously append data to a file, creating the file if it does not yet
-exist. `data` can be a string or a [`Buffer`](/api/buffer#buffer).
+exist. `data` can be a string or a [`Buffer`](/api/v19/buffer#buffer).
If `options` is a string, then it specifies the `encoding`.
The `mode` option only affects the newly created file. See [`fs.open()`][]
for more details.
-The `path` may be specified as a [`FileHandle`](/api/fs#filehandle) that has been opened
+The `path` may be specified as a [`FileHandle`](/api/v19/fs#filehandle) that has been opened
for appending (using `fsPromises.open()`).
#### `fsPromises.chmod(path, mode)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -778,9 +772,9 @@ Changes the permissions of a file.
#### `fsPromises.chown(path, uid, gid)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -789,10 +783,10 @@ Changes the ownership of a file.
#### `fsPromises.copyFile(src, dest[, mode])`
-
+
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) source filename to copy
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) destination filename of the copy operation
+* `src` [`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) source filename to copy
+* `dest` [`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) destination filename of the copy operation
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Optional modifiers that specify the behavior of the copy
operation. It is possible to create a mask consisting of the bitwise OR of
two or more values (e.g.
@@ -822,7 +816,7 @@ try {
await copyFile('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
} catch {
- console.log('The file could not be copied');
+ console.error('The file could not be copied');
}
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
@@ -830,18 +824,22 @@ try {
await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
console.log('source.txt was copied to destination.txt');
} catch {
- console.log('The file could not be copied');
+ console.error('The file could not be copied');
}
```
#### `fsPromises.cp(src, dest[, options])`
-
+
+
+
+
+Experimental
-
+
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) source path to copy.
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) destination path to copy to.
+* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) source path to copy.
+* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) destination path to copy to.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `dereference` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) dereference symlinks. **Default:** `false`.
* `errorOnExist` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) when `force` is `false`, and the destination
@@ -849,6 +847,9 @@ try {
* `filter` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Function to filter copied files/directories. Return
`true` to copy the item, `false` to ignore it. Can also return a `Promise`
that resolves to `true` or `false` **Default:** `undefined`.
+ * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) source path to copy.
+ * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) destination path to copy to.
+ * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the `errorOnExist` option to change this behavior.
@@ -868,9 +869,9 @@ behavior is similar to `cp dir1/ dir2/`.
#### `fsPromises.lchmod(path, mode)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -880,9 +881,9 @@ This method is only implemented on macOS.
#### `fsPromises.lchown(path, uid, gid)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -891,9 +892,9 @@ Changes the ownership on a symbolic link.
#### `fsPromises.lutimes(path, atime, mtime)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -905,10 +906,10 @@ the symbolic link itself are changed.
#### `fsPromises.link(existingPath, newPath)`
-
+
-* `existingPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `existingPath` [`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)
+* `newPath` [`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)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
Creates a new link from the `existingPath` to the `newPath`. See the POSIX
@@ -916,13 +917,13 @@ link(2) documentation for more detail.
#### `fsPromises.lstat(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the numeric values in the returned
- [`fs.Stats`](/api/fs#fsstats) 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.Stats`](/api/fs#fsstats) object for the given
+ [`fs.Stats`](/api/v19/fs#fsstats) 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.Stats`](/api/v19/fs#fsstats) object for the given
symbolic link `path`.
Equivalent to [`fsPromises.stat()`][] unless `path` refers to a symbolic link,
@@ -931,9 +932,9 @@ Refer to the POSIX lstat(2) document for more detail.
#### `fsPromises.mkdir(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `recursive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Not supported on Windows. **Default:** `0o777`.
@@ -948,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 {
@@ -959,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');
@@ -978,12 +977,12 @@ makeDirectory().catch(console.error);
#### `fsPromises.mkdtemp(prefix[, options])`
-
+
* `prefix` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a string containing the filesystem path
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a string containing the file system path
of the newly created temporary directory.
Creates a unique temporary directory. A unique directory name is generated by
@@ -997,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);
}
@@ -1013,16 +1014,16 @@ characters directly to the `prefix` string. For instance, given a directory
#### `fsPromises.open(path, flags[, mode])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) See [support of file system `flags`][].
**Default:** `'r'`.
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the file mode (permission and sticky bits)
if the file is created. **Default:** `0o666` (readable and writable)
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`FileHandle`](/api/fs#filehandle) object.
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`FileHandle`](/api/v19/fs#filehandle) object.
-Opens a [`FileHandle`](/api/fs#filehandle).
+Opens a [`FileHandle`](/api/v19/fs#filehandle).
Refer to the POSIX open(2) documentation for more detail.
@@ -1033,20 +1034,20 @@ a colon, Node.js will open a file system stream, as described by
#### `fsPromises.opendir(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `encoding` [`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) **Default:** `'utf8'`
* `bufferSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of directory entries that are buffered
internally when reading from the directory. Higher values lead to better
performance but higher memory usage. **Default:** `32`
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an [`fs.Dir`](/api/fs#fsdir).
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with an [`fs.Dir`](/api/v19/fs#fsdir).
Asynchronously open a directory for iterative scanning. See the POSIX
opendir(3) documentation for more detail.
-Creates an [`fs.Dir`](/api/fs#fsdir), which contains all further functions for reading from
+Creates an [`fs.Dir`](/api/v19/fs#fsdir), which contains all further functions for reading from
and cleaning up the directory.
The `encoding` option sets the encoding for the `path` while opening the
@@ -1066,14 +1067,14 @@ try {
}
```
-When using the async iterator, the [`fs.Dir`](/api/fs#fsdir) object will be automatically
+When using the async iterator, the [`fs.Dir`](/api/v19/fs#fsdir) object will be automatically
closed after the iterator exits.
#### `fsPromises.readdir(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `withFileTypes` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
@@ -1085,10 +1086,10 @@ Reads the contents of a directory.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the filenames. If the `encoding` is set to `'buffer'`, the filenames returned
-will be passed as [`Buffer`](/api/buffer#buffer) objects.
+will be passed as [`Buffer`](/api/v19/buffer#buffer) objects.
If `options.withFileTypes` is set to `true`, the resolved array will contain
-[`fs.Dirent`](/api/fs#fsdirent) objects.
+[`fs.Dirent`](/api/v19/fs#fsdirent) objects.
```mjs
import { readdir } from 'node:fs/promises';
@@ -1104,19 +1105,19 @@ try {
#### `fsPromises.readFile(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`FileHandle`](/api/fs#filehandle) filename or `FileHandle`
+* `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) | [`FileHandle`](/api/v19/fs#filehandle) filename or `FileHandle`
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `null`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'r'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting an in-progress readFile
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows aborting an in-progress readFile
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the contents of the file.
Asynchronously reads the entire contents of a file.
If no encoding is specified (using `options.encoding`), the data is returned
-as a [`Buffer`](/api/buffer#buffer) object. Otherwise, the data will be a string.
+as a [`Buffer`](/api/v19/buffer#buffer) object. Otherwise, the data will be a string.
If `options` is a string, then it specifies the encoding.
@@ -1128,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);
@@ -1137,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() {
@@ -1154,7 +1153,7 @@ async function logFile() {
logFile();
```
-It is possible to abort an ongoing `readFile` using an [`AbortSignal`](/api/globals#abortsignal). If a
+It is possible to abort an ongoing `readFile` using an [`AbortSignal`](/api/v19/globals#abortsignal). If a
request is aborted the promise returned is rejected with an `AbortError`:
```mjs
@@ -1178,13 +1177,13 @@ try {
Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering `fs.readFile` performs.
-Any specified [`FileHandle`](/api/fs#filehandle) has to support reading.
+Any specified [`FileHandle`](/api/v19/fs#filehandle) has to support reading.
#### `fsPromises.readlink(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the `linkString` upon success.
@@ -1196,13 +1195,13 @@ readlink(2) documentation for more detail. The promise is resolved with the
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the link path returned. If the `encoding` is set to `'buffer'`, the link path
-returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+returned will be passed as a [`Buffer`](/api/v19/buffer#buffer) object.
#### `fsPromises.realpath(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with the resolved path upon success.
@@ -1215,7 +1214,7 @@ Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path. If the `encoding` is set to `'buffer'`, the path returned will be
-passed as a [`Buffer`](/api/buffer#buffer) object.
+passed as a [`Buffer`](/api/v19/buffer#buffer) object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on `/proc` in order for this function to work. Glibc does not have
@@ -1223,19 +1222,19 @@ this restriction.
#### `fsPromises.rename(oldPath, newPath)`
-
+
-* `oldPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `oldPath` [`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)
+* `newPath` [`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)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
Renames `oldPath` to `newPath`.
#### `fsPromises.rmdir(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `maxRetries` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
`EPERM` error is encountered, Node.js retries the operation with a linear
@@ -1261,9 +1260,9 @@ To get a behavior similar to the `rm -rf` Unix command, use
#### `fsPromises.rm(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, exceptions will be ignored if `path` does
not exist. **Default:** `false`.
@@ -1283,13 +1282,24 @@ Removes files and directories (modeled on the standard POSIX `rm` utility).
#### `fsPromises.stat(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the numeric values in the returned
- [`fs.Stats`](/api/fs#fsstats) 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.Stats`](/api/fs#fsstats) object for the
+ [`fs.Stats`](/api/v19/fs#fsstats) 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.Stats`](/api/v19/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/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)
+ * `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])`
@@ -1305,8 +1315,8 @@ changes:
-->
-* `target` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `target` [`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)
+* `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)
* `type` [`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) **Default:** `null`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -1321,9 +1331,9 @@ automatically be normalized to absolute path.
#### `fsPromises.truncate(path[, len])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -1332,9 +1342,9 @@ bytes.
#### `fsPromises.unlink(path)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
If `path` refers to a symbolic link, then the link is removed without affecting
@@ -1344,9 +1354,9 @@ documentation for more detail.
#### `fsPromises.utimes(path, atime, mtime)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
@@ -1362,9 +1372,9 @@ The `atime` and `mtime` arguments follow these rules:
#### `fsPromises.watch(filename[, options])`
-
+
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `filename` [`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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `persistent` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates whether the process should continue to run
as long as files are being watched. **Default:** `true`.
@@ -1374,11 +1384,11 @@ The `atime` and `mtime` arguments follow these rules:
`false`.
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Specifies the character encoding to be used for the
filename passed to the listener. **Default:** `'utf8'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An [`AbortSignal`](/api/globals#abortsignal) used to signal when the watcher
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) An [`AbortSignal`](/api/v19/globals#abortsignal) used to signal when the watcher
should stop.
* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) of objects with the properties:
* `eventType` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of change
- * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) The name of the file changed.
+ * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) The name of the file changed.
Returns an async iterator that watches for changes on `filename`, where `filename`
is either a file or a directory.
@@ -1410,15 +1420,15 @@ All the [caveats][] for `fs.watch()` also apply to `fsPromises.watch()`.
#### `fsPromises.writeFile(file, data[, options])`
-
+
-* `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`FileHandle`](/api/fs#filehandle) filename or `FileHandle`
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/stream#stream)
+* `file` [`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) | [`FileHandle`](/api/v19/fs#filehandle) filename or `FileHandle`
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface) | [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) | [`Stream`](/api/v19/stream#stream)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'w'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting an in-progress writeFile
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows aborting an in-progress writeFile
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with `undefined` upon success.
Asynchronously writes data to a file, replacing the file if it already exists.
@@ -1431,7 +1441,7 @@ If `options` is a string, then it specifies the encoding.
The `mode` option only affects the newly created file. See [`fs.open()`][]
for more details.
-Any specified [`FileHandle`](/api/fs#filehandle) has to support writing.
+Any specified [`FileHandle`](/api/v19/fs#filehandle) has to support writing.
It is unsafe to use `fsPromises.writeFile()` multiple times on the same file
without waiting for the promise to be settled.
@@ -1441,7 +1451,7 @@ method that performs multiple `write` calls internally to write the buffer
passed to it. For performance sensitive code consider using
[`fs.createWriteStream()`][] or [`filehandle.createWriteStream()`][].
-It is possible to use an [`AbortSignal`](/api/globals#abortsignal) to cancel an `fsPromises.writeFile()`.
+It is possible to use an [`AbortSignal`](/api/v19/globals#abortsignal) to cancel an `fsPromises.writeFile()`.
Cancelation is "best effort", and some amount of data is likely still
to be written.
@@ -1470,6 +1480,8 @@ system requests but rather the internal buffering `fs.writeFile` performs.
#### `fsPromises.constants`
+
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
Returns an object containing commonly used constants for file system
@@ -1488,9 +1500,9 @@ concurrent modifications on the same file or data corruption may occur.
#### `fs.access(path[, mode], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `fs.constants.F_OK`
* `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)
@@ -1658,10 +1670,10 @@ the user from reading or writing to it.
#### `fs.appendFile(path, data[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `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) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
@@ -1670,7 +1682,7 @@ the user from reading or writing to it.
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
Asynchronously append data to a file, creating the file if it does not yet
-exist. `data` can be a string or a [`Buffer`](/api/buffer#buffer).
+exist. `data` can be a string or a [`Buffer`](/api/v19/buffer#buffer).
The `mode` option only affects the newly created file. See [`fs.open()`][]
for more details.
@@ -1722,9 +1734,9 @@ open('message.txt', 'a', (err, fd) => {
#### `fs.chmod(path, mode, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `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)
@@ -1795,9 +1807,9 @@ implemented.
#### `fs.chown(path, uid, gid, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1810,7 +1822,7 @@ See the POSIX chown(2) documentation for more detail.
#### `fs.close(fd[, callback])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1826,10 +1838,10 @@ See the POSIX close(2) documentation for more detail.
#### `fs.copyFile(src, dest[, mode], callback)`
-
+
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) source filename to copy
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) destination filename of the copy operation
+* `src` [`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) source filename to copy
+* `dest` [`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) destination filename of the copy operation
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) modifiers for copy operation. **Default:** `0`.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1870,12 +1882,16 @@ copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
#### `fs.cp(src, dest[, options], callback)`
-
+
-
+
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) source path to copy.
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) destination path to copy to.
+Experimental
+
+
+
+* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) source path to copy.
+* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) destination path to copy to.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `dereference` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) dereference symlinks. **Default:** `false`.
* `errorOnExist` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) when `force` is `false`, and the destination
@@ -1883,6 +1899,9 @@ copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
* `filter` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Function to filter copied files/directories. Return
`true` to copy the item, `false` to ignore it. Can also return a `Promise`
that resolves to `true` or `false` **Default:** `undefined`.
+ * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) source path to copy.
+ * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) destination path to copy to.
+ * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the `errorOnExist` option to change this behavior.
@@ -1902,14 +1921,14 @@ behavior is similar to `cp dir1/ dir2/`.
#### `fs.createReadStream(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:**
`'r'`.
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `null`
- * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/fs#filehandle) **Default:** `null`
+ * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/v19/fs#filehandle) **Default:** `null`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
* `autoClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `emitClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
@@ -1917,9 +1936,9 @@ behavior is similar to `cp dir1/ dir2/`.
* `end` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `Infinity`
* `highWaterMark` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `64 * 1024`
* `fs` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
-* Returns: [`fs.ReadStream`](/api/fs#fsreadstream)
+* Returns: [`fs.ReadStream`](/api/v19/fs#fsreadstream)
-Unlike the 16 KiB default `highWaterMark` for a [`stream.Readable`](/api/stream#streamreadable), the stream
+Unlike the 16 KiB default `highWaterMark` for a [`stream.Readable`](/api/v19/stream#streamreadable), the stream
returned by this method has a default `highWaterMark` of 64 KiB.
`options` can include `start` and `end` values to read a range of bytes from
@@ -1928,12 +1947,12 @@ start counting at 0, allowed values are in the
\[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `fd` is specified and `start` is
omitted or `undefined`, `fs.createReadStream()` reads sequentially from the
current file position. The `encoding` can be any one of those accepted by
-[`Buffer`](/api/buffer#buffer).
+[`Buffer`](/api/v19/buffer#buffer).
If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
the specified file descriptor. This means that no `'open'` event will be
emitted. `fd` should be blocking; non-blocking `fd`s should be passed to
-[`net.Socket`](/api/net#netsocket).
+[`net.Socket`](/api/v19/net#netsocket).
If `fd` points to a character device that only supports blocking reads
(such as keyboard or sound card), read operations do not finish until data is
@@ -1987,26 +2006,26 @@ If `options` is a string, then it specifies the encoding.
#### `fs.createWriteStream(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:**
`'w'`.
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
- * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/fs#filehandle) **Default:** `null`
+ * `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/v19/fs#filehandle) **Default:** `null`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
* `autoClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `emitClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `start` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `fs` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
-* Returns: [`fs.WriteStream`](/api/fs#fswritestream)
+* Returns: [`fs.WriteStream`](/api/v19/fs#fswritestream)
`options` may also include a `start` option to allow writing data at some
position past the beginning of the file, allowed values are in the
\[0, [`Number.MAX_SAFE_INTEGER`][]] range. Modifying a file rather than
replacing it may require the `flags` option to be set to `r+` rather than the
-default `w`. The `encoding` can be any one of those accepted by [`Buffer`](/api/buffer#buffer).
+default `w`. The `encoding` can be any one of those accepted by [`Buffer`](/api/v19/buffer#buffer).
If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`
the file descriptor will be closed automatically. If `autoClose` is false,
@@ -2025,20 +2044,24 @@ will be disabled. When providing the `fs` option, overrides for at least one of
for `open` is also required. If `autoClose` is `true`, an override for `close`
is also required.
-Like [`fs.ReadStream`](/api/fs#fsreadstream), if `fd` is specified, [`fs.WriteStream`](/api/fs#fswritestream) will ignore the
+Like [`fs.ReadStream`](/api/v19/fs#fsreadstream), if `fd` is specified, [`fs.WriteStream`](/api/v19/fs#fswritestream) will ignore the
`path` argument and will use the specified file descriptor. This means that no
`'open'` event will be emitted. `fd` should be blocking; non-blocking `fd`s
-should be passed to [`net.Socket`](/api/net#netsocket).
+should be passed to [`net.Socket`](/api/v19/net#netsocket).
If `options` is a string, then it specifies the encoding.
#### `fs.exists(path, callback)`
-
+
+
+
+
+Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* `exists` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2172,7 +2195,7 @@ process.
#### `fs.fchmod(fd, mode, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2186,7 +2209,7 @@ See the POSIX fchmod(2) documentation for more detail.
#### `fs.fchown(fd, uid, gid, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2201,7 +2224,7 @@ See the POSIX fchown(2) documentation for more detail.
#### `fs.fdatasync(fd, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -2214,23 +2237,23 @@ exception are given to the completion callback.
#### `fs.fstat(fd[, options], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `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.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
+ [`fs.Stats`](/api/v19/fs#fsstats) 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.Stats`](/api/fs#fsstats)
+ * `stats` [`fs.Stats`](/api/v19/fs#fsstats)
-Invokes the callback with the [`fs.Stats`](/api/fs#fsstats) for the file descriptor.
+Invokes the callback with the [`fs.Stats`](/api/v19/fs#fsstats) for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
#### `fs.fsync(fd, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -2243,7 +2266,7 @@ than a possible exception are given to the completion callback.
#### `fs.ftruncate(fd[, len], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
@@ -2292,7 +2315,7 @@ If `len` is negative then `0` will be used.
#### `fs.futimes(fd, atime, mtime, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -2305,9 +2328,9 @@ descriptor. See [`fs.utimes()`][].
#### `fs.lchmod(path, mode, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `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) | [`AggregateError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError)
@@ -2321,9 +2344,9 @@ See the POSIX lchmod(2) documentation for more detail.
#### `fs.lchown(path, uid, gid, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -2336,9 +2359,9 @@ See the POSIX lchown(2) documentation for more detail.
#### `fs.lutimes(path, atime, mtime, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -2354,10 +2377,10 @@ callback.
#### `fs.link(existingPath, newPath, callback)`
-
+
-* `existingPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `existingPath` [`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)
+* `newPath` [`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)
* `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)
@@ -2367,18 +2390,18 @@ exception are given to the completion callback.
#### `fs.lstat(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the numeric values in the returned
- [`fs.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
+ [`fs.Stats`](/api/v19/fs#fsstats) 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.Stats`](/api/fs#fsstats)
+ * `stats` [`fs.Stats`](/api/v19/fs#fsstats)
-Retrieves the [`fs.Stats`](/api/fs#fsstats) for the symbolic link referred to by the path.
-The callback gets two arguments `(err, stats)` where `stats` is a [`fs.Stats`](/api/fs#fsstats)
+Retrieves the [`fs.Stats`](/api/v19/fs#fsstats) for the symbolic link referred to by the path.
+The callback gets two arguments `(err, stats)` where `stats` is a [`fs.Stats`](/api/v19/fs#fsstats)
object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic
link, then the link itself is stat-ed, not the file that it refers to.
@@ -2386,9 +2409,9 @@ See the POSIX lstat(2) documentation for more details.
#### `fs.mkdir(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `recursive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Not supported on Windows. **Default:** `0o777`.
@@ -2434,7 +2457,7 @@ See the POSIX mkdir(2) documentation for more details.
#### `fs.mkdtemp(prefix[, options], callback)`
-
+
* `prefix` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2459,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
@@ -2502,9 +2527,9 @@ mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
#### `fs.open(path[, flags[, mode]], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) See [support of file system `flags`][].
**Default:** `'r'`.
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666` (readable and writable)
@@ -2528,11 +2553,50 @@ 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)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `encoding` [`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) **Default:** `'utf8'`
* `bufferSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of directory entries that are buffered
@@ -2540,12 +2604,12 @@ Functions based on `fs.open()` exhibit this behavior as well:
performance but higher memory usage. **Default:** `32`
* `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)
- * `dir` [`fs.Dir`](/api/fs#fsdir)
+ * `dir` [`fs.Dir`](/api/v19/fs#fsdir)
Asynchronously open a directory. See the POSIX opendir(3) documentation for
more details.
-Creates an [`fs.Dir`](/api/fs#fsdir), which contains all further functions for reading from
+Creates an [`fs.Dir`](/api/v19/fs#fsdir), which contains all further functions for reading from
and cleaning up the directory.
The `encoding` option sets the encoding for the `path` while opening the
@@ -2553,10 +2617,10 @@ directory and subsequent read operations.
#### `fs.read(fd, buffer, offset, length, position, callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The buffer that the data will be
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The buffer that the data will be
written to.
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The position in `buffer` to write the data to.
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bytes to read.
@@ -2567,7 +2631,7 @@ directory and subsequent read operations.
* `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)
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `buffer` [`Buffer`](/api/buffer#buffer)
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer)
Read data from the file specified by `fd`.
@@ -2581,18 +2645,18 @@ a promise for an `Object` with `bytesRead` and `buffer` properties.
#### `fs.read(fd[, options], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) **Default:** `Buffer.alloc(16384)`
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) **Default:** `Buffer.alloc(16384)`
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
* `position` [`integer`](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) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
* `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)
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `buffer` [`Buffer`](/api/buffer#buffer)
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer)
Similar to the [`fs.read()`][] function, this version takes an optional
`options` object. If no `options` object is specified, it will default with the
@@ -2600,10 +2664,10 @@ above values.
#### `fs.read(fd, buffer[, options], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The buffer that the data will be
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) The buffer that the data will be
written to.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
@@ -2612,7 +2676,7 @@ above values.
* `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)
* `bytesRead` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `buffer` [`Buffer`](/api/buffer#buffer)
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer)
Similar to the [`fs.read()`][] function, this version takes an optional
`options` object. If no `options` object is specified, it will default with the
@@ -2620,9 +2684,9 @@ above values.
#### `fs.readdir(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `withFileTypes` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
@@ -2639,23 +2703,23 @@ See the POSIX readdir(3) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the filenames passed to the callback. If the `encoding` is set to `'buffer'`,
-the filenames returned will be passed as [`Buffer`](/api/buffer#buffer) objects.
+the filenames returned will be passed as [`Buffer`](/api/v19/buffer#buffer) objects.
If `options.withFileTypes` is set to `true`, the `files` array will contain
-[`fs.Dirent`](/api/fs#fsdirent) objects.
+[`fs.Dirent`](/api/v19/fs#fsdirent) objects.
#### `fs.readFile(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `null`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'r'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting an in-progress readFile
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows aborting an in-progress readFile
* `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) | [`AggregateError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError)
- * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+ * `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
Asynchronously reads the entire contents of a file.
@@ -2755,14 +2819,14 @@ different Node.js versions.
#### `fs.readlink(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `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)
- * `linkString` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+ * `linkString` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
Reads the contents of the symbolic link referred to by `path`. The callback gets
two arguments `(err, linkString)`.
@@ -2772,11 +2836,11 @@ See the POSIX readlink(2) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the link path passed to the callback. If the `encoding` is set to `'buffer'`,
-the link path returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+the link path returned will be passed as a [`Buffer`](/api/v19/buffer#buffer) object.
#### `fs.readv(fd, buffers[, position], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `buffers` ArrayBufferView\[]
@@ -2801,14 +2865,14 @@ a promise for an `Object` with `bytesRead` and `buffers` properties.
#### `fs.realpath(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `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)
- * `resolvedPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+ * `resolvedPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
Asynchronously computes the canonical pathname by resolving `.`, `..`, and
symbolic links.
@@ -2831,21 +2895,21 @@ Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path passed to the callback. If the `encoding` is set to `'buffer'`,
-the path returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+the path returned will be passed as a [`Buffer`](/api/v19/buffer#buffer) object.
If `path` resolves to a socket or a pipe, the function will return a system
dependent name for that object.
#### `fs.realpath.native(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `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)
- * `resolvedPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+ * `resolvedPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
Asynchronous realpath(3).
@@ -2856,7 +2920,7 @@ Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path passed to the callback. If the `encoding` is set to `'buffer'`,
-the path returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+the path returned will be passed as a [`Buffer`](/api/v19/buffer#buffer) object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on `/proc` in order for this function to work. Glibc does not have
@@ -2864,10 +2928,10 @@ this restriction.
#### `fs.rename(oldPath, newPath, callback)`
-
+
-* `oldPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `oldPath` [`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)
+* `newPath` [`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)
* `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)
@@ -2890,9 +2954,9 @@ rename('oldFile.txt', 'newFile.txt', (err) => {
#### `fs.rmdir(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `maxRetries` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
`EPERM` error is encountered, Node.js retries the operation with a linear
@@ -2919,9 +2983,9 @@ with options `{ recursive: true, force: true }`.
#### `fs.rm(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, exceptions will be ignored if `path` does
not exist. **Default:** `false`.
@@ -2944,18 +3008,18 @@ completion callback.
#### `fs.stat(path[, options], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the numeric values in the returned
- [`fs.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
+ [`fs.Stats`](/api/v19/fs#fsstats) 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.Stats`](/api/fs#fsstats)
+ * `stats` [`fs.Stats`](/api/v19/fs#fsstats)
Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
-`stats` is an [`fs.Stats`](/api/fs#fsstats) object.
+`stats` is an [`fs.Stats`](/api/v19/fs#fsstats) object.
In case of an error, the `err.code` will be one of [Common System Errors][].
@@ -3037,12 +3101,30 @@ Stats {
}
```
+#### `fs.statfs(path[, options], callback)`
+
+
+
+* `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)
+ * `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)`
-
+
-* `target` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `target` [`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)
+* `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)
* `type` [`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) **Default:** `null`
* `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)
@@ -3079,9 +3161,9 @@ $ tree .
#### `fs.truncate(path[, len], callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `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) | [`AggregateError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError)
@@ -3090,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) => {
@@ -3115,9 +3195,9 @@ See the POSIX truncate(2) documentation for more details.
#### `fs.unlink(path, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `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)
@@ -3140,9 +3220,9 @@ See the POSIX unlink(2) documentation for more details.
#### `fs.unwatchFile(filename[, listener])`
-
+
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `filename` [`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)
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional, a listener previously attached using
`fs.watchFile()`
@@ -3159,9 +3239,9 @@ and `fs.unwatchFile()` when possible.
#### `fs.utimes(path, atime, mtime, callback)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -3178,9 +3258,9 @@ The `atime` and `mtime` arguments follow these rules:
#### `fs.watch(filename[, options][, listener])`
-
+
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `filename` [`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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `persistent` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates whether the process should continue to run
as long as files are being watched. **Default:** `true`.
@@ -3190,11 +3270,11 @@ The `atime` and `mtime` arguments follow these rules:
`false`.
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Specifies the character encoding to be used for the
filename passed to the listener. **Default:** `'utf8'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows closing the watcher with an AbortSignal.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows closing the watcher with an AbortSignal.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) **Default:** `undefined`
* `eventType` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
- * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
-* Returns: [`fs.FSWatcher`](/api/fs#fsfswatcher)
+ * `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
+* Returns: [`fs.FSWatcher`](/api/v19/fs#fsfswatcher)
Watch for changes on `filename`, where `filename` is either a file or a
directory.
@@ -3210,15 +3290,15 @@ On most platforms, `'rename'` is emitted whenever a filename appears or
disappears in the directory.
The listener callback is attached to the `'change'` event fired by
-[`fs.FSWatcher`](/api/fs#fsfswatcher), but it is not the same thing as the `'change'` value of
+[`fs.FSWatcher`](/api/v19/fs#fsfswatcher), but it is not the same thing as the `'change'` value of
`eventType`.
If a `signal` is passed, aborting the corresponding AbortController will close
-the returned [`fs.FSWatcher`](/api/fs#fsfswatcher).
+the returned [`fs.FSWatcher`](/api/v19/fs#fsfswatcher).
##### Caveats
-
+
The `fs.watch` API is not 100% consistent across platforms, and is
unavailable in some situations.
@@ -3228,10 +3308,10 @@ renamed. An `EPERM` error is reported when the watched directory is deleted.
###### Availability
-
+
This feature depends on the underlying operating system providing a way
-to be notified of filesystem changes.
+to be notified of file system changes.
* On Linux systems, this uses [`inotify(7)`][].
* On BSD systems, this uses [`kqueue(2)`][].
@@ -3253,7 +3333,7 @@ this method is slower and less reliable.
###### Inodes
-
+
On Linux and macOS systems, `fs.watch()` resolves the path to an [inode][] and
watches the inode. If the watched path is deleted and recreated, it is assigned
@@ -3267,7 +3347,7 @@ content, and one for truncation).
###### Filename argument
-
+
Providing `filename` argument in the callback is only supported on Linux,
macOS, Windows, and AIX. Even on supported platforms, `filename` is not always
@@ -3288,17 +3368,17 @@ watch('somedir', (eventType, filename) => {
#### `fs.watchFile(filename[, options], listener)`
-
+
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `filename` [`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)
* `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
* `persistent` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
* `interval` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `5007`
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
- * `current` [`fs.Stats`](/api/fs#fsstats)
- * `previous` [`fs.Stats`](/api/fs#fsstats)
-* Returns: [`fs.StatWatcher`](/api/fs#fsstatwatcher)
+ * `current` [`fs.Stats`](/api/v19/fs#fsstats)
+ * `previous` [`fs.Stats`](/api/v19/fs#fsstats)
+* Returns: [`fs.StatWatcher`](/api/v19/fs#fsstatwatcher)
Watch for changes on `filename`. The callback `listener` will be called each
time the file is accessed.
@@ -3349,17 +3429,17 @@ This happens when:
#### `fs.write(fd, buffer, offset[, length[, position]], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
* `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
* `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)
* `bytesWritten` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
Write `buffer` to the file specified by `fd`.
@@ -3386,10 +3466,10 @@ the end of the file.
#### `fs.write(fd, buffer[, options], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
@@ -3397,7 +3477,7 @@ the end of the file.
* `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)
* `bytesWritten` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
Write `buffer` to the file specified by `fd`.
@@ -3407,7 +3487,7 @@ default with the above values.
#### `fs.write(fd, string[, position[, encoding]], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -3449,15 +3529,15 @@ details.
#### `fs.writeFile(file, data[, options], callback)`
-
+
-* `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `file` [`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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'w'`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting an in-progress writeFile
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows aborting an in-progress writeFile
* `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) | [`AggregateError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError)
@@ -3500,7 +3580,7 @@ Similarly to `fs.readFile` - `fs.writeFile` is a convenience method that
performs multiple `write` calls internally to write the buffer passed to it.
For performance sensitive code consider using [`fs.createWriteStream()`][].
-It is possible to use an [`AbortSignal`](/api/globals#abortsignal) to cancel an `fs.writeFile()`.
+It is possible to use an [`AbortSignal`](/api/v19/globals#abortsignal) to cancel an `fs.writeFile()`.
Cancelation is "best effort", and some amount of data is likely still
to be written.
@@ -3552,7 +3632,7 @@ to contain only `', World'`.
#### `fs.writev(fd, buffers[, position], callback)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `buffers` ArrayBufferView\[]
@@ -3589,9 +3669,9 @@ event loop until the operation completes or fails.
#### `fs.accessSync(path[, mode])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `fs.constants.F_OK`
Synchronously tests a user's permissions for the file or directory specified
@@ -3618,17 +3698,17 @@ try {
#### `fs.appendFileSync(path, data[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* `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) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'a'`.
Synchronously append data to a file, creating the file if it does not yet
-exist. `data` can be a string or a [`Buffer`](/api/buffer#buffer).
+exist. `data` can be a string or a [`Buffer`](/api/v19/buffer#buffer).
The `mode` option only affects the newly created file. See [`fs.open()`][]
for more details.
@@ -3674,9 +3754,9 @@ try {
#### `fs.chmodSync(path, mode)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
For detailed information, see the documentation of the asynchronous version of
@@ -3686,9 +3766,9 @@ See the POSIX chmod(2) documentation for more detail.
#### `fs.chownSync(path, uid, gid)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3699,7 +3779,7 @@ See the POSIX chown(2) documentation for more detail.
#### `fs.closeSync(fd)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3712,10 +3792,10 @@ See the POSIX close(2) documentation for more detail.
#### `fs.copyFileSync(src, dest[, mode])`
-
+
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) source filename to copy
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) destination filename of the copy operation
+* `src` [`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) source filename to copy
+* `dest` [`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) destination filename of the copy operation
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) modifiers for copy operation. **Default:** `0`.
Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it
@@ -3750,18 +3830,25 @@ copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
#### `fs.cpSync(src, dest[, options])`
-
+
+
+
+
+Experimental
-
+
-* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) source path to copy.
-* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) destination path to copy to.
+* `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) source path to copy.
+* `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) destination path to copy to.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `dereference` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) dereference symlinks. **Default:** `false`.
* `errorOnExist` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) when `force` is `false`, and the destination
exists, throw an error. **Default:** `false`.
* `filter` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Function to filter copied files/directories. Return
`true` to copy the item, `false` to ignore it. **Default:** `undefined`
+ * `src` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) source path to copy.
+ * `dest` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) destination path to copy to.
+ * Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the `errorOnExist` option to change this behavior.
@@ -3780,9 +3867,9 @@ behavior is similar to `cp dir1/ dir2/`.
#### `fs.existsSync(path)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
Returns `true` if the path exists, `false` otherwise.
@@ -3803,7 +3890,7 @@ if (existsSync('/etc/passwd'))
#### `fs.fchmodSync(fd, mode)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3814,7 +3901,7 @@ See the POSIX fchmod(2) documentation for more detail.
#### `fs.fchownSync(fd, uid, gid)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new owner's user id.
@@ -3826,7 +3913,7 @@ See the POSIX fchown(2) documentation for more detail.
#### `fs.fdatasyncSync(fd)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3836,21 +3923,21 @@ fdatasync(2) documentation for details. Returns `undefined`.
#### `fs.fstatSync(fd[, options])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `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.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
-* Returns: [`fs.Stats`](/api/fs#fsstats)
+ [`fs.Stats`](/api/v19/fs#fsstats) object should be `bigint`. **Default:** `false`.
+* Returns: [`fs.Stats`](/api/v19/fs#fsstats)
-Retrieves the [`fs.Stats`](/api/fs#fsstats) for the file descriptor.
+Retrieves the [`fs.Stats`](/api/v19/fs#fsstats) for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
#### `fs.fsyncSync(fd)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3860,7 +3947,7 @@ Refer to the POSIX fsync(2) documentation for more detail. Returns `undefined`.
#### `fs.ftruncateSync(fd[, len])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
@@ -3872,7 +3959,7 @@ this API: [`fs.ftruncate()`][].
#### `fs.futimesSync(fd, atime, mtime)`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -3882,9 +3969,9 @@ Synchronous version of [`fs.futimes()`][]. Returns `undefined`.
#### `fs.lchmodSync(path, mode)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
Changes the permissions on a symbolic link. Returns `undefined`.
@@ -3895,9 +3982,9 @@ See the POSIX lchmod(2) documentation for more detail.
#### `fs.lchownSync(path, uid, gid)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `uid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new owner's user id.
* `gid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The file's new group's group id.
@@ -3907,9 +3994,9 @@ See the POSIX lchown(2) documentation for more details.
#### `fs.lutimesSync(path, atime, mtime)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -3919,36 +4006,36 @@ the operation fails. This is the synchronous version of [`fs.lutimes()`][].
#### `fs.linkSync(existingPath, newPath)`
-
+
-* `existingPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `existingPath` [`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)
+* `newPath` [`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)
Creates a new link from the `existingPath` to the `newPath`. See the POSIX
link(2) documentation for more detail. Returns `undefined`.
#### `fs.lstatSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the numeric values in the returned
- [`fs.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
+ [`fs.Stats`](/api/v19/fs#fsstats) object should be `bigint`. **Default:** `false`.
* `throwIfNoEntry` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether an exception will be thrown
if no file system entry exists, rather than returning `undefined`.
**Default:** `true`.
-* Returns: [`fs.Stats`](/api/fs#fsstats)
+* Returns: [`fs.Stats`](/api/v19/fs#fsstats)
-Retrieves the [`fs.Stats`](/api/fs#fsstats) for the symbolic link referred to by `path`.
+Retrieves the [`fs.Stats`](/api/v19/fs#fsstats) for the symbolic link referred to by `path`.
See the POSIX lstat(2) documentation for more details.
#### `fs.mkdirSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `recursive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Not supported on Windows. **Default:** `0o777`.
@@ -3962,7 +4049,7 @@ See the POSIX mkdir(2) documentation for more details.
#### `fs.mkdtempSync(prefix[, options])`
-
+
* `prefix` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -3979,19 +4066,19 @@ object with an `encoding` property specifying the character encoding to use.
#### `fs.opendirSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `encoding` [`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) **Default:** `'utf8'`
* `bufferSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of directory entries that are buffered
internally when reading from the directory. Higher values lead to better
performance but higher memory usage. **Default:** `32`
-* Returns: [`fs.Dir`](/api/fs#fsdir)
+* Returns: [`fs.Dir`](/api/v19/fs#fsdir)
Synchronously open a directory. See opendir(3).
-Creates an [`fs.Dir`](/api/fs#fsdir), which contains all further functions for reading from
+Creates an [`fs.Dir`](/api/v19/fs#fsdir), which contains all further functions for reading from
and cleaning up the directory.
The `encoding` option sets the encoding for the `path` while opening the
@@ -3999,9 +4086,9 @@ directory and subsequent read operations.
#### `fs.openSync(path[, flags[, mode]])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `'r'`.
See [support of file system `flags`][].
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
@@ -4014,9 +4101,9 @@ this API: [`fs.open()`][].
#### `fs.readdirSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `withFileTypes` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
@@ -4029,20 +4116,20 @@ See the POSIX readdir(3) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the filenames returned. If the `encoding` is set to `'buffer'`,
-the filenames returned will be passed as [`Buffer`](/api/buffer#buffer) objects.
+the filenames returned will be passed as [`Buffer`](/api/v19/buffer#buffer) objects.
If `options.withFileTypes` is set to `true`, the result will contain
-[`fs.Dirent`](/api/fs#fsdirent) objects.
+[`fs.Dirent`](/api/v19/fs#fsdirent) objects.
#### `fs.readFileSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `null`
* `flag` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [support of file system `flags`][]. **Default:** `'r'`.
-* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
Returns the contents of the `path`.
@@ -4068,12 +4155,12 @@ readFileSync(''); // =>
#### `fs.readlinkSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
-* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
Returns the symbolic link's string value.
@@ -4082,14 +4169,14 @@ See the POSIX readlink(2) documentation for more details.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the link path returned. If the `encoding` is set to `'buffer'`,
-the link path returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+the link path returned will be passed as a [`Buffer`](/api/v19/buffer#buffer) object.
#### `fs.readSync(fd, buffer, offset, length[, position])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `position` [`integer`](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) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
@@ -4102,10 +4189,10 @@ this API: [`fs.read()`][].
#### `fs.readSync(fd, buffer[, options])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
@@ -4122,7 +4209,7 @@ this API: [`fs.read()`][].
#### `fs.readvSync(fd, buffers[, position])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `buffers` ArrayBufferView\[]
@@ -4134,12 +4221,12 @@ this API: [`fs.readv()`][].
#### `fs.realpathSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
-* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
Returns the resolved pathname.
@@ -4148,12 +4235,12 @@ this API: [`fs.realpath()`][].
#### `fs.realpathSync.native(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
-* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
Synchronous realpath(3).
@@ -4162,7 +4249,7 @@ Only paths that can be converted to UTF8 strings are supported.
The optional `options` argument can be a string specifying an encoding, or an
object with an `encoding` property specifying the character encoding to use for
the path returned. If the `encoding` is set to `'buffer'`,
-the path returned will be passed as a [`Buffer`](/api/buffer#buffer) object.
+the path returned will be passed as a [`Buffer`](/api/v19/buffer#buffer) object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on `/proc` in order for this function to work. Glibc does not have
@@ -4170,10 +4257,10 @@ this restriction.
#### `fs.renameSync(oldPath, newPath)`
-
+
-* `oldPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `newPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `oldPath` [`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)
+* `newPath` [`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)
Renames the file from `oldPath` to `newPath`. Returns `undefined`.
@@ -4181,9 +4268,9 @@ See the POSIX rename(2) documentation for more details.
#### `fs.rmdirSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `maxRetries` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
`EPERM` error is encountered, Node.js retries the operation with a linear
@@ -4207,9 +4294,9 @@ with options `{ recursive: true, force: true }`.
#### `fs.rmSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `force` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, exceptions will be ignored if `path` does
not exist. **Default:** `false`.
@@ -4229,25 +4316,40 @@ utility). Returns `undefined`.
#### `fs.statSync(path[, options])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `bigint` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the numeric values in the returned
- [`fs.Stats`](/api/fs#fsstats) object should be `bigint`. **Default:** `false`.
+ [`fs.Stats`](/api/v19/fs#fsstats) object should be `bigint`. **Default:** `false`.
* `throwIfNoEntry` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether an exception will be thrown
if no file system entry exists, rather than returning `undefined`.
**Default:** `true`.
-* Returns: [`fs.Stats`](/api/fs#fsstats)
+* Returns: [`fs.Stats`](/api/v19/fs#fsstats)
+
+Retrieves the [`fs.Stats`](/api/v19/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/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)
+ * `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
-Retrieves the [`fs.Stats`](/api/fs#fsstats) for the path.
+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])`
-
+
-* `target` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `target` [`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)
+* `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)
* `type` [`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) **Default:** `null`
Returns `undefined`.
@@ -4257,9 +4359,9 @@ this API: [`fs.symlink()`][].
#### `fs.truncateSync(path[, len])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `len` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
Truncates the file. Returns `undefined`. A file descriptor can also be
@@ -4270,17 +4372,17 @@ in the future.
#### `fs.unlinkSync(path)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
Synchronous unlink(2). Returns `undefined`.
#### `fs.utimesSync(path, atime, mtime)`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `atime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
* `mtime` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -4291,10 +4393,10 @@ this API: [`fs.utimes()`][].
#### `fs.writeFileSync(file, data[, options])`
-
+
-* `file` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `file` [`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) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) filename or file descriptor
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `encoding` [`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) **Default:** `'utf8'`
* `mode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0o666`
@@ -4310,10 +4412,10 @@ this API: [`fs.writeFile()`][].
#### `fs.writeSync(fd, buffer, offset[, length[, position]])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
* `position` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) **Default:** `null`
@@ -4324,10 +4426,10 @@ this API: [`fs.write(fd, buffer...)`][].
#### `fs.writeSync(fd, buffer[, options])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `offset` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `buffer.byteLength - offset`
@@ -4339,7 +4441,7 @@ this API: [`fs.write(fd, buffer...)`][].
#### `fs.writeSync(fd, string[, position[, encoding]])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -4352,7 +4454,7 @@ this API: [`fs.write(fd, string...)`][].
#### `fs.writevSync(fd, buffers[, position])`
-
+
* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `buffers` ArrayBufferView\[]
@@ -4369,7 +4471,7 @@ The common objects are shared by all of the file system API variants
#### `fs.Dir`
-
+
A class representing a directory stream.
@@ -4388,12 +4490,12 @@ try {
}
```
-When using the async iterator, the [`fs.Dir`](/api/fs#fsdir) object will be automatically
+When using the async iterator, the [`fs.Dir`](/api/v19/fs#fsdir) object will be automatically
closed after the iterator exits.
##### `dir.close()`
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
@@ -4405,7 +4507,7 @@ closed.
##### `dir.close(callback)`
-
+
* `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)
@@ -4417,14 +4519,14 @@ The `callback` will be called after the resource handle has been closed.
##### `dir.closeSync()`
-
+
Synchronously close the directory's underlying resource handle.
Subsequent reads will result in errors.
##### `dir.path`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -4433,14 +4535,14 @@ The read-only path of this directory as was provided to [`fs.opendir()`][],
##### `dir.read()`
-
+
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`fs.Dirent`](/api/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`fs.Dirent`](/api/v19/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
Asynchronously read the next directory entry via readdir(3) as an
-[`fs.Dirent`](/api/fs#fsdirent).
+[`fs.Dirent`](/api/v19/fs#fsdirent).
-A promise is returned that will be resolved with an [`fs.Dirent`](/api/fs#fsdirent), or `null`
+A promise is returned that will be resolved with an [`fs.Dirent`](/api/v19/fs#fsdirent), or `null`
if there are no more directory entries to read.
Directory entries returned by this function are in no particular order as
@@ -4450,17 +4552,17 @@ included in the iteration results.
##### `dir.read(callback)`
-
+
* `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)
- * `dirent` [`fs.Dirent`](/api/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
+ * `dirent` [`fs.Dirent`](/api/v19/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
Asynchronously read the next directory entry via readdir(3) as an
-[`fs.Dirent`](/api/fs#fsdirent).
+[`fs.Dirent`](/api/v19/fs#fsdirent).
After the read is completed, the `callback` will be called with an
-[`fs.Dirent`](/api/fs#fsdirent), or `null` if there are no more directory entries to read.
+[`fs.Dirent`](/api/v19/fs#fsdirent), or `null` if there are no more directory entries to read.
Directory entries returned by this function are in no particular order as
provided by the operating system's underlying directory mechanisms.
@@ -4469,11 +4571,11 @@ included in the iteration results.
##### `dir.readSync()`
-
+
-* Returns: [`fs.Dirent`](/api/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
+* Returns: [`fs.Dirent`](/api/v19/fs#fsdirent) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
-Synchronously read the next directory entry as an [`fs.Dirent`](/api/fs#fsdirent). See the
+Synchronously read the next directory entry as an [`fs.Dirent`](/api/v19/fs#fsdirent). See the
POSIX readdir(3) documentation for more detail.
If there are no more directory entries to read, `null` will be returned.
@@ -4485,17 +4587,17 @@ included in the iteration results.
##### `dir[Symbol.asyncIterator]()`
-
+
-* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) of [`fs.Dirent`](/api/fs#fsdirent)
+* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) of [`fs.Dirent`](/api/v19/fs#fsdirent)
Asynchronously iterates over the directory until all entries have
been read. Refer to the POSIX readdir(3) documentation for more detail.
-Entries returned by the async iterator are always an [`fs.Dirent`](/api/fs#fsdirent).
+Entries returned by the async iterator are always an [`fs.Dirent`](/api/v19/fs#fsdirent).
The `null` case from `dir.read()` is handled internally.
-See [`fs.Dir`](/api/fs#fsdir) for an example.
+See [`fs.Dir`](/api/v19/fs#fsdir) for an example.
Directory entries returned by this iterator are in no particular order as
provided by the operating system's underlying directory mechanisms.
@@ -4504,108 +4606,108 @@ included in the iteration results.
#### `fs.Dirent`
-
+
A representation of a directory entry, which can be a file or a subdirectory
-within the directory, as returned by reading from an [`fs.Dir`](/api/fs#fsdir). The
+within the directory, as returned by reading from an [`fs.Dir`](/api/v19/fs#fsdir). The
directory entry is a combination of the file name and file type pairs.
Additionally, when [`fs.readdir()`][] or [`fs.readdirSync()`][] is called with
the `withFileTypes` option set to `true`, the resulting array is filled with
-[`fs.Dirent`](/api/fs#fsdirent) objects, rather than strings or [`Buffer`](/api/buffer#buffer)s.
+[`fs.Dirent`](/api/v19/fs#fsdirent) objects, rather than strings or [`Buffer`](/api/v19/buffer#buffer)s.
##### `dirent.isBlockDevice()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a block device.
+Returns `true` if the [`fs.Dirent`](/api/v19/fs#fsdirent) object describes a block device.
##### `dirent.isCharacterDevice()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a character device.
+Returns `true` if the [`fs.Dirent`](/api/v19/fs#fsdirent) object describes a character device.
##### `dirent.isDirectory()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a file system
+Returns `true` if the [`fs.Dirent`](/api/v19/fs#fsdirent) object describes a file system
directory.
##### `dirent.isFIFO()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a first-in-first-out
+Returns `true` if the [`fs.Dirent`](/api/v19/fs#fsdirent) object describes a first-in-first-out
(FIFO) pipe.
##### `dirent.isFile()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a regular file.
+Returns `true` if the [`fs.Dirent`](/api/v19/fs#fsdirent) object describes a regular file.
##### `dirent.isSocket()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a socket.
+Returns `true` if the [`fs.Dirent`](/api/v19/fs#fsdirent) object describes a socket.
##### `dirent.isSymbolicLink()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Dirent`](/api/fs#fsdirent) object describes a symbolic link.
+Returns `true` if the [`fs.Dirent`](/api/v19/fs#fsdirent) object describes a symbolic link.
##### `dirent.name`
-
+
-* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
-The file name that this [`fs.Dirent`](/api/fs#fsdirent) object refers to. The type of this
+The file name that this [`fs.Dirent`](/api/v19/fs#fsdirent) object refers to. The type of this
value is determined by the `options.encoding` passed to [`fs.readdir()`][] or
[`fs.readdirSync()`][].
#### `fs.FSWatcher`
-
+
-* Extends [`EventEmitter`](/api/events#eventemitter)
+* Extends [`EventEmitter`](/api/v19/events#eventemitter)
-A successful call to [`fs.watch()`][] method will return a new [`fs.FSWatcher`](/api/fs#fsfswatcher)
+A successful call to [`fs.watch()`][] method will return a new [`fs.FSWatcher`](/api/v19/fs#fsfswatcher)
object.
-All [`fs.FSWatcher`](/api/fs#fsfswatcher) objects emit a `'change'` event whenever a specific watched
+All [`fs.FSWatcher`](/api/v19/fs#fsfswatcher) objects emit a `'change'` event whenever a specific watched
file is modified.
##### `'change'`
-
+
* `eventType` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The type of change event that has occurred
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) The filename that changed (if relevant/available)
+* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) The filename that changed (if relevant/available)
Emitted when something changes in a watched directory or file.
See more details in [`fs.watch()`][].
The `filename` argument may not be provided depending on operating system
-support. If `filename` is provided, it will be provided as a [`Buffer`](/api/buffer#buffer) if
+support. If `filename` is provided, it will be provided as a [`Buffer`](/api/v19/buffer#buffer) if
`fs.watch()` is called with its `encoding` option set to `'buffer'`, otherwise
`filename` will be a UTF-8 string.
@@ -4622,122 +4724,122 @@ watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
##### `'close'`
-
+
Emitted when the watcher stops watching for changes. The closed
-[`fs.FSWatcher`](/api/fs#fsfswatcher) object is no longer usable in the event handler.
+[`fs.FSWatcher`](/api/v19/fs#fsfswatcher) object is no longer usable in the event handler.
##### `'error'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
Emitted when an error occurs while watching the file. The errored
-[`fs.FSWatcher`](/api/fs#fsfswatcher) object is no longer usable in the event handler.
+[`fs.FSWatcher`](/api/v19/fs#fsfswatcher) object is no longer usable in the event handler.
##### `watcher.close()`
-
+
-Stop watching for changes on the given [`fs.FSWatcher`](/api/fs#fsfswatcher). Once stopped, the
-[`fs.FSWatcher`](/api/fs#fsfswatcher) object is no longer usable.
+Stop watching for changes on the given [`fs.FSWatcher`](/api/v19/fs#fsfswatcher). Once stopped, the
+[`fs.FSWatcher`](/api/v19/fs#fsfswatcher) object is no longer usable.
##### `watcher.ref()`
-
+
-* Returns: [`fs.FSWatcher`](/api/fs#fsfswatcher)
+* Returns: [`fs.FSWatcher`](/api/v19/fs#fsfswatcher)
When called, requests that the Node.js event loop _not_ exit so long as the
-[`fs.FSWatcher`](/api/fs#fsfswatcher) is active. Calling `watcher.ref()` multiple times will have
+[`fs.FSWatcher`](/api/v19/fs#fsfswatcher) is active. Calling `watcher.ref()` multiple times will have
no effect.
-By default, all [`fs.FSWatcher`](/api/fs#fsfswatcher) objects are "ref'ed", making it normally
+By default, all [`fs.FSWatcher`](/api/v19/fs#fsfswatcher) objects are "ref'ed", making it normally
unnecessary to call `watcher.ref()` unless `watcher.unref()` had been
called previously.
##### `watcher.unref()`
-
+
-* Returns: [`fs.FSWatcher`](/api/fs#fsfswatcher)
+* Returns: [`fs.FSWatcher`](/api/v19/fs#fsfswatcher)
-When called, the active [`fs.FSWatcher`](/api/fs#fsfswatcher) object will not require the Node.js
+When called, the active [`fs.FSWatcher`](/api/v19/fs#fsfswatcher) object will not require the Node.js
event loop to remain active. If there is no other activity keeping the
-event loop running, the process may exit before the [`fs.FSWatcher`](/api/fs#fsfswatcher) object's
+event loop running, the process may exit before the [`fs.FSWatcher`](/api/v19/fs#fsfswatcher) object's
callback is invoked. Calling `watcher.unref()` multiple times will have
no effect.
#### `fs.StatWatcher`
-
+
-* Extends [`EventEmitter`](/api/events#eventemitter)
+* Extends [`EventEmitter`](/api/v19/events#eventemitter)
-A successful call to `fs.watchFile()` method will return a new [`fs.StatWatcher`](/api/fs#fsstatwatcher)
+A successful call to `fs.watchFile()` method will return a new [`fs.StatWatcher`](/api/v19/fs#fsstatwatcher)
object.
##### `watcher.ref()`
-
+
-* Returns: [`fs.StatWatcher`](/api/fs#fsstatwatcher)
+* Returns: [`fs.StatWatcher`](/api/v19/fs#fsstatwatcher)
When called, requests that the Node.js event loop _not_ exit so long as the
-[`fs.StatWatcher`](/api/fs#fsstatwatcher) is active. Calling `watcher.ref()` multiple times will have
+[`fs.StatWatcher`](/api/v19/fs#fsstatwatcher) is active. Calling `watcher.ref()` multiple times will have
no effect.
-By default, all [`fs.StatWatcher`](/api/fs#fsstatwatcher) objects are "ref'ed", making it normally
+By default, all [`fs.StatWatcher`](/api/v19/fs#fsstatwatcher) objects are "ref'ed", making it normally
unnecessary to call `watcher.ref()` unless `watcher.unref()` had been
called previously.
##### `watcher.unref()`
-
+
-* Returns: [`fs.StatWatcher`](/api/fs#fsstatwatcher)
+* Returns: [`fs.StatWatcher`](/api/v19/fs#fsstatwatcher)
-When called, the active [`fs.StatWatcher`](/api/fs#fsstatwatcher) object will not require the Node.js
+When called, the active [`fs.StatWatcher`](/api/v19/fs#fsstatwatcher) object will not require the Node.js
event loop to remain active. If there is no other activity keeping the
-event loop running, the process may exit before the [`fs.StatWatcher`](/api/fs#fsstatwatcher) object's
+event loop running, the process may exit before the [`fs.StatWatcher`](/api/v19/fs#fsstatwatcher) object's
callback is invoked. Calling `watcher.unref()` multiple times will have
no effect.
#### `fs.ReadStream`
-
+
-* Extends: [`stream.Readable`](/api/stream#streamreadable)
+* Extends: [`stream.Readable`](/api/v19/stream#streamreadable)
-Instances of [`fs.ReadStream`](/api/fs#fsreadstream) are created and returned using the
+Instances of [`fs.ReadStream`](/api/v19/fs#fsreadstream) are created and returned using the
[`fs.createReadStream()`][] function.
##### `'close'`
-
+
-Emitted when the [`fs.ReadStream`](/api/fs#fsreadstream)'s underlying file descriptor has been closed.
+Emitted when the [`fs.ReadStream`](/api/v19/fs#fsreadstream)'s underlying file descriptor has been closed.
##### `'open'`
-
+
-* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Integer file descriptor used by the [`fs.ReadStream`](/api/fs#fsreadstream).
+* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Integer file descriptor used by the [`fs.ReadStream`](/api/v19/fs#fsreadstream).
-Emitted when the [`fs.ReadStream`](/api/fs#fsreadstream)'s file descriptor has been opened.
+Emitted when the [`fs.ReadStream`](/api/v19/fs#fsreadstream)'s file descriptor has been opened.
##### `'ready'`
-
+
-Emitted when the [`fs.ReadStream`](/api/fs#fsreadstream) is ready to be used.
+Emitted when the [`fs.ReadStream`](/api/v19/fs#fsreadstream) is ready to be used.
Fires immediately after `'open'`.
##### `readStream.bytesRead`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -4745,19 +4847,19 @@ The number of bytes that have been read so far.
##### `readStream.path`
-
+
-* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer)
+* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer)
The path to the file the stream is reading from as specified in the first
argument to `fs.createReadStream()`. If `path` is passed as a string, then
-`readStream.path` will be a string. If `path` is passed as a [`Buffer`](/api/buffer#buffer), then
-`readStream.path` will be a [`Buffer`](/api/buffer#buffer). If `fd` is specified, then
+`readStream.path` will be a string. If `path` is passed as a [`Buffer`](/api/v19/buffer#buffer), then
+`readStream.path` will be a [`Buffer`](/api/v19/buffer#buffer). If `fd` is specified, then
`readStream.path` will be `undefined`.
##### `readStream.pending`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -4766,9 +4868,9 @@ i.e. before the `'ready'` event is emitted.
#### `fs.Stats`
-
+
-A [`fs.Stats`](/api/fs#fsstats) object provides information about a file.
+A [`fs.Stats`](/api/v19/fs#fsstats) object provides information about a file.
Objects returned from [`fs.stat()`][], [`fs.lstat()`][], [`fs.fstat()`][], and
their synchronous counterparts are of this type.
@@ -4828,64 +4930,64 @@ BigIntStats {
##### `stats.isBlockDevice()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a block device.
+Returns `true` if the [`fs.Stats`](/api/v19/fs#fsstats) object describes a block device.
##### `stats.isCharacterDevice()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a character device.
+Returns `true` if the [`fs.Stats`](/api/v19/fs#fsstats) object describes a character device.
##### `stats.isDirectory()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a file system directory.
+Returns `true` if the [`fs.Stats`](/api/v19/fs#fsstats) object describes a file system directory.
-If the [`fs.Stats`](/api/fs#fsstats) object was obtained from [`fs.lstat()`][], this method will
+If the [`fs.Stats`](/api/v19/fs#fsstats) object was obtained from [`fs.lstat()`][], this method will
always return `false`. This is because [`fs.lstat()`][] returns information
about a symbolic link itself and not the path it resolves to.
##### `stats.isFIFO()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a first-in-first-out (FIFO)
+Returns `true` if the [`fs.Stats`](/api/v19/fs#fsstats) object describes a first-in-first-out (FIFO)
pipe.
##### `stats.isFile()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a regular file.
+Returns `true` if the [`fs.Stats`](/api/v19/fs#fsstats) object describes a regular file.
##### `stats.isSocket()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a socket.
+Returns `true` if the [`fs.Stats`](/api/v19/fs#fsstats) object describes a socket.
##### `stats.isSymbolicLink()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if the [`fs.Stats`](/api/fs#fsstats) object describes a symbolic link.
+Returns `true` if the [`fs.Stats`](/api/v19/fs#fsstats) object describes a symbolic link.
This method is only valid when using [`fs.lstat()`][].
@@ -4954,7 +5056,7 @@ The number of blocks allocated for this file.
##### `stats.atimeMs`
-
+
* [`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)
@@ -4963,7 +5065,7 @@ milliseconds since the POSIX Epoch.
##### `stats.mtimeMs`
-
+
* [`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)
@@ -4972,7 +5074,7 @@ milliseconds since the POSIX Epoch.
##### `stats.ctimeMs`
-
+
* [`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)
@@ -4981,7 +5083,7 @@ in milliseconds since the POSIX Epoch.
##### `stats.birthtimeMs`
-
+
* [`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)
@@ -4990,7 +5092,7 @@ milliseconds since the POSIX Epoch.
##### `stats.atimeNs`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -5001,7 +5103,7 @@ nanoseconds since the POSIX Epoch.
##### `stats.mtimeNs`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -5012,7 +5114,7 @@ nanoseconds since the POSIX Epoch.
##### `stats.ctimeNs`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -5023,7 +5125,7 @@ in nanoseconds since the POSIX Epoch.
##### `stats.birthtimeNs`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -5034,7 +5136,7 @@ nanoseconds since the POSIX Epoch.
##### `stats.atime`
-
+
* [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -5042,7 +5144,7 @@ The timestamp indicating the last time this file was accessed.
##### `stats.mtime`
-
+
* [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -5050,7 +5152,7 @@ The timestamp indicating the last time this file was modified.
##### `stats.ctime`
-
+
* [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -5058,7 +5160,7 @@ The timestamp indicating the last time the file status was changed.
##### `stats.birthtime`
-
+
* [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
@@ -5094,7 +5196,7 @@ The times in the stat object have the following semantics:
link(2), mknod(2), rename(2), unlink(2), utimes(2),
read(2), and write(2) system calls.
* `birthtime` "Birth Time": Time of file creation. Set once when the
- file is created. On filesystems where birthtime is not available,
+ file is created. On file systems where birthtime is not available,
this field may instead hold either the `ctime` or
`1970-01-01T00:00Z` (ie, Unix epoch timestamp `0`). This value may be greater
than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants,
@@ -5104,47 +5206,139 @@ 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`
-
+
-* Extends [`stream.Writable`](/api/stream#streamwritable)
+* Extends [`stream.Writable`](/api/v19/stream#streamwritable)
-Instances of [`fs.WriteStream`](/api/fs#fswritestream) are created and returned using the
+Instances of [`fs.WriteStream`](/api/v19/fs#fswritestream) are created and returned using the
[`fs.createWriteStream()`][] function.
##### `'close'`
-
+
-Emitted when the [`fs.WriteStream`](/api/fs#fswritestream)'s underlying file descriptor has been closed.
+Emitted when the [`fs.WriteStream`](/api/v19/fs#fswritestream)'s underlying file descriptor has been closed.
##### `'open'`
-
+
-* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Integer file descriptor used by the [`fs.WriteStream`](/api/fs#fswritestream).
+* `fd` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Integer file descriptor used by the [`fs.WriteStream`](/api/v19/fs#fswritestream).
-Emitted when the [`fs.WriteStream`](/api/fs#fswritestream)'s file is opened.
+Emitted when the [`fs.WriteStream`](/api/v19/fs#fswritestream)'s file is opened.
##### `'ready'`
-
+
-Emitted when the [`fs.WriteStream`](/api/fs#fswritestream) is ready to be used.
+Emitted when the [`fs.WriteStream`](/api/v19/fs#fswritestream) is ready to be used.
Fires immediately after `'open'`.
##### `writeStream.bytesWritten`
-
+
The number of bytes written so far. Does not include data that is still queued
for writing.
##### `writeStream.close([callback])`
-
+
* `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)
@@ -5155,16 +5349,16 @@ is closed.
##### `writeStream.path`
-
+
The path to the file the stream is writing to as specified in the first
argument to [`fs.createWriteStream()`][]. If `path` is passed as a string, then
-`writeStream.path` will be a string. If `path` is passed as a [`Buffer`](/api/buffer#buffer), then
-`writeStream.path` will be a [`Buffer`](/api/buffer#buffer).
+`writeStream.path` will be a string. If `path` is passed as a [`Buffer`](/api/v19/buffer#buffer), then
+`writeStream.path` will be a [`Buffer`](/api/v19/buffer#buffer).
##### `writeStream.pending`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -5198,7 +5392,7 @@ import { open, constants } from 'node:fs';
const {
O_RDWR,
O_CREAT,
- O_EXCL
+ O_EXCL,
} = constants;
open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {
@@ -5370,7 +5564,7 @@ On Windows, only `O_APPEND`, `O_CREAT`, `O_EXCL`, `O_RDONLY`, `O_RDWR`,
###### File type constants
-The following constants are meant for use with the [`fs.Stats`](/api/fs#fsstats) object's
+The following constants are meant for use with the [`fs.Stats`](/api/v19/fs#fsstats) object's
`mode` property for determining a file's type.
@@ -5417,7 +5611,7 @@ are available.
###### File mode constants
-The following constants are meant for use with the [`fs.Stats`](/api/fs#fsstats) object's
+The following constants are meant for use with the [`fs.Stats`](/api/v19/fs#fsstats) object's
`mode` property for determining the access permissions for a file.
@@ -5489,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');
@@ -5502,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);
@@ -5534,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) => {
@@ -5544,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) => {
@@ -5561,7 +5753,7 @@ rename('/tmp/hello', '/tmp/world', (err) => {
#### File paths
Most `fs` operations accept file paths that may be specified in the form of
-a string, a [`Buffer`](/api/buffer#buffer), or a [`URL`](/api/url#the-whatwg-url-api) object using the `file:` protocol.
+a string, a [`Buffer`](/api/v19/buffer#buffer), or a [`URL`](/api/v19/url#the-whatwg-url-api) object using the `file:` protocol.
##### String paths
@@ -5579,7 +5771,7 @@ try {
fd = await open('/open/some/file.txt', 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
@@ -5593,16 +5785,16 @@ try {
fd = await open('file.txt', 'r');
// Do something with the file
} finally {
- await fd.close();
+ await fd?.close();
}
```
##### File URL paths
-
+
For most `node:fs` module functions, the `path` or `filename` argument may be
-passed as a [`URL`](/api/url#the-whatwg-url-api) object using the `file:` protocol.
+passed as a [`URL`](/api/v19/url#the-whatwg-url-api) object using the `file:` protocol.
```mjs
import { readFileSync } from 'node:fs';
@@ -5614,8 +5806,8 @@ readFileSync(new URL('file:///tmp/hello'));
###### Platform-specific considerations
-On Windows, `file:` [`URL`](/api/url#the-whatwg-url-api)s with a host name convert to UNC paths, while `file:`
-[`URL`](/api/url#the-whatwg-url-api)s with drive letters convert to local absolute paths. `file:` [`URL`](/api/url#the-whatwg-url-api)s
+On Windows, `file:` [`URL`](/api/v19/url#the-whatwg-url-api)s with a host name convert to UNC paths, while `file:`
+[`URL`](/api/v19/url#the-whatwg-url-api)s with drive letters convert to local absolute paths. `file:` [`URL`](/api/v19/url#the-whatwg-url-api)s
with no host name and no drive letter will result in an error:
```mjs
@@ -5636,10 +5828,10 @@ readFileSync(new URL('file:///c/p/a/t/h/file'));
// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
```
-`file:` [`URL`](/api/url#the-whatwg-url-api)s with drive letters must use `:` as a separator just after
+`file:` [`URL`](/api/v19/url#the-whatwg-url-api)s with drive letters must use `:` as a separator just after
the drive letter. Using another separator will result in an error.
-On all other platforms, `file:` [`URL`](/api/url#the-whatwg-url-api)s with a host name are unsupported and
+On all other platforms, `file:` [`URL`](/api/v19/url#the-whatwg-url-api)s with a host name are unsupported and
will result in an error:
```mjs
@@ -5656,7 +5848,7 @@ readFileSync(new URL('file://hostname/p/a/t/h/file'));
readFileSync(new URL('file:///tmp/hello'));
```
-A `file:` [`URL`](/api/url#the-whatwg-url-api) having encoded slash characters will result in an error on all
+A `file:` [`URL`](/api/v19/url#the-whatwg-url-api) having encoded slash characters will result in an error on all
platforms:
```mjs
@@ -5675,7 +5867,7 @@ readFileSync(new URL('file:///p/a/t/h/%2f'));
/ characters */
```
-On Windows, `file:` [`URL`](/api/url#the-whatwg-url-api)s having encoded backslash will result in an error:
+On Windows, `file:` [`URL`](/api/v19/url#the-whatwg-url-api)s having encoded backslash will result in an error:
```mjs
import { readFileSync } from 'node:fs';
@@ -5689,10 +5881,10 @@ readFileSync(new URL('file:///C:/path/%5c'));
##### Buffer paths
-Paths specified using a [`Buffer`](/api/buffer#buffer) are useful primarily on certain POSIX
+Paths specified using a [`Buffer`](/api/v19/buffer#buffer) are useful primarily on certain POSIX
operating systems that treat file paths as opaque byte sequences. On such
systems, it is possible for a single file path to contain sub-sequences that
-use multiple character encodings. As with string paths, [`Buffer`](/api/buffer#buffer) paths may
+use multiple character encodings. As with string paths, [`Buffer`](/api/v19/buffer#buffer) paths may
be relative or absolute:
Example using an absolute path on POSIX:
@@ -5706,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();
}
```
@@ -5767,7 +5959,7 @@ open('/open/some/file.txt', 'r', (err, fd) => {
});
```
-The promise-based APIs use a [`FileHandle`](/api/fs#filehandle) object in place of the numeric
+The promise-based APIs use a [`FileHandle`](/api/v19/fs#filehandle) object in place of the numeric
file descriptor. These objects are better managed by the system to ensure
that resources are not leaked. However, it is still required that they are
closed when operations are completed:
@@ -5929,6 +6121,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/v19/globals.en.md b/content/api/v19/globals.en.md
index 2ea316ff3d..d3a301614c 100644
--- a/content/api/v19/globals.en.md
+++ b/content/api/v19/globals.en.md
@@ -5,9 +5,9 @@ category: 'api'
version: 'v19'
---
-
+
-
+
These objects are available in all modules. The following variables may appear
to be global but are not. They exist only in the scope of modules, see the
@@ -25,9 +25,9 @@ accessible.
### `AbortController`
-
+
-
+
A utility class used to signal cancelation in selected `Promise`-based APIs.
The API is based on the Web API [`AbortController`][].
@@ -45,7 +45,7 @@ console.log(ac.signal.aborted); // Prints True
#### `abortController.abort([reason])`
-
+
* `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) An optional reason, retrievable on the `AbortSignal`'s
`reason` property.
@@ -55,31 +55,31 @@ the `'abort'` event.
#### `abortController.signal`
-
+
-* Type: [`AbortSignal`](/api/globals#abortsignal)
+* Type: [`AbortSignal`](/api/v19/globals#abortsignal)
#### `AbortSignal`
-
+
-* Extends: [`EventTarget`](/api/events#eventtarget)
+* Extends: [`EventTarget`](/api/v19/events#eventtarget)
The `AbortSignal` is used to notify observers when the
`abortController.abort()` method is called.
##### Static method: `AbortSignal.abort([reason])`
-
+
* `reason`: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
-* Returns: [`AbortSignal`](/api/globals#abortsignal)
+* Returns: [`AbortSignal`](/api/v19/globals#abortsignal)
Returns a new already aborted `AbortSignal`.
##### Static method: `AbortSignal.timeout(delay)`
-
+
* `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before triggering
the AbortSignal.
@@ -88,7 +88,7 @@ Returns a new `AbortSignal` which will be aborted in `delay` milliseconds.
##### `'abort'`
-
+
The `'abort'` event is emitted when the `abortController.abort()` method
is called. The callback is invoked with a single object argument with a
@@ -121,13 +121,13 @@ result in memory leaks.
##### `abortSignal.aborted`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) True after the `AbortController` has been aborted.
##### `abortSignal.onabort`
-
+
* Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -136,7 +136,7 @@ when the `abortController.abort()` function has been called.
##### `abortSignal.reason`
-
+
* Type: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -150,23 +150,23 @@ console.log(ac.signal.reason); // Error('boom!');
##### `abortSignal.throwIfAborted()`
-
+
If `abortSignal.aborted` is `true`, throws `abortSignal.reason`.
### `Blob`
-
+
-
+
-See [`Blob`](/api/buffer#blob).
+See [`Blob`](/api/v19/buffer#blob).
### `Buffer`
-
+
-
+
* [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -174,9 +174,13 @@ Used to handle binary data. See the [buffer section][].
### `ByteLengthQueuingStrategy`
-
+
-
+
+
+Experimental.
+
+
A browser-compatible implementation of [`ByteLengthQueuingStrategy`][].
@@ -190,63 +194,75 @@ This variable may appear to be global but is not. See [`__filename`][].
### `atob(data)`
-
+
+
+
+
+Legacy. Use `Buffer.from(data, 'base64')` instead.
-
+
Global alias for [`buffer.atob()`][].
### `BroadcastChannel`
-
+
-See [`BroadcastChannel`](/api/worker_threads#broadcastchannel-extends-eventtarget).
+See [`BroadcastChannel`](/api/v19/worker_threads#broadcastchannel-extends-eventtarget).
### `btoa(data)`
-
+
-
+
+
+Legacy. Use `buf.toString('base64')` instead.
+
+
Global alias for [`buffer.btoa()`][].
### `clearImmediate(immediateObject)`
-
+
-
+
[`clearImmediate`][] is described in the [timers][] section.
### `clearInterval(intervalObject)`
-
+
-
+
[`clearInterval`][] is described in the [timers][] section.
### `clearTimeout(timeoutObject)`
-
+
-
+
[`clearTimeout`][] is described in the [timers][] section.
### `CompressionStream`
-
+
+
+
+
+Experimental.
-
+
A browser-compatible implementation of [`CompressionStream`][].
### `console`
-
+
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -254,72 +270,96 @@ Used to print to stdout and stderr. See the [`console`][] section.
### `CountQueuingStrategy`
-
+
-
+
+
+Experimental.
+
+
A browser-compatible implementation of [`CountQueuingStrategy`][].
### `Crypto`
-
+
+
+
+
+Experimental. Disable this API with the [`--no-experimental-global-webcrypto`][] CLI flag.
-
+
-A browser-compatible implementation of [`Crypto`](/api/webcrypto#crypto). This global is available
+A browser-compatible implementation of [`Crypto`](/api/v19/webcrypto#crypto). This global is available
only if the Node.js binary was compiled with including support for the
`node:crypto` module.
### `crypto`
-
+
-
+
+
+Experimental. Disable this API with the [`--no-experimental-global-webcrypto`][] CLI flag.
+
+
A browser-compatible implementation of the [Web Crypto API][].
### `CryptoKey`
-
+
+
+
-
+Experimental. Disable this API with the [`--no-experimental-global-webcrypto`][] CLI flag.
-A browser-compatible implementation of [`CryptoKey`](/api/webcrypto#cryptokey). This global is available
+
+
+A browser-compatible implementation of [`CryptoKey`](/api/v19/webcrypto#cryptokey). This global is available
only if the Node.js binary was compiled with including support for the
`node:crypto` module.
### `CustomEvent`
-
+
+
+
-
+Experimental. Disable this API with the [`--no-experimental-global-customevent`][] CLI flag.
-
+
+
+
A browser-compatible implementation of the [`CustomEvent` Web API][].
### `DecompressionStream`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`DecompressionStream`][].
### `Event`
-
+
-
+
A browser-compatible implementation of the `Event` class. See
[`EventTarget` and `Event` API][] for more details.
### `EventTarget`
-
+
-
+
A browser-compatible implementation of the `EventTarget` class. See
[`EventTarget` and `Event` API][] for more details.
@@ -330,25 +370,33 @@ This variable may appear to be global but is not. See [`exports`][].
### `fetch`
-
+
+
+
+
+Experimental. Disable this API with the [`--no-experimental-fetch`][] CLI flag.
-
+
A browser-compatible implementation of the [`fetch()`][] function.
### Class `FormData`
-
+
-
+
+
+Experimental. Disable this API with the [`--no-experimental-fetch`][] CLI flag.
+
+
A browser-compatible implementation of [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
### `global`
-
+
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The global namespace object.
@@ -359,33 +407,37 @@ Node.js this is different. The top-level scope is not the global scope;
### Class `Headers`
-
+
+
+
+
+Experimental. Disable this API with the [`--no-experimental-fetch`][] CLI flag.
-
+
A browser-compatible implementation of [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers).
### `MessageChannel`
-
+
-
+
The `MessageChannel` class. See [`MessageChannel`][] for more details.
### `MessageEvent`
-
+
-
+
The `MessageEvent` class. See [`MessageEvent`][] for more details.
### `MessagePort`
-
+
-
+
The `MessagePort` class. See [`MessagePort`][] for more details.
@@ -395,65 +447,65 @@ This variable may appear to be global but is not. See [`module`][].
### `PerformanceEntry`
-
+
-
+
The `PerformanceEntry` class. See [`PerformanceEntry`][] for more details.
### `PerformanceMark`
-
+
-
+
The `PerformanceMark` class. See [`PerformanceMark`][] for more details.
### `PerformanceMeasure`
-
+
-
+
The `PerformanceMeasure` class. See [`PerformanceMeasure`][] for more details.
### `PerformanceObserver`
-
+
-
+
The `PerformanceObserver` class. See [`PerformanceObserver`][] for more details.
### `PerformanceObserverEntryList`
-
+
-
+
The `PerformanceObserverEntryList` class. See
[`PerformanceObserverEntryList`][] for more details.
### `PerformanceResourceTiming`
-
+
-
+
The `PerformanceResourceTiming` class. See [`PerformanceResourceTiming`][] for
more details.
### `performance`
-
+
The [`perf_hooks.performance`][] object.
### `process`
-
+
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -461,9 +513,9 @@ The process object. See the [`process` object][] section.
### `queueMicrotask(callback)`
-
+
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Function to be queued.
@@ -499,49 +551,73 @@ DataHandler.prototype.load = async function load(key) {
### `ReadableByteStreamController`
-
+
-
+
+
+Experimental.
+
+
A browser-compatible implementation of [`ReadableByteStreamController`][].
### `ReadableStream`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`ReadableStream`][].
### `ReadableStreamBYOBReader`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`ReadableStreamBYOBReader`][].
### `ReadableStreamBYOBRequest`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`ReadableStreamBYOBRequest`][].
### `ReadableStreamDefaultController`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`ReadableStreamDefaultController`][].
### `ReadableStreamDefaultReader`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`ReadableStreamDefaultReader`][].
@@ -551,139 +627,167 @@ This variable may appear to be global but is not. See [`require()`][].
### `Response`
-
+
+
+
-
+Experimental. Disable this API with the [`--no-experimental-fetch`][] CLI flag.
+
+
A browser-compatible implementation of [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response).
### `Request`
-
+
+
+
-
+Experimental. Disable this API with the [`--no-experimental-fetch`][] CLI flag.
+
+
A browser-compatible implementation of [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request).
### `setImmediate(callback[, ...args])`
-
+
-
+
[`setImmediate`][] is described in the [timers][] section.
### `setInterval(callback, delay[, ...args])`
-
+
-
+
[`setInterval`][] is described in the [timers][] section.
### `setTimeout(callback, delay[, ...args])`
-
+
-
+
[`setTimeout`][] is described in the [timers][] section.
### `structuredClone(value[, options])`
-
+
-
+
The WHATWG [`structuredClone`][] method.
### `SubtleCrypto`
-
+
+
+
+
+Experimental. Disable this API with the [`--no-experimental-global-webcrypto`][] CLI flag.
-
+
-A browser-compatible implementation of [`SubtleCrypto`](/api/webcrypto#subtlecrypto). This global is available
+A browser-compatible implementation of [`SubtleCrypto`](/api/v19/webcrypto#subtlecrypto). This global is available
only if the Node.js binary was compiled with including support for the
`node:crypto` module.
### `DOMException`
-
+
-
+
The WHATWG `DOMException` class. See [`DOMException`][] for more details.
### `TextDecoder`
-
+
-
+
The WHATWG `TextDecoder` class. See the [`TextDecoder`][] section.
### `TextDecoderStream`
-
+
-
+
+
+Experimental.
+
+
A browser-compatible implementation of [`TextDecoderStream`][].
### `TextEncoder`
-
+
-
+
The WHATWG `TextEncoder` class. See the [`TextEncoder`][] section.
### `TextEncoderStream`
-
+
+
+
+
+Experimental.
-
+
A browser-compatible implementation of [`TextEncoderStream`][].
### `TransformStream`
-
+
-
+
+
+Experimental.
+
+
A browser-compatible implementation of [`TransformStream`][].
### `TransformStreamDefaultController`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`TransformStreamDefaultController`][].
### `URL`
-
+
-
+
The WHATWG `URL` class. See the [`URL`][] section.
### `URLSearchParams`
-
+
-
+
The WHATWG `URLSearchParams` class. See the [`URLSearchParams`][] section.
### `WebAssembly`
-
+
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -693,25 +797,37 @@ The object that acts as the namespace for all W3C
### `WritableStream`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`WritableStream`][].
### `WritableStreamDefaultController`
-
+
+
+
-
+Experimental.
+
+
A browser-compatible implementation of [`WritableStreamDefaultController`][].
### `WritableStreamDefaultWriter`
-
+
+
+
+
+Experimental.
-
+
A browser-compatible implementation of [`WritableStreamDefaultWriter`][].
diff --git a/content/api/v19/http.en.md b/content/api/v19/http.en.md
index 31ff0040d5..18ffcbc61f 100644
--- a/content/api/v19/http.en.md
+++ b/content/api/v19/http.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
To use the HTTP server and client one must `require('node:http')`.
@@ -54,7 +58,7 @@ list like the following:
### `http.Agent`
-
+
An `Agent` is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
@@ -105,7 +109,7 @@ http.get({
hostname: 'localhost',
port: 80,
path: '/',
- agent: false // Create a new agent just for this one request
+ agent: false, // Create a new agent just for this one request
}, (res) => {
// Do stuff with response
});
@@ -113,7 +117,7 @@ http.get({
#### `new Agent([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Set of configurable options to set on the agent.
Can have the following fields:
@@ -176,12 +180,12 @@ http.request(options, onResponseCallback);
#### `agent.createConnection(options[, callback])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Options containing connection details. Check
[`net.createConnection()`][] for the format of the options
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback function that receives the created socket
-* Returns: [`stream.Duplex`](/api/stream#streamduplex)
+* Returns: [`stream.Duplex`](/api/v19/stream#streamduplex)
Produces a socket/stream to be used for HTTP requests.
@@ -191,17 +195,17 @@ custom agents may override this method in case greater flexibility is desired.
A socket/stream can be supplied in one of two ways: by returning the
socket/stream from this function, or by passing the socket/stream to `callback`.
-This method is guaranteed to return an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This method is guaranteed to return an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specifies a socket
+type other than [`net.Socket`](/api/v19/net#netsocket).
`callback` has a signature of `(err, stream)`.
#### `agent.keepSocketAlive(socket)`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
Called when `socket` is detached from a request and could be persisted by the
`Agent`. Default behavior is to:
@@ -216,15 +220,15 @@ This method can be overridden by a particular `Agent` subclass. If this
method returns a falsy value, the socket will be destroyed instead of persisting
it for use with the next request.
-The `socket` argument can be an instance of [`net.Socket`](/api/net#netsocket), a subclass of
-[`stream.Duplex`](/api/stream#streamduplex).
+The `socket` argument can be an instance of [`net.Socket`](/api/v19/net#netsocket), a subclass of
+[`stream.Duplex`](/api/v19/stream#streamduplex).
#### `agent.reuseSocket(socket, request)`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
-* `request` [`http.ClientRequest`](/api/http#httpclientrequest)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
+* `request` [`http.ClientRequest`](/api/v19/http#httpclientrequest)
Called when `socket` is attached to `request` after being persisted because of
the keep-alive options. Default behavior is to:
@@ -235,12 +239,12 @@ socket.ref();
This method can be overridden by a particular `Agent` subclass.
-The `socket` argument can be an instance of [`net.Socket`](/api/net#netsocket), a subclass of
-[`stream.Duplex`](/api/stream#streamduplex).
+The `socket` argument can be an instance of [`net.Socket`](/api/v19/net#netsocket), a subclass of
+[`stream.Duplex`](/api/v19/stream#streamduplex).
#### `agent.destroy()`
-
+
Destroy any sockets that are currently in use by the agent.
@@ -252,7 +256,7 @@ terminates them.
#### `agent.freeSockets`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -264,7 +268,7 @@ removed from the array on `'timeout'`.
#### `agent.getName([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A set of options providing information for name generation
* `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A domain name or IP address of the server to issue the
@@ -283,7 +287,7 @@ that determine socket reusability.
#### `agent.maxFreeSockets`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -293,7 +297,7 @@ state.
#### `agent.maxSockets`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -302,7 +306,7 @@ can have open per origin. Origin is the returned value of [`agent.getName()`][].
#### `agent.maxTotalSockets`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -311,7 +315,7 @@ can have open. Unlike `maxSockets`, this parameter applies across all origins.
#### `agent.requests`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -320,7 +324,7 @@ sockets. Do not modify.
#### `agent.sockets`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -329,9 +333,9 @@ agent. Do not modify.
### `http.ClientRequest`
-
+
-* Extends: [`http.OutgoingMessage`](/api/http#httpoutgoingmessage)
+* Extends: [`http.OutgoingMessage`](/api/v19/http#httpoutgoingmessage)
This object is created internally and returned from [`http.request()`][]. It
represents an _in-progress_ request whose header has already been queued. The
@@ -359,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
@@ -368,35 +373,39 @@ identified by `code:` [`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`][].
#### `'abort'`
-
+
+
+
+
+Deprecated. Listen for the `'close'` event instead.
-
+
Emitted when the request has been aborted by the client. This event is only
emitted on the first call to `abort()`.
#### `'close'`
-
+
Indicates that the request is completed, or its underlying connection was
terminated prematurely (before the response completion).
#### `'connect'`
-
+
-* `response` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
-* `head` [`Buffer`](/api/buffer#buffer)
+* `response` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
+* `head` [`Buffer`](/api/v19/buffer#buffer)
Emitted each time a server responds to a request with a `CONNECT` method. If
this event is not being listened for, clients receiving a `CONNECT` method will
have their connections closed.
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This event is guaranteed to be passed an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specifies a socket
+type other than [`net.Socket`](/api/v19/net#netsocket).
A client and server pair demonstrating how to listen for the `'connect'` event:
@@ -431,7 +440,7 @@ proxy.listen(1337, '127.0.0.1', () => {
port: 1337,
host: '127.0.0.1',
method: 'CONNECT',
- path: 'www.google.com:80'
+ path: 'www.google.com:80',
};
const req = http.request(options);
@@ -457,7 +466,7 @@ proxy.listen(1337, '127.0.0.1', () => {
#### `'continue'`
-
+
Emitted when the server sends a '100 Continue' HTTP response, usually because
the request contained 'Expect: 100-continue'. This is an instruction that
@@ -465,7 +474,7 @@ the client should send the request body.
#### `'finish'`
-
+
Emitted when the request has been sent. More specifically, this event is emitted
when the last segment of the response headers and body have been handed off to
@@ -474,7 +483,7 @@ the server has received anything yet.
#### `'information'`
-
+
* `info` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `httpVersion` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -496,7 +505,7 @@ const http = require('node:http');
const options = {
host: '127.0.0.1',
port: 8080,
- path: '/length_request'
+ path: '/length_request',
};
// Make a request
@@ -515,26 +524,26 @@ upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the
#### `'response'`
-
+
-* `response` [`http.IncomingMessage`](/api/http#httpincomingmessage)
+* `response` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
Emitted when a response is received to this request. This event is emitted only
once.
#### `'socket'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This event is guaranteed to be passed an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specifies a socket
+type other than [`net.Socket`](/api/v19/net#netsocket).
#### `'timeout'`
-
+
Emitted when the underlying socket times out from inactivity. This only notifies
that the socket has been idle. The request must be destroyed manually.
@@ -543,20 +552,20 @@ See also: [`request.setTimeout()`][].
#### `'upgrade'`
-
+
-* `response` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
-* `head` [`Buffer`](/api/buffer#buffer)
+* `response` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
+* `head` [`Buffer`](/api/v19/buffer#buffer)
Emitted each time a server responds to a request with an upgrade. If this
event is not being listened for and the response status code is 101 Switching
Protocols, clients receiving an upgrade header will have their connections
closed.
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This event is guaranteed to be passed an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specifies a socket
+type other than [`net.Socket`](/api/v19/net#netsocket).
A client server pair demonstrating how to listen for the `'upgrade'` event.
@@ -586,8 +595,8 @@ server.listen(1337, '127.0.0.1', () => {
host: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
- 'Upgrade': 'websocket'
- }
+ 'Upgrade': 'websocket',
+ },
};
const req = http.request(options);
@@ -603,18 +612,26 @@ server.listen(1337, '127.0.0.1', () => {
#### `request.abort()`
-
+
+
+
+
+Deprecated: Use [`request.destroy()`][] instead.
-
+
Marks the request as aborting. Calling this will cause remaining data
in the response to be dropped and the socket to be destroyed.
#### `request.aborted`
-
+
-
+
+
+Deprecated. Check [`request.destroyed`][] instead.
+
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -623,25 +640,29 @@ been aborted.
#### `request.connection`
-
+
+
+
-
+Deprecated. Use [`request.socket`][].
-* [`stream.Duplex`](/api/stream#streamduplex)
+
+
+* [`stream.Duplex`](/api/v19/stream#streamduplex)
See [`request.socket`][].
#### `request.cork()`
-
+
See [`writable.cork()`][].
#### `request.end([data[, encoding]][, callback])`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -658,7 +679,7 @@ is finished.
#### `request.destroy([error])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Optional, an error to emit with `'error'` event.
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -671,7 +692,7 @@ See [`writable.destroy()`][] for further details.
##### `request.destroyed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -681,9 +702,13 @@ See [`writable.destroyed`][] for further details.
#### `request.finished`
-
+
+
+
+
+Deprecated. Use [`request.writableEnded`][].
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -693,7 +718,7 @@ request was initiated via [`http.get()`][].
#### `request.flushHeaders()`
-
+
Flushes the request headers.
@@ -707,7 +732,7 @@ the optimization and kickstarts the request.
#### `request.getHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -730,7 +755,7 @@ const cookie = request.getHeader('Cookie');
#### `request.getHeaderNames()`
-
+
* Returns: string\[]
@@ -747,7 +772,7 @@ const headerNames = request.getHeaderNames();
#### `request.getHeaders()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -772,7 +797,7 @@ const headers = request.getHeaders();
#### `request.getRawHeaderNames()`
-
+
* Returns: string\[]
@@ -789,7 +814,7 @@ const headerNames = request.getRawHeaderNames();
#### `request.hasHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -809,31 +834,31 @@ Limits maximum response headers count. If set to 0, no limit will be applied.
#### `request.path`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request path.
#### `request.method`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request method.
#### `request.host`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request host.
#### `request.protocol`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The request protocol.
#### `request.removeHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -845,7 +870,7 @@ request.removeHeader('Content-Type');
#### `request.reusedSocket`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether the request is send through a reused socket.
@@ -899,7 +924,7 @@ retriableRequest();
#### `request.setHeader(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -934,7 +959,7 @@ request.setHeader('Content-Disposition', `attachment; filename*=utf-8''${encodeU
#### `request.setNoDelay([noDelay])`
-
+
* `noDelay` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -943,7 +968,7 @@ Once a socket is assigned to this request and is connected
#### `request.setSocketKeepAlive([enable][, initialDelay])`
-
+
* `enable` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `initialDelay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -953,21 +978,21 @@ Once a socket is assigned to this request and is connected
#### `request.setTimeout(timeout[, callback])`
-
+
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Milliseconds before a request times out.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional function to be called when a timeout occurs.
Same as binding to the `'timeout'` event.
-* Returns: [`http.ClientRequest`](/api/http#httpclientrequest)
+* Returns: [`http.ClientRequest`](/api/v19/http#httpclientrequest)
Once a socket is assigned to this request and is connected
[`socket.setTimeout()`][] will be called.
#### `request.socket`
-
+
-* [`stream.Duplex`](/api/stream#streamduplex)
+* [`stream.Duplex`](/api/v19/stream#streamduplex)
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit `'readable'` events
@@ -988,19 +1013,19 @@ req.once('response', (res) => {
});
```
-This property is guaranteed to be an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specified a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This property is guaranteed to be an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specified a socket
+type other than [`net.Socket`](/api/v19/net#netsocket).
#### `request.uncork()`
-
+
See [`writable.uncork()`][].
#### `request.writableEnded`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1010,7 +1035,7 @@ does not indicate whether the data has been flushed, for this use
#### `request.writableFinished`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1019,9 +1044,9 @@ before the [`'finish'`][] event is emitted.
#### `request.write(chunk[, encoding][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1047,16 +1072,16 @@ nothing and waits for more input.
### `http.Server`
-
+
-* Extends: [`net.Server`](/api/net#netserver)
+* Extends: [`net.Server`](/api/v19/net#netserver)
#### `'checkContinue'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `response` [`http.ServerResponse`](/api/http#httpserverresponse)
+* `request` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
+* `response` [`http.ServerResponse`](/api/v19/http#httpserverresponse)
Emitted each time a request with an HTTP `Expect: 100-continue` is received.
If this event is not listened for, the server will automatically respond
@@ -1072,10 +1097,10 @@ not be emitted.
#### `'checkExpectation'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `response` [`http.ServerResponse`](/api/http#httpserverresponse)
+* `request` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
+* `response` [`http.ServerResponse`](/api/v19/http#httpserverresponse)
Emitted each time a request with an HTTP `Expect` header is received, where the
value is not `100-continue`. If this event is not listened for, the server will
@@ -1086,19 +1111,20 @@ not be emitted.
#### `'clientError'`
-
+
* `exception` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
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/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This event is guaranteed to be passed an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specifies a socket
+type other than [`net.Socket`](/api/v19/net#netsocket).
Default behavior is to try close the socket with a HTTP '400 Bad Request',
or a HTTP '431 Request Header Fields Too Large' in the case of a
@@ -1148,26 +1174,26 @@ server.on('clientError', (err, socket) => {
#### `'close'`
-
+
Emitted when the server closes.
#### `'connect'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) Arguments for the HTTP request, as it is in
+* `request` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage) Arguments for the HTTP request, as it is in
the [`'request'`][] event
-* `socket` [`stream.Duplex`](/api/stream#streamduplex) Network socket between the server and client
-* `head` [`Buffer`](/api/buffer#buffer) The first packet of the tunneling stream (may be empty)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex) Network socket between the server and client
+* `head` [`Buffer`](/api/v19/buffer#buffer) The first packet of the tunneling stream (may be empty)
Emitted each time a client requests an HTTP `CONNECT` method. If this event is
not listened for, then clients requesting a `CONNECT` method will have their
connections closed.
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This event is guaranteed to be passed an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specifies a socket
+type other than [`net.Socket`](/api/v19/net#netsocket).
After this event is emitted, the request's socket will not have a `'data'`
event listener, meaning it will need to be bound in order to handle data
@@ -1175,9 +1201,9 @@ sent to the server on that socket.
#### `'connection'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
This event is emitted when a new TCP stream is established. `socket` is
typically an object of type [`net.Socket`][]. Usually users will not want to
@@ -1192,17 +1218,17 @@ If `socket.setTimeout()` is called here, the timeout will be replaced with
`server.keepAliveTimeout` when the socket has served a request (if
`server.keepAliveTimeout` is non-zero).
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This event is guaranteed to be passed an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specifies a socket
+type other than [`net.Socket`](/api/v19/net#netsocket).
#### `'dropRequest'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) Arguments for the HTTP request, as it is in
+* `request` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage) Arguments for the HTTP request, as it is in
the [`'request'`][] event
-* `socket` [`stream.Duplex`](/api/stream#streamduplex) Network socket between the server and client
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex) Network socket between the server and client
When the number of requests on a socket reaches the threshold of
`server.maxRequestsPerSocket`, the server will drop new requests
@@ -1210,22 +1236,22 @@ and emit `'dropRequest'` event instead, then send `503` to client.
#### `'request'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage)
-* `response` [`http.ServerResponse`](/api/http#httpserverresponse)
+* `request` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
+* `response` [`http.ServerResponse`](/api/v19/http#httpserverresponse)
Emitted each time there is a request. There may be multiple requests
per connection (in the case of HTTP Keep-Alive connections).
#### `'upgrade'`
-
+
-* `request` [`http.IncomingMessage`](/api/http#httpincomingmessage) Arguments for the HTTP request, as it is in
+* `request` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage) Arguments for the HTTP request, as it is in
the [`'request'`][] event
-* `socket` [`stream.Duplex`](/api/stream#streamduplex) Network socket between the server and client
-* `head` [`Buffer`](/api/buffer#buffer) The first packet of the upgraded stream (may be empty)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex) Network socket between the server and client
+* `head` [`Buffer`](/api/v19/buffer#buffer) The first packet of the upgraded stream (may be empty)
Emitted each time a client requests an HTTP upgrade. Listening to this event
is optional and clients cannot insist on a protocol change.
@@ -1234,9 +1260,9 @@ After this event is emitted, the request's socket will not have a `'data'`
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.
-This event is guaranteed to be passed an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specifies a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This event is guaranteed to be passed an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specifies a socket
+type other than [`net.Socket`](/api/v19/net#netsocket).
#### `server.close([callback])`
@@ -1259,22 +1285,22 @@ See [`net.Server.close()`][].
#### `server.closeAllConnections()`
-
+
Closes all connections connected to this server.
#### `server.closeIdleConnections()`
-
+
Closes all connections connected to this server which are not sending a request
or waiting for a response.
#### `server.headersTimeout`
-
+
-* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `60000`
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** The minimum between [`server.requestTimeout`][] or `60000`.
Limit the amount of time the parser will wait to receive the complete HTTP
headers.
@@ -1293,13 +1319,13 @@ This method is identical to [`server.listen()`][] from [`net.Server`][].
#### `server.listening`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates whether or not the server is listening for connections.
#### `server.maxHeadersCount`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `2000`
@@ -1307,7 +1333,7 @@ Limits maximum incoming headers count. If set to 0, no limit will be applied.
#### `server.requestTimeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `300000`
@@ -1323,11 +1349,11 @@ reverse proxy in front.
#### `server.setTimeout([msecs][, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** 0 (no timeout)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.Server`](/api/http#httpserver)
+* Returns: [`http.Server`](/api/v19/http#httpserver)
Sets the timeout value for sockets, and emits a `'timeout'` event on
the Server object, passing the socket as an argument, if a timeout
@@ -1342,7 +1368,7 @@ explicitly.
#### `server.maxRequestsPerSocket`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Requests per socket. **Default:** 0 (no limit)
@@ -1357,7 +1383,7 @@ after the limit is reached will get `503 Service Unavailable` as a response.
#### `server.timeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** 0 (no timeout)
@@ -1371,7 +1397,7 @@ value only affects new connections to the server, not any existing connections.
#### `server.keepAliveTimeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** `5000` (5 seconds).
@@ -1391,23 +1417,23 @@ affects new connections to the server, not any existing connections.
### `http.ServerResponse`
-
+
-* Extends: [`http.OutgoingMessage`](/api/http#httpoutgoingmessage)
+* Extends: [`http.OutgoingMessage`](/api/v19/http#httpoutgoingmessage)
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the [`'request'`][] event.
#### `'close'`
-
+
Indicates that the response is completed, or its underlying connection was
terminated prematurely (before the response completion).
#### `'finish'`
-
+
Emitted when the response has been sent. More specifically, this event is
emitted when the last segment of the response headers and body have been
@@ -1416,7 +1442,7 @@ does not imply that the client has received anything yet.
#### `response.addTrailers(headers)`
-
+
* `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1443,25 +1469,29 @@ will result in a [`TypeError`][] being thrown.
#### `response.connection`
-
+
-
+
-* [`stream.Duplex`](/api/stream#streamduplex)
+Deprecated. Use [`response.socket`][].
+
+
+
+* [`stream.Duplex`](/api/v19/stream#streamduplex)
See [`response.socket`][].
#### `response.cork()`
-
+
See [`writable.cork()`][].
#### `response.end([data[, encoding]][, callback])`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -1478,9 +1508,13 @@ is finished.
#### `response.finished`
-
+
+
+
+
+Deprecated. Use [`response.writableEnded`][].
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1489,13 +1523,13 @@ has been called.
#### `response.flushHeaders()`
-
+
Flushes the response headers. See also: [`request.flushHeaders()`][].
#### `response.getHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -1518,7 +1552,7 @@ const setCookie = response.getHeader('set-cookie');
#### `response.getHeaderNames()`
-
+
* Returns: string\[]
@@ -1535,7 +1569,7 @@ const headerNames = response.getHeaderNames();
#### `response.getHeaders()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1560,7 +1594,7 @@ const headers = response.getHeaders();
#### `response.hasHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1574,7 +1608,7 @@ const hasContentType = response.hasHeader('content-type');
#### `response.headersSent`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1582,7 +1616,7 @@ Boolean (read-only). True if headers were sent, false otherwise.
#### `response.removeHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1594,15 +1628,15 @@ response.removeHeader('Content-Encoding');
#### `response.req`
-
+
-* [`http.IncomingMessage`](/api/http#httpincomingmessage)
+* [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
A reference to the original HTTP `request` object.
#### `response.sendDate`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1614,11 +1648,11 @@ in responses.
#### `response.setHeader(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
-* Returns: [`http.ServerResponse`](/api/http#httpserverresponse)
+* Returns: [`http.ServerResponse`](/api/v19/http#httpserverresponse)
Returns the response object.
@@ -1666,11 +1700,11 @@ is desired with potential future retrieval and modification, use
#### `response.setTimeout(msecs[, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.ServerResponse`](/api/http#httpserverresponse)
+* Returns: [`http.ServerResponse`](/api/v19/http#httpserverresponse)
Sets the Socket's timeout value to `msecs`. If a callback is
provided, then it is added as a listener on the `'timeout'` event on
@@ -1683,9 +1717,9 @@ timed out sockets must be handled explicitly.
#### `response.socket`
-
+
-* [`stream.Duplex`](/api/stream#streamduplex)
+* [`stream.Duplex`](/api/v19/stream#streamduplex)
Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit `'readable'` events
@@ -1701,13 +1735,13 @@ const server = http.createServer((req, res) => {
}).listen(3000);
```
-This property is guaranteed to be an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specified a socket
-type other than [`net.Socket`](/api/net#netsocket).
+This property is guaranteed to be an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specified a socket
+type other than [`net.Socket`](/api/v19/net#netsocket).
#### `response.statusCode`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `200`
@@ -1724,7 +1758,7 @@ status code which was sent out.
#### `response.statusMessage`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1740,15 +1774,26 @@ 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()`
-
+
See [`writable.uncork()`][].
#### `response.writableEnded`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1758,7 +1803,7 @@ does not indicate whether the data has been flushed, for this use
#### `response.writableFinished`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1767,9 +1812,9 @@ before the [`'finish'`][] event is emitted.
#### `response.write(chunk[, encoding][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default:** `'utf8'`
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1803,7 +1848,7 @@ buffer. Returns `false` if all or part of the data was queued in user memory.
#### `response.writeContinue()`
-
+
Sends an HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the [`'checkContinue'`][] event on
@@ -1811,7 +1856,7 @@ the request body should be sent. See the [`'checkContinue'`][] event on
#### `response.writeEarlyHints(hints[, callback])`
-
+
* `hints` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1836,7 +1881,7 @@ const earlyHintsLinks = [
];
response.writeEarlyHints({
'link': earlyHintsLinks,
- 'x-trace-id': 'id for diagnostics'
+ 'x-trace-id': 'id for diagnostics',
});
const earlyHintsCallback = () => console.log('early hints message sent');
@@ -1847,12 +1892,12 @@ response.writeEarlyHints({
#### `response.writeHead(statusCode[, statusMessage][, headers])`
-
+
* `statusCode` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `statusMessage` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
-* Returns: [`http.ServerResponse`](/api/http#httpserverresponse)
+* Returns: [`http.ServerResponse`](/api/v19/http#httpserverresponse)
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like `404`. The last argument, `headers`, are the response headers.
@@ -1871,7 +1916,7 @@ const body = 'hello world';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
- 'Content-Type': 'text/plain'
+ 'Content-Type': 'text/plain',
})
.end(body);
```
@@ -1913,46 +1958,54 @@ will result in a \[`Error`]\[] being thrown.
#### `response.writeProcessing()`
-
+
Sends a HTTP/1.1 102 Processing message to the client, indicating that
the request body should be sent.
### `http.IncomingMessage`
-
+
-* Extends: [`stream.Readable`](/api/stream#streamreadable)
+* Extends: [`stream.Readable`](/api/v19/stream#streamreadable)
An `IncomingMessage` object is created by [`http.Server`][] or
[`http.ClientRequest`][] and passed as the first argument to the [`'request'`][]
and [`'response'`][] event respectively. It may be used to access response
status, headers, and data.
-Different from its `socket` value which is a subclass of [`stream.Duplex`](/api/stream#streamduplex), the
-`IncomingMessage` itself extends [`stream.Readable`](/api/stream#streamreadable) and is created separately to
+Different from its `socket` value which is a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), the
+`IncomingMessage` itself extends [`stream.Readable`](/api/v19/stream#streamreadable) and is created separately to
parse and emit the incoming HTTP headers and payload, as the underlying socket
may be reused multiple times in case of keep-alive.
#### `'aborted'`
-
+
+
+
+
+Deprecated. Listen for `'close'` event instead.
-
+
Emitted when the request has been aborted.
#### `'close'`
-
+
Emitted when the request has been completed.
#### `message.aborted`
-
+
-
+
+
+Deprecated. Check `message.destroyed` from {stream.Readable}.
+
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1961,7 +2014,7 @@ been aborted.
#### `message.complete`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1975,7 +2028,7 @@ server fully transmitted a message before a connection was terminated:
const req = http.request({
host: '127.0.0.1',
port: 8080,
- method: 'POST'
+ method: 'POST',
}, (res) => {
res.resume();
res.on('end', () => {
@@ -1988,15 +2041,19 @@ const req = http.request({
#### `message.connection`
-
+
-
+
+
+Deprecated. Use [`message.socket`][].
+
+
Alias for [`message.socket`][].
#### `message.destroy([error])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -2007,7 +2064,7 @@ as an argument to any listeners on the event.
#### `message.headers`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2031,13 +2088,17 @@ header name:
`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
`last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`,
`retry-after`, `server`, or `user-agent` are discarded.
+ To allow duplicate values of the headers listed above to be joined,
+ use the option `joinDuplicateHeaders` in [`http.request()`][]
+ and [`http.createServer()`][]. See RFC 9110 Section 5.3 for more
+ information.
* `set-cookie` is always an array. Duplicates are added to the array.
* For duplicate `cookie` headers, the values are joined together with `; `.
* For all other headers, the values are joined together with `, `.
#### `message.headersDistinct`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2055,7 +2116,7 @@ console.log(request.headersDistinct);
#### `message.httpVersion`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2068,7 +2129,7 @@ Also `message.httpVersionMajor` is the first integer and
#### `message.method`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2078,7 +2139,7 @@ The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
#### `message.rawHeaders`
-
+
* string\[]
@@ -2106,7 +2167,7 @@ console.log(request.rawHeaders);
#### `message.rawTrailers`
-
+
* string\[]
@@ -2115,32 +2176,32 @@ received. Only populated at the `'end'` event.
#### `message.setTimeout(msecs[, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.IncomingMessage`](/api/http#httpincomingmessage)
+* Returns: [`http.IncomingMessage`](/api/v19/http#httpincomingmessage)
Calls `message.socket.setTimeout(msecs, callback)`.
#### `message.socket`
-
+
-* [`stream.Duplex`](/api/stream#streamduplex)
+* [`stream.Duplex`](/api/v19/stream#streamduplex)
The [`net.Socket`][] object associated with the connection.
With HTTPS support, use [`request.socket.getPeerCertificate()`][] to obtain the
client's authentication details.
-This property is guaranteed to be an instance of the [`net.Socket`](/api/net#netsocket) class,
-a subclass of [`stream.Duplex`](/api/stream#streamduplex), unless the user specified a socket
-type other than [`net.Socket`](/api/net#netsocket) or internally nulled.
+This property is guaranteed to be an instance of the [`net.Socket`](/api/v19/net#netsocket) class,
+a subclass of [`stream.Duplex`](/api/v19/stream#streamduplex), unless the user specified a socket
+type other than [`net.Socket`](/api/v19/net#netsocket) or internally nulled.
#### `message.statusCode`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2150,7 +2211,7 @@ The 3-digit HTTP response status code. E.G. `404`.
#### `message.statusMessage`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2161,7 +2222,7 @@ Error`.
#### `message.trailers`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2169,7 +2230,7 @@ The request/response trailers object. Only populated at the `'end'` event.
#### `message.trailersDistinct`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2179,7 +2240,7 @@ Only populated at the `'end'` event.
#### `message.url`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2223,9 +2284,9 @@ URL {
### `http.OutgoingMessage`
-
+
-* Extends: [`Stream`](/api/stream#stream)
+* Extends: [`Stream`](/api/v19/stream#stream)
This class serves as the parent class of [`http.ClientRequest`][]
and [`http.ServerResponse`][]. It is an abstract outgoing message from
@@ -2233,19 +2294,19 @@ the perspective of the participants of an HTTP transaction.
#### `'drain'`
-
+
Emitted when the buffer of the message is free again.
#### `'finish'`
-
+
Emitted when the transmission is finished successfully.
#### `'prefinish'`
-
+
Emitted after `outgoingMessage.end()` is called.
When the event is emitted, all data has been processed but not necessarily
@@ -2253,7 +2314,7 @@ completely flushed.
#### `outgoingMessage.addTrailers(headers)`
-
+
* `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2278,7 +2339,7 @@ will result in a `TypeError` being thrown.
#### `outgoingMessage.appendHeader(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header name
* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header value
@@ -2298,21 +2359,25 @@ a single time with values joined using `; `.
#### `outgoingMessage.connection`
-
+
+
+
-
+Deprecated: Use [`outgoingMessage.socket`][] instead.
+
+
Alias of [`outgoingMessage.socket`][].
#### `outgoingMessage.cork()`
-
+
See [`writable.cork()`][].
#### `outgoingMessage.destroy([error])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Optional, an error to emit with `error` event
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -2322,9 +2387,9 @@ and is connected, that socket will be destroyed as well.
#### `outgoingMessage.end(chunk[, encoding][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Optional, **Default**: `utf8`
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -2342,7 +2407,7 @@ If `callback` is provided, it will be called when the message is finished
#### `outgoingMessage.flushHeaders()`
-
+
Flushes the message headers.
@@ -2357,7 +2422,7 @@ bypasses the optimization and kickstarts the message.
#### `outgoingMessage.getHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Name of header
* Returns [`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)
@@ -2367,7 +2432,7 @@ set, the returned value will be `undefined`.
#### `outgoingMessage.getHeaderNames()`
-
+
* Returns string\[]
@@ -2376,7 +2441,7 @@ All names are lowercase.
#### `outgoingMessage.getHeaders()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2401,7 +2466,7 @@ const headers = outgoingMessage.getHeaders();
#### `outgoingMessage.hasHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2415,7 +2480,7 @@ const hasContentType = outgoingMessage.hasHeader('content-type');
#### `outgoingMessage.headersSent`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2423,7 +2488,7 @@ Read-only. `true` if the headers were sent, otherwise `false`.
#### `outgoingMessage.pipe()`
-
+
Overrides the `stream.pipe()` method inherited from the legacy `Stream` class
which is the parent class of `http.OutgoingMessage`.
@@ -2433,7 +2498,7 @@ write-only stream.
#### `outgoingMessage.removeHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header name
@@ -2445,7 +2510,7 @@ outgoingMessage.removeHeader('Content-Encoding');
#### `outgoingMessage.setHeader(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Header name
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Header value
@@ -2455,9 +2520,49 @@ 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/v19/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])`
-
+
* `msesc` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional function to be called when a timeout
@@ -2469,9 +2574,9 @@ Once a socket is associated with the message and is connected,
#### `outgoingMessage.socket`
-
+
-* [`stream.Duplex`](/api/stream#streamduplex)
+* [`stream.Duplex`](/api/v19/stream#streamduplex)
Reference to the underlying socket. Usually, users will not want to access
this property.
@@ -2480,13 +2585,13 @@ After calling `outgoingMessage.end()`, this property will be nulled.
#### `outgoingMessage.uncork()`
-
+
See [`writable.uncork()`][]
#### `outgoingMessage.writableCorked`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2494,7 +2599,7 @@ The number of times `outgoingMessage.cork()` has been called.
#### `outgoingMessage.writableEnded`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2504,7 +2609,7 @@ not indicate whether the data has been flushed. For that purpose, use
#### `outgoingMessage.writableFinished`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2512,7 +2617,7 @@ Is `true` if all data has been flushed to the underlying system.
#### `outgoingMessage.writableHighWaterMark`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2521,7 +2626,7 @@ buffer level when [`writable.write()`][] starts returning false (`16384`).
#### `outgoingMessage.writableLength`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2529,7 +2634,7 @@ The number of buffered bytes.
#### `outgoingMessage.writableObjectMode`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2537,9 +2642,9 @@ Always `false`.
#### `outgoingMessage.write(chunk[, encoding][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) **Default**: `utf8`
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2558,7 +2663,7 @@ memory. The `'drain'` event will be emitted when the buffer is free again.
### `http.METHODS`
-
+
* string\[]
@@ -2566,7 +2671,7 @@ A list of the HTTP methods that are supported by the parser.
### `http.STATUS_CODES`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2576,35 +2681,35 @@ Found'`.
### `http.createServer([options][, requestListener])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `IncomingMessage` [`http.IncomingMessage`](/api/http#httpincomingmessage) Specifies the `IncomingMessage`
- class to be used. Useful for extending the original `IncomingMessage`.
- **Default:** `IncomingMessage`.
- * `ServerResponse` [`http.ServerResponse`](/api/http#httpserverresponse) Specifies the `ServerResponse` class
- to be used. Useful for extending the original `ServerResponse`. **Default:**
- `ServerResponse`.
- * `requestTimeout`: Sets the timeout value in milliseconds for receiving
- the entire request from the client.
- See [`server.requestTimeout`][] for more information.
- **Default:** `300000`.
+ * `connectionsCheckingInterval`: Sets the interval value in milliseconds to
+ check for request and headers timeout in incomplete requests.
+ **Default:** `30000`.
* `headersTimeout`: Sets the timeout value in milliseconds for receiving
the complete HTTP headers from the client.
See [`server.headersTimeout`][] for more information.
**Default:** `60000`.
+ * `insecureHTTPParser` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Use an insecure HTTP parser that accepts
+ invalid HTTP headers when `true`. Using the insecure parser should be
+ avoided. See [`--insecure-http-parser`][] for more information.
+ **Default:** `false`.
+ * `IncomingMessage` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage) Specifies the `IncomingMessage`
+ class to be used. Useful for extending the original `IncomingMessage`.
+ **Default:** `IncomingMessage`.
+ * `keepAlive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to `true`, it enables keep-alive functionality
+ on the socket immediately after a new incoming connection is received,
+ similarly on what is done in \[`socket.setKeepAlive([enable][, initialDelay])`]\[`socket.setKeepAlive(enable, initialDelay)`].
+ **Default:** `false`.
+ * `keepAliveInitialDelay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If set to a positive number, it sets the
+ initial delay before the first keepalive probe is sent on an idle socket.
+ **Default:** `0`.
* `keepAliveTimeout`: The number of milliseconds of inactivity a server
needs to wait for additional incoming data, after it has finished writing
the last response, before a socket will be destroyed.
See [`server.keepAliveTimeout`][] for more information.
**Default:** `5000`.
- * `connectionsCheckingInterval`: Sets the interval value in milliseconds to
- check for request and headers timeout in incomplete requests.
- **Default:** `30000`.
- * `insecureHTTPParser` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Use an insecure HTTP parser that accepts
- invalid HTTP headers when `true`. Using the insecure parser should be
- avoided. See [`--insecure-http-parser`][] for more information.
- **Default:** `false`
* `maxHeaderSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Optionally overrides the value of
[`--max-http-header-size`][] for requests received by this server, i.e.
the maximum length of request headers in bytes.
@@ -2612,41 +2717,43 @@ Found'`.
* `noDelay` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to `true`, it disables the use of Nagle's
algorithm immediately after a new incoming connection is received.
**Default:** `true`.
- * `keepAlive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to `true`, it enables keep-alive functionality
- on the socket immediately after a new incoming connection is received,
- similarly on what is done in \[`socket.setKeepAlive([enable][, initialDelay])`]\[`socket.setKeepAlive(enable, initialDelay)`].
+ * `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.
**Default:** `false`.
- * `keepAliveInitialDelay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If set to a positive number, it sets the
- initial delay before the first keepalive probe is sent on an idle socket.
- **Default:** `0`.
+ * `ServerResponse` [`http.ServerResponse`](/api/v19/http#httpserverresponse) Specifies the `ServerResponse` class
+ to be used. Useful for extending the original `ServerResponse`. **Default:**
+ `ServerResponse`.
* `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 `; `.
* `requestListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.Server`](/api/http#httpserver)
+* Returns: [`http.Server`](/api/v19/http#httpserver)
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
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
- data: 'Hello World!'
+ data: 'Hello World!',
}));
});
server.listen(8000);
-```
-
-```cjs
+--------------
const http = require('node:http');
// Create a local server to receive data from
@@ -2656,7 +2763,7 @@ const server = http.createServer();
server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
- data: 'Hello World!'
+ data: 'Hello World!',
}));
});
@@ -2667,14 +2774,14 @@ server.listen(8000);
### `http.get(url[, options][, callback])`
-
+
-* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api)
+* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Accepts the same `options` as
[`http.request()`][], with the `method` always set to `GET`.
Properties that are inherited from the prototype are ignored.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.ClientRequest`](/api/http#httpclientrequest)
+* Returns: [`http.ClientRequest`](/api/v19/http#httpclientrequest)
Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and
@@ -2728,7 +2835,7 @@ http.get('http://localhost:8000/', (res) => {
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
- data: 'Hello World!'
+ data: 'Hello World!',
}));
});
@@ -2737,16 +2844,16 @@ server.listen(8000);
### `http.globalAgent`
-
+
-* [`http.Agent`](/api/http#httpagent)
+* [`http.Agent`](/api/v19/http#httpagent)
Global instance of `Agent` which is used as the default for all HTTP client
requests.
### `http.maxHeaderSize`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2761,11 +2868,11 @@ This can be overridden for servers and client requests by passing the
### `http.request(url[, options][, callback])`
-
+
-* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api)
+* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `agent` [`http.Agent`](/api/http#httpagent) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Controls [`Agent`][] behavior. Possible
+ * `agent` [`http.Agent`](/api/v19/http#httpagent) | [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Controls [`Agent`][] behavior. Possible
values:
* `undefined` (default): use [`http.globalAgent`][] for this host and port.
* `Agent` object: explicitly use the passed in `Agent`.
@@ -2810,7 +2917,7 @@ This can be overridden for servers and client requests by passing the
* `protocol` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Protocol to use. **Default:** `'http:'`.
* `setHost` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type): Specifies whether or not to automatically add the
`Host` header. Defaults to `true`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal): An AbortSignal that may be used to abort an ongoing
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal): An AbortSignal that may be used to abort an ongoing
request.
* `socketPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Unix domain socket. Cannot be used if one of `host`
or `port` is specified, as those specify a TCP Socket.
@@ -2819,8 +2926,12 @@ This can be overridden for servers and client requests by passing the
* `uniqueHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) A list of request headers that should be sent
only once. If the header's value is an array, the items will be joined
using `; `.
+ * `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.
+ **Default:** `false`.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.ClientRequest`](/api/http#httpclientrequest)
+* Returns: [`http.ClientRequest`](/api/v19/http#httpclientrequest)
`options` in [`socket.connect()`][] are also supported.
@@ -2845,7 +2956,7 @@ upload a file with a POST request, then write to the `ClientRequest` object.
const http = require('node:http');
const postData = JSON.stringify({
- 'msg': 'Hello World!'
+ 'msg': 'Hello World!',
});
const options = {
@@ -2855,8 +2966,8 @@ const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
- 'Content-Length': Buffer.byteLength(postData)
- }
+ 'Content-Length': Buffer.byteLength(postData),
+ },
};
const req = http.request(options, (res) => {
@@ -3020,11 +3131,12 @@ Passing an `AbortSignal` and then calling `abort` on the corresponding
`AbortController` will behave the same way as calling `.destroy()` on the
request itself.
-### `http.validateHeaderName(name)`
+### `http.validateHeaderName(name[, label])`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `label` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Label for error message. **Default:** `'Header name'`.
Performs the low-level validations on the provided `name` that are done when
`res.setHeader(name, value)` is called.
@@ -3044,15 +3156,15 @@ const { validateHeaderName } = require('node:http');
try {
validateHeaderName('');
} catch (err) {
- err instanceof TypeError; // --> true
- err.code; // --> 'ERR_INVALID_HTTP_TOKEN'
- err.message; // --> 'Header name must be a valid HTTP token [""]'
+ console.error(err instanceof TypeError); // --> true
+ console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'
+ console.error(err.message); // --> 'Header name must be a valid HTTP token [""]'
}
```
### `http.validateHeaderValue(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -3076,27 +3188,27 @@ const { validateHeaderValue } = require('node:http');
try {
validateHeaderValue('x-my-header', undefined);
} catch (err) {
- err instanceof TypeError; // --> true
- err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'; // --> true
- err.message; // --> 'Invalid value "undefined" for header "x-my-header"'
+ console.error(err instanceof TypeError); // --> true
+ console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true
+ console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"'
}
try {
validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
- err instanceof TypeError; // --> true
- err.code === 'ERR_INVALID_CHAR'; // --> true
- err.message; // --> 'Invalid character in header content ["x-my-header"]'
+ console.error(err instanceof TypeError); // --> true
+ console.error(err.code === 'ERR_INVALID_CHAR'); // --> true
+ console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]'
}
```
-### `http.setMaxIdleHTTPParsers`
+### `http.setMaxIdleHTTPParsers(max)`
-
+
-* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+* `max` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `1000`.
-Set the maximum number of idle HTTP parsers. **Default:** `1000`.
+Set the maximum number of idle HTTP parsers.
[RFC 8187]: https://www.rfc-editor.org/rfc/rfc8187.txt
[`'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`]: /api/v19/errors#err_http_content_length_mismatch
@@ -3111,6 +3223,7 @@ Set the maximum number of idle HTTP parsers. **Default:** `1000`.
[`Buffer.byteLength()`]: /api/v19/buffer#static-method-bufferbytelengthstring-encoding
[`Duplex`]: /api/v19/stream#class-streamduplex
[`HPE_HEADER_OVERFLOW`]: /api/v19/errors#hpe_header_overflow
+[`Headers`]: /api/v19/globals#class-headers
[`TypeError`]: /api/v19/errors#class-typeerror
[`URL`]: /api/v19/url#the-whatwg-url-api
[`agent.createConnection()`]: #agentcreateconnectionoptions-callback
@@ -3124,6 +3237,7 @@ Set the maximum number of idle HTTP parsers. **Default:** `1000`.
[`http.IncomingMessage`]: #class-httpincomingmessage
[`http.ServerResponse`]: #class-httpserverresponse
[`http.Server`]: #class-httpserver
+[`http.createServer()`]: #httpcreateserveroptions-requestlistener
[`http.get()`]: #httpgetoptions-callback
[`http.globalAgent`]: #httpglobalagent
[`http.request()`]: #httprequestoptions-callback
@@ -3136,6 +3250,7 @@ Set the maximum number of idle HTTP parsers. **Default:** `1000`.
[`net.createConnection()`]: /api/v19/net#netcreateconnectionoptions-connectlistener
[`new URL()`]: /api/v19/url#new-urlinput-base
[`outgoingMessage.setHeader(name, value)`]: #outgoingmessagesetheadername-value
+[`outgoingMessage.setHeaders()`]: #outgoingmessagesetheadersheaders
[`outgoingMessage.socket`]: #outgoingmessagesocket
[`removeHeader(name)`]: #requestremoveheadername
[`request.destroy()`]: #requestdestroyerror
@@ -3154,6 +3269,7 @@ Set the maximum number of idle HTTP parsers. **Default:** `1000`.
[`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/v19/http2.en.md b/content/api/v19/http2.en.md
index d1a87d4741..dd9474a989 100644
--- a/content/api/v19/http2.en.md
+++ b/content/api/v19/http2.en.md
@@ -5,13 +5,17 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
-
+Stable
+
+
+
+
The `node:http2` module provides an implementation of the [HTTP/2][] protocol.
It can be accessed using:
@@ -33,7 +37,7 @@ let http2;
try {
http2 = require('node:http2');
} catch (err) {
- console.log('http2 support is disabled!');
+ console.error('http2 support is disabled!');
}
```
@@ -51,7 +55,7 @@ let http2;
try {
http2 = await import('node:http2');
} catch (err) {
- console.log('http2 support is disabled!');
+ console.error('http2 support is disabled!');
}
```
@@ -80,7 +84,7 @@ const fs = require('node:fs');
const server = http2.createSecureServer({
key: fs.readFileSync('localhost-privkey.pem'),
- cert: fs.readFileSync('localhost-cert.pem')
+ cert: fs.readFileSync('localhost-cert.pem'),
});
server.on('error', (err) => console.error(err));
@@ -88,7 +92,7 @@ server.on('stream', (stream, headers) => {
// stream is a Duplex
stream.respond({
'content-type': 'text/html; charset=utf-8',
- ':status': 200
+ ':status': 200,
});
stream.end('
Hello World
');
});
@@ -111,7 +115,7 @@ The following illustrates an HTTP/2 client:
const http2 = require('node:http2');
const fs = require('node:fs');
const client = http2.connect('https://localhost:8443', {
- ca: fs.readFileSync('localhost-cert.pem')
+ ca: fs.readFileSync('localhost-cert.pem'),
});
client.on('error', (err) => console.error(err));
@@ -135,9 +139,9 @@ req.end();
#### `Http2Session`
-
+
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v19/events#eventemitter)
Instances of the `http2.Http2Session` class represent an active communications
session between an HTTP/2 client and server. Instances of this class are _not_
@@ -173,17 +177,17 @@ solely on the API of the `Http2Session`.
##### `'close'`
-
+
The `'close'` event is emitted once the `Http2Session` has been destroyed. Its
listener does not expect any arguments.
##### `'connect'`
-
+
-* `session` [`Http2Session`](/api/http2#http2session)
-* `socket` [`net.Socket`](/api/net#netsocket)
+* `session` [`Http2Session`](/api/v19/http2#http2session)
+* `socket` [`net.Socket`](/api/v19/net#netsocket)
The `'connect'` event is emitted once the `Http2Session` has been successfully
connected to the remote peer and communication may begin.
@@ -192,7 +196,7 @@ User code will typically not listen for this event directly.
##### `'error'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -201,7 +205,7 @@ an `Http2Session`.
##### `'frameError'`
-
+
* `type` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The frame type.
* `code` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The error code.
@@ -220,12 +224,12 @@ immediately following the `'frameError'` event.
##### `'goaway'`
-
+
* `errorCode` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The HTTP/2 error code specified in the `GOAWAY` frame.
* `lastStreamID` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The ID of the last stream the remote peer successfully
processed (or `0` if no ID is specified).
-* `opaqueData` [`Buffer`](/api/buffer#buffer) If additional opaque data was included in the `GOAWAY`
+* `opaqueData` [`Buffer`](/api/v19/buffer#buffer) If additional opaque data was included in the `GOAWAY`
frame, a `Buffer` instance will be passed containing that data.
The `'goaway'` event is emitted when a `GOAWAY` frame is received.
@@ -235,7 +239,7 @@ event is emitted.
##### `'localSettings'`
-
+
* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.
@@ -255,16 +259,16 @@ session.on('localSettings', (settings) => {
##### `'ping'`
-
+
-* `payload` [`Buffer`](/api/buffer#buffer) The `PING` frame 8-byte payload
+* `payload` [`Buffer`](/api/v19/buffer#buffer) The `PING` frame 8-byte payload
The `'ping'` event is emitted whenever a `PING` frame is received from the
connected peer.
##### `'remoteSettings'`
-
+
* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.
@@ -279,9 +283,9 @@ session.on('remoteSettings', (settings) => {
##### `'stream'`
-
+
-* `stream` [`Http2Stream`](/api/http2#http2stream) A reference to the stream
+* `stream` [`Http2Stream`](/api/v19/http2#http2stream) A reference to the stream
* `headers` {HTTP/2 Headers Object} An object describing the headers
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags
* `rawHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the raw header names followed by
@@ -297,7 +301,7 @@ session.on('stream', (stream, headers, flags) => {
// ...
stream.respond({
':status': 200,
- 'content-type': 'text/plain; charset=utf-8'
+ 'content-type': 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
@@ -318,13 +322,13 @@ const server = http2.createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
- ':status': 200
+ ':status': 200,
});
stream.on('error', (error) => console.error(error));
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,
@@ -333,7 +337,7 @@ stream level, as shown above.
##### `'timeout'`
-
+
After the `http2session.setTimeout()` method is used to set the timeout period
for this `Http2Session`, the `'timeout'` event is emitted if there is no
@@ -347,7 +351,7 @@ session.on('timeout', () => { /* .. */ });
##### `http2session.alpnProtocol`
-
+
* [`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)
@@ -358,7 +362,7 @@ property.
##### `http2session.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -372,7 +376,7 @@ If specified, the `callback` function is registered as a handler for the
##### `http2session.closed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -381,7 +385,7 @@ Will be `true` if this `Http2Session` instance has been closed, otherwise
##### `http2session.connecting`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -391,7 +395,7 @@ callback.
##### `http2session.destroy([error][, code])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) An `Error` object if the `Http2Session` is being destroyed
due to an error.
@@ -411,7 +415,7 @@ If there are any remaining open `Http2Streams` associated with the
##### `http2session.destroyed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -420,7 +424,7 @@ longer be used, otherwise `false`.
##### `http2session.encrypted`
-
+
* [`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)
@@ -431,11 +435,11 @@ or stream.
##### `http2session.goaway([code[, lastStreamID[, opaqueData]]])`
-
+
* `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) An HTTP/2 error code
* `lastStreamID` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The numeric ID of the last processed `Http2Stream`
-* `opaqueData` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A `TypedArray` or `DataView`
+* `opaqueData` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A `TypedArray` or `DataView`
instance containing additional data to be carried within the `GOAWAY` frame.
Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the
@@ -443,7 +447,7 @@ Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the
##### `http2session.localSettings`
-
+
* {HTTP/2 Settings Object}
@@ -452,7 +456,7 @@ A prototype-less object describing the current local settings of this
##### `http2session.originSet`
-
+
* [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
@@ -464,7 +468,7 @@ The `originSet` property is only available when using a secure TLS connection.
##### `http2session.pendingSettingsAck`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -475,9 +479,9 @@ frames have been acknowledged.
##### `http2session.ping([payload, ]callback)`
-
+
-* `payload` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Optional ping payload.
+* `payload` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Optional ping payload.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -512,14 +516,14 @@ If the `payload` argument is not specified, the default payload will be the
##### `http2session.ref()`
-
+
Calls [`ref()`][`net.Socket.prototype.ref()`] on this `Http2Session`
instance's underlying [`net.Socket`][].
##### `http2session.remoteSettings`
-
+
* {HTTP/2 Settings Object}
@@ -528,7 +532,7 @@ A prototype-less object describing the current remote settings of this
##### `http2session.setLocalWindowSize(windowSize)`
-
+
* `windowSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -550,7 +554,7 @@ server.on('connect', (session) => {
##### `http2session.setTimeout(msecs, callback)`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -561,9 +565,9 @@ registered as a listener on the `'timeout'` event.
##### `http2session.socket`
-
+
-* [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket)
+* [`net.Socket`](/api/v19/net#netsocket) | [`tls.TLSSocket`](/api/v19/tls#tlstlssocket)
Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but
limits available methods to ones safe to use with HTTP/2.
@@ -578,7 +582,7 @@ All other interactions will be routed directly to the socket.
##### `http2session.state`
-
+
Provides miscellaneous information about the current state of the
`Http2Session`.
@@ -607,7 +611,7 @@ An object describing the current status of this `Http2Session`.
##### `http2session.settings([settings][, callback])`
-
+
* `settings` {HTTP/2 Settings Object}
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback that is called once the session is connected or
@@ -629,7 +633,7 @@ multiple `SETTINGS` frames while acknowledgment is still pending.
##### `http2session.type`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -640,24 +644,24 @@ client.
##### `http2session.unref()`
-
+
Calls [`unref()`][`net.Socket.prototype.unref()`] on this `Http2Session`
instance's underlying [`net.Socket`][].
#### `ServerHttp2Session`
-
+
-* Extends: [`Http2Session`](/api/http2#http2session)
+* Extends: [`Http2Session`](/api/v19/http2#http2session)
##### `serverhttp2session.altsvc(alt, originOrStream)`
-
+
* `alt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A description of the alternative service configuration as
defined by [RFC 7838][].
-* `originOrStream` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Either a URL string specifying
+* `originOrStream` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Either a URL string specifying
the origin (or an `Object` with an `origin` property) or the numeric
identifier of an active `Http2Stream` as given by the `http2stream.id`
property.
@@ -719,7 +723,7 @@ are passed through as provided by the user or received from the peer.
##### `serverhttp2session.origin(...origins)`
-
+
* `origins` { string | URL | Object } One or more URL Strings passed as
separate arguments.
@@ -768,13 +772,13 @@ server.on('stream', (stream) => {
#### `ClientHttp2Session`
-
+
-* Extends: [`Http2Session`](/api/http2#http2session)
+* Extends: [`Http2Session`](/api/v19/http2#http2session)
##### `'altsvc'`
-
+
* `alt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `origin` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -798,7 +802,7 @@ client.on('altsvc', (alt, origin, streamId) => {
##### `'origin'`
-
+
* `origins` string\[]
@@ -821,7 +825,7 @@ The `'origin'` event is only emitted when using a secure TLS connection.
##### `clienthttp2session.request(headers[, options])`
-
+
* `headers` {HTTP/2 Headers Object}
@@ -840,10 +844,10 @@ The `'origin'` event is only emitted when using a secure TLS connection.
and `256` (inclusive).
* `waitForTrailers` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, the `Http2Stream` will emit the
`'wantTrailers'` event after the final `DATA` frame has been sent.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An AbortSignal that may be used to abort an ongoing
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) An AbortSignal that may be used to abort an ongoing
request.
-* Returns: [`ClientHttp2Stream`](/api/http2#clienthttp2stream)
+* Returns: [`ClientHttp2Stream`](/api/v19/http2#clienthttp2stream)
For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`
creates and returns an `Http2Stream` instance that can be used to send an
@@ -863,7 +867,7 @@ const http2 = require('node:http2');
const clientSession = http2.connect('https://localhost:1234');
const {
HTTP2_HEADER_PATH,
- HTTP2_HEADER_STATUS
+ HTTP2_HEADER_STATUS,
} = http2.constants;
const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });
@@ -896,9 +900,9 @@ they respectively default to:
#### `Http2Stream`
-
+
-* Extends: [`stream.Duplex`](/api/stream#streamduplex)
+* Extends: [`stream.Duplex`](/api/v19/stream#streamduplex)
Each instance of the `Http2Stream` class represents a bidirectional HTTP/2
communications stream over an `Http2Session` instance. Any single `Http2Session`
@@ -928,7 +932,7 @@ encoding.
```js
stream.respond({
'content-type': 'text/html; charset=utf-8',
- ':status': 200
+ ':status': 200,
});
```
@@ -979,7 +983,7 @@ destroyed.
##### `'aborted'`
-
+
The `'aborted'` event is emitted whenever a `Http2Stream` instance is
abnormally aborted in mid-communication.
@@ -990,7 +994,7 @@ has not been ended.
##### `'close'`
-
+
The `'close'` event is emitted when the `Http2Stream` is destroyed. Once
this event is emitted, the `Http2Stream` instance is no longer usable.
@@ -1001,7 +1005,7 @@ the `http2stream.rstCode` property. If the code is any value other than
##### `'error'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -1010,7 +1014,7 @@ an `Http2Stream`.
##### `'frameError'`
-
+
* `type` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The frame type.
* `code` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The error code.
@@ -1025,7 +1029,7 @@ error code. The `Http2Stream` instance will be destroyed immediately after the
##### `'ready'`
-
+
The `'ready'` event is emitted when the `Http2Stream` has been opened, has
been assigned an `id`, and can be used. The listener does not expect any
@@ -1033,7 +1037,7 @@ arguments.
##### `'timeout'`
-
+
The `'timeout'` event is emitted after no activity is received for this
`Http2Stream` within the number of milliseconds set using
@@ -1042,7 +1046,7 @@ Its listener does not expect any arguments.
##### `'trailers'`
-
+
* `headers` {HTTP/2 Headers Object} An object describing the headers
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags
@@ -1063,7 +1067,7 @@ stream.on('trailers', (headers, flags) => {
##### `'wantTrailers'`
-
+
The `'wantTrailers'` event is emitted when the `Http2Stream` has queued the
final `DATA` frame to be sent on a frame and the `Http2Stream` is ready to send
@@ -1072,7 +1076,7 @@ option must be set for this event to be emitted.
##### `http2stream.aborted`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1081,7 +1085,7 @@ the `'aborted'` event will have been emitted.
##### `http2stream.bufferSize`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1090,7 +1094,7 @@ See [`net.Socket.bufferSize`][] for details.
##### `http2stream.close(code[, callback])`
-
+
* `code` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Unsigned 32-bit integer identifying the error code.
**Default:** `http2.constants.NGHTTP2_NO_ERROR` (`0x00`).
@@ -1102,7 +1106,7 @@ connected HTTP/2 peer.
##### `http2stream.closed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1110,7 +1114,7 @@ Set to `true` if the `Http2Stream` instance has been closed.
##### `http2stream.destroyed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1119,7 +1123,7 @@ usable.
##### `http2stream.endAfterHeaders`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1129,7 +1133,7 @@ and the readable side of the `Http2Stream` will be closed.
##### `http2stream.id`
-
+
* [`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)
@@ -1138,7 +1142,7 @@ if the stream identifier has not yet been assigned.
##### `http2stream.pending`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1147,7 +1151,7 @@ numeric stream identifier.
##### `http2stream.priority(options)`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `exclusive` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true` and `parent` identifies a parent Stream,
@@ -1166,7 +1170,7 @@ Updates the priority for this `Http2Stream` instance.
##### `http2stream.rstCode`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1177,7 +1181,7 @@ calling `http2stream.close()`, or `http2stream.destroy()`. Will be
##### `http2stream.sentHeaders`
-
+
* {HTTP/2 Headers Object}
@@ -1185,7 +1189,7 @@ An object containing the outbound headers sent for this `Http2Stream`.
##### `http2stream.sentInfoHeaders`
-
+
* {HTTP/2 Headers Object\[]}
@@ -1194,7 +1198,7 @@ sent for this `Http2Stream`.
##### `http2stream.sentTrailers`
-
+
* {HTTP/2 Headers Object}
@@ -1202,16 +1206,16 @@ An object containing the outbound trailers sent for this `HttpStream`.
##### `http2stream.session`
-
+
-* [`Http2Session`](/api/http2#http2session)
+* [`Http2Session`](/api/v19/http2#http2session)
A reference to the `Http2Session` instance that owns this `Http2Stream`. The
value will be `undefined` after the `Http2Stream` instance is destroyed.
##### `http2stream.setTimeout(msecs, callback)`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1228,7 +1232,7 @@ req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));
##### `http2stream.state`
-
+
Provides miscellaneous information about the current state of the
`Http2Stream`.
@@ -1250,7 +1254,7 @@ A current state of this `Http2Stream`.
##### `http2stream.sendTrailers(headers)`
-
+
* `headers` {HTTP/2 Headers Object}
@@ -1278,9 +1282,9 @@ fields (e.g. `':method'`, `':path'`, etc).
#### `ClientHttp2Stream`
-
+
-* Extends [`Http2Stream`](/api/http2#http2stream)
+* Extends [`Http2Stream`](/api/v19/http2#http2stream)
The `ClientHttp2Stream` class is an extension of `Http2Stream` that is
used exclusively on HTTP/2 Clients. `Http2Stream` instances on the client
@@ -1289,7 +1293,7 @@ the client.
##### `'continue'`
-
+
Emitted when the server sends a `100 Continue` status, usually because
the request contained `Expect: 100-continue`. This is an instruction that
@@ -1297,7 +1301,7 @@ the client should send the request body.
##### `'headers'`
-
+
* `headers` {HTTP/2 Headers Object}
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1315,7 +1319,7 @@ stream.on('headers', (headers, flags) => {
##### `'push'`
-
+
* `headers` {HTTP/2 Headers Object}
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1332,7 +1336,7 @@ stream.on('push', (headers, flags) => {
##### `'response'`
-
+
* `headers` {HTTP/2 Headers Object}
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1353,9 +1357,9 @@ req.on('response', (headers, flags) => {
#### `ServerHttp2Stream`
-
+
-* Extends: [`Http2Stream`](/api/http2#http2stream)
+* Extends: [`Http2Stream`](/api/v19/http2#http2stream)
The `ServerHttp2Stream` class is an extension of [`Http2Stream`][] that is
used exclusively on HTTP/2 Servers. `Http2Stream` instances on the server
@@ -1364,7 +1368,7 @@ provide additional methods such as `http2stream.pushStream()` and
##### `http2stream.additionalHeaders(headers)`
-
+
* `headers` {HTTP/2 Headers Object}
@@ -1372,7 +1376,7 @@ Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer.
##### `http2stream.headersSent`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1380,7 +1384,7 @@ True if headers were sent, false otherwise (read-only).
##### `http2stream.pushAllowed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1391,7 +1395,7 @@ accepts push streams, `false` otherwise. Settings are the same for every
##### `http2stream.pushStream(headers[, options], callback)`
-
+
* `headers` {HTTP/2 Headers Object}
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1404,7 +1408,7 @@ accepts push streams, `false` otherwise. Settings are the same for every
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback that is called once the push stream has been
initiated.
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
- * `pushStream` [`ServerHttp2Stream`](/api/http2#serverhttp2stream) The returned `pushStream` object.
+ * `pushStream` [`ServerHttp2Stream`](/api/v19/http2#serverhttp2stream) The returned `pushStream` object.
* `headers` {HTTP/2 Headers Object} Headers object the `pushStream` was
initiated with.
@@ -1435,7 +1439,7 @@ and will throw an error.
##### `http2stream.respond([headers[, options]])`
-
+
* `headers` {HTTP/2 Headers Object}
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1477,9 +1481,9 @@ server.on('stream', (stream) => {
##### `http2stream.respondWithFD(fd[, headers[, options]])`
-
+
-* `fd` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/fs#filehandle) A readable file descriptor.
+* `fd` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`FileHandle`](/api/v19/fs#filehandle) A readable file descriptor.
* `headers` {HTTP/2 Headers Object}
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `statCheck` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1508,7 +1512,7 @@ server.on('stream', (stream) => {
const headers = {
'content-length': stat.size,
'last-modified': stat.mtime.toUTCString(),
- 'content-type': 'text/plain; charset=utf-8'
+ 'content-type': 'text/plain; charset=utf-8',
};
stream.respondWithFD(fd, headers);
stream.on('close', () => fs.closeSync(fd));
@@ -1553,7 +1557,7 @@ server.on('stream', (stream) => {
const headers = {
'content-length': stat.size,
'last-modified': stat.mtime.toUTCString(),
- 'content-type': 'text/plain; charset=utf-8'
+ 'content-type': 'text/plain; charset=utf-8',
};
stream.respondWithFD(fd, headers, { waitForTrailers: true });
stream.on('wantTrailers', () => {
@@ -1566,9 +1570,9 @@ server.on('stream', (stream) => {
##### `http2stream.respondWithFile(path[, headers[, options]])`
-
+
-* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`URL`](/api/url#the-whatwg-url-api)
+* `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)
* `headers` {HTTP/2 Headers Object}
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `statCheck` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1615,7 +1619,7 @@ server.on('stream', (stream) => {
}
} catch (err) {
// Perform actual error handling.
- console.log(err);
+ console.error(err);
}
stream.end();
}
@@ -1681,9 +1685,9 @@ server.on('stream', (stream) => {
#### `Http2Server`
-
+
-* Extends: [`net.Server`](/api/net#netserver)
+* Extends: [`net.Server`](/api/v19/net#netserver)
Instances of `Http2Server` are created using the `http2.createServer()`
function. The `Http2Server` class is not exported directly by the
@@ -1691,10 +1695,10 @@ function. The `Http2Server` class is not exported directly by the
##### `'checkContinue'`
-
+
-* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest)
-* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse)
+* `request` [`http2.Http2ServerRequest`](/api/v19/http2#http2http2serverrequest)
+* `response` [`http2.Http2ServerResponse`](/api/v19/http2#http2http2serverresponse)
If a [`'request'`][] listener is registered or [`http2.createServer()`][] is
supplied a callback function, the `'checkContinue'` event is emitted each time
@@ -1712,9 +1716,9 @@ not be emitted.
##### `'connection'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
This event is emitted when a new TCP stream is established. `socket` is
typically an object of type [`net.Socket`][]. Usually users will not want to
@@ -1725,38 +1729,38 @@ into the HTTP server. In that case, any [`Duplex`][] stream can be passed.
##### `'request'`
-
+
-* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest)
-* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse)
+* `request` [`http2.Http2ServerRequest`](/api/v19/http2#http2http2serverrequest)
+* `response` [`http2.Http2ServerResponse`](/api/v19/http2#http2http2serverresponse)
Emitted each time there is a request. There may be multiple requests
per session. See the [Compatibility API][].
##### `'session'`
-
+
-* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session)
+* `session` [`ServerHttp2Session`](/api/v19/http2#serverhttp2session)
The `'session'` event is emitted when a new `Http2Session` is created by the
`Http2Server`.
##### `'sessionError'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
-* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session)
+* `session` [`ServerHttp2Session`](/api/v19/http2#serverhttp2session)
The `'sessionError'` event is emitted when an `'error'` event is emitted by
an `Http2Session` object associated with the `Http2Server`.
##### `'stream'`
-
+
-* `stream` [`Http2Stream`](/api/http2#http2stream) A reference to the stream
+* `stream` [`Http2Stream`](/api/v19/http2#http2stream) A reference to the stream
* `headers` {HTTP/2 Headers Object} An object describing the headers
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags
* `rawHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the raw header names followed by
@@ -1773,7 +1777,7 @@ const {
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS,
- HTTP2_HEADER_CONTENT_TYPE
+ HTTP2_HEADER_CONTENT_TYPE,
} = http2.constants;
const server = http2.createServer();
@@ -1783,7 +1787,7 @@ server.on('stream', (stream, headers, flags) => {
// ...
stream.respond({
[HTTP2_HEADER_STATUS]: 200,
- [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'
+ [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
@@ -1792,7 +1796,7 @@ server.on('stream', (stream, headers, flags) => {
##### `'timeout'`
-
+
The `'timeout'` event is emitted when there is no activity on the Server for
a given number of milliseconds set using `http2server.setTimeout()`.
@@ -1800,7 +1804,7 @@ a given number of milliseconds set using `http2server.setTimeout()`.
##### `server.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1815,11 +1819,11 @@ closed, although the server has already stopped allowing new sessions. See
##### `server.setTimeout([msecs][, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** 0 (no timeout)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`Http2Server`](/api/http2#http2server)
+* Returns: [`Http2Server`](/api/v19/http2#http2server)
Used to set the timeout value for http2 server requests,
and sets a callback function that is called when there is no activity
@@ -1832,7 +1836,7 @@ error will be thrown.
##### `server.timeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** 0 (no timeout)
@@ -1846,7 +1850,7 @@ value only affects new connections to the server, not any existing connections.
##### `server.updateSettings([settings])`
-
+
* `settings` {HTTP/2 Settings Object}
@@ -1858,9 +1862,9 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument.
#### `Http2SecureServer`
-
+
-* Extends: [`tls.Server`](/api/tls#tlsserver)
+* Extends: [`tls.Server`](/api/v19/tls#tlsserver)
Instances of `Http2SecureServer` are created using the
`http2.createSecureServer()` function. The `Http2SecureServer` class is not
@@ -1868,10 +1872,10 @@ exported directly by the `node:http2` module.
##### `'checkContinue'`
-
+
-* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest)
-* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse)
+* `request` [`http2.Http2ServerRequest`](/api/v19/http2#http2http2serverrequest)
+* `response` [`http2.Http2ServerResponse`](/api/v19/http2#http2http2serverresponse)
If a [`'request'`][] listener is registered or [`http2.createSecureServer()`][]
is supplied a callback function, the `'checkContinue'` event is emitted each
@@ -1889,9 +1893,9 @@ not be emitted.
##### `'connection'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
This event is emitted when a new TCP stream is established, before the TLS
handshake begins. `socket` is typically an object of type [`net.Socket`][].
@@ -1902,38 +1906,38 @@ into the HTTP server. In that case, any [`Duplex`][] stream can be passed.
##### `'request'`
-
+
-* `request` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest)
-* `response` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse)
+* `request` [`http2.Http2ServerRequest`](/api/v19/http2#http2http2serverrequest)
+* `response` [`http2.Http2ServerResponse`](/api/v19/http2#http2http2serverresponse)
Emitted each time there is a request. There may be multiple requests
per session. See the [Compatibility API][].
##### `'session'`
-
+
-* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session)
+* `session` [`ServerHttp2Session`](/api/v19/http2#serverhttp2session)
The `'session'` event is emitted when a new `Http2Session` is created by the
`Http2SecureServer`.
##### `'sessionError'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
-* `session` [`ServerHttp2Session`](/api/http2#serverhttp2session)
+* `session` [`ServerHttp2Session`](/api/v19/http2#serverhttp2session)
The `'sessionError'` event is emitted when an `'error'` event is emitted by
an `Http2Session` object associated with the `Http2SecureServer`.
##### `'stream'`
-
+
-* `stream` [`Http2Stream`](/api/http2#http2stream) A reference to the stream
+* `stream` [`Http2Stream`](/api/v19/http2#http2stream) A reference to the stream
* `headers` {HTTP/2 Headers Object} An object describing the headers
* `flags` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The associated numeric flags
* `rawHeaders` [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) An array containing the raw header names followed by
@@ -1950,7 +1954,7 @@ const {
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS,
- HTTP2_HEADER_CONTENT_TYPE
+ HTTP2_HEADER_CONTENT_TYPE,
} = http2.constants;
const options = getOptionsSomehow();
@@ -1962,7 +1966,7 @@ server.on('stream', (stream, headers, flags) => {
// ...
stream.respond({
[HTTP2_HEADER_STATUS]: 200,
- [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8'
+ [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain; charset=utf-8',
});
stream.write('hello ');
stream.end('world');
@@ -1971,7 +1975,7 @@ server.on('stream', (stream, headers, flags) => {
##### `'timeout'`
-
+
The `'timeout'` event is emitted when there is no activity on the Server for
a given number of milliseconds set using `http2secureServer.setTimeout()`.
@@ -1979,9 +1983,9 @@ a given number of milliseconds set using `http2secureServer.setTimeout()`.
##### `'unknownProtocol'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
The `'unknownProtocol'` event is emitted when a connecting client fails to
negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler
@@ -2001,7 +2005,7 @@ See the [Compatibility API][].
##### `server.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -2016,11 +2020,11 @@ closed, although the server has already stopped allowing new sessions. See
##### `server.setTimeout([msecs][, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `120000` (2 minutes)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`Http2SecureServer`](/api/http2#http2secureserver)
+* Returns: [`Http2SecureServer`](/api/v19/http2#http2secureserver)
Used to set the timeout value for http2 secure server requests,
and sets a callback function that is called when there is no activity
@@ -2033,7 +2037,7 @@ error will be thrown.
##### `server.timeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Timeout in milliseconds. **Default:** 0 (no timeout)
@@ -2047,7 +2051,7 @@ value only affects new connections to the server, not any existing connections.
##### `server.updateSettings([settings])`
-
+
* `settings` {HTTP/2 Settings Object}
@@ -2059,7 +2063,7 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument.
#### `http2.createServer([options][, onRequestHandler])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `maxDeflateDynamicTableSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Sets the maximum dynamic table size
@@ -2116,17 +2120,17 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument.
**Default:** `100`.
* `settings` {HTTP/2 Settings Object} The initial settings to send to the
remote peer upon connection.
- * `Http1IncomingMessage` [`http.IncomingMessage`](/api/http#httpincomingmessage) Specifies the
+ * `Http1IncomingMessage` [`http.IncomingMessage`](/api/v19/http#httpincomingmessage) Specifies the
`IncomingMessage` class to used for HTTP/1 fallback. Useful for extending
the original `http.IncomingMessage`. **Default:** `http.IncomingMessage`.
- * `Http1ServerResponse` [`http.ServerResponse`](/api/http#httpserverresponse) Specifies the `ServerResponse`
+ * `Http1ServerResponse` [`http.ServerResponse`](/api/v19/http#httpserverresponse) Specifies the `ServerResponse`
class to used for HTTP/1 fallback. Useful for extending the original
`http.ServerResponse`. **Default:** `http.ServerResponse`.
- * `Http2ServerRequest` [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest) Specifies the
+ * `Http2ServerRequest` [`http2.Http2ServerRequest`](/api/v19/http2#http2http2serverrequest) Specifies the
`Http2ServerRequest` class to use.
Useful for extending the original `Http2ServerRequest`.
**Default:** `Http2ServerRequest`.
- * `Http2ServerResponse` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) Specifies the
+ * `Http2ServerResponse` [`http2.Http2ServerResponse`](/api/v19/http2#http2http2serverresponse) Specifies the
`Http2ServerResponse` class to use.
Useful for extending the original `Http2ServerResponse`.
**Default:** `Http2ServerResponse`.
@@ -2136,7 +2140,7 @@ Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument.
**Default:** `10000`.
* ...: Any [`net.createServer()`][] option can be provided.
* `onRequestHandler` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) See [Compatibility API][]
-* Returns: [`Http2Server`](/api/http2#http2server)
+* Returns: [`Http2Server`](/api/v19/http2#http2server)
Returns a `net.Server` instance that creates and manages `Http2Session`
instances.
@@ -2158,17 +2162,17 @@ const server = http2.createServer();
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
- ':status': 200
+ ':status': 200,
});
stream.end('
Hello World
');
});
-server.listen(80);
+server.listen(8000);
```
#### `http2.createSecureServer(options[, onRequestHandler])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `allowHTTP1` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Incoming client connections that do not support
@@ -2235,7 +2239,7 @@ server.listen(80);
the socket has not been destroyed by that time the server will destroy it.
**Default:** `10000`.
* `onRequestHandler` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) See [Compatibility API][]
-* Returns: [`Http2SecureServer`](/api/http2#http2secureserver)
+* Returns: [`Http2SecureServer`](/api/v19/http2#http2secureserver)
Returns a `tls.Server` instance that creates and manages `Http2Session`
instances.
@@ -2246,7 +2250,7 @@ const fs = require('node:fs');
const options = {
key: fs.readFileSync('server-key.pem'),
- cert: fs.readFileSync('server-cert.pem')
+ cert: fs.readFileSync('server-cert.pem'),
};
// Create a secure HTTP/2 server
@@ -2255,19 +2259,19 @@ const server = http2.createSecureServer(options);
server.on('stream', (stream, headers) => {
stream.respond({
'content-type': 'text/html; charset=utf-8',
- ':status': 200
+ ':status': 200,
});
stream.end('
Hello World
');
});
-server.listen(80);
+server.listen(8443);
```
#### `http2.connect(authority[, options][, listener])`
-
+
-* `authority` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) The remote HTTP/2 server to connect to. This must
+* `authority` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) The remote HTTP/2 server to connect to. This must
be in the form of a minimal, valid URL with the `http://` or `https://`
prefix, host name, and IP port (if a non-default port is used). Userinfo
(user ID and password), path, querystring, and fragment details in the
@@ -2334,7 +2338,7 @@ server.listen(80);
**Default:** `10000`.
* `listener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Will be registered as a one-time listener of the
[`'connect'`][] event.
-* Returns: [`ClientHttp2Session`](/api/http2#clienthttp2session)
+* Returns: [`ClientHttp2Session`](/api/v19/http2#clienthttp2session)
Returns a `ClientHttp2Session` instance.
@@ -2349,7 +2353,7 @@ client.close();
#### `http2.constants`
-
+
##### Error codes for `RST_STREAM` and `GOAWAY`
@@ -2375,7 +2379,7 @@ a given number of milliseconds set using `http2server.setTimeout()`.
#### `http2.getDefaultSettings()`
-
+
* Returns: {HTTP/2 Settings Object}
@@ -2385,10 +2389,10 @@ so instances returned may be safely modified for use.
#### `http2.getPackedSettings([settings])`
-
+
* `settings` {HTTP/2 Settings Object}
-* Returns: [`Buffer`](/api/buffer#buffer)
+* Returns: [`Buffer`](/api/v19/buffer#buffer)
Returns a `Buffer` instance containing serialized representation of the given
HTTP/2 settings as specified in the [HTTP/2][] specification. This is intended
@@ -2405,9 +2409,9 @@ console.log(packed.toString('base64'));
#### `http2.getUnpackedSettings(buf)`
-
+
-* `buf` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) The packed settings.
+* `buf` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) The packed settings.
* Returns: {HTTP/2 Settings Object}
Returns a [HTTP/2 Settings Object][] containing the deserialized settings from
@@ -2415,7 +2419,7 @@ the given `Buffer` as generated by `http2.getPackedSettings()`.
#### `http2.sensitiveHeaders`
-
+
* [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type)
@@ -2434,7 +2438,7 @@ to send more than one value per header field).
const headers = {
':status': '200',
'content-type': 'text-plain',
- 'ABC': ['has', 'more', 'than', 'one', 'value']
+ 'ABC': ['has', 'more', 'than', 'one', 'value'],
};
stream.respond(headers);
@@ -2485,7 +2489,7 @@ const headers = {
'content-type': 'text-plain',
'cookie': 'some-cookie',
'other-sensitive-header': 'very secret data',
- [http2.sensitiveHeaders]: ['cookie', 'other-sensitive-header']
+ [http2.sensitiveHeaders]: ['cookie', 'other-sensitive-header'],
};
stream.respond(headers);
@@ -2499,7 +2503,7 @@ all headers marked as sensitive, including ones marked that way automatically.
#### Settings object
-
+
The `http2.getDefaultSettings()`, `http2.getPackedSettings()`,
`http2.createServer()`, `http2.createSecureServer()`,
@@ -2662,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) => {
@@ -2758,7 +2762,7 @@ const key = readFileSync('./key.pem');
const server = createSecureServer(
{ cert, key, allowHTTP1: true },
- onRequest
+ onRequest,
).listen(4443);
function onRequest(req, res) {
@@ -2768,7 +2772,7 @@ function onRequest(req, res) {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({
alpnProtocol,
- httpVersion: req.httpVersion
+ httpVersion: req.httpVersion,
}));
}
```
@@ -2778,9 +2782,9 @@ HTTP/2.
#### `http2.Http2ServerRequest`
-
+
-* Extends: [`stream.Readable`](/api/stream#streamreadable)
+* Extends: [`stream.Readable`](/api/v19/stream#streamreadable)
A `Http2ServerRequest` object is created by [`http2.Server`][] or
[`http2.SecureServer`][] and passed as the first argument to the
@@ -2789,7 +2793,7 @@ data.
##### `'aborted'`
-
+
The `'aborted'` event is emitted whenever a `Http2ServerRequest` instance is
abnormally aborted in mid-communication.
@@ -2799,14 +2803,14 @@ side has not been ended.
##### `'close'`
-
+
Indicates that the underlying [`Http2Stream`][] was closed.
Just like `'end'`, this event occurs only once per response.
##### `request.aborted`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2815,7 +2819,7 @@ been aborted.
##### `request.authority`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2826,7 +2830,7 @@ to set either `:authority` or `host`, this value is derived from
##### `request.complete`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2835,17 +2839,21 @@ been completed, aborted, or destroyed.
##### `request.connection`
-
+
+
+
+
+Deprecated. Use [`request.socket`][].
-
+
-* [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket)
+* [`net.Socket`](/api/v19/net#netsocket) | [`tls.TLSSocket`](/api/v19/tls#tlstlssocket)
See [`request.socket`][].
##### `request.destroy([error])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -2857,7 +2865,7 @@ It does nothing if the stream was already destroyed.
##### `request.headers`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2889,7 +2897,7 @@ assert(request.url); // Fails because the :path header has been removed
##### `request.httpVersion`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2902,7 +2910,7 @@ Also `message.httpVersionMajor` is the first integer and
##### `request.method`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2910,7 +2918,7 @@ The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`.
##### `request.rawHeaders`
-
+
* string\[]
@@ -2938,7 +2946,7 @@ console.log(request.rawHeaders);
##### `request.rawTrailers`
-
+
* string\[]
@@ -2947,7 +2955,7 @@ received. Only populated at the `'end'` event.
##### `request.scheme`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2956,11 +2964,11 @@ portion of the target URL.
##### `request.setTimeout(msecs, callback)`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest)
+* Returns: [`http2.Http2ServerRequest`](/api/v19/http2#http2http2serverrequest)
Sets the [`Http2Stream`][]'s timeout value to `msecs`. If a callback is
provided, then it is added as a listener on the `'timeout'` event on
@@ -2973,9 +2981,9 @@ events, timed out sockets must be handled explicitly.
##### `request.socket`
-
+
-* [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket)
+* [`net.Socket`](/api/v19/net#netsocket) | [`tls.TLSSocket`](/api/v19/tls#tlstlssocket)
Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but
applies getters, setters, and methods based on HTTP/2 logic.
@@ -2998,15 +3006,15 @@ authentication details.
##### `request.stream`
-
+
-* [`Http2Stream`](/api/http2#http2stream)
+* [`Http2Stream`](/api/v19/http2#http2stream)
The [`Http2Stream`][] object backing the request.
##### `request.trailers`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -3014,7 +3022,7 @@ The request/response trailers object. Only populated at the `'end'` event.
##### `request.url`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -3055,23 +3063,23 @@ URL {
#### `http2.Http2ServerResponse`
-
+
-* Extends: [`Stream`](/api/stream#stream)
+* Extends: [`Stream`](/api/v19/stream#stream)
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the [`'request'`][] event.
##### `'close'`
-
+
Indicates that the underlying [`Http2Stream`][] was terminated before
[`response.end()`][] was called or able to flush.
##### `'finish'`
-
+
Emitted when the response has been sent. More specifically, this event is
emitted when the last segment of the response headers and body have been
@@ -3082,7 +3090,7 @@ After this event, no more events will be emitted on the response object.
##### `response.addTrailers(headers)`
-
+
* `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -3094,17 +3102,21 @@ will result in a [`TypeError`][] being thrown.
##### `response.connection`
-
+
-
+
-* [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket)
+Deprecated. Use [`response.socket`][].
+
+
+
+* [`net.Socket`](/api/v19/net#netsocket) | [`tls.TLSSocket`](/api/v19/tls#tlstlssocket)
See [`response.socket`][].
##### `response.createPushResponse(headers, callback)`
-
+
* `headers` {HTTP/2 Headers Object} An object describing the headers
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called once `http2stream.pushStream()` is finished,
@@ -3112,7 +3124,7 @@ See [`response.socket`][].
has been rejected, or the state of `Http2ServerRequest` is closed prior to
calling the `http2stream.pushStream()` method
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
- * `res` [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse) The newly-created `Http2ServerResponse`
+ * `res` [`http2.Http2ServerResponse`](/api/v19/http2#http2http2serverresponse) The newly-created `Http2ServerResponse`
object
Call [`http2stream.pushStream()`][] with the given headers, and wrap the
@@ -3122,9 +3134,9 @@ called with an error `ERR_HTTP2_INVALID_STREAM`.
##### `response.end([data[, encoding]][, callback])`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -3141,9 +3153,13 @@ is finished.
##### `response.finished`
-
+
+
+
+
+Deprecated. Use [`response.writableEnded`][].
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -3152,7 +3168,7 @@ as `false`. After [`response.end()`][] executes, the value will be `true`.
##### `response.getHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -3166,7 +3182,7 @@ const contentType = response.getHeader('content-type');
##### `response.getHeaderNames()`
-
+
* Returns: string\[]
@@ -3183,7 +3199,7 @@ const headerNames = response.getHeaderNames();
##### `response.getHeaders()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -3208,7 +3224,7 @@ const headers = response.getHeaders();
##### `response.hasHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -3222,7 +3238,7 @@ const hasContentType = response.hasHeader('content-type');
##### `response.headersSent`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -3230,7 +3246,7 @@ True if headers were sent, false otherwise (read-only).
##### `response.removeHeader(name)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -3242,15 +3258,15 @@ response.removeHeader('Content-Encoding');
##### `response.req`
-
+
-* [`http2.Http2ServerRequest`](/api/http2#http2http2serverrequest)
+* [`http2.Http2ServerRequest`](/api/v19/http2#http2http2serverrequest)
A reference to the original HTTP2 `request` object.
##### `response.sendDate`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -3262,7 +3278,7 @@ in responses.
##### `response.setHeader(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `value` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -3300,11 +3316,11 @@ const server = http2.createServer((req, res) => {
##### `response.setTimeout(msecs[, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse)
+* Returns: [`http2.Http2ServerResponse`](/api/v19/http2#http2http2serverresponse)
Sets the [`Http2Stream`][]'s timeout value to `msecs`. If a callback is
provided, then it is added as a listener on the `'timeout'` event on
@@ -3317,9 +3333,9 @@ events, timed out sockets must be handled explicitly.
##### `response.socket`
-
+
-* [`net.Socket`](/api/net#netsocket) | [`tls.TLSSocket`](/api/tls#tlstlssocket)
+* [`net.Socket`](/api/v19/net#netsocket) | [`tls.TLSSocket`](/api/v19/tls#tlstlssocket)
Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but
applies getters, setters, and methods based on HTTP/2 logic.
@@ -3349,7 +3365,7 @@ const server = http2.createServer((req, res) => {
##### `response.statusCode`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3366,7 +3382,7 @@ status code which was sent out.
##### `response.statusMessage`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -3375,15 +3391,15 @@ an empty string.
##### `response.stream`
-
+
-* [`Http2Stream`](/api/http2#http2stream)
+* [`Http2Stream`](/api/v19/http2#http2stream)
The [`Http2Stream`][] object backing the response.
##### `response.writableEnded`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -3393,9 +3409,9 @@ does not indicate whether the data has been flushed, for this use
##### `response.write(chunk[, encoding][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -3430,7 +3446,7 @@ buffer. Returns `false` if all or part of the data was queued in user memory.
##### `response.writeContinue()`
-
+
Sends a status `100 Continue` to the client, indicating that the request body
should be sent. See the [`'checkContinue'`][] event on `Http2Server` and
@@ -3438,7 +3454,7 @@ should be sent. See the [`'checkContinue'`][] event on `Http2Server` and
##### `response.writeEarlyHints(hints)`
-
+
* `hints` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -3466,12 +3482,12 @@ response.writeEarlyHints({
##### `response.writeHead(statusCode[, statusMessage][, headers])`
-
+
* `statusCode` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `statusMessage` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `headers` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
-* Returns: [`http2.Http2ServerResponse`](/api/http2#http2http2serverresponse)
+* Returns: [`http2.Http2ServerResponse`](/api/v19/http2#http2http2serverresponse)
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like `404`. The last argument, `headers`, are the response headers.
diff --git a/content/api/v19/https.en.md b/content/api/v19/https.en.md
index c9c994134c..33622e3570 100644
--- a/content/api/v19/https.en.md
+++ b/content/api/v19/https.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.
@@ -27,7 +31,7 @@ let https;
try {
https = require('node:https');
} catch (err) {
- console.log('https support is disabled!');
+ console.error('https support is disabled!');
}
```
@@ -45,20 +49,20 @@ let https;
try {
https = await import('node:https');
} catch (err) {
- console.log('https support is disabled!');
+ console.error('https support is disabled!');
}
```
### `https.Agent`
-
+
An [`Agent`][] object for HTTPS similar to [`http.Agent`][]. See
[`https.request()`][] for more information.
#### `new Agent([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Set of configurable options to set on the agent.
Can have the same fields as for [`http.Agent(options)`][], and
@@ -75,10 +79,10 @@ An [`Agent`][] object for HTTPS similar to [`http.Agent`][]. See
##### `'keylog'`
-
+
-* `line` [`Buffer`](/api/buffer#buffer) Line of ASCII text, in NSS `SSLKEYLOGFILE` format.
-* `tlsSocket` [`tls.TLSSocket`](/api/tls#tlstlssocket) The `tls.TLSSocket` instance on which it was
+* `line` [`Buffer`](/api/v19/buffer#buffer) Line of ASCII text, in NSS `SSLKEYLOGFILE` format.
+* `tlsSocket` [`tls.TLSSocket`](/api/v19/tls#tlstlssocket) The `tls.TLSSocket` instance on which it was
generated.
The `keylog` event is emitted when key material is generated or received by a
@@ -99,36 +103,36 @@ https.globalAgent.on('keylog', (line, tlsSocket) => {
### `https.Server`
-
+
-* Extends: [`tls.Server`](/api/tls#tlsserver)
+* Extends: [`tls.Server`](/api/v19/tls#tlsserver)
See [`http.Server`][] for more information.
#### `server.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`https.Server`](/api/https#httpsserver)
+* Returns: [`https.Server`](/api/v19/https#httpsserver)
See [`server.close()`][] in the `node:http` module.
#### `server.closeAllConnections()`
-
+
See [`server.closeAllConnections()`][] in the `node:http` module.
#### `server.closeIdleConnections()`
-
+
See [`server.closeIdleConnections()`][] in the `node:http` module.
#### `server.headersTimeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `60000`
@@ -147,25 +151,25 @@ See [`server.maxHeadersCount`][] in the `node:http` module.
#### `server.requestTimeout`
-
+
-* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
+* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `300000`
See [`server.requestTimeout`][] in the `node:http` module.
#### `server.setTimeout([msecs][, callback])`
-
+
* `msecs` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `120000` (2 minutes)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`https.Server`](/api/https#httpsserver)
+* Returns: [`https.Server`](/api/v19/https#httpsserver)
See [`server.setTimeout()`][] in the `node:http` module.
#### `server.timeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** 0 (no timeout)
@@ -173,7 +177,7 @@ See [`server.timeout`][] in the `node:http` module.
#### `server.keepAliveTimeout`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `5000` (5 seconds)
@@ -181,12 +185,12 @@ See [`server.keepAliveTimeout`][] in the `node:http` module.
### `https.createServer([options][, requestListener])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Accepts `options` from [`tls.createServer()`][],
[`tls.createSecureContext()`][] and [`http.createServer()`][].
* `requestListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A listener to be added to the `'request'` event.
-* Returns: [`https.Server`](/api/https#httpsserver)
+* Returns: [`https.Server`](/api/v19/https#httpsserver)
```js
// curl -k https://localhost:8000/
@@ -195,7 +199,7 @@ const fs = require('node:fs');
const options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
- cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
+ cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
};
https.createServer(options, (req, res) => {
@@ -212,7 +216,7 @@ const fs = require('node:fs');
const options = {
pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
- passphrase: 'sample'
+ passphrase: 'sample',
};
https.createServer(options, (req, res) => {
@@ -225,10 +229,10 @@ https.createServer(options, (req, res) => {
### `https.get(url[, options][, callback])`
-
+
-* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api)
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Accepts the same `options` as
+* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api)
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) Accepts the same `options` as
[`https.request()`][], with the `method` always set to `GET`.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -256,7 +260,7 @@ https.get('https://encrypted.google.com/', (res) => {
### `https.globalAgent`
-
+
Global instance of [`https.Agent`][] for all HTTPS client requests.
@@ -264,16 +268,16 @@ Global instance of [`https.Agent`][] for all HTTPS client requests.
### `https.request(url[, options][, callback])`
-
+
-* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api)
-* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Accepts all `options` from
+* `url` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api)
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) Accepts all `options` from
[`http.request()`][], with some differences in default values:
* `protocol` **Default:** `'https:'`
* `port` **Default:** `443`
* `agent` **Default:** `https.globalAgent`
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`http.ClientRequest`](/api/http#httpclientrequest)
+* Returns: [`http.ClientRequest`](/api/v19/http#httpclientrequest)
Makes a request to a secure web server.
@@ -298,7 +302,7 @@ const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
- method: 'GET'
+ method: 'GET',
};
const req = https.request(options, (res) => {
@@ -325,7 +329,7 @@ const options = {
path: '/',
method: 'GET',
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
- cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
+ cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
};
options.agent = new https.Agent(options);
@@ -344,7 +348,7 @@ const options = {
method: 'GET',
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
- agent: false
+ agent: false,
};
const req = https.request(options, (res) => {
diff --git a/content/api/v19/inspector.en.md b/content/api/v19/inspector.en.md
index 27f1cac0f3..9fe1483b7e 100644
--- a/content/api/v19/inspector.en.md
+++ b/content/api/v19/inspector.en.md
@@ -5,51 +5,55 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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');
```
### Promises API
-
+
+
+Experimental
-
+
+
+
#### `inspector.Session`
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v19/events#eventemitter)
The `inspector.Session` is used for dispatching messages to the V8 inspector
back-end and receiving message responses and notifications.
##### `new inspector.Session()`
-
+
Create a new instance of the `inspector.Session` class. The inspector session
needs to be connected through [`session.connect()`][] before the messages
@@ -57,7 +61,7 @@ can be dispatched to the inspector backend.
##### `'inspectorNotification'`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The notification message object
@@ -73,7 +77,7 @@ It is also possible to subscribe only to notifications with specific method:
##### ``;
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The notification message object
@@ -93,20 +97,20 @@ session.on('Debugger.paused', ({ params }) => {
##### `session.connect()`
-
+
Connects a session to the inspector back-end.
##### `session.connectToMainThread()`
-
+
Connects a session to the main thread inspector back-end. An exception will
be thrown if this API was not called on a Worker thread.
##### `session.disconnect()`
-
+
Immediately close the session. All pending message callbacks will be called
with an error. [`session.connect()`][] will need to be called to be able to send
@@ -115,7 +119,7 @@ enabled agents or configured breakpoints.
##### `session.post(method[, params])`
-
+
* `method` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `params` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -133,7 +137,7 @@ try {
} catch (error) {
console.error(error);
}
-// Output: { type: 'number', value: 4, description: '4' }
+// Output: { result: { type: 'number', value: 4, description: '4' } }
```
The latest version of the V8 inspector protocol is published on the
@@ -197,14 +201,14 @@ fs.closeSync(fd);
#### `inspector.Session`
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v19/events#eventemitter)
The `inspector.Session` is used for dispatching messages to the V8 inspector
back-end and receiving message responses and notifications.
##### `new inspector.Session()`
-
+
Create a new instance of the `inspector.Session` class. The inspector session
needs to be connected through [`session.connect()`][] before the messages
@@ -212,7 +216,7 @@ can be dispatched to the inspector backend.
##### `'inspectorNotification'`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The notification message object
@@ -228,7 +232,7 @@ It is also possible to subscribe only to notifications with specific method:
##### ``;
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The notification message object
@@ -248,20 +252,20 @@ session.on('Debugger.paused', ({ params }) => {
##### `session.connect()`
-
+
Connects a session to the inspector back-end.
##### `session.connectToMainThread()`
-
+
Connects a session to the main thread inspector back-end. An exception will
be thrown if this API was not called on a Worker thread.
##### `session.disconnect()`
-
+
Immediately close the session. All pending message callbacks will be called
with an error. [`session.connect()`][] will need to be called to be able to send
@@ -270,7 +274,7 @@ enabled agents or configured breakpoints.
##### `session.post(method[, params][, callback])`
-
+
* `method` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `params` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -294,6 +298,10 @@ 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.
+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
@@ -352,7 +360,7 @@ session.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => {
#### `inspector.close()`
-
+
Deactivate the inspector. Blocks until there are no active connections.
@@ -409,7 +417,7 @@ undefined
#### `inspector.waitForDebugger()`
-
+
Blocks until a client (existing or connected later) has sent
`Runtime.runIfWaitingForDebugger` command.
diff --git a/content/api/v19/intl.en.md b/content/api/v19/intl.en.md
index a6d9785233..430821cf94 100644
--- a/content/api/v19/intl.en.md
+++ b/content/api/v19/intl.en.md
@@ -5,9 +5,9 @@ category: 'api'
version: 'v19'
---
-
+
-
+
Node.js has many features that make it easier to write internationalized
programs. Some of them are:
diff --git a/content/api/v19/module.en.md b/content/api/v19/module.en.md
index 2680c90ee0..0eb966aa49 100644
--- a/content/api/v19/module.en.md
+++ b/content/api/v19/module.en.md
@@ -5,9 +5,9 @@ category: 'api'
version: 'v19'
---
-
+
-
+
### The `Module` object
@@ -19,7 +19,7 @@ via `import 'node:module'` or `require('node:module')`.
#### `module.builtinModules`
-
+
* string\[]
@@ -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;
@@ -43,12 +41,12 @@ const builtin = require('node:module').builtinModules;
#### `module.createRequire(filename)`
-
+
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) Filename to be used to construct the require
+* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/v19/url#the-whatwg-url-api) Filename to be used to construct the require
function. Must be a file URL object, file URL string, or absolute path
string.
-* Returns: [`require`](/api/modules#requireid) Require function
+* Returns: [`require`](/api/v19/modules#requireid) Require function
```mjs
import { createRequire } from 'node:module';
@@ -60,7 +58,7 @@ const siblingModule = require('./sibling-module');
#### `module.isBuiltin(moduleName)`
-
+
* `moduleName` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) name of the module
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) returns true if the module is builtin else returns false
@@ -74,7 +72,7 @@ isBuiltin('wss'); // false
#### `module.syncBuiltinESMExports()`
-
+
The `module.syncBuiltinESMExports()` method updates all the live bindings for
builtin [ES Modules][] to match the properties of the [CommonJS][] exports. It
@@ -111,9 +109,13 @@ import('node:fs').then((esmFS) => {
### Source map v3 support
-
+
+
+
-
+Experimental
+
+
Helpers for interacting with the source map cache. This cache is
populated when source map parsing is enabled and
@@ -123,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');
@@ -139,10 +139,10 @@ const { findSourceMap, SourceMap } = require('node:module');
#### `module.findSourceMap(path)`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* Returns: [`module.SourceMap`](/api/module#modulesourcemap) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Returns `module.SourceMap` if a source
+* Returns: [`module.SourceMap`](/api/v19/module#modulesourcemap) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) Returns `module.SourceMap` if a source
map is found, `undefined` otherwise.
`path` is the resolved path for the file for which a corresponding source map
@@ -150,7 +150,7 @@ should be fetched.
#### `module.SourceMap`
-
+
##### `new SourceMap(payload)`
diff --git a/content/api/v19/modules.en.md b/content/api/v19/modules.en.md
index c508579374..ac3f129bf0 100644
--- a/content/api/v19/modules.en.md
+++ b/content/api/v19/modules.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
CommonJS modules are the original way to package JavaScript code for Node.js.
Node.js also supports the [ECMAScript modules][] standard used by browsers
@@ -74,7 +78,7 @@ The CommonJS module system is implemented in the [`module` core module][].
### Enabling
-
+
Node.js has two module systems: CommonJS modules and [ECMAScript modules][].
@@ -95,8 +99,8 @@ By default, Node.js will treat the following as CommonJS modules:
* Files with an extension that is not `.mjs`, `.cjs`, `.json`, `.node`, or `.js`
(when the nearest parent `package.json` file contains a top-level field
[`"type"`][] with a value of `"module"`, those files will be recognized as
- CommonJS modules only if they are being `require`d, not when used as the
- command-line entry point of the program).
+ CommonJS modules only if they are being included via `require()`, not when
+ used as the command-line entry point of the program).
See [Determining module system][] for more details.
@@ -105,7 +109,7 @@ always use the ECMAScript module loader.
### Accessing the main module
-
+
When a file is run directly from Node.js, `require.main` is set to its
`module`. That means that it is possible to determine whether a file has been
@@ -119,7 +123,7 @@ and the main module is out of reach.
### Package manager tips
-
+
The semantics of the Node.js `require()` function were designed to be general
enough to support reasonable directory structures. Package manager programs
@@ -182,7 +186,7 @@ regarding which files are parsed as ECMAScript modules.
### All together
-
+
To get the exact filename that will be loaded when `require()` is called, use
the `require.resolve()` function.
@@ -196,7 +200,7 @@ require(X) from module at path Y
a. return the core module
b. STOP
2. If X begins with '/'
- a. set Y to be the filesystem root
+ a. set Y to be the file system root
3. If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
@@ -277,20 +281,15 @@ LOAD_PACKAGE_SELF(X, DIR)
6. RESOLVE_ESM_MATCH(MATCH)
RESOLVE_ESM_MATCH(MATCH)
-1. let { RESOLVED, EXACT } = MATCH
-2. let RESOLVED_PATH = fileURLToPath(RESOLVED)
-3. If EXACT is true,
- a. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension
- format. STOP
-4. Otherwise, if EXACT is false,
- a. LOAD_AS_FILE(RESOLVED_PATH)
- b. LOAD_AS_DIRECTORY(RESOLVED_PATH)
-5. THROW "not found"
+1. let RESOLVED_PATH = fileURLToPath(MATCH)
+2. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension
+ format. STOP
+3. THROW "not found"
### Caching
-
+
Modules are cached after the first time they are loaded. This means (among other
things) that every call to `require('foo')` will get exactly the same object
@@ -306,7 +305,7 @@ function.
#### Module caching caveats
-
+
Modules are cached based on their resolved filename. Since modules may resolve
to a different filename based on the location of the calling module (loading
@@ -321,9 +320,9 @@ irrespective of whether or not `./foo` and `./FOO` are the same file.
### Core modules
-
+
-
+
Node.js has several modules compiled into the binary. These modules are
described in greater detail elsewhere in this documentation.
@@ -344,7 +343,7 @@ as [`module.builtinModules`][].
### Cycles
-
+
When there are circular `require()` calls, a module might not have finished
executing when it is returned.
@@ -408,7 +407,7 @@ correctly within an application.
### File modules
-
+
If the exact filename is not found, then Node.js will attempt to load the
required filename with the added extensions: `.js`, `.json`, and finally
@@ -438,9 +437,13 @@ If the given path does not exist, `require()` will throw a
### Folders as modules
-
+
+
+
-
+Legacy: Use [subpath exports][] or [subpath imports][] instead.
+
+
There are three ways in which a folder may be passed to `require()` as
an argument.
@@ -481,7 +484,7 @@ folders as modules, and work for both `require` and `import`.
### Loading from `node_modules` folders
-
+
If the module identifier passed to `require()` is not a
[core](#core-modules) module, and does not begin with `'/'`, `'../'`, or
@@ -513,7 +516,7 @@ same module resolution semantics.
### Loading from the global folders
-
+
If the `NODE_PATH` environment variable is set to a colon-delimited list
of absolute paths, then Node.js will search those paths for modules if they
@@ -547,7 +550,7 @@ folder. These will be loaded faster, and more reliably.
### The module wrapper
-
+
Before a module's code is executed, Node.js will wrap it with a function
wrapper that looks like the following:
@@ -573,9 +576,9 @@ By doing this, Node.js achieves a few things:
#### `__dirname`
-
+
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -593,9 +596,9 @@ console.log(path.dirname(__filename));
#### `__filename`
-
+
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -630,9 +633,9 @@ References to `__filename` within `b.js` will return
#### `exports`
-
+
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -642,11 +645,11 @@ See the section about the [exports shortcut][] for details on when to use
#### `module`
-
+
-
+
-* [`module`](/api/modules#the-module-object)
+* [`module`](/api/v19/modules#the-module-object)
A reference to the current module, see the section about the
[`module` object][]. In particular, `module.exports` is used for defining what
@@ -654,9 +657,9 @@ a module exports and makes available through `require()`.
#### `require(id)`
-
+
-
+
* `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) module name or path
* Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) exported module content
@@ -683,7 +686,7 @@ const crypto = require('node:crypto');
##### `require.cache`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -710,9 +713,13 @@ assert.strictEqual(require('node:fs'), realFs);
##### `require.extensions`
-
+
+
+
+
+Deprecated
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -734,9 +741,9 @@ extensions gets slower with each registered extension.
##### `require.main`
-
+
-* [`module`](/api/modules#the-module-object) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+* [`module`](/api/v19/modules#the-module-object) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
The `Module` object representing the entry script loaded when the Node.js
process launched, or `undefined` if the entry point of the program is not a
@@ -745,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
```
@@ -770,7 +775,7 @@ Module {
##### `require.resolve(request[, options])`
-
+
* `request` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The module path to resolve.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -789,7 +794,7 @@ If the module can not be found, a `MODULE_NOT_FOUND` error is thrown.
###### `require.resolve.paths(request)`
-
+
* `request` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The module path whose lookup paths are being retrieved.
* Returns: [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
@@ -800,11 +805,11 @@ Returns an array containing the paths searched during resolution of `request` or
### The `module` object
-
+
-
+
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -815,7 +820,7 @@ a global but rather local to each module.
#### `module.children`
-
+
* module\[]
@@ -823,7 +828,7 @@ The module objects required for the first time by this one.
#### `module.exports`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -876,7 +881,7 @@ console.log(x.a);
##### `exports` shortcut
-
+
The `exports` variable is available within a module's file-level scope, and is
assigned the value of `module.exports` before the module is evaluated.
@@ -921,7 +926,7 @@ function require(/* ... */) {
#### `module.filename`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -929,7 +934,7 @@ The fully resolved filename of the module.
#### `module.id`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -938,14 +943,14 @@ filename.
#### `module.isPreloading`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the module is running during the Node.js preload
phase.
#### `module.loaded`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -954,11 +959,15 @@ loading.
#### `module.parent`
-
+
+
+
+
+Deprecated: Please use [`require.main`][] and [`module.children`][] instead.
-
+
-* [`module`](/api/modules#the-module-object) | [`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)
+* [`module`](/api/v19/modules#the-module-object) | [`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)
The module that first required this one, or `null` if the current module is the
entry point of the current process, or `undefined` if the module was loaded by
@@ -966,7 +975,7 @@ something that is not a CommonJS module (E.G.: REPL or `import`).
#### `module.path`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -975,7 +984,7 @@ The directory name of the module. This is usually the same as the
#### `module.paths`
-
+
* string\[]
@@ -983,7 +992,7 @@ The search paths for the module.
#### `module.require(id)`
-
+
* `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) exported module content
diff --git a/content/api/v19/n-api.en.md b/content/api/v19/n-api.en.md
index 08eabeac71..8fbf7ee838 100644
--- a/content/api/v19/n-api.en.md
+++ b/content/api/v19/n-api.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
+
+Stable
+
+
Node-API (formerly N-API) is an API for building native Addons. It is
independent from the underlying JavaScript runtime (for example, V8) and is
@@ -50,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);
@@ -85,7 +87,8 @@ for `node-addon-api`.
The [Node-API Resource](https://nodejs.github.io/node-addon-examples/) offers
an excellent orientation and tips for developers just getting started with
-Node-API and `node-addon-api`.
+Node-API and `node-addon-api`. Additional media resources can be found on the
+[Node-API Media][] page.
### Implications of ABI stability
@@ -386,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"
@@ -487,7 +488,7 @@ is tied to the life cycle of the Agent.
#### `napi_set_instance_data`
-
+
```c
napi_status napi_set_instance_data(napi_env env,
@@ -514,7 +515,7 @@ by the previous call, it will not be called.
#### `napi_get_instance_data`
-
+
```c
napi_status napi_get_instance_data(napi_env env,
@@ -539,7 +540,7 @@ introspectable only with other Node-API calls.
#### `napi_status`
-
+
Integral status code indicating the success or failure of a Node-API call.
Currently, the following status codes are supported.
@@ -577,7 +578,7 @@ it can be obtained by calling `napi_get_last_error_info`.
#### `napi_extended_error_info`
-
+
```c
typedef struct {
@@ -618,7 +619,7 @@ This is an opaque pointer that is used to represent a JavaScript value.
#### `napi_threadsafe_function`
-
+
This is an opaque pointer that represents a JavaScript function which can be
called asynchronously from multiple threads via
@@ -626,7 +627,7 @@ called asynchronously from multiple threads via
#### `napi_threadsafe_function_release_mode`
-
+
A value to be given to `napi_release_threadsafe_function()` to indicate whether
the thread-safe function is to be closed immediately (`napi_tsfn_abort`) or
@@ -642,7 +643,7 @@ typedef enum {
#### `napi_threadsafe_function_call_mode`
-
+
A value to be given to `napi_call_threadsafe_function()` to indicate whether
the call should block whenever the queue associated with the thread-safe
@@ -678,14 +679,14 @@ For more details, review the [Object lifetime management][].
##### `napi_escapable_handle_scope`
-
+
Escapable handle scopes are a special type of handle scope to return values
created within a particular handle scope to a parent scope.
##### `napi_ref`
-
+
This is the abstraction to use to reference a `napi_value`. This allows for
users to manage the lifetimes of JavaScript values, including defining their
@@ -695,7 +696,7 @@ For more details, review the [Object lifetime management][].
##### `napi_type_tag`
-
+
A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID
with which JavaScript objects can be "tagged" in order to ensure that they are
@@ -715,7 +716,7 @@ typedef struct {
##### `napi_async_cleanup_hook_handle`
-
+
An opaque value returned by [`napi_add_async_cleanup_hook`][]. It must be passed
to [`napi_remove_async_cleanup_hook`][] when the chain of asynchronous cleanup
@@ -725,7 +726,7 @@ events completes.
##### `napi_callback_info`
-
+
Opaque datatype that is passed to a callback function. It can be used for
getting additional information about the context in which the callback was
@@ -733,7 +734,7 @@ invoked.
##### `napi_callback`
-
+
Function pointer type for user-provided native functions which are to be
exposed to JavaScript via Node-API. Callback functions should satisfy the
@@ -748,7 +749,7 @@ handle and/or callback scope inside a `napi_callback` is not necessary.
##### `napi_finalize`
-
+
Function pointer type for add-on provided functions that allow the user to be
notified when externally-owned data is ready to be cleaned up because the
@@ -768,7 +769,7 @@ handle and/or callback scope inside the function body is not necessary.
##### `napi_async_execute_callback`
-
+
Function pointer used with functions that support asynchronous
operations. Callback functions must satisfy the following signature:
@@ -784,7 +785,7 @@ it will likely result in execution of JavaScript.
##### `napi_async_complete_callback`
-
+
Function pointer used with functions that support asynchronous
operations. Callback functions must satisfy the following signature:
@@ -800,7 +801,7 @@ handle and/or callback scope inside the function body is not necessary.
##### `napi_threadsafe_function_call_js`
-
+
Function pointer used with asynchronous thread-safe function calls. The callback
will be called on the main thread. Its purpose is to use a data item arriving
@@ -842,9 +843,24 @@ typedef void (*napi_threadsafe_function_call_js)(napi_env env,
Unless for reasons discussed in [Object Lifetime Management][], creating a
handle and/or callback scope inside the function body is not necessary.
+##### `napi_cleanup_hook`
+
+
+
+Function pointer used with [`napi_add_env_cleanup_hook`][]. It will be called
+when the environment is being torn down.
+
+Callback functions must satisfy the following signature:
+
+```c
+typedef void (*napi_cleanup_hook)(void* data);
+```
+
+* `[in] data`: The data that was passed to [`napi_add_env_cleanup_hook`][].
+
##### `napi_async_cleanup_hook`
-
+
Function pointer used with [`napi_add_async_cleanup_hook`][]. It will be called
when the environment is being torn down.
@@ -898,7 +914,7 @@ In order to retrieve this information [`napi_get_last_error_info`][]
is provided which returns a `napi_extended_error_info` structure.
The format of the `napi_extended_error_info` structure is as follows:
-
+
```c
typedef struct napi_extended_error_info {
@@ -923,7 +939,7 @@ logging purposes.
##### `napi_get_last_error_info`
-
+
```c
napi_status
@@ -1035,7 +1051,7 @@ TypeError [ERR_ERROR_1]
##### `napi_throw`
-
+
```c
NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error);
@@ -1050,7 +1066,7 @@ This API throws the JavaScript value provided.
##### `napi_throw_error`
-
+
```c
NAPI_EXTERN napi_status napi_throw_error(napi_env env,
@@ -1068,7 +1084,7 @@ This API throws a JavaScript `Error` with the text provided.
##### `napi_throw_type_error`
-
+
```c
NAPI_EXTERN napi_status napi_throw_type_error(napi_env env,
@@ -1086,7 +1102,7 @@ This API throws a JavaScript `TypeError` with the text provided.
##### `napi_throw_range_error`
-
+
```c
NAPI_EXTERN napi_status napi_throw_range_error(napi_env env,
@@ -1104,9 +1120,13 @@ This API throws a JavaScript `RangeError` with the text provided.
##### `node_api_throw_syntax_error`
-
+
+
+
-
+Experimental
+
+
```c
NAPI_EXTERN napi_status node_api_throw_syntax_error(napi_env env,
@@ -1124,7 +1144,7 @@ This API throws a JavaScript `SyntaxError` with the text provided.
##### `napi_is_error`
-
+
```c
NAPI_EXTERN napi_status napi_is_error(napi_env env,
@@ -1143,7 +1163,7 @@ This API queries a `napi_value` to check if it represents an error object.
##### `napi_create_error`
-
+
```c
NAPI_EXTERN napi_status napi_create_error(napi_env env,
@@ -1165,7 +1185,7 @@ This API returns a JavaScript `Error` with the text provided.
##### `napi_create_type_error`
-
+
```c
NAPI_EXTERN napi_status napi_create_type_error(napi_env env,
@@ -1187,7 +1207,7 @@ This API returns a JavaScript `TypeError` with the text provided.
##### `napi_create_range_error`
-
+
```c
NAPI_EXTERN napi_status napi_create_range_error(napi_env env,
@@ -1209,9 +1229,13 @@ This API returns a JavaScript `RangeError` with the text provided.
##### `node_api_create_syntax_error`
-
+
+
+
-
+Experimental
+
+
```c
NAPI_EXTERN napi_status node_api_create_syntax_error(napi_env env,
@@ -1233,7 +1257,7 @@ This API returns a JavaScript `SyntaxError` with the text provided.
##### `napi_get_and_clear_last_exception`
-
+
```c
napi_status napi_get_and_clear_last_exception(napi_env env,
@@ -1249,7 +1273,7 @@ This API can be called even if there is a pending JavaScript exception.
##### `napi_is_exception_pending`
-
+
```c
napi_status napi_is_exception_pending(napi_env env, bool* result);
@@ -1264,7 +1288,7 @@ This API can be called even if there is a pending JavaScript exception.
##### `napi_fatal_exception`
-
+
```c
napi_status napi_fatal_exception(napi_env env, napi_value err);
@@ -1283,7 +1307,7 @@ thrown to immediately terminate the process.
##### `napi_fatal_error`
-
+
```c
NAPI_NO_RETURN void napi_fatal_error(const char* location,
@@ -1396,7 +1420,7 @@ can only be called once.
##### `napi_open_handle_scope`
-
+
```c
NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env,
@@ -1412,7 +1436,7 @@ This API opens a new scope.
##### `napi_close_handle_scope`
-
+
```c
NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env,
@@ -1431,7 +1455,7 @@ This API can be called even if there is a pending JavaScript exception.
##### `napi_open_escapable_handle_scope`
-
+
```c
NAPI_EXTERN napi_status
@@ -1449,7 +1473,7 @@ to the outer scope.
##### `napi_close_escapable_handle_scope`
-
+
```c
NAPI_EXTERN napi_status
@@ -1469,7 +1493,7 @@ This API can be called even if there is a pending JavaScript exception.
##### `napi_escape_handle`
-
+
```c
napi_status napi_escape_handle(napi_env env,
@@ -1541,7 +1565,7 @@ will not be freed. This can be avoided by calling
##### `napi_create_reference`
-
+
```c
NAPI_EXTERN napi_status napi_create_reference(napi_env env,
@@ -1563,7 +1587,7 @@ to the `Object` passed in.
##### `napi_delete_reference`
-
+
```c
NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref);
@@ -1580,7 +1604,7 @@ This API can be called even if there is a pending JavaScript exception.
##### `napi_reference_ref`
-
+
```c
NAPI_EXTERN napi_status napi_reference_ref(napi_env env,
@@ -1599,7 +1623,7 @@ passed in and returns the resulting reference count.
##### `napi_reference_unref`
-
+
```c
NAPI_EXTERN napi_status napi_reference_unref(napi_env env,
@@ -1618,7 +1642,7 @@ passed in and returns the resulting reference count.
##### `napi_get_reference_value`
-
+
```c
NAPI_EXTERN napi_status napi_get_reference_value(napi_env env,
@@ -1652,11 +1676,11 @@ should be freed up.
##### `napi_add_env_cleanup_hook`
-
+
```c
NODE_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env,
- void (*fun)(void* arg),
+ napi_cleanup_hook fun,
void* arg);
```
@@ -1679,7 +1703,7 @@ For asynchronous cleanup, [`napi_add_async_cleanup_hook`][] is available.
##### `napi_remove_env_cleanup_hook`
-
+
```c
NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env,
@@ -1696,7 +1720,7 @@ with `napi_add_env_cleanup_hook`, otherwise the process will abort.
##### `napi_add_async_cleanup_hook`
-
+
```c
NAPI_EXTERN napi_status napi_add_async_cleanup_hook(
@@ -1728,7 +1752,7 @@ is being torn down anyway.
##### `napi_remove_async_cleanup_hook`
-
+
```c
NAPI_EXTERN napi_status napi_remove_async_cleanup_hook(
@@ -1882,7 +1906,7 @@ the `napi_value` in question is of the JavaScript type expected by the API.
##### `napi_key_collection_mode`
-
+
```c
typedef enum {
@@ -1901,7 +1925,7 @@ of the objects's prototype chain as well.
##### `napi_key_filter`
-
+
```c
typedef enum {
@@ -1918,7 +1942,7 @@ Property filter bits. They can be or'ed to build a composite filter.
##### `napi_key_conversion`
-
+
```c
typedef enum {
@@ -1983,7 +2007,7 @@ Elements of this enum correspond to
##### `napi_create_array`
-
+
```c
napi_status napi_create_array(napi_env env, napi_value* result)
@@ -2000,7 +2024,7 @@ JavaScript arrays are described in
##### `napi_create_array_with_length`
-
+
```c
napi_status napi_create_array_with_length(napi_env env,
@@ -2027,7 +2051,7 @@ JavaScript arrays are described in
##### `napi_create_arraybuffer`
-
+
```c
napi_status napi_create_arraybuffer(napi_env env,
@@ -2059,7 +2083,7 @@ JavaScript `ArrayBuffer` objects are described in
##### `napi_create_buffer`
-
+
```c
napi_status napi_create_buffer(napi_env env,
@@ -2081,7 +2105,7 @@ fully-supported data structure, in most cases using a `TypedArray` will suffice.
##### `napi_create_buffer_copy`
-
+
```c
napi_status napi_create_buffer_copy(napi_env env,
@@ -2107,7 +2131,7 @@ structure, in most cases using a `TypedArray` will suffice.
##### `napi_create_date`
-
+
```c
napi_status napi_create_date(napi_env env,
@@ -2131,7 +2155,7 @@ JavaScript `Date` objects are described in
##### `napi_create_external`
-
+
```c
napi_status napi_create_external(napi_env env,
@@ -2156,12 +2180,7 @@ is used to pass external data through JavaScript code, so it can be retrieved
later by native code using [`napi_get_value_external`][].
The API adds a `napi_finalize` callback which will be called when the JavaScript
-object just created is ready for garbage collection. It is similar to
-`napi_wrap()` except that:
-
-* the native data cannot be retrieved later using `napi_unwrap()`,
-* nor can it be removed later using `napi_remove_wrap()`, and
-* the object created by the API can be used with `napi_wrap()`.
+object just created has been garbage collected.
The created value is not an object, and therefore does not support additional
properties. It is considered a distinct value type: calling `napi_typeof()` with
@@ -2169,7 +2188,7 @@ an external value yields `napi_external`.
##### `napi_create_external_arraybuffer`
-
+
```c
napi_status
@@ -2212,19 +2231,14 @@ managed. The caller must ensure that the byte buffer remains valid until the
finalize callback is called.
The API adds a `napi_finalize` callback which will be called when the JavaScript
-object just created is ready for garbage collection. It is similar to
-`napi_wrap()` except that:
-
-* the native data cannot be retrieved later using `napi_unwrap()`,
-* nor can it be removed later using `napi_remove_wrap()`, and
-* the object created by the API can be used with `napi_wrap()`.
+object just created has been garbage collected.
JavaScript `ArrayBuffer`s are described in
[Section 24.1][] of the ECMAScript Language Specification.
##### `napi_create_external_buffer`
-
+
```c
napi_status napi_create_external_buffer(napi_env env,
@@ -2265,18 +2279,13 @@ backed by the passed in buffer. While this is still a fully-supported data
structure, in most cases using a `TypedArray` will suffice.
The API adds a `napi_finalize` callback which will be called when the JavaScript
-object just created is ready for garbage collection. It is similar to
-`napi_wrap()` except that:
-
-* the native data cannot be retrieved later using `napi_unwrap()`,
-* nor can it be removed later using `napi_remove_wrap()`, and
-* the object created by the API can be used with `napi_wrap()`.
+object just created has been garbage collected.
For Node.js >=4 `Buffers` are `Uint8Array`s.
##### `napi_create_object`
-
+
```c
napi_status napi_create_object(napi_env env, napi_value* result)
@@ -2295,7 +2304,7 @@ ECMAScript Language Specification.
##### `napi_create_symbol`
-
+
```c
napi_status napi_create_symbol(napi_env env,
@@ -2317,9 +2326,13 @@ of the ECMAScript Language Specification.
##### `node_api_symbol_for`
-
+
-
+
+
+Experimental
+
+
```c
napi_status node_api_symbol_for(napi_env env,
@@ -2346,7 +2359,7 @@ Language Specification.
##### `napi_create_typedarray`
-
+
```c
napi_status napi_create_typedarray(napi_env env,
@@ -2381,7 +2394,7 @@ JavaScript `TypedArray` objects are described in
##### `napi_create_dataview`
-
+
```c
napi_status napi_create_dataview(napi_env env,
@@ -2415,7 +2428,7 @@ JavaScript `DataView` objects are described in
##### `napi_create_int32`
-
+
```c
napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result)
@@ -2435,7 +2448,7 @@ The JavaScript `number` type is described in
##### `napi_create_uint32`
-
+
```c
napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result)
@@ -2455,7 +2468,7 @@ The JavaScript `number` type is described in
##### `napi_create_int64`
-
+
```c
napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result)
@@ -2478,7 +2491,7 @@ outside the range of [`Number.MIN_SAFE_INTEGER`][] `-(2**53 - 1)` -
##### `napi_create_double`
-
+
```c
napi_status napi_create_double(napi_env env, double value, napi_value* result)
@@ -2498,7 +2511,7 @@ The JavaScript `number` type is described in
##### `napi_create_bigint_int64`
-
+
```c
napi_status napi_create_bigint_int64(napi_env env,
@@ -2516,7 +2529,7 @@ This API converts the C `int64_t` type to the JavaScript `BigInt` type.
##### `napi_create_bigint_uint64`
-
+
```c
napi_status napi_create_bigint_uint64(napi_env env,
@@ -2534,7 +2547,7 @@ This API converts the C `uint64_t` type to the JavaScript `BigInt` type.
##### `napi_create_bigint_words`
-
+
```c
napi_status napi_create_bigint_words(napi_env env,
@@ -2561,7 +2574,7 @@ The resulting `BigInt` is calculated as: (–1)`sign_bit` (`words[0]`
##### `napi_create_string_latin1`
-
+
```c
napi_status napi_create_string_latin1(napi_env env,
@@ -2586,7 +2599,7 @@ The JavaScript `string` type is described in
##### `napi_create_string_utf16`
-
+
```c
napi_status napi_create_string_utf16(napi_env env,
@@ -2611,7 +2624,7 @@ The JavaScript `string` type is described in
##### `napi_create_string_utf8`
-
+
```c
napi_status napi_create_string_utf8(napi_env env,
@@ -2638,7 +2651,7 @@ The JavaScript `string` type is described in
##### `napi_get_array_length`
-
+
```c
napi_status napi_get_array_length(napi_env env,
@@ -2660,7 +2673,7 @@ Specification.
##### `napi_get_arraybuffer_info`
-
+
```c
napi_status napi_get_arraybuffer_info(napi_env env,
@@ -2690,7 +2703,7 @@ trigger a GC.
##### `napi_get_buffer_info`
-
+
```c
napi_status napi_get_buffer_info(napi_env env,
@@ -2715,7 +2728,7 @@ lifetime is not guaranteed if it's managed by the VM.
##### `napi_get_prototype`
-
+
```c
napi_status napi_get_prototype(napi_env env,
@@ -2733,7 +2746,7 @@ Returns `napi_ok` if the API succeeded.
##### `napi_get_typedarray_info`
-
+
```c
napi_status napi_get_typedarray_info(napi_env env,
@@ -2772,7 +2785,7 @@ is managed by the VM.
##### `napi_get_dataview_info`
-
+
```c
napi_status napi_get_dataview_info(napi_env env,
@@ -2801,7 +2814,7 @@ This API returns various properties of a `DataView`.
##### `napi_get_date_value`
-
+
```c
napi_status napi_get_date_value(napi_env env,
@@ -2825,7 +2838,7 @@ This API returns the C double primitive of time value for the given JavaScript
##### `napi_get_value_bool`
-
+
```c
napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result)
@@ -2844,7 +2857,7 @@ This API returns the C boolean primitive equivalent of the given JavaScript
##### `napi_get_value_double`
-
+
```c
napi_status napi_get_value_double(napi_env env,
@@ -2865,7 +2878,7 @@ This API returns the C double primitive equivalent of the given JavaScript
##### `napi_get_value_bigint_int64`
-
+
```c
napi_status napi_get_value_bigint_int64(napi_env env,
@@ -2889,7 +2902,7 @@ This API returns the C `int64_t` primitive equivalent of the given JavaScript
##### `napi_get_value_bigint_uint64`
-
+
```c
napi_status napi_get_value_bigint_uint64(napi_env env,
@@ -2913,7 +2926,7 @@ This API returns the C `uint64_t` primitive equivalent of the given JavaScript
##### `napi_get_value_bigint_words`
-
+
```c
napi_status napi_get_value_bigint_words(napi_env env,
@@ -2940,7 +2953,7 @@ both set to `NULL`, in order to get only `word_count`.
##### `napi_get_value_external`
-
+
```c
napi_status napi_get_value_external(napi_env env,
@@ -2960,7 +2973,7 @@ This API retrieves the external data pointer that was previously passed to
##### `napi_get_value_int32`
-
+
```c
napi_status napi_get_value_int32(napi_env env,
@@ -2988,7 +3001,7 @@ result to zero.
##### `napi_get_value_int64`
-
+
```c
napi_status napi_get_value_int64(napi_env env,
@@ -3016,7 +3029,7 @@ result to zero.
##### `napi_get_value_string_latin1`
-
+
```c
napi_status napi_get_value_string_latin1(napi_env env,
@@ -3044,7 +3057,7 @@ in.
##### `napi_get_value_string_utf8`
-
+
```c
napi_status napi_get_value_string_utf8(napi_env env,
@@ -3071,7 +3084,7 @@ This API returns the UTF8-encoded string corresponding the value passed in.
##### `napi_get_value_string_utf16`
-
+
```c
napi_status napi_get_value_string_utf16(napi_env env,
@@ -3098,7 +3111,7 @@ This API returns the UTF16-encoded string corresponding the value passed in.
##### `napi_get_value_uint32`
-
+
```c
napi_status napi_get_value_uint32(napi_env env,
@@ -3121,7 +3134,7 @@ This API returns the C primitive equivalent of the given `napi_value` as a
##### `napi_get_boolean`
-
+
```c
napi_status napi_get_boolean(napi_env env, bool value, napi_value* result)
@@ -3139,7 +3152,7 @@ represent the given boolean value.
##### `napi_get_global`
-
+
```c
napi_status napi_get_global(napi_env env, napi_value* result)
@@ -3154,7 +3167,7 @@ This API returns the `global` object.
##### `napi_get_null`
-
+
```c
napi_status napi_get_null(napi_env env, napi_value* result)
@@ -3169,7 +3182,7 @@ This API returns the `null` object.
##### `napi_get_undefined`
-
+
```c
napi_status napi_get_undefined(napi_env env, napi_value* result)
@@ -3197,7 +3210,7 @@ These APIs support doing one of the following:
#### `napi_coerce_to_bool`
-
+
```c
napi_status napi_coerce_to_bool(napi_env env,
@@ -3216,7 +3229,7 @@ This API implements the abstract operation `ToBoolean()` as defined in
#### `napi_coerce_to_number`
-
+
```c
napi_status napi_coerce_to_number(napi_env env,
@@ -3237,7 +3250,7 @@ object.
#### `napi_coerce_to_object`
-
+
```c
napi_status napi_coerce_to_object(napi_env env,
@@ -3256,7 +3269,7 @@ This API implements the abstract operation `ToObject()` as defined in
#### `napi_coerce_to_string`
-
+
```c
napi_status napi_coerce_to_string(napi_env env,
@@ -3277,7 +3290,7 @@ object.
#### `napi_typeof`
-
+
```c
napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result)
@@ -3304,7 +3317,7 @@ If `value` has a type that is invalid, an error is returned.
#### `napi_instanceof`
-
+
```c
napi_status napi_instanceof(napi_env env,
@@ -3327,7 +3340,7 @@ defined in [Section 12.10.4][] of the ECMAScript Language Specification.
#### `napi_is_array`
-
+
```c
napi_status napi_is_array(napi_env env, napi_value value, bool* result)
@@ -3344,7 +3357,7 @@ as defined in [Section 7.2.2][] of the ECMAScript Language Specification.
#### `napi_is_arraybuffer`
-
+
```c
napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result)
@@ -3360,7 +3373,7 @@ This API checks if the `Object` passed in is an array buffer.
#### `napi_is_buffer`
-
+
```c
napi_status napi_is_buffer(napi_env env, napi_value value, bool* result)
@@ -3377,7 +3390,7 @@ This API checks if the `Object` passed in is a buffer.
#### `napi_is_date`
-
+
```c
napi_status napi_is_date(napi_env env, napi_value value, bool* result)
@@ -3394,7 +3407,7 @@ This API checks if the `Object` passed in is a date.
#### `napi_is_error`
-
+
```c
napi_status napi_is_error(napi_env env, napi_value value, bool* result)
@@ -3410,7 +3423,7 @@ This API checks if the `Object` passed in is an `Error`.
#### `napi_is_typedarray`
-
+
```c
napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result)
@@ -3426,7 +3439,7 @@ This API checks if the `Object` passed in is a typed array.
#### `napi_is_dataview`
-
+
```c
napi_status napi_is_dataview(napi_env env, napi_value value, bool* result)
@@ -3442,7 +3455,7 @@ This API checks if the `Object` passed in is a `DataView`.
#### `napi_strict_equals`
-
+
```c
napi_status napi_strict_equals(napi_env env,
@@ -3463,7 +3476,7 @@ defined in [Section 7.2.14][] of the ECMAScript Language Specification.
#### `napi_detach_arraybuffer`
-
+
```c
napi_status napi_detach_arraybuffer(napi_env env,
@@ -3486,7 +3499,7 @@ defined in [Section 24.1.1.3][] of the ECMAScript Language Specification.
#### `napi_is_detached_arraybuffer`
-
+
```c
napi_status napi_is_detached_arraybuffer(napi_env env,
@@ -3613,7 +3626,7 @@ reasons. Consider the following JavaScript:
const obj = {};
Object.defineProperties(obj, {
'foo': { value: 123, writable: true, configurable: true, enumerable: true },
- 'bar': { value: 456, writable: true, configurable: true, enumerable: true }
+ 'bar': { value: 456, writable: true, configurable: true, enumerable: true },
});
```
@@ -3650,7 +3663,7 @@ if (status != napi_ok) return status;
##### `napi_property_attributes`
-
+
```c
typedef enum {
@@ -3743,7 +3756,7 @@ typedef struct {
##### `napi_get_property_names`
-
+
```c
napi_status napi_get_property_names(napi_env env,
@@ -3766,7 +3779,7 @@ included.
##### `napi_get_all_property_names`
-
+
```c
napi_get_all_property_names(napi_env env,
@@ -3794,7 +3807,7 @@ of this object.
##### `napi_set_property`
-
+
```c
napi_status napi_set_property(napi_env env,
@@ -3814,7 +3827,7 @@ This API set a property on the `Object` passed in.
##### `napi_get_property`
-
+
```c
napi_status napi_get_property(napi_env env,
@@ -3834,7 +3847,7 @@ This API gets the requested property from the `Object` passed in.
##### `napi_has_property`
-
+
```c
napi_status napi_has_property(napi_env env,
@@ -3854,7 +3867,7 @@ This API checks if the `Object` passed in has the named property.
##### `napi_delete_property`
-
+
```c
napi_status napi_delete_property(napi_env env,
@@ -3875,7 +3888,7 @@ This API attempts to delete the `key` own property from `object`.
##### `napi_has_own_property`
-
+
```c
napi_status napi_has_own_property(napi_env env,
@@ -3897,7 +3910,7 @@ perform any conversion between data types.
##### `napi_set_named_property`
-
+
```c
napi_status napi_set_named_property(napi_env env,
@@ -3918,7 +3931,7 @@ created from the string passed in as `utf8Name`.
##### `napi_get_named_property`
-
+
```c
napi_status napi_get_named_property(napi_env env,
@@ -3939,7 +3952,7 @@ created from the string passed in as `utf8Name`.
##### `napi_has_named_property`
-
+
```c
napi_status napi_has_named_property(napi_env env,
@@ -3960,7 +3973,7 @@ created from the string passed in as `utf8Name`.
##### `napi_set_element`
-
+
```c
napi_status napi_set_element(napi_env env,
@@ -3980,7 +3993,7 @@ This API sets an element on the `Object` passed in.
##### `napi_get_element`
-
+
```c
napi_status napi_get_element(napi_env env,
@@ -4000,7 +4013,7 @@ This API gets the element at the requested index.
##### `napi_has_element`
-
+
```c
napi_status napi_has_element(napi_env env,
@@ -4021,7 +4034,7 @@ requested index.
##### `napi_delete_element`
-
+
```c
napi_status napi_delete_element(napi_env env,
@@ -4042,7 +4055,7 @@ This API attempts to delete the specified `index` from `object`.
##### `napi_define_properties`
-
+
```c
napi_status napi_define_properties(napi_env env,
@@ -4067,7 +4080,7 @@ specification).
##### `napi_object_freeze`
-
+
```c
napi_status napi_object_freeze(napi_env env,
@@ -4089,7 +4102,7 @@ ECMA-262 specification.
##### `napi_object_seal`
-
+
```c
napi_status napi_object_seal(napi_env env,
@@ -4132,7 +4145,7 @@ whenever `object` is garbage-collected by passing both `object` and the data to
#### `napi_call_function`
-
+
```c
NAPI_EXTERN napi_status napi_call_function(napi_env env,
@@ -4200,7 +4213,7 @@ if (status != napi_ok) return;
#### `napi_create_function`
-
+
```c
napi_status napi_create_function(napi_env env,
@@ -4279,7 +4292,7 @@ Language Specification.
#### `napi_get_cb_info`
-
+
```c
napi_status napi_get_cb_info(napi_env env,
@@ -4313,7 +4326,7 @@ call like the arguments and the `this` pointer from a given callback info.
#### `napi_get_new_target`
-
+
```c
napi_status napi_get_new_target(napi_env env,
@@ -4332,7 +4345,7 @@ callback is not a constructor call, the result is `NULL`.
#### `napi_new_instance`
-
+
```c
napi_status napi_new_instance(napi_env env,
@@ -4565,7 +4578,7 @@ query(napi_env env, napi_callback_info info) {
#### `napi_define_class`
-
+
```c
napi_status napi_define_class(napi_env env,
@@ -4635,7 +4648,7 @@ the JavaScript function and the data to [`napi_add_finalizer`][].
#### `napi_wrap`
-
+
```c
napi_status napi_wrap(napi_env env,
@@ -4652,7 +4665,7 @@ napi_status napi_wrap(napi_env env,
* `[in] native_object`: The native instance that will be wrapped in the
JavaScript object.
* `[in] finalize_cb`: Optional native callback that can be used to free the
- native instance when the JavaScript object is ready for garbage-collection.
+ native instance when the JavaScript object has been garbage-collected.
[`napi_finalize`][] provides more details.
* `[in] finalize_hint`: Optional contextual hint that is passed to the
finalize callback.
@@ -4696,7 +4709,7 @@ first.
#### `napi_unwrap`
-
+
```c
napi_status napi_unwrap(napi_env env,
@@ -4721,7 +4734,7 @@ then by calling `napi_unwrap()` on the wrapper object.
#### `napi_remove_wrap`
-
+
```c
napi_status napi_remove_wrap(napi_env env,
@@ -4742,7 +4755,7 @@ JavaScript object becomes garbage-collected.
#### `napi_type_tag_object`
-
+
```c
napi_status napi_type_tag_object(napi_env env,
@@ -4766,7 +4779,7 @@ If the object already has an associated type tag, this API will return
#### `napi_check_object_type_tag`
-
+
```c
napi_status napi_check_object_type_tag(napi_env env,
@@ -4790,12 +4803,12 @@ matches `type_tag`, then `result` is set to `true`.
#### `napi_add_finalizer`
-
+
```c
napi_status napi_add_finalizer(napi_env env,
napi_value js_object,
- void* native_object,
+ void* finalize_data,
napi_finalize finalize_cb,
void* finalize_hint,
napi_ref* result);
@@ -4804,10 +4817,9 @@ napi_status napi_add_finalizer(napi_env env,
* `[in] env`: The environment that the API is invoked under.
* `[in] js_object`: The JavaScript object to which the native data will be
attached.
-* `[in] native_object`: The native data that will be attached to the JavaScript
- object.
+* `[in] finalize_data`: Optional data to be passed to `finalize_cb`.
* `[in] finalize_cb`: Native callback that will be used to free the
- native data when the JavaScript object is ready for garbage-collection.
+ native data when the JavaScript object has been garbage-collected.
[`napi_finalize`][] provides more details.
* `[in] finalize_hint`: Optional contextual hint that is passed to the
finalize callback.
@@ -4816,14 +4828,9 @@ napi_status napi_add_finalizer(napi_env env,
Returns `napi_ok` if the API succeeded.
Adds a `napi_finalize` callback which will be called when the JavaScript object
-in `js_object` is ready for garbage collection. This API is similar to
-`napi_wrap()` except that:
+in `js_object` has been garbage-collected.
-* the native data cannot be retrieved later using `napi_unwrap()`,
-* nor can it be removed later using `napi_remove_wrap()`, and
-* the API can be called multiple times with different data items in order to
- attach each of them to the JavaScript object, and
-* the object manipulated by the API can be used with `napi_wrap()`.
+This API can be called multiple times on a single JavaScript object.
_Caution_: The optional returned reference (if obtained) should be deleted via
[`napi_delete_reference`][] ONLY in response to the finalize callback
@@ -4888,7 +4895,7 @@ callback invocation, even when it was cancelled.
#### `napi_create_async_work`
-
+
```c
napi_status napi_create_async_work(napi_env env,
@@ -4932,7 +4939,7 @@ the [`async_hooks` documentation][async_hooks `type`] for more information.
#### `napi_delete_async_work`
-
+
```c
napi_status napi_delete_async_work(napi_env env,
@@ -4950,7 +4957,7 @@ This API can be called even if there is a pending JavaScript exception.
#### `napi_queue_async_work`
-
+
```c
napi_status napi_queue_async_work(napi_env env,
@@ -4968,7 +4975,7 @@ with the same `napi_async_work` item or the result will be undefined.
#### `napi_cancel_async_work`
-
+
```c
napi_status napi_cancel_async_work(napi_env env,
@@ -4998,7 +5005,7 @@ the runtime.
#### `napi_async_init`
-
+
```c
napi_status napi_async_init(napi_env env,
@@ -5036,7 +5043,7 @@ the linkage between async callbacks.
#### `napi_async_destroy`
-
+
```c
napi_status napi_async_destroy(napi_env env,
@@ -5052,7 +5059,7 @@ This API can be called even if there is a pending JavaScript exception.
#### `napi_make_callback`
-
+
```c
NAPI_EXTERN napi_status napi_make_callback(napi_env env,
@@ -5100,7 +5107,7 @@ JavaScript during the callback are ran before returning back to C/C++.
#### `napi_open_callback_scope`
-
+
```c
NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env,
@@ -5127,7 +5134,7 @@ the required scope.
#### `napi_close_callback_scope`
-
+
```c
NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env,
@@ -5143,7 +5150,7 @@ This API can be called even if there is a pending JavaScript exception.
#### `napi_get_node_version`
-
+
```c
typedef struct {
@@ -5170,7 +5177,7 @@ The returned buffer is statically allocated and does not need to be freed.
#### `napi_get_version`
-
+
```c
napi_status napi_get_version(napi_env env,
@@ -5200,7 +5207,7 @@ support it:
#### `napi_adjust_external_memory`
-
+
```c
NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env,
@@ -5279,7 +5286,7 @@ deferred = NULL;
#### `napi_create_promise`
-
+
```c
napi_status napi_create_promise(napi_env env,
@@ -5299,7 +5306,7 @@ This API creates a deferred object and a JavaScript promise.
#### `napi_resolve_deferred`
-
+
```c
napi_status napi_resolve_deferred(napi_env env,
@@ -5322,7 +5329,7 @@ The deferred object is freed upon successful completion.
#### `napi_reject_deferred`
-
+
```c
napi_status napi_reject_deferred(napi_env env,
@@ -5345,7 +5352,7 @@ The deferred object is freed upon successful completion.
#### `napi_is_promise`
-
+
```c
napi_status napi_is_promise(napi_env env,
@@ -5365,7 +5372,7 @@ underlying JavaScript engine.
#### `napi_run_script`
-
+
```c
NAPI_EXTERN napi_status napi_run_script(napi_env env,
@@ -5397,7 +5404,7 @@ a specific `napi_env`.
#### `napi_get_uv_event_loop`
-
+
```c
NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env,
@@ -5533,7 +5540,7 @@ being destroyed.
#### `napi_create_threadsafe_function`
-
+
```c
NAPI_EXTERN napi_status
@@ -5576,7 +5583,7 @@ napi_create_threadsafe_function(napi_env env,
#### `napi_get_threadsafe_function_context`
-
+
```c
NAPI_EXTERN napi_status
@@ -5591,7 +5598,7 @@ This API may be called from any thread which makes use of `func`.
#### `napi_call_threadsafe_function`
-
+
```c
NAPI_EXTERN napi_status
@@ -5620,7 +5627,7 @@ This API may be called from any thread which makes use of `func`.
#### `napi_acquire_threadsafe_function`
-
+
```c
NAPI_EXTERN napi_status
@@ -5639,7 +5646,7 @@ This API may be called from any thread which will start making use of `func`.
#### `napi_release_threadsafe_function`
-
+
```c
NAPI_EXTERN napi_status
@@ -5665,7 +5672,7 @@ This API may be called from any thread which will stop making use of `func`.
#### `napi_ref_threadsafe_function`
-
+
```c
NAPI_EXTERN napi_status
@@ -5688,7 +5695,7 @@ This API may only be called from the main thread.
#### `napi_unref_threadsafe_function`
-
+
```c
NAPI_EXTERN napi_status
@@ -5708,16 +5715,18 @@ This API may only be called from the main thread.
#### `node_api_get_module_file_name`
-
+
-
+
-```c
+Experimental
+
+
+
+```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
@@ -5739,6 +5748,7 @@ the add-on's file name during loading.
[GitHub releases]: https://help.github.com/en/github/administering-a-repository/about-releases
[LLVM]: https://llvm.org
[Native Abstractions for Node.js]: https://github.com/nodejs/nan
+[Node-API Media]: https://github.com/nodejs/abi-stable-node/blob/HEAD/node-api-media.md
[Object lifetime management]: #object-lifetime-management
[Object wrap]: #object-wrap
[Section 12.10.4]: https://tc39.github.io/ecma262/#sec-instanceofoperator
diff --git a/content/api/v19/navigation.json b/content/api/v19/navigation.json
index f08717ab83..a4c27b7326 100644
--- a/content/api/v19/navigation.json
+++ b/content/api/v19/navigation.json
@@ -85,6 +85,12 @@
"type": "class",
"name": "buffer"
},
+ {
+ "slug": "/api/v19/buffer/#file",
+ "title": "File",
+ "type": "class",
+ "name": "buffer"
+ },
{
"slug": "/api/v19/buffer/#slowbuffer",
"title": "SlowBuffer",
@@ -433,6 +439,12 @@
"type": "class",
"name": "fs"
},
+ {
+ "slug": "/api/v19/fs/#fsstatfs",
+ "title": "fsStatFs",
+ "type": "class",
+ "name": "fs"
+ },
{
"slug": "/api/v19/fs/#fsstats",
"title": "fsStats",
@@ -1147,6 +1159,12 @@
"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",
@@ -1250,14 +1268,14 @@
"name": "test"
},
{
- "slug": "/api/v19/test/#tapstream",
- "title": "TapStream",
+ "slug": "/api/v19/test/#testcontext",
+ "title": "TestContext",
"type": "class",
"name": "test"
},
{
- "slug": "/api/v19/test/#testcontext",
- "title": "TestContext",
+ "slug": "/api/v19/test/#testsstream",
+ "title": "TestsStream",
"type": "class",
"name": "test"
},
@@ -1405,6 +1423,12 @@
"type": "class",
"name": "v8"
},
+ {
+ "slug": "/api/v19/v8/#v8gcprofiler",
+ "title": "v8GCProfiler",
+ "type": "class",
+ "name": "v8"
+ },
{
"slug": "/api/v19/v8/#v8serializer",
"title": "v8Serializer",
diff --git a/content/api/v19/net.en.md b/content/api/v19/net.en.md
index 92f2958761..f2573ec4ca 100644
--- a/content/api/v19/net.en.md
+++ b/content/api/v19/net.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
The `node:net` module provides an asynchronous network API for creating stream-based
TCP or [IPC][] servers ([`net.createServer()`][]) and clients
@@ -32,7 +36,7 @@ sockets on other operating systems.
[`socket.connect()`][] take a `path` parameter to identify IPC endpoints.
On Unix, the local domain is also known as the Unix domain. The path is a
-filesystem pathname. It gets truncated to an OS-dependent length of
+file system pathname. It gets truncated to an OS-dependent length of
`sizeof(sockaddr_un.sun_path) - 1`. Typical values are 107 bytes on Linux and
103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket,
it will unlink the Unix domain socket as well. For example,
@@ -40,7 +44,7 @@ it will unlink the Unix domain socket as well. For example,
[`server.close()`][] will unlink it. But if a user creates the Unix domain
socket outside of these abstractions, the user will need to remove it. The same
applies when a Node.js API creates a Unix domain socket but the program then
-crashes. In short, a Unix domain socket will be visible in the filesystem and
+crashes. In short, a Unix domain socket will be visible in the file system and
will persist until unlinked.
On Windows, the local domain is implemented using a named pipe. The path _must_
@@ -61,7 +65,7 @@ net.createServer().listen(
### `net.BlockList`
-
+
The `BlockList` object can be used with some network APIs to specify rules for
disabling inbound or outbound access to specific IP addresses, IP ranges, or
@@ -69,20 +73,20 @@ IP subnets.
#### `blockList.addAddress(address[, type])`
-
+
-* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/net#netsocketaddress) An IPv4 or IPv6 address.
+* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/v19/net#netsocketaddress) An IPv4 or IPv6 address.
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.
Adds a rule to block the given IP address.
#### `blockList.addRange(start, end[, type])`
-
+
-* `start` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/net#netsocketaddress) The starting IPv4 or IPv6 address in the
+* `start` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/v19/net#netsocketaddress) The starting IPv4 or IPv6 address in the
range.
-* `end` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/net#netsocketaddress) The ending IPv4 or IPv6 address in the range.
+* `end` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/v19/net#netsocketaddress) The ending IPv4 or IPv6 address in the range.
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.
Adds a rule to block a range of IP addresses from `start` (inclusive) to
@@ -90,9 +94,9 @@ Adds a rule to block a range of IP addresses from `start` (inclusive) to
#### `blockList.addSubnet(net, prefix[, type])`
-
+
-* `net` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/net#netsocketaddress) The network IPv4 or IPv6 address.
+* `net` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/v19/net#netsocketaddress) The network IPv4 or IPv6 address.
* `prefix` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of CIDR prefix bits. For IPv4, this
must be a value between `0` and `32`. For IPv6, this must be between
`0` and `128`.
@@ -102,9 +106,9 @@ Adds a rule to block a range of IP addresses specified as a subnet mask.
#### `blockList.check(address[, type])`
-
+
-* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/net#netsocketaddress) The IP address to check
+* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`net.SocketAddress`](/api/v19/net#netsocketaddress) The IP address to check
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Either `'ipv4'` or `'ipv6'`. **Default:** `'ipv4'`.
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -128,7 +132,7 @@ console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true
#### `blockList.rules`
-
+
* Type: string\[]
@@ -136,11 +140,11 @@ The list of rules added to the blocklist.
### `net.SocketAddress`
-
+
#### `new net.SocketAddress([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `address` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The network address as either an IPv4 or IPv6 string.
@@ -153,33 +157,33 @@ The list of rules added to the blocklist.
#### `socketaddress.address`
-
+
* Type [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
#### `socketaddress.family`
-
+
* Type [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Either `'ipv4'` or `'ipv6'`.
#### `socketaddress.flowlabel`
-
+
* Type [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
#### `socketaddress.port`
-
+
* Type [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
### `net.Server`
-
+
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v19/events#eventemitter)
This class is used to create a TCP or [IPC][] server.
@@ -189,29 +193,29 @@ This class is used to create a TCP or [IPC][] server.
[`net.createServer([options][, connectionListener])`][`net.createServer()`].
* `connectionListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Automatically set as a listener for the
[`'connection'`][] event.
-* Returns: [`net.Server`](/api/net#netserver)
+* Returns: [`net.Server`](/api/v19/net#netserver)
`net.Server` is an [`EventEmitter`][] with the following events:
#### `'close'`
-
+
Emitted when the server closes. If connections exist, this
event is not emitted until all connections are ended.
#### `'connection'`
-
+
-* [`net.Socket`](/api/net#netsocket) The connection object
+* [`net.Socket`](/api/v19/net#netsocket) The connection object
Emitted when a new connection is made. `socket` is an instance of
`net.Socket`.
#### `'error'`
-
+
* [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -222,13 +226,13 @@ event will **not** be emitted directly following this event unless
#### `'listening'`
-
+
Emitted when the server has been bound after calling [`server.listen()`][].
#### `'drop'`
-
+
When the number of connections reaches the threshold of `server.maxConnections`,
the server will drop new connections and emit `'drop'` event instead. If it is a
@@ -244,7 +248,7 @@ TCP server, the argument is as follows, otherwise the argument is `undefined`.
#### `server.address()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`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)
@@ -275,10 +279,10 @@ emitted or after calling `server.close()`.
#### `server.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called when the server is closed.
-* Returns: [`net.Server`](/api/net#netserver)
+* Returns: [`net.Server`](/api/v19/net#netserver)
Stops the server from accepting new connections and keeps existing
connections. This function is asynchronous, the server is finally closed
@@ -289,10 +293,10 @@ was not open when it was closed.
#### `server.getConnections(callback)`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`net.Server`](/api/net#netserver)
+* Returns: [`net.Server`](/api/v19/net#netserver)
Asynchronously get the number of concurrent connections on the server. Works
when sockets were sent to forks.
@@ -337,7 +341,7 @@ after a certain amount of time:
```js
server.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
- console.log('Address in use, retrying...');
+ console.error('Address in use, retrying...');
setTimeout(() => {
server.close();
server.listen(PORT, HOST);
@@ -348,12 +352,12 @@ server.on('error', (e) => {
##### `server.listen(handle[, backlog][, callback])`
-
+
* `handle` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `backlog` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Common parameter of [`server.listen()`][] functions
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`net.Server`](/api/net#netserver)
+* Returns: [`net.Server`](/api/v19/net#netserver)
Start a server listening for connections on a given `handle` that has
already been bound to a port, a Unix domain socket, or a Windows named pipe.
@@ -366,7 +370,7 @@ Listening on a file descriptor is not supported on Windows.
##### `server.listen(options[, callback])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Required. Supports the following properties:
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -383,10 +387,10 @@ Listening on a file descriptor is not supported on Windows.
* `ipv6Only` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) For TCP servers, setting `ipv6Only` to `true` will
disable dual-stack support, i.e., binding to host `::` won't make
`0.0.0.0` be bound. **Default:** `false`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An AbortSignal that may be used to close a listening server.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) An AbortSignal that may be used to close a listening server.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
functions.
-* Returns: [`net.Server`](/api/net#netserver)
+* Returns: [`net.Server`](/api/v19/net#netserver)
If `port` is specified, it behaves the same as
[`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port)`].
@@ -404,7 +408,7 @@ shown below.
server.listen({
host: 'localhost',
port: 80,
- exclusive: true
+ exclusive: true,
});
```
@@ -424,7 +428,7 @@ const controller = new AbortController();
server.listen({
host: 'localhost',
port: 80,
- signal: controller.signal
+ signal: controller.signal,
});
// Later, when you want to close the server.
controller.abort();
@@ -432,25 +436,25 @@ controller.abort();
##### `server.listen(path[, backlog][, callback])`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Path the server should listen to. See
[Identifying paths for IPC connections][].
* `backlog` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Common parameter of [`server.listen()`][] functions.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function).
-* Returns: [`net.Server`](/api/net#netserver)
+* Returns: [`net.Server`](/api/v19/net#netserver)
Start an [IPC][] server listening for connections on the given `path`.
##### `server.listen([port[, host[, backlog]]][, callback])`
-
+
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `backlog` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Common parameter of [`server.listen()`][] functions.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function).
-* Returns: [`net.Server`](/api/net#netserver)
+* Returns: [`net.Server`](/api/v19/net#netserver)
Start a TCP server listening for connections on the given `port` and `host`.
@@ -468,13 +472,13 @@ may cause the `net.Server` to also listen on the [unspecified IPv4 address][]
#### `server.listening`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Indicates whether or not the server is listening for connections.
#### `server.maxConnections`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -486,9 +490,9 @@ with [`child_process.fork()`][].
#### `server.ref()`
-
+
-* Returns: [`net.Server`](/api/net#netserver)
+* Returns: [`net.Server`](/api/v19/net#netserver)
Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will
_not_ let the program exit if it's the only server left (the default behavior).
@@ -496,9 +500,9 @@ If the server is `ref`ed calling `ref()` again will have no effect.
#### `server.unref()`
-
+
-* Returns: [`net.Server`](/api/net#netserver)
+* Returns: [`net.Server`](/api/v19/net#netserver)
Calling `unref()` on a server will allow the program to exit if this is the only
active server in the event system. If the server is already `unref`ed calling
@@ -506,9 +510,9 @@ active server in the event system. If the server is already `unref`ed calling
### `net.Socket`
-
+
-* Extends: [`stream.Duplex`](/api/stream#streamduplex)
+* Extends: [`stream.Duplex`](/api/v19/stream#streamduplex)
This class is an abstraction of a TCP socket or a streaming [IPC][] endpoint
(uses named pipes on Windows, and Unix domain sockets otherwise). It is also
@@ -525,7 +529,7 @@ it to interact with the client.
#### `new net.Socket([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Available options are:
* `fd` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If specified, wrap around an existing socket with
@@ -538,9 +542,9 @@ it to interact with the client.
otherwise ignored. **Default:** `false`.
* `writable` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Allow writes on the socket when an `fd` is passed,
otherwise ignored. **Default:** `false`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An Abort signal that may be used to destroy the
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) An Abort signal that may be used to destroy the
socket.
-* Returns: [`net.Socket`](/api/net#netsocket)
+* Returns: [`net.Socket`](/api/v19/net#netsocket)
Creates a new socket object.
@@ -549,7 +553,7 @@ endpoint, depending on what it [`connect()`][`socket.connect()`] to.
#### `'close'`
-
+
* `hadError` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the socket had a transmission error.
@@ -558,16 +562,16 @@ which says if the socket was closed due to a transmission error.
#### `'connect'`
-
+
Emitted when a socket connection is successfully established.
See [`net.createConnection()`][].
#### `'data'`
-
+
-* [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* [`Buffer`](/api/v19/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
Emitted when data is received. The argument `data` will be a `Buffer` or
`String`. Encoding of data is set by [`socket.setEncoding()`][].
@@ -577,7 +581,7 @@ emits a `'data'` event.
#### `'drain'`
-
+
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
@@ -585,7 +589,7 @@ See also: the return values of `socket.write()`.
#### `'end'`
-
+
Emitted when the other end of the socket signals the end of transmission, thus
ending the readable side of the socket.
@@ -600,7 +604,7 @@ FIN packet back).
#### `'error'`
-
+
* [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -609,7 +613,7 @@ following this event.
#### `'lookup'`
-
+
Emitted after resolving the host name but before connecting.
Not applicable to Unix sockets.
@@ -621,7 +625,7 @@ Not applicable to Unix sockets.
#### `'ready'`
-
+
Emitted when a socket is ready to be used.
@@ -629,7 +633,7 @@ Triggered immediately after `'connect'`.
#### `'timeout'`
-
+
Emitted if the socket times out from inactivity. This is only to notify that
the socket has been idle. The user must manually close the connection.
@@ -638,7 +642,7 @@ See also: [`socket.setTimeout()`][].
#### `socket.address()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -646,11 +650,27 @@ Returns the bound `address`, the address `family` name and `port` of the
socket as reported by the operating system:
`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
+#### `socket.autoSelectFamilyAttemptedAddresses`
+
+
+
+* string\[]
+
+This property is only present if the family autoselection algorithm is enabled in
+[`socket.connect(options)`][] and it is an array of the addresses that have been attempted.
+
+Each address is a string in the form of `$IP:$PORT`. If the connection was successful,
+then the last address is the one that the socket is currently connected to.
+
#### `socket.bufferSize`
-
+
+
+
-
+Deprecated: Use [`writable.writableLength`][] instead.
+
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -671,7 +691,7 @@ Users who experience large or growing `bufferSize` should attempt to
#### `socket.bytesRead`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -679,7 +699,7 @@ The amount of received bytes.
#### `socket.bytesWritten`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -696,7 +716,7 @@ Possible signatures:
for [IPC][] connections.
* [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]
for TCP connections.
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
This function is asynchronous. When the connection is established, the
[`'connect'`][] event will be emitted. If there is a problem connecting,
@@ -711,12 +731,12 @@ behavior.
##### `socket.connect(options[, connectListener])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `connectListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Common parameter of [`socket.connect()`][]
methods. Will be added as a listener for the [`'connect'`][] event once.
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Initiate a connection on a given socket. Normally this method is not needed,
the socket should be created and opened with [`net.createConnection()`][]. Use
@@ -740,6 +760,22 @@ For TCP connections, available `options` are:
**Default:** `false`.
* `keepAliveInitialDelay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) If set to a positive number, it sets the initial delay before
the first keepalive probe is sent on an idle socket.**Default:** `0`.
+* `autoSelectFamily` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type): If set to `true`, it enables a family autodetection algorithm
+ that loosely implements section 5 of [RFC 8305][].
+ The `all` option passed to lookup is set to `true` and the sockets attempts to connect to all
+ obtained IPv6 and IPv4 addresses, in sequence, until a connection is established.
+ The first returned AAAA address is tried first, then the first returned A address,
+ then the second returned AAAA address and so on.
+ Each connection attempt is given the amount of time specified by the `autoSelectFamilyAttemptTimeout`
+ option before timing out and trying the next address.
+ Ignored if the `family` option is not `0` or if `localAddress` is set.
+ Connection errors are not emitted if at least one connection succeeds.
+ **Default:** initially `false`, but it can be changed at runtime using [`net.setDefaultAutoSelectFamily(value)`][]
+ or via the command line option `--enable-network-family-autoselection`.
+* `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:** initially `250`, but it can be changed at runtime using [`net.setDefaultAutoSelectFamilyAttemptTimeout(value)`][]
For [IPC][] connections, available `options` are:
@@ -755,7 +791,7 @@ For both types, available `options` include:
The socket will emit events like `'error'`, `'end'`, and `'close'`
as usual. Methods like `pause()` and `resume()` will also behave as
expected.
- * `buffer` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Either a reusable chunk of memory to
+ * `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Either a reusable chunk of memory to
use for storing incoming data or a function that returns such.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) This function is called for every chunk of incoming
data. Two arguments are passed to it: the number of bytes written to
@@ -775,8 +811,8 @@ net.connect({
callback: function(nread, buf) {
// Received data is available in `buf` from 0 to `nread`.
console.log(buf.toString('utf8', 0, nread));
- }
- }
+ },
+ },
});
```
@@ -786,7 +822,7 @@ net.connect({
[Identifying paths for IPC connections][].
* `connectListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Common parameter of [`socket.connect()`][]
methods. Will be added as a listener for the [`'connect'`][] event once.
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Initiate an [IPC][] connection on the given socket.
@@ -796,13 +832,13 @@ called with `{ path: path }` as `options`.
##### `socket.connect(port[, host][, connectListener])`
-
+
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Port the client should connect to.
* `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Host the client should connect to.
* `connectListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Common parameter of [`socket.connect()`][]
methods. Will be added as a listener for the [`'connect'`][] event once.
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Initiate a TCP connection on the given socket.
@@ -812,7 +848,7 @@ called with `{port: port, host: host}` as `options`.
#### `socket.connecting`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -826,10 +862,10 @@ callback is a listener for the `'connect'` event.
#### `socket.destroy([error])`
-
+
* `error` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
-* Returns: [`net.Socket`](/api/net#netsocket)
+* Returns: [`net.Socket`](/api/v19/net#netsocket)
Ensures that no more I/O activity happens on this socket.
Destroys the stream and closes the connection.
@@ -843,14 +879,22 @@ 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])`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Only used when data is `string`. **Default:** `'utf8'`.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Optional callback for when the socket is finished.
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Half-closes the socket. i.e., it sends a FIN packet. It is possible the
server will still send some data.
@@ -859,7 +903,7 @@ See [`writable.end()`][] for further details.
#### `socket.localAddress`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -870,7 +914,7 @@ connects on `'192.168.1.1'`, the value of `socket.localAddress` would be
#### `socket.localPort`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -878,7 +922,7 @@ The numeric representation of the local port. For example, `80` or `21`.
#### `socket.localFamily`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -886,14 +930,14 @@ The string representation of the local IP family. `'IPv4'` or `'IPv6'`.
#### `socket.pause()`
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Pauses the reading of data. That is, [`'data'`][] events will not be emitted.
Useful to throttle back an upload.
#### `socket.pending`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -903,9 +947,9 @@ has not yet been called or because it is still in the process of connecting
#### `socket.ref()`
-
+
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will
_not_ let the program exit if it's the only socket left (the default behavior).
@@ -913,7 +957,7 @@ If the socket is `ref`ed calling `ref` again will have no effect.
#### `socket.remoteAddress`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -923,7 +967,7 @@ the socket is destroyed (for example, if the client disconnected).
#### `socket.remoteFamily`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -931,7 +975,7 @@ The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
#### `socket.remotePort`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -939,9 +983,9 @@ The numeric representation of the remote port. For example, `80` or `21`.
#### `socket.resetAndDestroy()`
-
+
-* Returns: [`net.Socket`](/api/net#netsocket)
+* Returns: [`net.Socket`](/api/v19/net#netsocket)
Close the TCP connection by sending an RST packet and destroy the stream.
If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected.
@@ -950,27 +994,27 @@ If this is not a TCP socket (for example, a pipe), calling this method will imme
#### `socket.resume()`
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Resumes reading after a call to [`socket.pause()`][].
#### `socket.setEncoding([encoding])`
-
+
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Set the encoding for the socket as a [Readable Stream][]. See
[`readable.setEncoding()`][] for more information.
#### `socket.setKeepAlive([enable][, initialDelay])`
-
+
* `enable` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `false`
* `initialDelay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) **Default:** `0`
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Enable/disable keep-alive functionality, and optionally set the initial
delay before the first keepalive probe is sent on an idle socket.
@@ -989,10 +1033,10 @@ Enabling the keep-alive functionality will set the following socket options:
#### `socket.setNoDelay([noDelay])`
-
+
* `noDelay` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) **Default:** `true`
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Enable/disable the use of Nagle's algorithm.
@@ -1007,11 +1051,11 @@ algorithm.
#### `socket.setTimeout(timeout[, callback])`
-
+
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Sets the socket to timeout after `timeout` milliseconds of inactivity on
the socket. By default `net.Socket` do not have a timeout.
@@ -1035,7 +1079,7 @@ The optional `callback` parameter will be added as a one-time listener for the
#### `socket.timeout`
-
+
* [`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)
@@ -1044,9 +1088,9 @@ It is `undefined` if a timeout has not been set.
#### `socket.unref()`
-
+
-* Returns: [`net.Socket`](/api/net#netsocket) The socket itself.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The socket itself.
Calling `unref()` on a socket will allow the program to exit if this is the only
active socket in the event system. If the socket is already `unref`ed calling
@@ -1054,9 +1098,9 @@ active socket in the event system. If the socket is already `unref`ed calling
#### `socket.write(data[, encoding][, callback])`
-
+
-* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
+* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Only used when data is `string`. **Default:** `utf8`.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1076,7 +1120,7 @@ information.
#### `socket.readyState`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1102,34 +1146,34 @@ Possible signatures:
#### `net.connect(options[, connectListener])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `connectListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`net.Socket`](/api/net#netsocket)
+* Returns: [`net.Socket`](/api/v19/net#netsocket)
Alias to
[`net.createConnection(options[, connectListener])`][`net.createConnection(options)`].
#### `net.connect(path[, connectListener])`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `connectListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`net.Socket`](/api/net#netsocket)
+* Returns: [`net.Socket`](/api/v19/net#netsocket)
Alias to
[`net.createConnection(path[, connectListener])`][`net.createConnection(path)`].
#### `net.connect(port[, host][, connectListener])`
-
+
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `connectListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`net.Socket`](/api/net#netsocket)
+* Returns: [`net.Socket`](/api/v19/net#netsocket)
Alias to
[`net.createConnection(port[, host][, connectListener])`][`net.createConnection(port, host)`].
@@ -1156,7 +1200,7 @@ The [`net.connect()`][] function is an alias to this function.
#### `net.createConnection(options[, connectListener])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Required. Will be passed to both the
[`new net.Socket([options])`][`new net.Socket(options)`] call and the
@@ -1165,7 +1209,7 @@ The [`net.connect()`][] function is an alias to this function.
* `connectListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Common parameter of the
[`net.createConnection()`][] functions. If supplied, will be added as
a listener for the [`'connect'`][] event on the returned socket once.
-* Returns: [`net.Socket`](/api/net#netsocket) The newly created socket used to start the connection.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The newly created socket used to start the connection.
For available options, see
[`new net.Socket([options])`][`new net.Socket(options)`]
@@ -1204,7 +1248,7 @@ const client = net.createConnection({ path: '/tmp/echo.sock' });
#### `net.createConnection(path[, connectListener])`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Path the socket should connect to. Will be passed to
[`socket.connect(path[, connectListener])`][`socket.connect(path)`].
@@ -1213,7 +1257,7 @@ const client = net.createConnection({ path: '/tmp/echo.sock' });
[`net.createConnection()`][] functions, an "once" listener for the
`'connect'` event on the initiating socket. Will be passed to
[`socket.connect(path[, connectListener])`][`socket.connect(path)`].
-* Returns: [`net.Socket`](/api/net#netsocket) The newly created socket used to start the connection.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The newly created socket used to start the connection.
Initiates an [IPC][] connection.
@@ -1224,7 +1268,7 @@ then returns the `net.Socket` that starts the connection.
#### `net.createConnection(port[, host][, connectListener])`
-
+
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Port the socket should connect to. Will be passed to
[`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`].
@@ -1235,7 +1279,7 @@ then returns the `net.Socket` that starts the connection.
[`net.createConnection()`][] functions, an "once" listener for the
`'connect'` event on the initiating socket. Will be passed to
[`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`].
-* Returns: [`net.Socket`](/api/net#netsocket) The newly created socket used to start the connection.
+* Returns: [`net.Socket`](/api/v19/net#netsocket) The newly created socket used to start the connection.
Initiates a TCP connection.
@@ -1246,7 +1290,7 @@ then returns the `net.Socket` that starts the connection.
### `net.createServer([options][, connectionListener])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `allowHalfOpen` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to `false`, then the socket will
@@ -1266,7 +1310,7 @@ then returns the `net.Socket` that starts the connection.
* `connectionListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Automatically set as a listener for the
[`'connection'`][] event.
-* Returns: [`net.Server`](/api/net#netserver)
+* Returns: [`net.Server`](/api/v19/net#netserver)
Creates a new TCP or [IPC][] server.
@@ -1329,9 +1373,42 @@ 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)`
-
+
* `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1350,7 +1427,7 @@ net.isIP('fhqwhgads'); // returns 0
### `net.isIPv4(input)`
-
+
* `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1367,7 +1444,7 @@ net.isIPv4('fhqwhgads'); // returns false
### `net.isIPv6(input)`
-
+
* `input` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1381,6 +1458,7 @@ net.isIPv6('fhqwhgads'); // returns false
[IPC]: #ipc-support
[Identifying paths for IPC connections]: #identifying-paths-for-ipc-connections
+[RFC 8305]: https://www.rfc-editor.org/rfc/rfc8305.txt
[Readable Stream]: /api/v19/stream#class-streamreadable
[`'close'`]: #event-close
[`'connect'`]: #event-connect
@@ -1406,6 +1484,8 @@ net.isIPv6('fhqwhgads'); // returns false
[`net.createConnection(path)`]: #netcreateconnectionpath-connectlistener
[`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 7f6abfc3d4..0eb83122d9 100644
--- a/content/api/v19/os.en.md
+++ b/content/api/v19/os.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
The `node:os` module provides operating system-related utility methods and
properties. It can be accessed using:
@@ -20,7 +24,7 @@ const os = require('node:os');
### `os.EOL`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -29,9 +33,20 @@ The operating system-specific end-of-line marker.
* `\n` on POSIX
* `\r\n` on Windows
+### `os.availableParallelism()`
+
+
+
+* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
+
+Returns an estimate of the default amount of parallelism a program should use.
+Always returns a value greater than zero.
+
+This function is a small wrapper about libuv's [`uv_available_parallelism()`][].
+
### `os.arch()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -43,7 +58,7 @@ The return value is equivalent to [`process.arch`][].
### `os.constants`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -53,7 +68,7 @@ process signals, and so on. The specific constants defined are described in
### `os.cpus()`
-
+
* Returns: Object\[]
@@ -80,8 +95,8 @@ The properties included on each object include:
nice: 0,
sys: 30340,
idle: 1070356870,
- irq: 0
- }
+ irq: 0,
+ },
},
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
@@ -91,8 +106,8 @@ The properties included on each object include:
nice: 0,
sys: 26980,
idle: 1071569080,
- irq: 0
- }
+ irq: 0,
+ },
},
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
@@ -102,8 +117,8 @@ The properties included on each object include:
nice: 0,
sys: 21750,
idle: 1070919370,
- irq: 0
- }
+ irq: 0,
+ },
},
{
model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
@@ -113,8 +128,8 @@ The properties included on each object include:
nice: 0,
sys: 19430,
idle: 1070905480,
- irq: 20
- }
+ irq: 20,
+ },
},
]
```
@@ -122,9 +137,13 @@ The properties included on each object include:
`nice` values are POSIX-only. On Windows, the `nice` values of all processors
are always 0.
+`os.cpus().length` should not be used to calculate the amount of parallelism
+available to an application. Use
+[`os.availableParallelism()`](#osavailableparallelism) for this purpose.
+
### `os.devNull`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -135,7 +154,7 @@ The platform-specific file path of the null device.
### `os.endianness()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -146,7 +165,7 @@ Possible values are `'BE'` for big endian and `'LE'` for little endian.
### `os.freemem()`
-
+
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -154,7 +173,7 @@ Returns the amount of free system memory in bytes as an integer.
### `os.getPriority([pid])`
-
+
* `pid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The process ID to retrieve scheduling priority for.
**Default:** `0`.
@@ -165,7 +184,7 @@ not provided or is `0`, the priority of the current process is returned.
### `os.homedir()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -179,7 +198,7 @@ Otherwise it uses the path to the profile directory of the current user.
### `os.hostname()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -187,7 +206,7 @@ Returns the host name of the operating system as a string.
### `os.loadavg()`
-
+
* Returns: number\[]
@@ -199,9 +218,23 @@ system and expressed as a fractional number.
The load average is a Unix-specific concept. On Windows, the return value is
always `[0, 0, 0]`.
+### `os.machine()`
+
+
+
+* Returns [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+
+Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,
+`mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`.
+
+On POSIX systems, the machine type is determined by calling
+[`uname(3)`][]. On Windows, `RtlGetVersion()` is used, and if it is not
+available, `GetVersionExW()` will be used. See
+[https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
+
### `os.networkInterfaces()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -270,7 +303,7 @@ The properties available on the assigned network address object include:
### `os.platform()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -286,7 +319,7 @@ operating system. [Android support is experimental][Android building].
### `os.release()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -298,7 +331,7 @@ On POSIX systems, the operating system release is determined by calling
### `os.setPriority([pid, ]priority)`
-
+
* `pid` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The process ID to set scheduling priority for.
**Default:** `0`.
@@ -320,7 +353,7 @@ privileges. Otherwise the set priority will be silently reduced to
### `os.tmpdir()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -329,7 +362,7 @@ string.
### `os.totalmem()`
-
+
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -337,7 +370,7 @@ Returns the total amount of system memory in bytes as an integer.
### `os.type()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -349,7 +382,7 @@ about the output of running [`uname(3)`][] on various operating systems.
### `os.uptime()`
-
+
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -357,7 +390,7 @@ Returns the system uptime in number of seconds.
### `os.userInfo([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Character encoding used to interpret resulting strings.
@@ -379,7 +412,7 @@ Throws a [`SystemError`][] if a user has no `username` or `homedir`.
### `os.version()`
-
+
* Returns [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -390,20 +423,6 @@ On POSIX systems, the operating system release is determined by calling
available, `GetVersionExW()` will be used. See
[https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
-### `os.machine()`
-
-
-
-* Returns [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-
-Returns the machine type as a string, such as `arm`, `aarch64`, `mips`,
-`mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`.
-
-On POSIX systems, the machine type is determined by calling
-[`uname(3)`][]. On Windows, `RtlGetVersion()` is used, and if it is not
-available, `GetVersionExW()` will be used. See
-[https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
-
### OS constants
The following constants are exported by `os.constants`.
@@ -412,7 +431,7 @@ Not all constants will be available on every operating system.
#### Signal constants
-
+
The following signal constants are exported by `os.constants.signals`.
@@ -1197,7 +1216,7 @@ information.
#### Priority constants
-
+
The following process scheduling constants are exported by
`os.constants.priority`.
@@ -1267,3 +1286,4 @@ The following process scheduling constants are exported by
[`process.arch`]: /api/v19/process#processarch
[`process.platform`]: /api/v19/process#processplatform
[`uname(3)`]: https://linux.die.net/man/3/uname
+[`uv_available_parallelism()`]: https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism
diff --git a/content/api/v19/packages.en.md b/content/api/v19/packages.en.md
index 85066497b1..23e48652db 100644
--- a/content/api/v19/packages.en.md
+++ b/content/api/v19/packages.en.md
@@ -5,11 +5,11 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
### Introduction
@@ -157,7 +157,7 @@ package:
#### `--input-type` flag
-
+
Strings passed in as an argument to `--eval` (or `-e`), or piped to `node` via
`STDIN`, are treated as [ES modules][] when the `--input-type=module` flag
@@ -175,7 +175,11 @@ unspecified.
### Determining package manager
-
+
+
+Experimental
+
+
While all Node.js projects are expected to be installable by all package
managers once published, their development teams are often required to use one
@@ -311,7 +315,7 @@ alongside `"exports"` pointing to the same module:
#### Subpath exports
-
+
When using the [`"exports"`][] field, custom subpaths can be defined along
with the main entry point by treating the main entry point as the
@@ -362,7 +366,7 @@ in relative and absolute import specifiers.
#### Exports sugar
-
+
If the `"."` export is the only export, the [`"exports"`][] field provides sugar
for this case being the direct [`"exports"`][] field value.
@@ -385,7 +389,7 @@ can be written:
#### Subpath imports
-
+
In addition to the [`"exports"`][] field, there is a package `"imports"` field
to create private mappings that only apply to import specifiers from within the
@@ -424,7 +428,7 @@ exports field.
#### Subpath patterns
-
+
For packages with a small number of exports or imports, we recommend
explicitly listing each exports subpath entry. But for packages that have
@@ -474,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": {
@@ -482,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
@@ -494,7 +496,7 @@ import featureX from 'es-module-package/features/x.js';
#### Conditional exports
-
+
Conditional exports provide a way to map to different paths depending on
certain conditions. They are supported for both CommonJS and ES module imports.
@@ -603,7 +605,7 @@ conditions behave analogously to nested JavaScript `if` statements.
#### Resolving user conditions
-
+
When running Node.js, custom user conditions can be added with the
`--conditions` flag:
@@ -635,6 +637,9 @@ is provided below to assist with ecosystem coordination.
the given export. _This condition should always be included first._
* `"deno"` - indicates a variation for the Deno platform.
* `"browser"` - any web browser environment.
+* `"react-native"` - will be matched by the React Native framework (all
+ platforms). _To target React Native for Web, `"browser"` should be specified
+ before this condition._
* `"development"` - can be used to define a development-only environment
entry point, for example to provide additional debugging context such as
better error messages when running in a development mode. _Must always be
@@ -661,7 +666,7 @@ course.
#### Self-referencing a package using its name
-
+
Within a package, the values defined in the package's
`package.json` [`"exports"`][] field can be referenced via the package's name.
@@ -710,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
```
@@ -830,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;
@@ -951,9 +950,9 @@ CommonJS and ES module instances of the package:
```js
// ./node_modules/pkg/index.mjs
import state from './state.cjs';
- export
- state
- ;
+ export {
+ state,
+ };
```
Even if `pkg` is used via both `require` and `import` in an application (for
@@ -1015,7 +1014,7 @@ The following fields in `package.json` files are used in Node.js:
#### `"name"`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1034,7 +1033,7 @@ The `"name"` field can be used in addition to the [`"exports"`][] field to
#### `"main"`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1060,9 +1059,13 @@ require('./path/to/directory');
#### `"packageManager"`
-
+
+
+
-
+Experimental
+
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1073,9 +1076,9 @@ require('./path/to/directory');
```
The `"packageManager"` field defines which package manager is expected to be
-used when working on the current project. It can set to any of the
+used when working on the current project. It can be set to any of the
[supported package managers][], and will ensure that your teams use the exact
-same package manager versions without having to install anything else than
+same package manager versions without having to install anything else other than
Node.js.
This field is currently experimental and needs to be opted-in; check the
@@ -1083,7 +1086,7 @@ This field is currently experimental and needs to be opted-in; check the
#### `"type"`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1098,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
```
@@ -1128,7 +1129,7 @@ as ES modules and `.cjs` files are always treated as CommonJS.
#### `"exports"`
-
+
* Type: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | string\[]
@@ -1153,7 +1154,7 @@ All paths defined in the `"exports"` must be relative file URLs starting with
#### `"imports"`
-
+
* Type: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
diff --git a/content/api/v19/path.en.md b/content/api/v19/path.en.md
index 3b3645742d..96e5242e3e 100644
--- a/content/api/v19/path.en.md
+++ b/content/api/v19/path.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
The `node:path` module provides utilities for working with file and directory
paths. It can be accessed using:
@@ -69,7 +73,7 @@ example, `path.resolve('C:\\')` can potentially return a different result than
### `path.basename(path[, suffix])`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `suffix` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) An optional suffix to remove
@@ -105,7 +109,7 @@ and is not a string.
### `path.delimiter`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -136,7 +140,7 @@ process.env.PATH.split(path.delimiter);
### `path.dirname(path)`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -154,7 +158,7 @@ A [`TypeError`][] is thrown if `path` is not a string.
### `path.extname(path)`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -189,7 +193,7 @@ A [`TypeError`][] is thrown if `path` is not a string.
### `path.format(pathObject)`
-
+
* `pathObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Any JavaScript object having the following properties:
* `dir` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -217,7 +221,7 @@ For example, on POSIX:
path.format({
root: '/ignored',
dir: '/home/user/dir',
- base: 'file.txt'
+ base: 'file.txt',
});
// Returns: '/home/user/dir/file.txt'
@@ -227,7 +231,7 @@ path.format({
path.format({
root: '/',
base: 'file.txt',
- ext: 'ignored'
+ ext: 'ignored',
});
// Returns: '/file.txt'
@@ -235,7 +239,7 @@ path.format({
path.format({
root: '/',
name: 'file',
- ext: '.txt'
+ ext: '.txt',
});
// Returns: '/file.txt'
@@ -243,7 +247,7 @@ path.format({
path.format({
root: '/',
name: 'file',
- ext: 'txt'
+ ext: 'txt',
});
// Returns: '/file.txt'
```
@@ -253,14 +257,14 @@ On Windows:
```js
path.format({
dir: 'C:\\path\\dir',
- base: 'file.txt'
+ base: 'file.txt',
});
// Returns: 'C:\\path\\dir\\file.txt'
```
### `path.isAbsolute(path)`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -294,7 +298,7 @@ A [`TypeError`][] is thrown if `path` is not a string.
### `path.join([...paths])`
-
+
* `...paths` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A sequence of path segments
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -318,7 +322,7 @@ A [`TypeError`][] is thrown if any of the path segments is not a string.
### `path.normalize(path)`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -360,7 +364,7 @@ A [`TypeError`][] is thrown if `path` is not a string.
### `path.parse(path)`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -379,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: '/',
@@ -387,9 +391,7 @@ path.parse('/home/user/dir/file.txt');
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
-```
-
-```text
+--------------
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
@@ -401,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:\\',
@@ -409,9 +411,7 @@ path.parse('C:\\path\\dir\\file.txt');
// base: 'file.txt',
// ext: '.txt',
// name: 'file' }
-```
-
-```text
+--------------
┌─────────────────────┬────────────┐
│ dir │ base │
├──────┬ ├──────┬─────┤
@@ -425,7 +425,7 @@ A [`TypeError`][] is thrown if `path` is not a string.
### `path.posix`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -436,7 +436,7 @@ The API is accessible via `require('node:path').posix` or `require('node:path/po
### `path.relative(from, to)`
-
+
* `from` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `to` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -467,7 +467,7 @@ A [`TypeError`][] is thrown if either `from` or `to` is not a string.
### `path.resolve([...paths])`
-
+
* `...paths` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A sequence of paths or path segments
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -508,7 +508,7 @@ A [`TypeError`][] is thrown if any of the arguments is not a string.
### `path.sep`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -537,7 +537,7 @@ slashes (`\`).
### `path.toNamespacedPath(path)`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -551,7 +551,7 @@ method is non-operational and always returns `path` without modifications.
### `path.win32`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
diff --git a/content/api/v19/perf_hooks.en.md b/content/api/v19/perf_hooks.en.md
index 38953f287e..99c2e5e597 100644
--- a/content/api/v19/perf_hooks.en.md
+++ b/content/api/v19/perf_hooks.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
This module provides an implementation of a subset of the W3C
[Web Performance APIs][] as well as additional APIs for
@@ -43,14 +47,14 @@ doSomeLongRunningProcess(() => {
### `perf_hooks.performance`
-
+
An object that can be used to collect performance metrics from the current
Node.js instance. It is similar to [`window.performance`][] in browsers.
#### `performance.clearMarks([name])`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -59,7 +63,7 @@ Performance Timeline. If `name` is provided, removes only the named mark.
#### `performance.clearMeasures([name])`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -68,7 +72,7 @@ Performance Timeline. If `name` is provided, removes only the named measure.
#### `performance.clearResourceTimings([name])`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -77,7 +81,7 @@ the Resource Timeline. If `name` is provided, removes only the named resource.
#### `performance.eventLoopUtilization([utilization1[, utilization2]])`
-
+
* `utilization1` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The result of a previous call to
`eventLoopUtilization()`.
@@ -136,7 +140,7 @@ are not guaranteed to reflect any correct state of the event loop.
#### `performance.getEntries()`
-
+
* Returns: PerformanceEntry\[]
@@ -147,7 +151,7 @@ performance entries of certain types or that have certain names, see
#### `performance.getEntriesByName(name[, type])`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -160,7 +164,7 @@ equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to
#### `performance.getEntriesByType(type)`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: PerformanceEntry\[]
@@ -171,7 +175,7 @@ is equal to `type`.
#### `performance.mark([name[, options]])`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -193,7 +197,7 @@ Performance Timeline manually with `performance.clearMarks`.
#### `performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode)`
-
+
* `timingInfo` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) [Fetch Timing Info][]
* `requestedUrl` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The resource url
@@ -216,7 +220,7 @@ Performance Timeline manually with `performance.clearResourceTimings`.
#### `performance.measure(name[, startMarkOrOptions[, endMark]])`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `startMarkOrOptions` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Optional.
@@ -254,9 +258,9 @@ Performance Timeline manually with `performance.clearMeasures`.
#### `performance.nodeTiming`
-
+
-* [`PerformanceNodeTiming`](/api/perf_hooks#performancenodetiming)
+* [`PerformanceNodeTiming`](/api/v19/perf_hooks#performancenodetiming)
_This property is an extension by Node.js. It is not available in Web browsers._
@@ -265,7 +269,7 @@ metrics for specific Node.js operational milestones.
#### `performance.now()`
-
+
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -274,7 +278,7 @@ the start of the current `node` process.
#### `performance.setResourceTimingBufferSize(maxSize)`
-
+
Sets the global performance resource timing buffer size to the specified number
of "resource" type performance entry objects.
@@ -283,7 +287,7 @@ By default the max buffer size is set to 250.
#### `performance.timeOrigin`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -292,11 +296,11 @@ which the current `node` process began, measured in Unix time.
#### `performance.timerify(fn[, options])`
-
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `histogram` [`RecordableHistogram`](/api/perf_hooks#recordablehistogram-extends-histogram) A histogram object created using
+ * `histogram` [`RecordableHistogram`](/api/v19/perf_hooks#recordablehistogram-extends-histogram) A histogram object created using
`perf_hooks.createHistogram()` that will record runtime durations in
nanoseconds.
@@ -309,7 +313,7 @@ event type in order for the timing details to be accessed.
```js
const {
performance,
- PerformanceObserver
+ PerformanceObserver,
} = require('node:perf_hooks');
function someFunction() {
@@ -337,14 +341,14 @@ invoked.
#### `performance.toJSON()`
-
+
An object which is JSON representation of the `performance` object. It
is similar to [`window.performance.toJSON`][] in browsers.
##### `'resourcetimingbufferfull'`
-
+
The `'resourcetimingbufferfull'` event is fired when the global performance
resource timing buffer is full. Adjust resource timing buffer size with
@@ -354,13 +358,13 @@ more entries to be added to the performance timeline buffer.
### `PerformanceEntry`
-
+
The constructor of this class is not exposed to users directly.
#### `performanceEntry.duration`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -369,7 +373,7 @@ be meaningful for all Performance Entry types.
#### `performanceEntry.entryType`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -385,7 +389,7 @@ The type of the performance entry. It may be one of:
#### `performanceEntry.name`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -393,7 +397,7 @@ The name of the performance entry.
#### `performanceEntry.startTime`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -402,15 +406,15 @@ Performance Entry.
### `PerformanceMark`
-
+
-* Extends: [`PerformanceEntry`](/api/perf_hooks#performanceentry)
+* Extends: [`PerformanceEntry`](/api/v19/perf_hooks#performanceentry)
Exposes marks created via the `Performance.mark()` method.
#### `performanceMark.detail`
-
+
* [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -418,9 +422,9 @@ Additional detail specified when creating with `Performance.mark()` method.
### `PerformanceMeasure`
-
+
-* Extends: [`PerformanceEntry`](/api/perf_hooks#performanceentry)
+* Extends: [`PerformanceEntry`](/api/v19/perf_hooks#performanceentry)
Exposes measures created via the `Performance.measure()` method.
@@ -428,7 +432,7 @@ The constructor of this class is not exposed to users directly.
#### `performanceMeasure.detail`
-
+
* [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -436,9 +440,9 @@ Additional detail specified when creating with `Performance.measure()` method.
### `PerformanceNodeEntry`
-
+
-* Extends: [`PerformanceEntry`](/api/perf_hooks#performanceentry)
+* Extends: [`PerformanceEntry`](/api/v19/perf_hooks#performanceentry)
_This class is an extension by Node.js. It is not available in Web browsers._
@@ -448,7 +452,7 @@ The constructor of this class is not exposed to users directly.
#### `performanceNodeEntry.detail`
-
+
* [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -456,9 +460,13 @@ Additional detail specific to the `entryType`.
#### `performanceNodeEntry.flags`
-
+
+
+
-
+Deprecated: Use `performanceNodeEntry.detail` instead.
+
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -476,9 +484,13 @@ The value may be one of:
#### `performanceNodeEntry.kind`
-
+
+
+
+
+Deprecated: Use `performanceNodeEntry.detail` instead.
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -604,9 +616,9 @@ same as the result of `queryxxx` or `getHostByAddr`.
### `PerformanceNodeTiming`
-
+
-* Extends: [`PerformanceEntry`](/api/perf_hooks#performanceentry)
+* Extends: [`PerformanceEntry`](/api/v19/perf_hooks#performanceentry)
_This property is an extension by Node.js. It is not available in Web browsers._
@@ -615,7 +627,7 @@ is not exposed to users.
#### `performanceNodeTiming.bootstrapComplete`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -625,7 +637,7 @@ has the value of -1.
#### `performanceNodeTiming.environment`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -634,7 +646,7 @@ initialized.
#### `performanceNodeTiming.idleTime`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -646,7 +658,7 @@ value of 0.
#### `performanceNodeTiming.loopExit`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -656,7 +668,7 @@ It can only have a value of not -1 in a handler of the [`'exit'`][] event.
#### `performanceNodeTiming.loopStart`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -666,7 +678,7 @@ main script), the property has the value of -1.
#### `performanceNodeTiming.nodeStart`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -675,7 +687,7 @@ initialized.
#### `performanceNodeTiming.v8Start`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -684,9 +696,9 @@ initialized.
### `PerformanceResourceTiming`
-
+
-* Extends: [`PerformanceEntry`](/api/perf_hooks#performanceentry)
+* Extends: [`PerformanceEntry`](/api/v19/perf_hooks#performanceentry)
Provides detailed network timing data regarding the loading of an application's
resources.
@@ -695,7 +707,7 @@ The constructor of this class is not exposed to users directly.
#### `performanceResourceTiming.workerStart`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -705,7 +717,7 @@ will always return 0.
#### `performanceResourceTiming.redirectStart`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -714,7 +726,7 @@ of the fetch which initiates the redirect.
#### `performanceResourceTiming.redirectEnd`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -723,7 +735,7 @@ receiving the last byte of the response of the last redirect.
#### `performanceResourceTiming.fetchStart`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -732,7 +744,7 @@ to fetch the resource.
#### `performanceResourceTiming.domainLookupStart`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -741,7 +753,7 @@ the domain name lookup for the resource.
#### `performanceResourceTiming.domainLookupEnd`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -750,7 +762,7 @@ after the Node.js finished the domain name lookup for the resource.
#### `performanceResourceTiming.connectStart`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -760,7 +772,7 @@ the resource.
#### `performanceResourceTiming.connectEnd`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -770,7 +782,7 @@ the resource.
#### `performanceResourceTiming.secureConnectionStart`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -779,7 +791,7 @@ before Node.js starts the handshake process to secure the current connection.
#### `performanceResourceTiming.requestStart`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -788,7 +800,7 @@ before Node.js receives the first byte of the response from the server.
#### `performanceResourceTiming.responseEnd`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -798,7 +810,7 @@ the transport connection is closed, whichever comes first.
#### `performanceResourceTiming.transferSize`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -807,7 +819,7 @@ includes the response header fields plus the response payload body.
#### `performanceResourceTiming.encodedBodySize`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -817,7 +829,7 @@ content-codings.
#### `performanceResourceTiming.decodedBodySize`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -827,20 +839,30 @@ content-codings.
#### `performanceResourceTiming.toJSON()`
-
+
Returns a `object` that is the JSON representation of the
`PerformanceResourceTiming` object
### `PerformanceObserver`
+
+
+#### `PerformanceObserver.supportedEntryTypes`
+
+
+
+* string\[]
+
+Get supported types.
+
#### `new PerformanceObserver(callback)`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
- * `list` [`PerformanceObserverEntryList`](/api/perf_hooks#performanceobserverentrylist)
- * `observer` [`PerformanceObserver`](/api/perf_hooks#perf_hooksperformanceobserver)
+ * `list` [`PerformanceObserverEntryList`](/api/v19/perf_hooks#performanceobserverentrylist)
+ * `observer` [`PerformanceObserver`](/api/v19/perf_hooks#perf_hooksperformanceobserver)
`PerformanceObserver` objects provide notifications when new
`PerformanceEntry` instances have been added to the Performance Timeline.
@@ -848,7 +870,7 @@ Returns a `object` that is the JSON representation of the
```js
const {
performance,
- PerformanceObserver
+ PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((list, observer) => {
@@ -875,33 +897,33 @@ notified about new `PerformanceEntry` instances. The callback receives a
#### `performanceObserver.disconnect()`
-
+
Disconnects the `PerformanceObserver` instance from all notifications.
#### `performanceObserver.observe(options)`
-
+
* `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) A single [`PerformanceEntry`](/api/perf_hooks#performanceentry) type. Must not be given
+ * `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A single [`PerformanceEntry`](/api/v19/perf_hooks#performanceentry) type. Must not be given
if `entryTypes` is already specified.
* `entryTypes` string\[] An array of strings identifying the types of
- [`PerformanceEntry`](/api/perf_hooks#performanceentry) instances the observer is interested in. If not
+ [`PerformanceEntry`](/api/v19/perf_hooks#performanceentry) instances the observer is interested in. If not
provided an error will be thrown.
* `buffered` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If true, the observer callback is called with a
list global `PerformanceEntry` buffered entries. If false, only
`PerformanceEntry`s created after the time point are sent to the
observer callback. **Default:** `false`.
-Subscribes the [`PerformanceObserver`](/api/perf_hooks#perf_hooksperformanceobserver) instance to notifications of new
-[`PerformanceEntry`](/api/perf_hooks#performanceentry) instances identified either by `options.entryTypes`
+Subscribes the [`PerformanceObserver`](/api/v19/perf_hooks#perf_hooksperformanceobserver) instance to notifications of new
+[`PerformanceEntry`](/api/v19/perf_hooks#performanceentry) instances identified either by `options.entryTypes`
or `options.type`:
```js
const {
performance,
- PerformanceObserver
+ PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((list, observer) => {
@@ -915,7 +937,7 @@ for (let n = 0; n < 3; n++)
### `PerformanceObserverEntryList`
-
+
The `PerformanceObserverEntryList` class is used to provide access to the
`PerformanceEntry` instances passed to a `PerformanceObserver`.
@@ -923,7 +945,7 @@ The constructor of this class is not exposed to users.
#### `performanceObserverEntryList.getEntries()`
-
+
* Returns: PerformanceEntry\[]
@@ -933,7 +955,7 @@ with respect to `performanceEntry.startTime`.
```js
const {
performance,
- PerformanceObserver
+ PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((perfObserverList, observer) => {
@@ -967,7 +989,7 @@ performance.mark('meow');
#### `performanceObserverEntryList.getEntriesByName(name[, type])`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -981,7 +1003,7 @@ equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to
```js
const {
performance,
- PerformanceObserver
+ PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((perfObserverList, observer) => {
@@ -1023,7 +1045,7 @@ performance.mark('meow');
#### `performanceObserverEntryList.getEntriesByType(type)`
-
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: PerformanceEntry\[]
@@ -1035,7 +1057,7 @@ is equal to `type`.
```js
const {
performance,
- PerformanceObserver
+ PerformanceObserver,
} = require('node:perf_hooks');
const obs = new PerformanceObserver((perfObserverList, observer) => {
@@ -1068,7 +1090,7 @@ performance.mark('meow');
### `perf_hooks.createHistogram([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `lowest` [`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) The lowest discernible value. Must be an integer
@@ -1078,18 +1100,18 @@ performance.mark('meow');
**Default:** `Number.MAX_SAFE_INTEGER`.
* `figures` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of accuracy digits. Must be a number between
`1` and `5`. **Default:** `3`.
-* Returns [`RecordableHistogram`](/api/perf_hooks#recordablehistogram-extends-histogram)
+* Returns [`RecordableHistogram`](/api/v19/perf_hooks#recordablehistogram-extends-histogram)
-Returns a [`RecordableHistogram`](/api/perf_hooks#recordablehistogram-extends-histogram).
+Returns a [`RecordableHistogram`](/api/v19/perf_hooks#recordablehistogram-extends-histogram).
### `perf_hooks.monitorEventLoopDelay([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `resolution` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The sampling rate in milliseconds. Must be greater
than zero. **Default:** `10`.
-* Returns: [`IntervalHistogram`](/api/perf_hooks#intervalhistogram-extends-histogram)
+* Returns: [`IntervalHistogram`](/api/v19/perf_hooks#intervalhistogram-extends-histogram)
_This property is an extension by Node.js. It is not available in Web browsers._
@@ -1119,11 +1141,11 @@ console.log(h.percentile(99));
### `Histogram`
-
+
#### `histogram.count`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1131,7 +1153,7 @@ The number of samples recorded by the histogram.
#### `histogram.countBigInt`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -1139,7 +1161,7 @@ The number of samples recorded by the histogram.
#### `histogram.exceeds`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1148,7 +1170,7 @@ loop delay threshold.
#### `histogram.exceedsBigInt`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -1157,7 +1179,7 @@ loop delay threshold.
#### `histogram.max`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1165,7 +1187,7 @@ The maximum recorded event loop delay.
#### `histogram.maxBigInt`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -1173,7 +1195,7 @@ The maximum recorded event loop delay.
#### `histogram.mean`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1181,7 +1203,7 @@ The mean of the recorded event loop delays.
#### `histogram.min`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1189,7 +1211,7 @@ The minimum recorded event loop delay.
#### `histogram.minBigInt`
-
+
* [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -1197,7 +1219,7 @@ The minimum recorded event loop delay.
#### `histogram.percentile(percentile)`
-
+
* `percentile` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A percentile value in the range (0, 100].
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1206,7 +1228,7 @@ Returns the value at the given percentile.
#### `histogram.percentileBigInt(percentile)`
-
+
* `percentile` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A percentile value in the range (0, 100].
* Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -1215,7 +1237,7 @@ Returns the value at the given percentile.
#### `histogram.percentiles`
-
+
* [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
@@ -1223,7 +1245,7 @@ Returns a `Map` object detailing the accumulated percentile distribution.
#### `histogram.percentilesBigInt`
-
+
* [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
@@ -1231,13 +1253,13 @@ Returns a `Map` object detailing the accumulated percentile distribution.
#### `histogram.reset()`
-
+
Resets the collected histogram data.
#### `histogram.stddev`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1249,7 +1271,7 @@ A `Histogram` that is periodically updated on a given interval.
#### `histogram.disable()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1258,7 +1280,7 @@ stopped, `false` if it was already stopped.
#### `histogram.enable()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1267,31 +1289,31 @@ started, `false` if it was already started.
#### Cloning an `IntervalHistogram`
-[`IntervalHistogram`](/api/perf_hooks#intervalhistogram-extends-histogram) instances can be cloned via [`MessagePort`](/api/worker_threads#messageport). On the receiving
-end, the histogram is cloned as a plain [`Histogram`](/api/perf_hooks#histogram) object that does not
+[`IntervalHistogram`](/api/v19/perf_hooks#intervalhistogram-extends-histogram) instances can be cloned via [`MessagePort`](/api/v19/worker_threads#messageport). On the receiving
+end, the histogram is cloned as a plain [`Histogram`](/api/v19/perf_hooks#histogram) object that does not
implement the `enable()` and `disable()` methods.
### `RecordableHistogram extends Histogram`
-
+
#### `histogram.add(other)`
-
+
-* `other` [`RecordableHistogram`](/api/perf_hooks#recordablehistogram-extends-histogram)
+* `other` [`RecordableHistogram`](/api/v19/perf_hooks#recordablehistogram-extends-histogram)
Adds the values from `other` to this histogram.
#### `histogram.record(val)`
-
+
* `val` [`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) The amount to record in the histogram.
#### `histogram.recordDelta()`
-
+
Calculates the amount of time (in nanoseconds) that has passed since the
previous call to `recordDelta()` and records that amount in the histogram.
@@ -1309,7 +1331,7 @@ to execute the callback).
const async_hooks = require('node:async_hooks');
const {
performance,
- PerformanceObserver
+ PerformanceObserver,
} = require('node:perf_hooks');
const set = new Set();
@@ -1328,7 +1350,7 @@ const hook = async_hooks.createHook({
`Timeout-${id}-Init`,
`Timeout-${id}-Destroy`);
}
- }
+ },
});
hook.enable();
@@ -1352,7 +1374,7 @@ dependencies:
'use strict';
const {
performance,
- PerformanceObserver
+ PerformanceObserver,
} = require('node:perf_hooks');
const mod = require('node:module');
diff --git a/content/api/v19/permissions.en.md b/content/api/v19/permissions.en.md
index 1cc953d8e3..89ca7ccebe 100644
--- a/content/api/v19/permissions.en.md
+++ b/content/api/v19/permissions.en.md
@@ -22,13 +22,17 @@ If you find a potential security vulnerability, please refer to our
#### Policies
-
+
-
+
-
+
-
+Experimental
+
+
+
+
Node.js contains experimental support for creating policies on loading code.
@@ -46,7 +50,7 @@ and granting read permissions to the user id running Node.js.
##### Enabling
-
+
The `--experimental-policy` flag can be used to enable features for policies
when loading modules.
@@ -391,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"
@@ -402,9 +406,7 @@ Given an import map:
}
}
}
-```
-
-```json
+--------------
{
"dependencies": true,
"scopes": {
diff --git a/content/api/v19/policy.en.md b/content/api/v19/policy.en.md
index be422e97dc..c60a378f92 100644
--- a/content/api/v19/policy.en.md
+++ b/content/api/v19/policy.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
+
+Experimental
+
+
The former Policies documentation is now at [Permissions documentation][]
diff --git a/content/api/v19/process.en.md b/content/api/v19/process.en.md
index aa87134ca9..d0c7f22685 100644
--- a/content/api/v19/process.en.md
+++ b/content/api/v19/process.en.md
@@ -5,20 +5,18 @@ category: 'api'
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');
```
@@ -28,7 +26,7 @@ The `process` object is an instance of [`EventEmitter`][].
#### `'beforeExit'`
-
+
The `'beforeExit'` event is emitted when Node.js empties its event loop and has
no additional work to schedule. Normally, the Node.js process will exit when
@@ -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) => {
@@ -85,7 +81,7 @@ console.log('This message is displayed first.');
#### `'disconnect'`
-
+
If the Node.js process is spawned with an IPC channel (see the [Child Process][]
and [Cluster][] documentation), the `'disconnect'` event will be emitted when
@@ -93,7 +89,7 @@ the IPC channel is closed.
#### `'exit'`
-
+
* `code` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -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) => {
@@ -153,11 +145,11 @@ process.on('exit', (code) => {
#### `'message'`
-
+
* `message` { Object | boolean | number | string | null } a parsed JSON object
or a serializable primitive value.
-* `sendHandle` [`net.Server`](/api/net#netserver) | [`net.Socket`](/api/net#netsocket) a [`net.Server`][] or [`net.Socket`][]
+* `sendHandle` [`net.Server`](/api/v19/net#netserver) | [`net.Socket`](/api/v19/net#netsocket) a [`net.Server`][] or [`net.Socket`][]
object, or undefined.
If the Node.js process is spawned with an IPC channel (see the [Child Process][]
@@ -175,9 +167,13 @@ See [Advanced serialization for `child_process`][] for more details.
#### `'multipleResolves'`
-
+
+
+
-
+Deprecated
+
+
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The resolution type. One of `'resolve'` or `'reject'`.
* `promise` [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) The promise that resolved or rejected more than once.
@@ -199,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) => {
@@ -226,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) => {
@@ -259,7 +253,7 @@ main().then(console.log);
#### `'rejectionHandled'`
-
+
* `promise` [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) The late handled promise.
@@ -287,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();
@@ -297,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();
@@ -319,7 +311,7 @@ most convenient for scripts).
#### `'uncaughtException'`
-
+
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The uncaught exception.
* `origin` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Indicates if the exception originates from an unhandled
@@ -340,14 +332,14 @@ 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) => {
fs.writeSync(
process.stderr.fd,
`Caught exception: ${err}\n` +
- `Exception origin: ${origin}`
+ `Exception origin: ${origin}`,
);
});
@@ -358,16 +350,14 @@ 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) => {
fs.writeSync(
process.stderr.fd,
`Caught exception: ${err}\n` +
- `Exception origin: ${origin}`
+ `Exception origin: ${origin}`,
);
});
@@ -413,7 +403,7 @@ needed.
#### `'uncaughtExceptionMonitor'`
-
+
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The uncaught exception.
* `origin` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Indicates if the exception originates from an unhandled
@@ -432,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) => {
@@ -442,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) => {
@@ -458,7 +446,7 @@ nonexistentFunc();
#### `'unhandledRejection'`
-
+
* `reason` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The object with which the promise was rejected
(typically an [`Error`][] object).
@@ -472,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) => {
@@ -483,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) => {
@@ -501,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() {
@@ -511,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() {
@@ -534,7 +518,7 @@ being emitted.
#### `'warning'`
-
+
* `warning` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Key properties of the warning are:
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the warning. **Default:** `'Warning'`.
@@ -550,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) => {
@@ -558,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) => {
@@ -615,11 +597,11 @@ The `*-deprecation` command-line flags only affect warnings that use the name
#### `'worker'`
-
+
-* `worker` [`Worker`](/api/worker_threads#worker) The [`Worker`](/api/worker_threads#worker) that was created.
+* `worker` [`Worker`](/api/v19/worker_threads#worker) The [`Worker`](/api/v19/worker_threads#worker) that was created.
-The `'worker'` event is emitted after a new [`Worker`](/api/worker_threads#worker) thread has been created.
+The `'worker'` event is emitted after a new [`Worker`](/api/v19/worker_threads#worker) thread has been created.
##### Emitting custom warnings
@@ -651,9 +633,9 @@ A few of the warning types that are most common include:
#### Signal events
-
+
-
+
Signal events will be emitted when the Node.js process receives a signal. Please
refer to signal(7) for a listing of standard POSIX signal names such as
@@ -667,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.
@@ -684,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.
@@ -751,7 +731,7 @@ but Node.js offers some emulation with [`process.kill()`][], and
### `process.abort()`
-
+
The `process.abort()` method causes the Node.js process to exit immediately and
generate a core file.
@@ -760,7 +740,7 @@ This feature is not available in [`Worker`][] threads.
### `process.allowedNodeEnvironmentFlags`
-
+
* [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
@@ -789,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) => {
@@ -798,9 +778,7 @@ allowedNodeEnvironmentFlags.forEach((flag) => {
// --abort_on_uncaught_exception
// ...
});
-```
-
-```cjs
+--------------
const { allowedNodeEnvironmentFlags } = require('node:process');
allowedNodeEnvironmentFlags.forEach((flag) => {
@@ -821,7 +799,7 @@ contain what _would have_ been allowable.
### `process.arch`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -829,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}`);
@@ -843,7 +819,7 @@ console.log(`This processor architecture is ${arch}`);
### `process.argv`
-
+
* string\[]
@@ -856,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
@@ -892,7 +866,7 @@ Would generate the output:
### `process.argv0`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -909,7 +883,7 @@ $ bash -c 'exec -a customArgv0 ./node'
### `process.channel`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -920,7 +894,7 @@ property is `undefined`.
#### `process.channel.ref()`
-
+
This method makes the IPC channel keep the event loop of the process
running if `.unref()` has been called before.
@@ -931,7 +905,7 @@ explicitly request a specific behavior.
#### `process.channel.unref()`
-
+
This method makes the IPC channel not keep the event loop of the process
running, and lets it finish even while the channel is open.
@@ -942,7 +916,7 @@ explicitly request a specific behavior.
### `process.chdir(directory)`
-
+
* `directory` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -950,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()}`);
@@ -960,9 +934,7 @@ try {
} catch (err) {
console.error(`chdir: ${err}`);
}
-```
-
-```cjs
+--------------
const { chdir, cwd } = require('node:process');
console.log(`Starting directory: ${cwd()}`);
@@ -978,7 +950,7 @@ This feature is not available in [`Worker`][] threads.
### `process.config`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1018,7 +990,7 @@ An example of the possible output looks like:
### `process.connected`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1030,9 +1002,28 @@ 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])`
-
+
* `previousValue` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A previous return value from calling
`process.cpuUsage()`
@@ -1049,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();
@@ -1061,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();
@@ -1079,20 +1068,18 @@ console.log(cpuUsage(startUsage));
### `process.cwd()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
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()}`);
@@ -1100,19 +1087,17 @@ console.log(`Current directory: ${cwd()}`);
### `process.debugPort`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
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;
@@ -1120,7 +1105,7 @@ process.debugPort = 5858;
### `process.disconnect()`
-
+
If the Node.js process is spawned with an IPC channel (see the [Child Process][]
and [Cluster][] documentation), the `process.disconnect()` method will close the
@@ -1135,11 +1120,11 @@ If the Node.js process was not spawned with an IPC channel,
### `process.dlopen(module, filename[, flags])`
-
+
* `module` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `flags` [`os.constants.dlopen`](/api/os#dlopen-constants) **Default:** `os.constants.dlopen.RTLD_LAZY`
+* `flags` [`os.constants.dlopen`](/api/v19/os#dlopen-constants) **Default:** `os.constants.dlopen.RTLD_LAZY`
The `process.dlopen()` method allows dynamically loading shared objects. It is
primarily used by `require()` to load C++ Addons, and should not be used
@@ -1159,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';
@@ -1168,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');
@@ -1182,7 +1165,7 @@ module.exports.foo();
### `process.emitWarning(warning[, options])`
-
+
* `warning` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The warning to emit.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1198,26 +1181,24 @@ 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.
emitWarning('Something happened!', {
code: 'MY_WARNING',
- detail: 'This is some additional information'
+ detail: 'This is some additional information',
});
// 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.
emitWarning('Something happened!', {
code: 'MY_WARNING',
- detail: 'This is some additional information'
+ detail: 'This is some additional information',
});
// Emits:
// (node:56338) [MY_WARNING] Warning: Something happened!
@@ -1228,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) => {
@@ -1238,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) => {
@@ -1256,7 +1235,7 @@ If `warning` is passed as an `Error` object, the `options` argument is ignored.
### `process.emitWarning(warning[, type[, code]][, ctor])`
-
+
* `warning` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The warning to emit.
* `type` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) When `warning` is a `String`, `type` is the name to use
@@ -1270,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.
@@ -1286,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.
@@ -1302,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');
@@ -1320,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) => {
@@ -1329,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) => {
@@ -1346,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.
@@ -1357,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.
@@ -1393,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() {
@@ -1406,9 +1375,7 @@ emitMyWarning();
// Emits: (node: 56339) Warning: Only warn once!
emitMyWarning();
// Emits nothing
-```
-
-```cjs
+--------------
const { emitWarning } = require('node:process');
function emitMyWarning() {
@@ -1425,7 +1392,7 @@ emitMyWarning();
### `process.env`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1460,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';
@@ -1478,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;
@@ -1487,9 +1452,7 @@ console.log(env.test);
env.test = undefined;
console.log(env.test);
// => 'undefined'
-```
-
-```cjs
+--------------
const { env } = require('node:process');
env.test = null;
@@ -1502,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;
@@ -1522,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;
@@ -1547,7 +1506,7 @@ are visible to the operating system or to native add-ons.
### `process.execArgv`
-
+
* string\[]
@@ -1579,7 +1538,7 @@ threads with this property.
### `process.execPath`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1592,7 +1551,7 @@ that started the Node.js process. Symbolic links, if any, are resolved.
### `process.exit([code])`
-
+
* `code` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The exit code. **Default:** `0`.
@@ -1604,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);
@@ -1632,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:
@@ -1640,9 +1597,7 @@ if (someConditionNotMet()) {
printUsageToStdout();
exit(1);
}
-```
-
-```cjs
+--------------
const { exit } = require('node:process');
// This is an example of what *not* to do:
@@ -1661,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
@@ -1670,9 +1625,7 @@ if (someConditionNotMet()) {
printUsageToStdout();
process.exitCode = 1;
}
-```
-
-```cjs
+--------------
const process = require('node:process');
// How to properly set the exit code while letting
@@ -1692,7 +1645,7 @@ than the current process.
### `process.exitCode`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1705,9 +1658,13 @@ previous setting of `process.exitCode`.
### `process.getActiveResourcesInfo()`
-
+
+
+
-
+Experimental
+
+
* Returns: string\[]
@@ -1715,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';
@@ -1725,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');
@@ -1741,20 +1696,18 @@ console.log('After:', getActiveResourcesInfo());
### `process.getegid()`
-
+
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) {
@@ -1767,22 +1720,20 @@ Android).
### `process.geteuid()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
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) {
@@ -1795,22 +1746,20 @@ Android).
### `process.getgid()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
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) {
@@ -1823,7 +1772,7 @@ Android).
### `process.getgroups()`
-
+
* Returns: integer\[]
@@ -1831,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) {
@@ -1852,22 +1799,20 @@ Android).
### `process.getuid()`
-
+
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
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) {
@@ -1880,7 +1825,7 @@ Android).
### `process.hasUncaughtExceptionCaptureCallback()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1889,9 +1834,13 @@ Indicates whether a callback has been set using
### `process.hrtime([time])`
-
+
-
+
+
+Legacy. Use [`process.hrtime.bigint()`][] instead.
+
+
* `time` integer\[] The result of a previous call to `process.hrtime()`
* Returns: integer\[]
@@ -1913,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;
@@ -1927,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;
@@ -1947,7 +1894,7 @@ setTimeout(() => {
### `process.hrtime.bigint()`
-
+
* Returns: [`bigint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
@@ -1958,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();
@@ -1971,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();
@@ -1990,7 +1935,7 @@ setTimeout(() => {
### `process.initgroups(user, extraGroup)`
-
+
* `user` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The user name or numeric identifier.
* `extraGroup` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A group name or numeric identifier.
@@ -2002,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 ]
@@ -2010,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 ]
@@ -2028,7 +1971,7 @@ This feature is not available in [`Worker`][] threads.
### `process.kill(pid[, signal])`
-
+
* `pid` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A process ID
* `signal` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The signal to send, either as a string or number.
@@ -2049,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', () => {
@@ -2062,9 +2005,7 @@ setTimeout(() => {
}, 100);
kill(process.pid, 'SIGHUP');
-```
-
-```cjs
+--------------
const process = require('node:process');
process.on('SIGHUP', () => {
@@ -2084,9 +2025,13 @@ debugger. See [Signal Events][].
### `process.mainModule`
-
+
-
+
+
+Deprecated: Use [`require.main`][] instead.
+
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2101,7 +2046,7 @@ is no entry script.
### `process.memoryUsage()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `rss` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2113,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());
@@ -2125,9 +2070,7 @@ console.log(memoryUsage());
// external: 49879,
// arrayBuffers: 9386
// }
-```
-
-```cjs
+--------------
const { memoryUsage } = require('node:process');
console.log(memoryUsage());
@@ -2162,7 +2105,7 @@ program memory allocations.
### `process.memoryUsage.rss()`
-
+
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -2176,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());
@@ -2192,7 +2133,7 @@ console.log(memoryUsage.rss());
### `process.nextTick(callback[, ...args])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Additional arguments to pass when invoking the `callback`
@@ -2203,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');
@@ -2215,9 +2156,7 @@ console.log('scheduled');
// start
// scheduled
// nextTick callback
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
console.log('start');
@@ -2235,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) {
@@ -2250,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) {
@@ -2300,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) {
@@ -2311,9 +2248,7 @@ function definitelyAsync(arg, cb) {
fs.stat('file', cb);
}
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
function definitelyAsync(arg, cb) {
@@ -2334,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));
@@ -2344,9 +2279,7 @@ nextTick(() => console.log(1));
// 1
// 2
// 3
-```
-
-```cjs
+--------------
const { nextTick } = require('node:process');
Promise.resolve().then(() => console.log(2));
@@ -2406,7 +2339,7 @@ needed, use `queueMicrotask()`.
### `process.noDeprecation`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2418,19 +2351,17 @@ flag's behavior.
### `process.pid`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
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}`);
@@ -2438,7 +2369,7 @@ console.log(`This process is pid ${pid}`);
### `process.platform`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2455,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}`);
@@ -2473,20 +2402,18 @@ Android operating system. However, Android support in Node.js
### `process.ppid`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
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}`);
@@ -2494,7 +2421,7 @@ console.log(`The parent process is pid ${ppid}`);
### `process.release`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2540,7 +2467,7 @@ relied upon to exist.
### `process.report`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2550,7 +2477,7 @@ reports for the current process. Additional documentation is available in the
#### `process.report.compact`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2558,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}`);
@@ -2572,7 +2497,7 @@ console.log(`Reports are compact? ${report.compact}`);
#### `process.report.directory`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2580,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}`);
@@ -2594,7 +2517,7 @@ console.log(`Report directory is ${report.directory}`);
#### `process.report.filename`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -2605,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}`);
@@ -2619,7 +2540,7 @@ console.log(`Report filename is ${report.filename}`);
#### `process.report.getReport([err])`
-
+
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) A custom error used for reporting the JavaScript stack.
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2628,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();
@@ -2637,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();
@@ -2654,20 +2573,18 @@ Additional documentation is available in the [report documentation][].
#### `process.report.reportOnFatalError`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
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}`);
@@ -2675,20 +2592,18 @@ console.log(`Report on fatal error: ${report.reportOnFatalError}`);
#### `process.report.reportOnSignal`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
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}`);
@@ -2696,19 +2611,17 @@ console.log(`Report on signal: ${report.reportOnSignal}`);
#### `process.report.reportOnUncaughtException`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
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}`);
@@ -2716,20 +2629,18 @@ console.log(`Report on exception: ${report.reportOnUncaughtException}`);
#### `process.report.signal`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
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}`);
@@ -2737,7 +2648,7 @@ console.log(`Report signal: ${report.signal}`);
#### `process.report.writeReport([filename][, err])`
-
+
* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Name of the file where the report is written. This
should be a relative path, that will be appended to the directory specified in
@@ -2755,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();
@@ -2771,7 +2680,7 @@ Additional documentation is available in the [report documentation][].
### `process.resourceUsage()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) the resource usage for the current process. All of these
values come from the `uv_getrusage` call which returns
@@ -2816,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());
@@ -2841,9 +2750,7 @@ console.log(resourceUsage());
involuntaryContextSwitches: 1
}
*/
-```
-
-```cjs
+--------------
const { resourceUsage } = require('node:process');
console.log(resourceUsage());
@@ -2872,10 +2779,10 @@ console.log(resourceUsage());
### `process.send(message[, sendHandle[, options]][, callback])`
-
+
* `message` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
-* `sendHandle` [`net.Server`](/api/net#netserver) | [`net.Socket`](/api/net#netsocket)
+* `sendHandle` [`net.Server`](/api/v19/net#netserver) | [`net.Socket`](/api/v19/net#netsocket)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) used to parameterize the sending of certain types of
handles.`options` supports the following properties:
* `keepOpen` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) A value that can be used when passing instances of
@@ -2896,7 +2803,7 @@ not be the same as what is originally sent.
### `process.setegid(id)`
-
+
* `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A group name or ID
@@ -2905,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) {
@@ -2914,12 +2821,10 @@ if (process.getegid && process.setegid) {
process.setegid(501);
console.log(`New gid: ${process.getegid()}`);
} catch (err) {
- console.log(`Failed to set gid: ${err}`);
+ console.error(`Failed to set gid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getegid && process.setegid) {
@@ -2928,7 +2833,7 @@ if (process.getegid && process.setegid) {
process.setegid(501);
console.log(`New gid: ${process.getegid()}`);
} catch (err) {
- console.log(`Failed to set gid: ${err}`);
+ console.error(`Failed to set gid: ${err}`);
}
}
```
@@ -2939,7 +2844,7 @@ This feature is not available in [`Worker`][] threads.
### `process.seteuid(id)`
-
+
* `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A user name or ID
@@ -2948,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) {
@@ -2957,12 +2862,10 @@ if (process.geteuid && process.seteuid) {
process.seteuid(501);
console.log(`New uid: ${process.geteuid()}`);
} catch (err) {
- console.log(`Failed to set uid: ${err}`);
+ console.error(`Failed to set uid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.geteuid && process.seteuid) {
@@ -2971,7 +2874,7 @@ if (process.geteuid && process.seteuid) {
process.seteuid(501);
console.log(`New uid: ${process.geteuid()}`);
} catch (err) {
- console.log(`Failed to set uid: ${err}`);
+ console.error(`Failed to set uid: ${err}`);
}
}
```
@@ -2982,7 +2885,7 @@ This feature is not available in [`Worker`][] threads.
### `process.setgid(id)`
-
+
* `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The group name or ID
@@ -2991,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) {
@@ -3000,12 +2903,10 @@ if (process.getgid && process.setgid) {
process.setgid(501);
console.log(`New gid: ${process.getgid()}`);
} catch (err) {
- console.log(`Failed to set gid: ${err}`);
+ console.error(`Failed to set gid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgid && process.setgid) {
@@ -3014,7 +2915,7 @@ if (process.getgid && process.setgid) {
process.setgid(501);
console.log(`New gid: ${process.getgid()}`);
} catch (err) {
- console.log(`Failed to set gid: ${err}`);
+ console.error(`Failed to set gid: ${err}`);
}
}
```
@@ -3025,7 +2926,7 @@ This feature is not available in [`Worker`][] threads.
### `process.setgroups(groups)`
-
+
* `groups` integer\[]
@@ -3035,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) {
@@ -3043,12 +2944,10 @@ if (process.getgroups && process.setgroups) {
process.setgroups([501]);
console.log(process.getgroups()); // new groups
} catch (err) {
- console.log(`Failed to set groups: ${err}`);
+ console.error(`Failed to set groups: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getgroups && process.setgroups) {
@@ -3056,7 +2955,7 @@ if (process.getgroups && process.setgroups) {
process.setgroups([501]);
console.log(process.getgroups()); // new groups
} catch (err) {
- console.log(`Failed to set groups: ${err}`);
+ console.error(`Failed to set groups: ${err}`);
}
}
```
@@ -3067,7 +2966,7 @@ This feature is not available in [`Worker`][] threads.
### `process.setuid(id)`
-
+
* `id` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -3076,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) {
@@ -3085,12 +2984,10 @@ if (process.getuid && process.setuid) {
process.setuid(501);
console.log(`New uid: ${process.getuid()}`);
} catch (err) {
- console.log(`Failed to set uid: ${err}`);
+ console.error(`Failed to set uid: ${err}`);
}
}
-```
-
-```cjs
+--------------
const process = require('node:process');
if (process.getuid && process.setuid) {
@@ -3099,7 +2996,7 @@ if (process.getuid && process.setuid) {
process.setuid(501);
console.log(`New uid: ${process.getuid()}`);
} catch (err) {
- console.log(`Failed to set uid: ${err}`);
+ console.error(`Failed to set uid: ${err}`);
}
}
```
@@ -3110,9 +3007,13 @@ This feature is not available in [`Worker`][] threads.
### `process.setSourceMapsEnabled(val)`
-
+
+
+
+
+Experimental
-
+
* `val` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -3127,7 +3028,7 @@ enabled will be parsed and loaded.
### `process.setUncaughtExceptionCaptureCallback(fn)`
-
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
@@ -3151,7 +3052,7 @@ Using this function is mutually exclusive with using the deprecated
### `process.stderr`
-* [`Stream`](/api/stream#stream)
+* [`Stream`](/api/v19/stream#stream)
The `process.stderr` property returns a stream connected to
`stderr` (fd `2`). It is a [`net.Socket`][] (which is a [Duplex][]
@@ -3171,7 +3072,7 @@ this field does not exist.
### `process.stdin`
-* [`Stream`](/api/stream#stream)
+* [`Stream`](/api/v19/stream#stream)
The `process.stdin` property returns a stream connected to
`stdin` (fd `0`). It is a [`net.Socket`][] (which is a [Duplex][]
@@ -3198,7 +3099,7 @@ this field does not exist.
### `process.stdout`
-* [`Stream`](/api/stream#stream)
+* [`Stream`](/api/v19/stream#stream)
The `process.stdout` property returns a stream connected to
`stdout` (fd `1`). It is a [`net.Socket`][] (which is a [Duplex][]
@@ -3207,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);
@@ -3280,7 +3179,7 @@ See the [TTY][] documentation for more information.
### `process.throwDeprecation`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -3309,7 +3208,7 @@ Thrown:
### `process.title`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -3332,7 +3231,7 @@ Services Manager.
### `process.traceDeprecation`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -3344,39 +3243,41 @@ flag's behavior.
### `process.umask()`
-
+
+
+
- between threads, and is a potential security vulnerability. There is no safe,\n> cross-platform alternative API."}}} />
+Deprecated. Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential security vulnerability. There is no safe, cross-platform alternative API.
+
+
`process.umask()` returns the Node.js process's file mode creation mask. Child
processes inherit the mask from the parent process.
### `process.umask(mask)`
-
+
* `mask` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
`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;
const oldmask = umask(newmask);
console.log(
- `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`
+ `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`,
);
-```
-
-```cjs
+--------------
const { umask } = require('node:process');
const newmask = 0o022;
const oldmask = umask(newmask);
console.log(
- `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`
+ `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`,
);
```
@@ -3384,7 +3285,7 @@ In [`Worker`][] threads, `process.umask(mask)` will throw an exception.
### `process.uptime()`
-
+
* Returns: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -3396,20 +3297,18 @@ seconds.
### `process.version`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
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}`);
@@ -3421,7 +3320,7 @@ To get the version string without the prepended _v_, use
### `process.versions`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -3430,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);
@@ -3571,6 +3468,7 @@ cases:
[process_warning]: #event-warning
[report documentation]: /api/v19/report
[terminal raw mode]: /api/v19/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/v19/punycode.en.md b/content/api/v19/punycode.en.md
index dd4081ef52..840ff3b00e 100644
--- a/content/api/v19/punycode.en.md
+++ b/content/api/v19/punycode.en.md
@@ -5,13 +5,17 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
-
+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
@@ -44,7 +48,7 @@ the module must be directed to the [Punycode.js][] project.
### `punycode.decode(string)`
-
+
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -58,7 +62,7 @@ punycode.decode('--dqo34k'); // '☃-⌘'
### `punycode.encode(string)`
-
+
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -72,7 +76,7 @@ punycode.encode('☃-⌘'); // '--dqo34k'
### `punycode.toASCII(domain)`
-
+
* `domain` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -90,7 +94,7 @@ punycode.toASCII('example.com'); // 'example.com'
### `punycode.toUnicode(domain)`
-
+
* `domain` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -107,11 +111,11 @@ punycode.toUnicode('example.com'); // 'example.com'
### `punycode.ucs2`
-
+
#### `punycode.ucs2.decode(string)`
-
+
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -126,7 +130,7 @@ punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]
#### `punycode.ucs2.encode(codePoints)`
-
+
* `codePoints` integer\[]
@@ -140,7 +144,7 @@ punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'
### `punycode.version`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
diff --git a/content/api/v19/querystring.en.md b/content/api/v19/querystring.en.md
index 46fa214287..0a409cda27 100644
--- a/content/api/v19/querystring.en.md
+++ b/content/api/v19/querystring.en.md
@@ -5,13 +5,17 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
-
+
+
+
+
+
The `node:querystring` module provides utilities for parsing and formatting URL
query strings. It can be accessed using:
@@ -20,25 +24,25 @@ query strings. It can be accessed using:
const querystring = require('node:querystring');
```
-`querystring` is more performant than [`URLSearchParams`](/api/url#urlsearchparams) but is not a
-standardized API. Use [`URLSearchParams`](/api/url#urlsearchparams) when performance is not critical or
+`querystring` is more performant than [`URLSearchParams`](/api/v19/url#urlsearchparams) but is not a
+standardized API. Use [`URLSearchParams`](/api/v19/url#urlsearchparams) when performance is not critical or
when compatibility with browser code is desirable.
### `querystring.decode()`
-
+
The `querystring.decode()` function is an alias for `querystring.parse()`.
### `querystring.encode()`
-
+
The `querystring.encode()` function is an alias for `querystring.stringify()`.
### `querystring.escape(str)`
-
+
* `str` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -53,7 +57,7 @@ necessary by assigning `querystring.escape` to an alternative function.
### `querystring.parse(str[, sep[, eq[, options]]])`
-
+
* `str` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The URL query string to parse
* `sep` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The substring used to delimit key and value pairs in the
@@ -97,7 +101,7 @@ querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,
### `querystring.stringify(obj[, sep[, eq[, options]]])`
-
+
* `obj` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The object to serialize into a URL query string
* `sep` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The substring used to delimit key and value pairs in the
@@ -138,7 +142,7 @@ querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
### `querystring.unescape(str)`
-
+
* `str` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
diff --git a/content/api/v19/readline.en.md b/content/api/v19/readline.en.md
index 46517caa1c..f19cdd2974 100644
--- a/content/api/v19/readline.en.md
+++ b/content/api/v19/readline.en.md
@@ -5,39 +5,39 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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';
@@ -48,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');
@@ -72,9 +70,9 @@ received on the `input` stream.
### `InterfaceConstructor`
-
+
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v19/events#eventemitter)
Instances of the `InterfaceConstructor` class are constructed using the
`readlinePromises.createInterface()` or `readline.createInterface()` method.
@@ -85,7 +83,7 @@ and is read from, the `input` stream.
#### `'close'`
-
+
The `'close'` event is emitted when one of the following occur:
@@ -105,7 +103,7 @@ emitted.
#### `'line'`
-
+
The `'line'` event is emitted whenever the `input` stream receives an
end-of-line input (`\n`, `\r`, or `\r\n`). This usually occurs when the user
@@ -125,7 +123,7 @@ rl.on('line', (input) => {
#### `'history'`
-
+
The `'history'` event is emitted whenever the history array has changed.
@@ -146,7 +144,7 @@ rl.on('history', (history) => {
#### `'pause'`
-
+
The `'pause'` event is emitted when one of the following occur:
@@ -164,7 +162,7 @@ rl.on('pause', () => {
#### `'resume'`
-
+
The `'resume'` event is emitted whenever the `input` stream is resumed.
@@ -178,7 +176,7 @@ rl.on('resume', () => {
#### `'SIGCONT'`
-
+
The `'SIGCONT'` event is emitted when a Node.js process previously moved into
the background using Ctrl+Z (i.e. `SIGTSTP`) is then
@@ -200,7 +198,7 @@ The `'SIGCONT'` event is _not_ supported on Windows.
#### `'SIGINT'`
-
+
The `'SIGINT'` event is emitted whenever the `input` stream receives
a Ctrl+C input, known typically as `SIGINT`. If there are no
@@ -219,7 +217,7 @@ rl.on('SIGINT', () => {
#### `'SIGTSTP'`
-
+
The `'SIGTSTP'` event is emitted when the `input` stream receives
a Ctrl+Z input, typically known as `SIGTSTP`. If there are
@@ -246,7 +244,7 @@ The `'SIGTSTP'` event is _not_ supported on Windows.
#### `rl.close()`
-
+
The `rl.close()` method closes the `InterfaceConstructor` instance and
relinquishes control over the `input` and `output` streams. When called,
@@ -257,7 +255,7 @@ from being emitted by the `InterfaceConstructor` instance.
#### `rl.pause()`
-
+
The `rl.pause()` method pauses the `input` stream, allowing it to be resumed
later if necessary.
@@ -267,7 +265,7 @@ Calling `rl.pause()` does not immediately pause other events (including
#### `rl.prompt([preserveCursor])`
-
+
* `preserveCursor` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, prevents the cursor placement from
being reset to `0`.
@@ -284,13 +282,13 @@ If the `InterfaceConstructor` was created with `output` set to `null` or
#### `rl.resume()`
-
+
The `rl.resume()` method resumes the `input` stream if it has been paused.
#### `rl.setPrompt(prompt)`
-
+
* `prompt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -299,7 +297,7 @@ whenever `rl.prompt()` is called.
#### `rl.getPrompt()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) the current prompt string
@@ -307,7 +305,7 @@ The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`.
#### `rl.write(data[, key])`
-
+
* `data` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `key` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -340,7 +338,7 @@ The `rl.write()` method will write the data to the `readline` `Interface`'s
#### `rl[Symbol.asyncIterator]()`
-
+
* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
@@ -376,7 +374,7 @@ asynchronous iteration may result in missed lines.
#### `rl.line`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -400,7 +398,7 @@ const rl = readline.createInterface(process.stdin);
const showResults = debounce(() => {
console.log(
'\n',
- values.filter((val) => val.startsWith(rl.line)).join(' ')
+ values.filter((val) => val.startsWith(rl.line)).join(' '),
);
}, 300);
process.stdin.on('keypress', (c, k) => {
@@ -410,7 +408,7 @@ process.stdin.on('keypress', (c, k) => {
#### `rl.cursor`
-
+
* [`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)
@@ -423,7 +421,7 @@ as well as the column where the terminal caret will be rendered.
#### `rl.getCursorPos()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `rows` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the row of the prompt the cursor currently lands on
@@ -435,15 +433,19 @@ line prompts are included in the calculations.
### Promises API
-
+
+
+
-
+Experimental
+
+
#### `readlinePromises.Interface`
-
+
-* Extends: [`readline.InterfaceConstructor`](/api/readline#interfaceconstructor)
+* Extends: [`readline.InterfaceConstructor`](/api/v19/readline#interfaceconstructor)
Instances of the `readlinePromises.Interface` class are constructed using the
`readlinePromises.createInterface()` method. Every instance is associated with a
@@ -453,12 +455,12 @@ and is read from, the `input` stream.
##### `rl.question(query[, options])`
-
+
* `query` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A statement or query to write to `output`, prepended to the
prompt.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Optionally allows the `question()` to be canceled
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Optionally allows the `question()` to be canceled
using an `AbortSignal`.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) A promise that is fulfilled with the user's
input in response to the `query`.
@@ -497,19 +499,19 @@ console.log(`Oh, so your favorite food is ${answer}`);
#### `readlinePromises.Readline`
-
+
##### `new readlinePromises.Readline(stream[, options])`
-
+
-* `stream` [`stream.Writable`](/api/stream#streamwritable) A [TTY][] stream.
+* `stream` [`stream.Writable`](/api/v19/stream#streamwritable) A [TTY][] stream.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `autoCommit` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, no need to call `rl.commit()`.
##### `rl.clearLine(dir)`
-
+
* `dir` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `-1`: to the left from cursor
@@ -525,7 +527,7 @@ was passed to the constructor.
##### `rl.clearScreenDown()`
-
+
* Returns: this
@@ -537,7 +539,7 @@ was passed to the constructor.
##### `rl.commit()`
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
@@ -546,7 +548,7 @@ The `rl.commit()` method sends all the pending actions to the associated
##### `rl.cursorTo(x[, y])`
-
+
* `x` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `y` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -559,7 +561,7 @@ was passed to the constructor.
##### `rl.moveCursor(dx, dy)`
-
+
* `dx` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `dy` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -573,7 +575,7 @@ was passed to the constructor.
##### `rl.rollback()`
-
+
* Returns: this
@@ -582,12 +584,12 @@ sending it to the associated `stream`.
#### `readlinePromises.createInterface(options)`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `input` [`stream.Readable`](/api/stream#streamreadable) The [Readable][] stream to listen to. This option
+ * `input` [`stream.Readable`](/api/v19/stream#streamreadable) The [Readable][] stream to listen to. This option
is _required_.
- * `output` [`stream.Writable`](/api/stream#streamwritable) The [Writable][] stream to write readline data
+ * `output` [`stream.Writable`](/api/v19/stream#streamwritable) The [Writable][] stream to write readline data
to.
* `completer` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) An optional function used for Tab autocompletion.
* `terminal` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the `input` and `output` streams should be
@@ -619,7 +621,7 @@ sending it to the associated `stream`.
**Default:** `500`.
* `tabSize` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of spaces a tab is equal to (minimum 1).
**Default:** `8`.
-* Returns: [`readlinePromises.Interface`](/api/readline#readlinepromisesinterface)
+* Returns: [`readlinePromises.Interface`](/api/v19/readline#readlinepromisesinterface)
The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface`
instance.
@@ -628,7 +630,7 @@ instance.
const readlinePromises = require('node:readline/promises');
const rl = readlinePromises.createInterface({
input: process.stdin,
- output: process.stdout
+ output: process.stdout,
});
```
@@ -676,13 +678,13 @@ async function completer(linePartial) {
### Callback API
-
+
#### `readline.Interface`
-
+
-* Extends: [`readline.InterfaceConstructor`](/api/readline#interfaceconstructor)
+* Extends: [`readline.InterfaceConstructor`](/api/v19/readline#interfaceconstructor)
Instances of the `readline.Interface` class are constructed using the
`readline.createInterface()` method. Every instance is associated with a
@@ -692,12 +694,12 @@ and is read from, the `input` stream.
##### `rl.question(query[, options], callback)`
-
+
* `query` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A statement or query to write to `output`, prepended to the
prompt.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Optionally allows the `question()` to be canceled
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Optionally allows the `question()` to be canceled
using an `AbortController`.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function that is invoked with the user's
input in response to the `query`.
@@ -745,9 +747,9 @@ setTimeout(() => ac.abort(), 10000);
#### `readline.clearLine(stream, dir[, callback])`
-
+
-* `stream` [`stream.Writable`](/api/stream#streamwritable)
+* `stream` [`stream.Writable`](/api/v19/stream#streamwritable)
* `dir` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `-1`: to the left from cursor
* `1`: to the right from cursor
@@ -762,9 +764,9 @@ in a specified direction identified by `dir`.
#### `readline.clearScreenDown(stream[, callback])`
-
+
-* `stream` [`stream.Writable`](/api/stream#streamwritable)
+* `stream` [`stream.Writable`](/api/v19/stream#streamwritable)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked once the operation completes.
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `false` if `stream` wishes for the calling code to wait for
the `'drain'` event to be emitted before continuing to write additional data;
@@ -775,12 +777,12 @@ the current position of the cursor down.
#### `readline.createInterface(options)`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `input` [`stream.Readable`](/api/stream#streamreadable) The [Readable][] stream to listen to. This option
+ * `input` [`stream.Readable`](/api/v19/stream#streamreadable) The [Readable][] stream to listen to. This option
is _required_.
- * `output` [`stream.Writable`](/api/stream#streamwritable) The [Writable][] stream to write readline data
+ * `output` [`stream.Writable`](/api/v19/stream#streamwritable) The [Writable][] stream to write readline data
to.
* `completer` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) An optional function used for Tab autocompletion.
* `terminal` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the `input` and `output` streams should be
@@ -812,9 +814,9 @@ the current position of the cursor down.
**Default:** `500`.
* `tabSize` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of spaces a tab is equal to (minimum 1).
**Default:** `8`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows closing the interface using an AbortSignal.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows closing the interface using an AbortSignal.
Aborting the signal will internally call `close` on the interface.
-* Returns: [`readline.Interface`](/api/readline#readlineinterface)
+* Returns: [`readline.Interface`](/api/v19/readline#readlineinterface)
The `readline.createInterface()` method creates a new `readline.Interface`
instance.
@@ -823,7 +825,7 @@ instance.
const readline = require('node:readline');
const rl = readline.createInterface({
input: process.stdin,
- output: process.stdout
+ output: process.stdout,
});
```
@@ -875,9 +877,9 @@ function completer(linePartial, callback) {
#### `readline.cursorTo(stream, x[, y][, callback])`
-
+
-* `stream` [`stream.Writable`](/api/stream#streamwritable)
+* `stream` [`stream.Writable`](/api/v19/stream#streamwritable)
* `x` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `y` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked once the operation completes.
@@ -890,9 +892,9 @@ given [TTY][] `stream`.
#### `readline.moveCursor(stream, dx, dy[, callback])`
-
+
-* `stream` [`stream.Writable`](/api/stream#streamwritable)
+* `stream` [`stream.Writable`](/api/v19/stream#streamwritable)
* `dx` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `dy` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked once the operation completes.
@@ -905,10 +907,10 @@ position in a given [TTY][] `stream`.
### `readline.emitKeypressEvents(stream[, interface])`
-
+
-* `stream` [`stream.Readable`](/api/stream#streamreadable)
-* `interface` [`readline.InterfaceConstructor`](/api/readline#interfaceconstructor)
+* `stream` [`stream.Readable`](/api/v19/stream#streamreadable)
+* `interface` [`readline.InterfaceConstructor`](/api/v19/readline#interfaceconstructor)
The `readline.emitKeypressEvents()` method causes the given [Readable][]
stream to begin emitting `'keypress'` events corresponding to received input.
@@ -938,7 +940,7 @@ const readline = require('node:readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
- prompt: 'OHAI> '
+ prompt: 'OHAI> ',
});
rl.prompt();
@@ -974,7 +976,7 @@ async function processLineByLine() {
const rl = readline.createInterface({
input: fileStream,
- crlfDelay: Infinity
+ crlfDelay: Infinity,
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
@@ -996,7 +998,7 @@ const readline = require('node:readline');
const rl = readline.createInterface({
input: fs.createReadStream('sample.txt'),
- crlfDelay: Infinity
+ crlfDelay: Infinity,
});
rl.on('line', (line) => {
@@ -1016,7 +1018,7 @@ const { createInterface } = require('node:readline');
try {
const rl = createInterface({
input: createReadStream('big-file.txt'),
- crlfDelay: Infinity
+ crlfDelay: Infinity,
});
rl.on('line', (line) => {
diff --git a/content/api/v19/repl.en.md b/content/api/v19/repl.en.md
index 6ad0414eb6..a95343e630 100644
--- a/content/api/v19/repl.en.md
+++ b/content/api/v19/repl.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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
@@ -137,7 +141,7 @@ const r = repl.start('> ');
Object.defineProperty(r.context, 'm', {
configurable: false,
enumerable: true,
- value: msg
+ value: msg,
});
```
@@ -154,7 +158,7 @@ global or scoped variable, the input `fs` will be evaluated on-demand as
##### Global uncaught exceptions
-
+
The REPL uses the [`domain`][] module to catch all uncaught exceptions for that
REPL session.
@@ -181,7 +185,7 @@ This use of the [`domain`][] module in the REPL has these side effects:
##### Assignment of the `_` (underscore) variable
-
+
The default evaluator will, by default, assign the result of the most recently
evaluated expression to the special variable `_` (underscore).
@@ -206,7 +210,7 @@ Explicitly setting `_error` to a value will disable this behavior.
```console
> throw new Error('foo');
-Error: foo
+Uncaught Error: foo
> _error.message
'foo'
```
@@ -219,8 +223,8 @@ Support for the `await` keyword is enabled at the top level.
> await Promise.resolve(123)
123
> await Promise.reject(new Error('REPL await'))
-Error: REPL await
- at repl:1:45
+Uncaught Error: REPL await
+ at REPL2:1:54
> const timeout = util.promisify(setTimeout);
undefined
> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);
@@ -249,7 +253,7 @@ undefined
#### Reverse-i-search
-
+
The REPL supports bi-directional reverse-i-search similar to [ZSH][]. It is
triggered with Ctrl+R to search backward
@@ -360,10 +364,10 @@ function myWriter(output) {
### `REPLServer`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) See [`repl.start()`][]
-* Extends: [`readline.Interface`](/api/readline#readlineinterface)
+* Extends: [`readline.Interface`](/api/v19/readline#readlineinterface)
Instances of `repl.REPLServer` are created using the [`repl.start()`][] method
or directly using the JavaScript `new` keyword.
@@ -379,7 +383,7 @@ const secondInstance = new repl.REPLServer(options);
#### `'exit'`
-
+
The `'exit'` event is emitted when the REPL is exited either by receiving the
`.exit` command as input, the user pressing Ctrl+C twice
@@ -397,7 +401,7 @@ replServer.on('exit', () => {
#### `'reset'`
-
+
The `'reset'` event is emitted when the REPL's context is reset. This occurs
whenever the `.clear` command is received as input _unless_ the REPL is using
@@ -441,7 +445,7 @@ Clearing context...
#### `replServer.defineCommand(keyword, cmd)`
-
+
* `keyword` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The command keyword (_without_ a leading `.` character).
* `cmd` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to invoke when the command is processed.
@@ -467,7 +471,7 @@ replServer.defineCommand('sayhello', {
this.clearBufferedCommand();
console.log(`Hello, ${name}!`);
this.displayPrompt();
- }
+ },
});
replServer.defineCommand('saybye', function saybye() {
console.log('Goodbye!');
@@ -486,7 +490,7 @@ Goodbye!
#### `replServer.displayPrompt([preserveCursor])`
-
+
* `preserveCursor` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -505,7 +509,7 @@ within the action function for commands registered using the
#### `replServer.clearBufferedCommand()`
-
+
The `replServer.clearBufferedCommand()` method clears any command that has been
buffered but not yet executed. This method is primarily intended to be
@@ -514,9 +518,13 @@ called from within the action function for commands registered using the
#### `replServer.parseREPLKeyword(keyword[, rest])`
-
+
+
+
+
+Deprecated.
-
+
* `keyword` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) the potential keyword to parse and execute
* `rest` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) any parameters to the keyword command
@@ -527,12 +535,12 @@ Returns `true` if `keyword` is a valid keyword, otherwise `false`.
#### `replServer.setupHistory(historyPath, callback)`
-
+
* `historyPath` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) the path to the history file
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) called when history writes are ready or upon error
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
- * `repl` [`repl.REPLServer`](/api/repl#replserver)
+ * `repl` [`repl.REPLServer`](/api/v19/repl#replserver)
Initializes a history log file for the REPL instance. When executing the
Node.js binary and using the command-line REPL, a history file is initialized
@@ -542,7 +550,7 @@ with REPL instances programmatically.
### `repl.builtinModules`
-
+
* string\[]
@@ -550,14 +558,14 @@ A list of the names of all Node.js modules, e.g., `'http'`.
### `repl.start([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `prompt` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The input prompt to display. **Default:** `'> '`
(with a trailing space).
- * `input` [`stream.Readable`](/api/stream#streamreadable) The `Readable` stream from which REPL input will
+ * `input` [`stream.Readable`](/api/v19/stream#streamreadable) The `Readable` stream from which REPL input will
be read. **Default:** `process.stdin`.
- * `output` [`stream.Writable`](/api/stream#streamwritable) The `Writable` stream to which REPL output will
+ * `output` [`stream.Writable`](/api/v19/stream#streamwritable) The `Writable` stream to which REPL output will
be written. **Default:** `process.stdout`.
* `terminal` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, specifies that the `output` should be
treated as a TTY terminal.
@@ -597,7 +605,7 @@ A list of the names of all Node.js modules, e.g., `'http'`.
previews or not. **Default:** `true` with the default eval function and
`false` in case a custom eval function is used. If `terminal` is falsy, then
there are no previews and the value of `preview` has no effect.
-* Returns: [`repl.REPLServer`](/api/repl#replserver)
+* Returns: [`repl.REPLServer`](/api/v19/repl#replserver)
The `repl.start()` method creates and starts a [`repl.REPLServer`][] instance.
@@ -683,7 +691,7 @@ let connections = 0;
repl.start({
prompt: 'Node.js via stdin> ',
input: process.stdin,
- output: process.stdout
+ output: process.stdout,
});
net.createServer((socket) => {
@@ -691,7 +699,7 @@ net.createServer((socket) => {
repl.start({
prompt: 'Node.js via Unix socket> ',
input: socket,
- output: socket
+ output: socket,
}).on('exit', () => {
socket.end();
});
@@ -702,7 +710,7 @@ net.createServer((socket) => {
repl.start({
prompt: 'Node.js via TCP socket> ',
input: socket,
- output: socket
+ output: socket,
}).on('exit', () => {
socket.end();
});
diff --git a/content/api/v19/report.en.md b/content/api/v19/report.en.md
index 9b86213436..817171be37 100644
--- a/content/api/v19/report.en.md
+++ b/content/api/v19/report.en.md
@@ -5,13 +5,17 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
-
+Stable
+
+
+
+
Delivers a JSON-formatted diagnostic summary, written to a file.
@@ -572,9 +576,9 @@ In cases where standard streams are used, the value in `directory` is ignored.
URLs are not supported. Defaults to a composite filename that contains
timestamp, PID, and sequence number.
-`directory` specifies the filesystem directory where the report will be written.
-URLs are not supported. Defaults to the current working directory of the
-Node.js process.
+`directory` specifies the file system directory where the report will be
+written. URLs are not supported. Defaults to the current working directory of
+the Node.js process.
```js
// Trigger report only on uncaught exceptions.
@@ -609,7 +613,7 @@ Specific API documentation can be found under
### Interaction with workers
-
+
[`Worker`][] threads can create reports in the same way that the main thread
does.
diff --git a/content/api/v19/single-executable-applications.en.md b/content/api/v19/single-executable-applications.en.md
new file mode 100644
index 0000000000..9ff1b81641
--- /dev/null
+++ b/content/api/v19/single-executable-applications.en.md
@@ -0,0 +1,187 @@
+---
+title: 'single-executable-applications'
+displayTitle: 'Single executable applications'
+category: 'api'
+version: 'v19'
+---
+
+
+
+
+
+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. 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.
+ * `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
+ ```
+
+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!
+ ```
+
+### 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 (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.
+
+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/v19/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
+[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 63d81f9dba..b535d1d3b7 100644
--- a/content/api/v19/stream.en.md
+++ b/content/api/v19/stream.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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.
@@ -55,13 +59,220 @@ and [`stream.addAbortSignal()`][].
#### Streams Promises API
-
+
The `stream/promises` API provides an alternative set of asynchronous utility
functions for streams that return `Promise` objects rather than using
callbacks. The API is accessible via `require('node:stream/promises')`
or `require('node:stream').promises`.
+#### `stream.pipeline(source[, ...transforms], destination[, options])`
+
+#### `stream.pipeline(streams[, options])`
+
+
+
+* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]
+* `source` [`Stream`](/api/v19/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)
+ * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
+* `...transforms` [`Stream`](/api/v19/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+ * `source` [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
+ * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
+* `destination` [`Stream`](/api/v19/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+ * `source` [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
+ * Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) | [`AsyncIterable`](https://tc39.github.io/ecma262/#sec-asynciterable-interface)
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal)
+ * `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|mjs
+const { pipeline } = require('node:stream/promises');
+const fs = require('node:fs');
+const zlib = require('node:zlib');
+
+async function run() {
+ await pipeline(
+ fs.createReadStream('archive.tar'),
+ zlib.createGzip(),
+ fs.createWriteStream('archive.tar.gz'),
+ );
+ console.log('Pipeline succeeded.');
+}
+
+run().catch(console.error);
+--------------
+import { pipeline } from 'node:stream/promises';
+import { createReadStream, createWriteStream } from 'node:fs';
+import { createGzip } from 'node:zlib';
+
+await pipeline(
+ createReadStream('archive.tar'),
+ createGzip(),
+ createWriteStream('archive.tar.gz'),
+);
+console.log('Pipeline succeeded.');
+```
+
+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|mjs
+const { pipeline } = require('node:stream/promises');
+const fs = require('node:fs');
+const zlib = require('node:zlib');
+
+async function run() {
+ const ac = new AbortController();
+ const signal = ac.signal;
+
+ setImmediate(() => ac.abort());
+ await pipeline(
+ fs.createReadStream('archive.tar'),
+ zlib.createGzip(),
+ fs.createWriteStream('archive.tar.gz'),
+ { signal },
+ );
+}
+
+run().catch(console.error); // AbortError
+--------------
+import { pipeline } from 'node:stream/promises';
+import { createReadStream, createWriteStream } from 'node:fs';
+import { createGzip } from 'node:zlib';
+
+const ac = new AbortController();
+const { signal } = ac;
+setImmediate(() => ac.abort());
+try {
+ await pipeline(
+ createReadStream('archive.tar'),
+ createGzip(),
+ createWriteStream('archive.tar.gz'),
+ { signal },
+ );
+} catch (err) {
+ console.error(err); // AbortError
+}
+```
+
+The `pipeline` API also supports async generators:
+
+```cjs|mjs
+const { pipeline } = require('node:stream/promises');
+const fs = require('node:fs');
+
+async function run() {
+ await pipeline(
+ fs.createReadStream('lowercase.txt'),
+ async function* (source, { signal }) {
+ source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.
+ for await (const chunk of source) {
+ yield await processChunk(chunk, { signal });
+ }
+ },
+ fs.createWriteStream('uppercase.txt'),
+ );
+ console.log('Pipeline succeeded.');
+}
+
+run().catch(console.error);
+--------------
+import { pipeline } from 'node:stream/promises';
+import { createReadStream, createWriteStream } from 'node:fs';
+
+await pipeline(
+ createReadStream('lowercase.txt'),
+ async function* (source, { signal }) {
+ source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.
+ for await (const chunk of source) {
+ yield await processChunk(chunk, { signal });
+ }
+ },
+ createWriteStream('uppercase.txt'),
+);
+console.log('Pipeline succeeded.');
+```
+
+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|mjs
+const { pipeline } = require('node:stream/promises');
+const fs = require('node:fs');
+
+async function run() {
+ await pipeline(
+ async function* ({ signal }) {
+ await someLongRunningfn({ signal });
+ yield 'asd';
+ },
+ fs.createWriteStream('uppercase.txt'),
+ );
+ console.log('Pipeline succeeded.');
+}
+
+run().catch(console.error);
+--------------
+import { pipeline } from 'node:stream/promises';
+import fs from 'node:fs';
+await pipeline(
+ async function* ({ signal }) {
+ await someLongRunningfn({ signal });
+ yield 'asd';
+ },
+ fs.createWriteStream('uppercase.txt'),
+);
+console.log('Pipeline succeeded.');
+```
+
+The `pipeline` API provides [callback version][stream-pipeline]:
+
+#### `stream.finished(stream[, options])`
+
+
+
+* `stream` [`Stream`](/api/v19/stream#stream)
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+ * `error` [`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)
+ * `readable` [`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)
+ * `writable` [`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)
+ * `signal`: [`AbortSignal`](/api/v19/globals#abortsignal) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+* 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|mjs
+const { finished } = require('node:stream/promises');
+const fs = require('node:fs');
+
+const rs = fs.createReadStream('archive.tar');
+
+async function run() {
+ await finished(rs);
+ console.log('Stream is done reading.');
+}
+
+run().catch(console.error);
+rs.resume(); // Drain the stream.
+--------------
+import { finished } from 'node:stream/promises';
+import { createReadStream } from 'node:fs';
+
+const rs = createReadStream('archive.tar');
+
+async function run() {
+ await finished(rs);
+ console.log('Stream is done reading.');
+}
+
+run().catch(console.error);
+rs.resume(); // Drain the stream.
+```
+
+The `finished` API provides [callback version][stream-finished]:
+
#### Object mode
All streams created by Node.js APIs operate exclusively on strings and `Buffer`
@@ -76,7 +287,7 @@ object mode is not safe.
#### Buffering
-
+
Both [`Writable`][] and [`Readable`][] streams will store data in an internal
buffer.
@@ -130,7 +341,7 @@ the internal buffers can be retrieved using `writable.writableBuffer` or
### API for stream consumers
-
+
Almost all Node.js applications, no matter how simple, use streams in some
manner. The following is an example of using streams in a Node.js application
@@ -175,7 +386,7 @@ server.listen(1337);
// $ curl localhost:1337 -d "\"foo\""
// string
// $ curl localhost:1337 -d "not json"
-// error: Unexpected token o in JSON at position 1
+// error: Unexpected token 'o', "not json" is not valid JSON
```
[`Writable`][] streams (such as `res` in the example) expose methods such as
@@ -233,13 +444,13 @@ myStream.end('done writing data');
##### `stream.Writable`
-
+
-
+
###### Event: `'close'`
-
+
The `'close'` event is emitted when the stream and any of its underlying
resources (a file descriptor, for example) have been closed. The event indicates
@@ -250,7 +461,7 @@ created with the `emitClose` option.
###### Event: `'drain'`
-
+
If a call to [`stream.write(chunk)`][stream-write] returns `false`, the
`'drain'` event will be emitted when it is appropriate to resume writing data
@@ -286,7 +497,7 @@ function writeOneMillionTimes(writer, data, encoding, callback) {
###### Event: `'error'`
-
+
* [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -302,7 +513,7 @@ After `'error'`, no further events other than `'close'` _should_ be emitted
###### Event: `'finish'`
-
+
The `'finish'` event is emitted after the [`stream.end()`][stream-end] method
has been called, and all data has been flushed to the underlying system.
@@ -320,9 +531,9 @@ writer.end('This is the end\n');
###### Event: `'pipe'`
-
+
-* `src` [`stream.Readable`](/api/stream#streamreadable) source stream that is piping to this writable
+* `src` [`stream.Readable`](/api/v19/stream#streamreadable) source stream that is piping to this writable
The `'pipe'` event is emitted when the [`stream.pipe()`][] method is called on
a readable stream, adding this writable to its set of destinations.
@@ -339,9 +550,9 @@ reader.pipe(writer);
###### Event: `'unpipe'`
-
+
-* `src` [`stream.Readable`](/api/stream#streamreadable) The source stream that
+* `src` [`stream.Readable`](/api/v19/stream#streamreadable) The source stream that
[unpiped][`stream.unpipe()`] this writable
The `'unpipe'` event is emitted when the [`stream.unpipe()`][] method is called
@@ -364,7 +575,7 @@ reader.unpipe(writer);
###### `writable.cork()`
-
+
The `writable.cork()` method forces all written data to be buffered in memory.
The buffered data will be flushed when either the [`stream.uncork()`][] or
@@ -383,7 +594,7 @@ See also: [`writable.uncork()`][], [`writable._writev()`][stream-_writev].
###### `writable.destroy([error])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Optional, an error to emit with `'error'` event.
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -397,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();
@@ -405,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();
@@ -434,7 +643,7 @@ but instead implement [`writable._destroy()`][writable-_destroy].
###### `writable.closed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -442,7 +651,7 @@ Is `true` after `'close'` has been emitted.
###### `writable.destroyed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -460,9 +669,9 @@ console.log(myStream.destroyed); // true
###### `writable.end([chunk[, encoding]][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional data to write. For streams
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional data to write. For streams
not operating in object mode, `chunk` must be a string, `Buffer` or
`Uint8Array`. For object mode streams, `chunk` may be any JavaScript value
other than `null`.
@@ -489,7 +698,7 @@ file.end('world!');
###### `writable.setDefaultEncoding(encoding)`
-
+
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The new default encoding
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -499,7 +708,7 @@ The `writable.setDefaultEncoding()` method sets the default `encoding` for a
###### `writable.uncork()`
-
+
The `writable.uncork()` method flushes all data buffered since
[`stream.cork()`][] was called.
@@ -536,7 +745,7 @@ See also: [`writable.cork()`][].
###### `writable.writable`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -545,9 +754,13 @@ the stream has not been destroyed, errored, or ended.
###### `writable.writableAborted`
-
+
+
+
+
+Experimental
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -555,7 +768,7 @@ Returns whether the stream was destroyed or errored before emitting `'finish'`.
###### `writable.writableEnded`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -565,7 +778,7 @@ does not indicate whether the data has been flushed, for this use
###### `writable.writableCorked`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -574,7 +787,7 @@ called in order to fully uncork the stream.
###### `writable.errored`
-
+
* [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -582,7 +795,7 @@ Returns error if the stream has been destroyed with an error.
###### `writable.writableFinished`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -590,7 +803,7 @@ Is set to `true` immediately before the [`'finish'`][] event is emitted.
###### `writable.writableHighWaterMark`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -598,7 +811,7 @@ Return the value of `highWaterMark` passed when creating this `Writable`.
###### `writable.writableLength`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -608,7 +821,7 @@ the status of the `highWaterMark`.
###### `writable.writableNeedDrain`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -616,7 +829,7 @@ Is `true` if the stream's buffer has been full and stream will emit `'drain'`.
###### `writable.writableObjectMode`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -624,9 +837,9 @@ Getter for the property `objectMode` of a given `Writable` stream.
###### `writable.write(chunk[, encoding][, callback])`
-
+
-* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional data to write. For streams
+* `chunk` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional data to write. For streams
not operating in object mode, `chunk` must be a string, `Buffer` or
`Uint8Array`. For object mode streams, `chunk` may be any JavaScript value
other than `null`.
@@ -794,8 +1007,10 @@ pass.unpipe(writable);
// readableFlowing is now false.
pass.on('data', (chunk) => { console.log(chunk.toString()); });
+// readableFlowing is still false.
pass.write('ok'); // Will not emit 'data'.
pass.resume(); // Must be called to make stream emit 'data'.
+// readableFlowing is now true.
```
While `readable.readableFlowing` is `false`, data may be accumulating
@@ -812,13 +1027,13 @@ lead to unintuitive behavior.
##### `stream.Readable`
-
+
-
+
###### Event: `'close'`
-
+
The `'close'` event is emitted when the stream and any of its underlying
resources (a file descriptor, for example) have been closed. The event indicates
@@ -829,9 +1044,9 @@ created with the `emitClose` option.
###### Event: `'data'`
-
+
-* `chunk` [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The chunk of data. For streams that are not
+* `chunk` [`Buffer`](/api/v19/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The chunk of data. For streams that are not
operating in object mode, the chunk will be either a string or `Buffer`.
For streams that are in object mode, the chunk can be any JavaScript value
other than `null`.
@@ -861,7 +1076,7 @@ readable.on('data', (chunk) => {
###### Event: `'end'`
-
+
The `'end'` event is emitted when there is no more data to be consumed from
the stream.
@@ -883,7 +1098,7 @@ readable.on('end', () => {
###### Event: `'error'`
-
+
* [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -896,14 +1111,14 @@ The listener callback will be passed a single `Error` object.
###### Event: `'pause'`
-
+
The `'pause'` event is emitted when [`stream.pause()`][stream-pause] is called
and `readableFlowing` is not `false`.
###### Event: `'readable'`
-
+
The `'readable'` event is emitted when there is data available to be read from
the stream or when the end of the stream has been reached. Effectively, the
@@ -963,14 +1178,14 @@ will start flowing, i.e. `'data'` events will be emitted without calling
###### Event: `'resume'`
-
+
The `'resume'` event is emitted when [`stream.resume()`][stream-resume] is
called and `readableFlowing` is not `true`.
###### `readable.destroy([error])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) Error which will be passed as payload in `'error'` event
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -988,7 +1203,7 @@ Implementors should not override this method, but instead implement
###### `readable.closed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -996,7 +1211,7 @@ Is `true` after `'close'` has been emitted.
###### `readable.destroyed`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1004,7 +1219,7 @@ Is `true` after [`readable.destroy()`][readable-destroy] has been called.
###### `readable.isPaused()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1025,7 +1240,7 @@ readable.isPaused(); // === false
###### `readable.pause()`
-
+
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -1051,12 +1266,12 @@ event listener.
###### `readable.pipe(destination[, options])`
-
+
-* `destination` [`stream.Writable`](/api/stream#streamwritable) The destination for writing data
+* `destination` [`stream.Writable`](/api/v19/stream#streamwritable) The destination for writing data
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Pipe options
* `end` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) End the writer when the reader ends. **Default:** `true`.
-* Returns: [`stream.Writable`](/api/stream#streamwritable) The _destination_, allowing for a chain of pipes if
+* Returns: [`stream.Writable`](/api/v19/stream#streamwritable) The _destination_, allowing for a chain of pipes if
it is a [`Duplex`][] or a [`Transform`][] stream
The `readable.pipe()` method attaches a [`Writable`][] stream to the `readable`,
@@ -1113,10 +1328,10 @@ closed until the Node.js process exits, regardless of the specified options.
###### `readable.read([size])`
-
+
* `size` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Optional argument to specify how much data to read.
-* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
+* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
The `readable.read()` method reads data out of the internal buffer and
returns it. If no data is available to be read, `null` is returned. By default,
@@ -1195,7 +1410,7 @@ been emitted will return `null`. No runtime error will be raised.
###### `readable.readable`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1204,9 +1419,13 @@ the stream has not been destroyed or emitted `'error'` or `'end'`.
###### `readable.readableAborted`
-
+
-
+
+
+Experimental
+
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1214,9 +1433,13 @@ Returns whether the stream was destroyed or errored before emitting `'end'`.
###### `readable.readableDidRead`
-
+
+
+
-
+Experimental
+
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1224,7 +1447,7 @@ Returns whether `'data'` has been emitted.
###### `readable.readableEncoding`
-
+
* [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1233,7 +1456,7 @@ property can be set using the [`readable.setEncoding()`][] method.
###### `readable.readableEnded`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1241,7 +1464,7 @@ Becomes `true` when [`'end'`][] event is emitted.
###### `readable.errored`
-
+
* [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -1249,7 +1472,7 @@ Returns error if the stream has been destroyed with an error.
###### `readable.readableFlowing`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1258,7 +1481,7 @@ in the [Three states][] section.
###### `readable.readableHighWaterMark`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1266,7 +1489,7 @@ Returns the value of `highWaterMark` passed when creating this `Readable`.
###### `readable.readableLength`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1276,7 +1499,7 @@ the status of the `highWaterMark`.
###### `readable.readableObjectMode`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1284,7 +1507,7 @@ Getter for the property `objectMode` of a given `Readable` stream.
###### `readable.resume()`
-
+
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -1307,7 +1530,7 @@ event listener.
###### `readable.setEncoding(encoding)`
-
+
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The encoding to use.
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -1338,9 +1561,9 @@ readable.on('data', (chunk) => {
###### `readable.unpipe([destination])`
-
+
-* `destination` [`stream.Writable`](/api/stream#streamwritable) Optional specific stream to unpipe
+* `destination` [`stream.Writable`](/api/v19/stream#streamwritable) Optional specific stream to unpipe
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
The `readable.unpipe()` method detaches a `Writable` stream previously attached
@@ -1368,9 +1591,9 @@ setTimeout(() => {
###### `readable.unshift(chunk[, encoding])`
-
+
-* `chunk` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`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) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Chunk of data to unshift onto the
+* `chunk` [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`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) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Chunk of data to unshift onto the
read queue. For streams not operating in object mode, `chunk` must be a
string, `Buffer`, `Uint8Array`, or `null`. For object mode streams, `chunk`
may be any JavaScript value.
@@ -1441,9 +1664,9 @@ process of performing a read.
###### `readable.wrap(stream)`
-
+
-* `stream` [`Stream`](/api/stream#stream) An "old style" readable stream
+* `stream` [`Stream`](/api/v19/stream#stream) An "old style" readable stream
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
Prior to Node.js 0.10, streams did not implement the entire `node:stream`
@@ -1472,7 +1695,7 @@ myReader.on('readable', () => {
###### `readable[Symbol.asyncIterator]()`
-
+
* Returns: [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface) to fully consume the stream.
@@ -1500,15 +1723,19 @@ has less then 64 KiB of data because no `highWaterMark` option is provided to
###### `readable.compose(stream[, options])`
-
+
+
+
+
+Experimental
-
+
-* `stream` [`Stream`](/api/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)
+* `stream` [`Stream`](/api/v19/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)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
-* Returns: [`Duplex`](/api/stream#streamduplex) a stream composed with the stream `stream`.
+* Returns: [`Duplex`](/api/v19/stream#streamduplex) a stream composed with the stream `stream`.
```mjs
import { Readable } from 'node:stream';
@@ -1533,9 +1760,13 @@ See [`stream.compose`][] for more information.
###### `readable.iterator([options])`
-
+
-
+
+
+Experimental
+
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `destroyOnReturn` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When set to `false`, calling `return` on the
@@ -1585,22 +1816,26 @@ showBoth();
###### `readable.map(fn[, options])`
-
+
+
+
-
+Experimental
+
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to map over every chunk in the
stream.
* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) aborted if the stream is destroyed allowing to
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) aborted if the stream is destroyed allowing to
abort the `fn` call early.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the maximum concurrent invocation of `fn` to call
on the stream at once. **Default:** `1`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
-* Returns: [`Readable`](/api/stream#streamreadable) a stream mapped with the function `fn`.
+* Returns: [`Readable`](/api/v19/stream#streamreadable) a stream mapped with the function `fn`.
This method allows mapping over the stream. The `fn` function will be called
for every chunk in the stream. If the `fn` function returns a promise - that
@@ -1628,21 +1863,25 @@ for await (const result of dnsResults) {
###### `readable.filter(fn[, options])`
-
+
+
+
-
+Experimental
+
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to filter chunks from the stream.
* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) aborted if the stream is destroyed allowing to
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) aborted if the stream is destroyed allowing to
abort the `fn` call early.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the maximum concurrent invocation of `fn` to call
on the stream at once. **Default:** `1`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
-* Returns: [`Readable`](/api/stream#streamreadable) a stream filtered with the predicate `fn`.
+* Returns: [`Readable`](/api/v19/stream#streamreadable) a stream filtered with the predicate `fn`.
This method allows filtering the stream. For each chunk in the stream the `fn`
function will be called and if it returns a truthy value, the chunk will be
@@ -1675,19 +1914,23 @@ for await (const result of dnsResults) {
###### `readable.forEach(fn[, options])`
-
+
+
+
+
+Experimental
-
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to call on each chunk of the stream.
* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) aborted if the stream is destroyed allowing to
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) aborted if the stream is destroyed allowing to
abort the `fn` call early.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the maximum concurrent invocation of `fn` to call
on the stream at once. **Default:** `1`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) a promise for when the stream has finished.
@@ -1732,12 +1975,16 @@ console.log('done'); // Stream has finished
###### `readable.toArray([options])`
-
+
-
+
+
+Experimental
+
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows cancelling the toArray operation if the
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows cancelling the toArray operation if the
signal is aborted.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) a promise containing an array with the contents of the
stream.
@@ -1768,19 +2015,23 @@ const dnsResults = await Readable.from([
###### `readable.some(fn[, options])`
-
+
+
+
-
+Experimental
+
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to call on each chunk of the stream.
* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) aborted if the stream is destroyed allowing to
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) aborted if the stream is destroyed allowing to
abort the `fn` call early.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the maximum concurrent invocation of `fn` to call
on the stream at once. **Default:** `1`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) a promise evaluating to `true` if `fn` returned a truthy
value for at least one of the chunks.
@@ -1807,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
@@ -1815,19 +2066,23 @@ console.log('done'); // Stream has finished
###### `readable.find(fn[, options])`
-
+
+
+
+
+Experimental
-
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to call on each chunk of the stream.
* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) aborted if the stream is destroyed allowing to
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) aborted if the stream is destroyed allowing to
abort the `fn` call early.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the maximum concurrent invocation of `fn` to call
on the stream at once. **Default:** `1`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) a promise evaluating to the first chunk for which `fn`
evaluated with a truthy value, or `undefined` if no element was found.
@@ -1855,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
@@ -1863,19 +2118,23 @@ console.log('done'); // Stream has finished
###### `readable.every(fn[, options])`
-
+
+
+
+
+Experimental
-
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to call on each chunk of the stream.
* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) aborted if the stream is destroyed allowing to
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) aborted if the stream is destroyed allowing to
abort the `fn` call early.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the maximum concurrent invocation of `fn` to call
on the stream at once. **Default:** `1`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) a promise evaluating to `true` if `fn` returned a truthy
value for all of the chunks.
@@ -1901,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);
@@ -1910,22 +2169,26 @@ console.log('done'); // Stream has finished
###### `readable.flatMap(fn[, options])`
-
+
-
+
+
+Experimental
+
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncGeneratorFunction`](https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a function to map over
every chunk in the stream.
* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) aborted if the stream is destroyed allowing to
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) aborted if the stream is destroyed allowing to
abort the `fn` call early.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `concurrency` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the maximum concurrent invocation of `fn` to call
on the stream at once. **Default:** `1`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
-* Returns: [`Readable`](/api/stream#streamreadable) a stream flat-mapped with the function `fn`.
+* Returns: [`Readable`](/api/v19/stream#streamreadable) a stream flat-mapped with the function `fn`.
This method returns a new stream by applying the given callback to each
chunk of the stream and then flattening the result.
@@ -1957,15 +2220,19 @@ for await (const result of concatResult) {
###### `readable.drop(limit[, options])`
-
+
+
+
-
+Experimental
+
+
* `limit` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the number of chunks to drop from the readable.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
-* Returns: [`Readable`](/api/stream#streamreadable) a stream with `limit` chunks dropped.
+* Returns: [`Readable`](/api/v19/stream#streamreadable) a stream with `limit` chunks dropped.
This method returns a new stream with the first `limit` chunks dropped.
@@ -1977,15 +2244,19 @@ await Readable.from([1, 2, 3, 4]).drop(2).toArray(); // [3, 4]
###### `readable.take(limit[, options])`
-
+
+
+
+
+Experimental
-
+
* `limit` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) the number of chunks to take from the readable.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
-* Returns: [`Readable`](/api/stream#streamreadable) a stream with `limit` chunks taken.
+* Returns: [`Readable`](/api/v19/stream#streamreadable) a stream with `limit` chunks taken.
This method returns a new stream with the first `limit` chunks.
@@ -1997,14 +2268,18 @@ await Readable.from([1, 2, 3, 4]).take(2).toArray(); // [1, 2]
###### `readable.asIndexedPairs([options])`
-
+
-
+
+
+Experimental
+
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
-* Returns: [`Readable`](/api/stream#streamreadable) a stream of indexed pairs.
+* Returns: [`Readable`](/api/v19/stream#streamreadable) a stream of indexed pairs.
This method returns a new stream with chunks of the underlying stream paired
with a counter in the form `[index, chunk]`. The first index value is 0 and it
@@ -2019,9 +2294,13 @@ console.log(pairs); // [[0, 'a'], [1, 'b'], [2, 'c']]
###### `readable.reduce(fn[, initial[, options]])`
-
+
+
+
-
+Experimental
+
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) a reducer function to call over every chunk
in the stream.
@@ -2029,11 +2308,11 @@ console.log(pairs); // [[0, 'a'], [1, 'b'], [2, 'c']]
`initial` value if specified or the first chunk of the stream otherwise.
* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) a chunk of data from the stream.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) aborted if the stream is destroyed allowing to
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) aborted if the stream is destroyed allowing to
abort the `fn` call early.
* `initial` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) the initial value to use in the reduction.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows destroying the stream if the signal is
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows destroying the stream if the signal is
aborted.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) a promise for the final value of the reduction.
@@ -2062,9 +2341,9 @@ console.log(ten); // 10
##### `stream.Duplex`
-
+
-
+
Duplex streams are streams that implement both the [`Readable`][] and
[`Writable`][] interfaces.
@@ -2077,7 +2356,7 @@ Examples of `Duplex` streams include:
###### `duplex.allowHalfOpen`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -2091,9 +2370,9 @@ emitted.
##### `stream.Transform`
-
+
-
+
Transform streams are [`Duplex`][] streams where the output is in some way
related to the input. Like all [`Duplex`][] streams, `Transform` streams
@@ -2106,7 +2385,7 @@ Examples of `Transform` streams include:
###### `transform.destroy([error])`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
* Returns: [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
@@ -2123,9 +2402,11 @@ further errors except from `_destroy()` may be emitted as `'error'`.
#### `stream.finished(stream[, options], callback)`
-
+
+
+* `stream` [`Stream`](/api/v19/stream#stream) | [`ReadableStream`](/api/v19/webstreams#readablestream) | [`WritableStream`](/api/v19/webstreams#writablestream)
-* `stream` [`Stream`](/api/stream#stream) A readable and/or writable stream.
+A readable and/or writable stream/webstream.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `error` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to `false`, then a call to `emit('error', err)` is
@@ -2136,7 +2417,7 @@ further errors except from `_destroy()` may be emitted as `'error'`.
* `writable` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When set to `false`, the callback will be called when
the stream ends even though the stream might still be writable.
**Default:** `true`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) allows aborting the wait for the stream finish. The
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) allows aborting the wait for the stream finish. The
underlying stream will _not_ be aborted if the signal is aborted. The
callback will get called with an `AbortError`. All registered
listeners added by this function will also be removed.
@@ -2173,22 +2454,7 @@ Especially useful in error handling scenarios where a stream is destroyed
prematurely (like an aborted HTTP request), and will not emit `'end'`
or `'finish'`.
-The `finished` API provides promise version:
-
-```js
-const { finished } = require('node:stream/promises');
-const fs = require('node:fs');
-
-const rs = fs.createReadStream('archive.tar');
-
-async function run() {
- await finished(rs);
- console.log('Stream is done reading.');
-}
-
-run().catch(console.error);
-rs.resume(); // Drain the stream.
-```
+The `finished` API provides [promise version][stream-finished-promise].
`stream.finished()` leaves dangling event listeners (in particular
`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been
@@ -2208,21 +2474,22 @@ const cleanup = finished(rs, (err) => {
#### `stream.pipeline(streams, callback)`
-
+
-* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]
-* `source` [`Stream`](/api/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/v19/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/v19/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/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `...transforms` [`Stream`](/api/v19/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`TransformStream`](/api/v19/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/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
+* `destination` [`Stream`](/api/v19/stream#stream) | [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`WritableStream`](/api/v19/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.
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
* `val` Resolved value of `Promise` returned by `destination`.
-* Returns: [`Stream`](/api/stream#stream)
+* Returns: [`Stream`](/api/v19/stream#stream)
A module method to pipe between streams and generators forwarding errors and
properly cleaning up and provide a callback when the pipeline is complete.
@@ -2247,101 +2514,11 @@ pipeline(
} else {
console.log('Pipeline succeeded.');
}
- }
+ },
);
```
-The `pipeline` API provides a promise version, which can also
-receive an options argument as the last parameter with a
-`signal` [`AbortSignal`](/api/globals#abortsignal) property. When the signal is aborted,
-`destroy` will be called on the underlying pipeline, with an
-`AbortError`.
-
-```js
-const { pipeline } = require('node:stream/promises');
-const fs = require('node:fs');
-const zlib = require('node:zlib');
-
-async function run() {
- await pipeline(
- fs.createReadStream('archive.tar'),
- zlib.createGzip(),
- fs.createWriteStream('archive.tar.gz')
- );
- console.log('Pipeline succeeded.');
-}
-
-run().catch(console.error);
-```
-
-To use an `AbortSignal`, pass it inside an options object,
-as the last argument:
-
-```js
-const { pipeline } = require('node:stream/promises');
-const fs = require('node:fs');
-const zlib = require('node:zlib');
-
-async function run() {
- const ac = new AbortController();
- const signal = ac.signal;
-
- setTimeout(() => ac.abort(), 1);
- await pipeline(
- fs.createReadStream('archive.tar'),
- zlib.createGzip(),
- fs.createWriteStream('archive.tar.gz'),
- { signal },
- );
-}
-
-run().catch(console.error); // AbortError
-```
-
-The `pipeline` API also supports async generators:
-
-```js
-const { pipeline } = require('node:stream/promises');
-const fs = require('node:fs');
-
-async function run() {
- await pipeline(
- fs.createReadStream('lowercase.txt'),
- async function* (source, { signal }) {
- source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.
- for await (const chunk of source) {
- yield await processChunk(chunk, { signal });
- }
- },
- fs.createWriteStream('uppercase.txt')
- );
- console.log('Pipeline succeeded.');
-}
-
-run().catch(console.error);
-```
-
-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.
-
-```js
-const { pipeline } = require('node:stream/promises');
-const fs = require('node:fs');
-
-async function run() {
- await pipeline(
- async function* ({ signal }) {
- await someLongRunningfn({ signal });
- yield 'asd';
- },
- fs.createWriteStream('uppercase.txt')
- );
- console.log('Pipeline succeeded.');
-}
-
-run().catch(console.error);
-```
+The `pipeline` API provides a [promise version][stream-pipeline-promise].
`stream.pipeline()` will call `stream.destroy(err)` on all streams except:
@@ -2378,12 +2555,17 @@ const server = http.createServer((req, res) => {
#### `stream.compose(...streams)`
-
+
-
+
-* `streams` Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]
-* Returns: [`stream.Duplex`](/api/stream#streamduplex)
+`stream.compose` is experimental.
+
+
+
+* `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
first stream and reads from the last. Each provided stream is piped into
@@ -2405,7 +2587,7 @@ import { compose, Transform } from 'node:stream';
const removeSpaces = new Transform({
transform(chunk, encoding, callback) {
callback(null, String(chunk).replace(' ', ''));
- }
+ },
});
async function* toUpper(source) {
@@ -2468,7 +2650,7 @@ See [`readable.compose(stream)`][] for `stream.compose` as operator.
#### `stream.Readable.from(iterable[, options])`
-
+
* `iterable` [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) Object implementing the `Symbol.asyncIterator` or
`Symbol.iterator` iterable protocol. Emits an 'error' event if a null
@@ -2476,7 +2658,7 @@ See [`readable.compose(stream)`][] for `stream.compose` as operator.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Options provided to `new stream.Readable([options])`.
By default, `Readable.from()` will set `options.objectMode` to `true`, unless
this is explicitly opted out by setting `options.objectMode` to `false`.
-* Returns: [`stream.Readable`](/api/stream#streamreadable)
+* Returns: [`stream.Readable`](/api/v19/stream#streamreadable)
A utility method for creating readable streams out of iterators.
@@ -2499,94 +2681,140 @@ Calling `Readable.from(string)` or `Readable.from(buffer)` will not have
the strings or buffers be iterated to match the other streams semantics
for performance reasons.
+If an `Iterable` object containing promises is passed as an argument,
+it might result in unhandled rejection.
+
+```js
+const { Readable } = require('node:stream');
+
+Readable.from([
+ new Promise((resolve) => setTimeout(resolve('1'), 1500)),
+ new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection
+]);
+```
+
#### `stream.Readable.fromWeb(readableStream[, options])`
-
+
+
+
-
+Experimental
-* `readableStream` [`ReadableStream`](/api/webstreams#readablestream)
+
+
+* `readableStream` [`ReadableStream`](/api/v19/webstreams#readablestream)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `objectMode` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
- * `signal` [`AbortSignal`](/api/globals#abortsignal)
-* Returns: [`stream.Readable`](/api/stream#streamreadable)
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal)
+* Returns: [`stream.Readable`](/api/v19/stream#streamreadable)
#### `stream.Readable.isDisturbed(stream)`
-
+
+
+
+
+Experimental
-
+
-* `stream` [`stream.Readable`](/api/stream#streamreadable) | [`ReadableStream`](/api/webstreams#readablestream)
+* `stream` [`stream.Readable`](/api/v19/stream#streamreadable) | [`ReadableStream`](/api/v19/webstreams#readablestream)
* Returns: `boolean`
Returns whether the stream has been read from or cancelled.
#### `stream.isErrored(stream)`
-
+
-
+
-* `stream` [`Readable`](/api/stream#streamreadable) | [`Writable`](/api/stream#streamwritable) | [`Duplex`](/api/stream#streamduplex) | [`WritableStream`](/api/webstreams#writablestream) | [`ReadableStream`](/api/webstreams#readablestream)
+Experimental
+
+
+
+* `stream` [`Readable`](/api/v19/stream#streamreadable) | [`Writable`](/api/v19/stream#streamwritable) | [`Duplex`](/api/v19/stream#streamduplex) | [`WritableStream`](/api/v19/webstreams#writablestream) | [`ReadableStream`](/api/v19/webstreams#readablestream)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
Returns whether the stream has encountered an error.
#### `stream.isReadable(stream)`
-
+
+
+
-
+Experimental
-* `stream` [`Readable`](/api/stream#streamreadable) | [`Duplex`](/api/stream#streamduplex) | [`ReadableStream`](/api/webstreams#readablestream)
+
+
+* `stream` [`Readable`](/api/v19/stream#streamreadable) | [`Duplex`](/api/v19/stream#streamduplex) | [`ReadableStream`](/api/v19/webstreams#readablestream)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
Returns whether the stream is readable.
#### `stream.Readable.toWeb(streamReadable[, options])`
-
+
+
+
+
+Experimental
-
+
-* `streamReadable` [`stream.Readable`](/api/stream#streamreadable)
+* `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)
-* Returns: [`ReadableStream`](/api/webstreams#readablestream)
+ * `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])`
-
+
-
+
-* `writableStream` [`WritableStream`](/api/webstreams#writablestream)
+Experimental
+
+
+
+* `writableStream` [`WritableStream`](/api/v19/webstreams#writablestream)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `decodeStrings` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `objectMode` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
- * `signal` [`AbortSignal`](/api/globals#abortsignal)
-* Returns: [`stream.Writable`](/api/stream#streamwritable)
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal)
+* Returns: [`stream.Writable`](/api/v19/stream#streamwritable)
#### `stream.Writable.toWeb(streamWritable)`
-
+
+
+
-
+Experimental
-* `streamWritable` [`stream.Writable`](/api/stream#streamwritable)
-* Returns: [`WritableStream`](/api/webstreams#writablestream)
+
+
+* `streamWritable` [`stream.Writable`](/api/v19/stream#streamwritable)
+* Returns: [`WritableStream`](/api/v19/webstreams#writablestream)
#### `stream.Duplex.from(src)`
-
+
-* `src` [`Stream`](/api/stream#stream) | [`Blob`](/api/buffer#blob) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`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) | [`AsyncGeneratorFunction`](https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
+* `src` [`Stream`](/api/v19/stream#stream) | [`Blob`](/api/v19/buffer#blob) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`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) | [`AsyncGeneratorFunction`](https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`ReadableStream`](/api/v19/webstreams#readablestream) | [`WritableStream`](/api/v19/webstreams#writablestream)
A utility method for creating duplex streams.
@@ -2606,31 +2834,49 @@ A utility method for creating duplex streams.
`writable` into `Stream` and then combines them into `Duplex` where the
`Duplex` will write to the `writable` and read from the `readable`.
* `Promise` converts into readable `Duplex`. Value `null` is ignored.
-* Returns: [`stream.Duplex`](/api/stream#streamduplex)
+* `ReadableStream` converts into readable `Duplex`.
+* `WritableStream` converts into writable `Duplex`.
+* Returns: [`stream.Duplex`](/api/v19/stream#streamduplex)
+
+If an `Iterable` object containing promises is passed as an argument,
+it might result in unhandled rejection.
+
+```js
+const { Duplex } = require('node:stream');
+
+Duplex.from([
+ new Promise((resolve) => setTimeout(resolve('1'), 1500)),
+ new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection
+]);
+```
#### `stream.Duplex.fromWeb(pair[, options])`
-
+
+
+
-
+Experimental
+
+
* `pair` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `readable` [`ReadableStream`](/api/webstreams#readablestream)
- * `writable` [`WritableStream`](/api/webstreams#writablestream)
+ * `readable` [`ReadableStream`](/api/v19/webstreams#readablestream)
+ * `writable` [`WritableStream`](/api/v19/webstreams#writablestream)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `allowHalfOpen` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `decodeStrings` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* `highWaterMark` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `objectMode` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
- * `signal` [`AbortSignal`](/api/globals#abortsignal)
-* Returns: [`stream.Duplex`](/api/stream#streamduplex)
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal)
+* Returns: [`stream.Duplex`](/api/v19/stream#streamduplex)
-```mjs
+```mjs|cjs
import { Duplex } from 'node:stream';
import {
ReadableStream,
- WritableStream
+ WritableStream,
} from 'node:stream/web';
const readable = new ReadableStream({
@@ -2642,12 +2888,12 @@ const readable = new ReadableStream({
const writable = new WritableStream({
write(chunk) {
console.log('writable', chunk);
- }
+ },
});
const pair = {
readable,
- writable
+ writable,
};
const duplex = Duplex.fromWeb(pair, { encoding: 'utf8', objectMode: true });
@@ -2656,13 +2902,11 @@ duplex.write('hello');
for await (const chunk of duplex) {
console.log('readable', chunk);
}
-```
-
-```cjs
+--------------
const { Duplex } = require('node:stream');
const {
ReadableStream,
- WritableStream
+ WritableStream,
} = require('node:stream/web');
const readable = new ReadableStream({
@@ -2674,12 +2918,12 @@ const readable = new ReadableStream({
const writable = new WritableStream({
write(chunk) {
console.log('writable', chunk);
- }
+ },
});
const pair = {
readable,
- writable
+ writable,
};
const duplex = Duplex.fromWeb(pair, { encoding: 'utf8', objectMode: true });
@@ -2689,16 +2933,20 @@ duplex.once('readable', () => console.log('readable', duplex.read()));
#### `stream.Duplex.toWeb(streamDuplex)`
-
+
+
+
+
+Experimental
-
+
-* `streamDuplex` [`stream.Duplex`](/api/stream#streamduplex)
+* `streamDuplex` [`stream.Duplex`](/api/v19/stream#streamduplex)
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `readable` [`ReadableStream`](/api/webstreams#readablestream)
- * `writable` [`WritableStream`](/api/webstreams#writablestream)
+ * `readable` [`ReadableStream`](/api/v19/webstreams#readablestream)
+ * `writable` [`WritableStream`](/api/v19/webstreams#writablestream)
-```mjs
+```mjs|cjs
import { Duplex } from 'node:stream';
const duplex = Duplex({
@@ -2710,7 +2958,7 @@ const duplex = Duplex({
write(chunk, encoding, callback) {
console.log('writable', chunk);
callback();
- }
+ },
});
const { readable, writable } = Duplex.toWeb(duplex);
@@ -2718,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({
@@ -2732,7 +2978,7 @@ const duplex = Duplex({
write(chunk, encoding, callback) {
console.log('writable', chunk);
callback();
- }
+ },
});
const { readable, writable } = Duplex.toWeb(duplex);
@@ -2745,17 +2991,19 @@ readable.getReader().read().then((result) => {
#### `stream.addAbortSignal(signal, stream)`
-
+
-* `signal` [`AbortSignal`](/api/globals#abortsignal) A signal representing possible cancellation
-* `stream` [`Stream`](/api/stream#stream) a stream to attach a signal to
+* `signal` [`AbortSignal`](/api/v19/globals#abortsignal) A signal representing possible cancellation
+* `stream` [`Stream`](/api/v19/stream#stream) | [`ReadableStream`](/api/v19/webstreams#readablestream) | [`WritableStream`](/api/v19/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');
@@ -2763,7 +3011,7 @@ const fs = require('node:fs');
const controller = new AbortController();
const read = addAbortSignal(
controller.signal,
- fs.createReadStream(('object.json'))
+ fs.createReadStream(('object.json')),
);
// Later, abort the operation closing the stream
controller.abort();
@@ -2776,7 +3024,7 @@ const controller = new AbortController();
setTimeout(() => controller.abort(), 10_000); // set a timeout
const stream = addAbortSignal(
controller.signal,
- fs.createReadStream(('object.json'))
+ fs.createReadStream(('object.json')),
);
(async () => {
try {
@@ -2793,9 +3041,40 @@ 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
-
+
The `node:stream` module API has been designed to make it possible to easily
implement streams using JavaScript's prototypal inheritance model.
@@ -2847,7 +3126,7 @@ expectations.
#### Simplified construction
-
+
For many simple cases, it is possible to create a stream without relying on
inheritance. This can be accomplished by directly creating instances of the
@@ -2866,7 +3145,7 @@ const myWritable = new Writable({
},
destroy() {
// Free resources...
- }
+ },
});
```
@@ -2880,7 +3159,7 @@ method.
##### `new stream.Writable([options])`
-
+
* `options` [`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) Buffer level when
@@ -2914,7 +3193,7 @@ method.
[`stream._construct()`][writable-_construct] method.
* `autoDestroy` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether this stream should automatically call
`.destroy()` on itself after ending. **Default:** `true`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) A signal representing possible cancellation.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) A signal representing possible cancellation.
```js
const { Writable } = require('node:stream');
@@ -2953,7 +3232,7 @@ const myWritable = new Writable({
},
writev(chunks, callback) {
// ...
- }
+ },
});
```
@@ -2972,7 +3251,7 @@ const myWritable = new Writable({
writev(chunks, callback) {
// ...
},
- signal: controller.signal
+ signal: controller.signal,
});
// Later, abort the operation closing the stream
controller.abort();
@@ -2980,7 +3259,7 @@ controller.abort();
##### `writable._construct(callback)`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Call this function (optionally with an error
argument) when the stream has finished initializing.
@@ -3029,9 +3308,9 @@ class WriteStream extends Writable {
##### `writable._write(chunk, encoding, callback)`
-
+
-* `chunk` [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `Buffer` to be written, converted from the
+* `chunk` [`Buffer`](/api/v19/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `Buffer` to be written, converted from the
`string` passed to [`stream.write()`][stream-write]. If the stream's
`decodeStrings` option is `false` or the stream is operating in object mode,
the chunk will not be converted & will be whatever was passed to
@@ -3082,7 +3361,7 @@ user programs.
* `chunks` Object\[] The data to be written. The value is an array of [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
that each represent a discrete chunk of data to write. The properties of
these objects are:
- * `chunk` [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A buffer instance or string containing the data to
+ * `chunk` [`Buffer`](/api/v19/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A buffer instance or string containing the data to
be written. The `chunk` will be a string if the `Writable` was created with
the `decodeStrings` option set to `false` and a string was passed to `write()`.
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The character encoding of the `chunk`. If `chunk` is
@@ -3105,7 +3384,7 @@ user programs.
##### `writable._destroy(err, callback)`
-
+
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) A possible error.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function that takes an optional error
@@ -3118,7 +3397,7 @@ once it is executed when a promise is resolved.
##### `writable._final(callback)`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Call this function (optionally with an error
argument) when finished writing any remaining data.
@@ -3152,7 +3431,7 @@ const myWritable = new Writable({
} else {
callback();
}
- }
+ },
});
```
@@ -3226,7 +3505,7 @@ constructor and implement the [`readable._read()`][] method.
##### `new stream.Readable([options])`
-
+
* `options` [`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) The maximum [number of bytes][hwm-gotcha] to store
@@ -3247,7 +3526,7 @@ constructor and implement the [`readable._read()`][] method.
[`stream._construct()`][readable-_construct] method.
* `autoDestroy` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether this stream should automatically call
`.destroy()` on itself after ending. **Default:** `true`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) A signal representing possible cancellation.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) A signal representing possible cancellation.
```js
const { Readable } = require('node:stream');
@@ -3283,7 +3562,7 @@ const { Readable } = require('node:stream');
const myReadable = new Readable({
read(size) {
// ...
- }
+ },
});
```
@@ -3298,7 +3577,7 @@ const read = new Readable({
read(size) {
// ...
},
- signal: controller.signal
+ signal: controller.signal,
});
// Later, abort the operation closing the stream
controller.abort();
@@ -3306,7 +3585,7 @@ controller.abort();
##### `readable._construct(callback)`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Call this function (optionally with an error
argument) when the stream has finished initializing.
@@ -3362,7 +3641,7 @@ class ReadStream extends Readable {
##### `readable._read(size)`
-
+
* `size` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Number of bytes to read asynchronously
@@ -3399,7 +3678,7 @@ user programs.
##### `readable._destroy(err, callback)`
-
+
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) A possible error.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function that takes an optional error
@@ -3410,9 +3689,9 @@ It can be overridden by child classes but it **must not** be called directly.
##### `readable.push(chunk[, encoding])`
-
+
-* `chunk` [`Buffer`](/api/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`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) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Chunk of data to push into the
+* `chunk` [`Buffer`](/api/v19/buffer#buffer) | [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) | [`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) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Chunk of data to push into the
read queue. For streams not operating in object mode, `chunk` must be a
string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be
any JavaScript value.
@@ -3495,13 +3774,13 @@ const myReadable = new Readable({
} else {
// Do some work.
}
- }
+ },
});
```
##### An example counting stream
-
+
The following is a basic example of a `Readable` stream that emits the numerals
from 1 to 1,000,000 in ascending order, and then ends.
@@ -3549,7 +3828,7 @@ constructor and implement _both_ the [`readable._read()`][] and
##### `new stream.Duplex(options)`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Passed to both `Writable` and `Readable`
constructors. Also has the following fields:
@@ -3605,7 +3884,7 @@ const myDuplex = new Duplex({
},
write(chunk, encoding, callback) {
// ...
- }
+ },
});
```
@@ -3637,7 +3916,7 @@ pipeline(
} catch (err) {
callback(err);
}
- }
+ },
}),
fs.createWriteStream('valid-object.json'),
(err) => {
@@ -3646,7 +3925,7 @@ pipeline(
} else {
console.log('completed');
}
- }
+ },
);
```
@@ -3717,7 +3996,7 @@ const myTransform = new Transform({
// Push the data onto the readable queue.
callback(null, '0'.repeat(data.length % 2) + data);
- }
+ },
});
myTransform.setEncoding('ascii');
@@ -3797,7 +4076,7 @@ const { Transform } = require('node:stream');
const myTransform = new Transform({
transform(chunk, encoding, callback) {
// ...
- }
+ },
});
```
@@ -3845,7 +4124,7 @@ user programs.
##### `transform._transform(chunk, encoding, callback)`
-* `chunk` [`Buffer`](/api/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `Buffer` to be transformed, converted from
+* `chunk` [`Buffer`](/api/v19/buffer#buffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The `Buffer` to be transformed, converted from
the `string` passed to [`stream.write()`][stream-write]. If the stream's
`decodeStrings` option is `false` or the stream is operating in object mode,
the chunk will not be converted & will be whatever was passed to
@@ -3906,7 +4185,7 @@ primarily for examples and testing, but there are some use cases where
### Additional notes
-
+
#### Streams compatibility with async generators and async iterators
@@ -3998,11 +4277,11 @@ pipelinePromise(iterator, writable)
});
```
-
+
#### Compatibility with older Node.js versions
-
+
Prior to Node.js 0.10, the `Readable` stream interface was simpler, but also
less powerful and less useful.
@@ -4170,7 +4449,11 @@ contain multi-byte characters.
[stream-_write]: #writable_writechunk-encoding-callback
[stream-_writev]: #writable_writevchunks-callback
[stream-end]: #writableendchunk-encoding-callback
+[stream-finished]: #streamfinishedstream-options-callback
+[stream-finished-promise]: #streamfinishedstream-options
[stream-pause]: #readablepause
+[stream-pipeline]: #streampipelinesource-transforms-destination-callback
+[stream-pipeline-promise]: #streampipelinesource-transforms-destination-options
[stream-push]: #readablepushchunk-encoding
[stream-read]: #readablereadsize
[stream-resume]: #readableresume
diff --git a/content/api/v19/string_decoder.en.md b/content/api/v19/string_decoder.en.md
index 03645aed17..93145e5b85 100644
--- a/content/api/v19/string_decoder.en.md
+++ b/content/api/v19/string_decoder.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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
@@ -53,7 +57,7 @@ console.log(decoder.end(Buffer.from([0xAC])));
#### `new StringDecoder([encoding])`
-
+
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The character [encoding][] the `StringDecoder` will use.
**Default:** `'utf8'`.
@@ -62,9 +66,9 @@ Creates a new `StringDecoder` instance.
#### `stringDecoder.end([buffer])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A `Buffer`, or `TypedArray`, or
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A `Buffer`, or `TypedArray`, or
`DataView` containing the bytes to decode.
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -78,9 +82,9 @@ After `end()` is called, the `stringDecoder` object can be reused for new input.
#### `stringDecoder.write(buffer)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A `Buffer`, or `TypedArray`, or
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A `Buffer`, or `TypedArray`, or
`DataView` containing the bytes to decode.
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
diff --git a/content/api/v19/synopsis.en.md b/content/api/v19/synopsis.en.md
index 0bb3a684e0..7d214f3c72 100644
--- a/content/api/v19/synopsis.en.md
+++ b/content/api/v19/synopsis.en.md
@@ -7,9 +7,9 @@ version: 'v19'
### Usage
-
+
-
+
`node [options] [V8 options] [script.js | -e "script" | - ] [arguments]`
diff --git a/content/api/v19/test.en.md b/content/api/v19/test.en.md
index 93ead19fa1..218dcc687f 100644
--- a/content/api/v19/test.en.md
+++ b/content/api/v19/test.en.md
@@ -5,31 +5,33 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
-The `node:test` module facilitates the creation of JavaScript tests that
-report results in [TAP][] format. To access it:
+Experimental
-```mjs
-import test from 'node:test';
-```
+
+
+
+
+The `node:test` module facilitates the creation of JavaScript tests.
+To access it:
-```cjs
+```mjs|cjs
+import test from 'node:test';
+--------------
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');
```
@@ -96,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
@@ -127,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
@@ -158,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', () => {
@@ -181,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');
```
@@ -263,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
@@ -272,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 marked as failed by the `test` module and reported as diagnostic
-warnings in the top level of the file's TAP output.
+warnings at the top level by the TestsStream.
```js
test('a test that creates asynchronous activity', (t) => {
@@ -296,6 +292,27 @@ test('a test that creates asynchronous activity', (t) => {
});
```
+### Watch mode
+
+
+
+
+
+Experimental
+
+
+
+The Node.js test runner supports running in watch mode by passing the `--watch` flag:
+
+```bash
+node --test --watch
+```
+
+In watch mode, the test runner will watch for changes to test files and
+their dependencies. When a change is detected, the test runner will
+rerun the tests affected by the change.
+The test runner will continue to run until the process is terminated.
+
### Running tests from the command line
The Node.js test runner can be invoked from the command line by passing the
@@ -357,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`
@@ -364,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';
@@ -385,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');
@@ -440,22 +505,203 @@ 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/v19/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, or a value provided for [`--import`][].
+
+#### 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])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for running tests. The following
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][].
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows aborting an in-progress test execution.
+ * `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.
If unspecified, subtests inherit this value from their parent.
@@ -465,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/test#tapstream)
+* Returns: TestsStream
```js
run({ files: [path.resolve('./tests/test.js')] })
@@ -474,7 +720,7 @@ run({ files: [path.resolve('./tests/test.js')] })
### `test([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`
@@ -483,16 +729,15 @@ 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
`only` tests, then this test will be run. Otherwise, the test is skipped.
**Default:** `false`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows aborting an in-progress test.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows aborting an in-progress test.
* `skip` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If truthy, the test is skipped. If a string is
provided, that string is displayed in the test results as the reason for
skipping the test. **Default:** `false`.
@@ -506,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) => {
@@ -553,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.
@@ -567,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`.
+
+
+Shorthand for [`test()`][].
-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.
+The `it()` function is imported from the `node:test` module.
### `it.skip([name][, options][, fn])`
@@ -593,9 +838,16 @@ 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])`
-
+
* `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 hook function.
If the hook uses callbacks,
@@ -603,7 +855,7 @@ same as [`it([name], { todo: true }[, fn])`][it options].
function.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the hook. The following
properties are supported:
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows aborting an in-progress hook.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows aborting an in-progress hook.
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
**Default:** `Infinity`.
@@ -621,7 +873,7 @@ describe('tests', async () => {
### `after([fn][, options])`
-
+
* `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 hook function.
If the hook uses callbacks,
@@ -629,7 +881,7 @@ describe('tests', async () => {
function.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the hook. The following
properties are supported:
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows aborting an in-progress hook.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows aborting an in-progress hook.
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
**Default:** `Infinity`.
@@ -647,7 +899,7 @@ describe('tests', async () => {
### `beforeEach([fn][, options])`
-
+
* `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 hook function.
If the hook uses callbacks,
@@ -655,7 +907,7 @@ describe('tests', async () => {
function.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the hook. The following
properties are supported:
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows aborting an in-progress hook.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows aborting an in-progress hook.
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
**Default:** `Infinity`.
@@ -665,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');
});
@@ -674,7 +926,7 @@ describe('tests', async () => {
### `afterEach([fn][, options])`
-
+
* `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 hook function.
If the hook uses callbacks,
@@ -682,7 +934,7 @@ describe('tests', async () => {
function.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the hook. The following
properties are supported:
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows aborting an in-progress hook.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows aborting an in-progress hook.
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
**Default:** `Infinity`.
@@ -692,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');
});
@@ -701,14 +953,14 @@ describe('tests', async () => {
### `MockFunctionContext`
-
+
The `MockFunctionContext` class is used to inspect or manipulate the behavior of
mocks created via the [`MockTracker`][] APIs.
#### `ctx.calls`
-
+
* [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
@@ -728,7 +980,7 @@ mock. Each entry in the array is an object with the following properties.
#### `ctx.callCount()`
-
+
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of times that this mock has been invoked.
@@ -738,7 +990,7 @@ is a getter that creates a copy of the internal call tracking array.
#### `ctx.mockImplementation(implementation)`
-
+
* `implementation` [`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 to be used as the
mock's new implementation.
@@ -773,7 +1025,7 @@ test('changes a mock behavior', (t) => {
#### `ctx.mockImplementationOnce(implementation[, onCall])`
-
+
* `implementation` [`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 to be used as the
mock's implementation for the invocation number specified by `onCall`.
@@ -813,16 +1065,22 @@ test('changes a mock behavior once', (t) => {
});
```
+#### `ctx.resetCalls()`
+
+
+
+Resets the call history of the mock function.
+
#### `ctx.restore()`
-
+
Resets the implementation of the mock function to its original behavior. The
mock can still be used after calling this function.
### `MockTracker`
-
+
The `MockTracker` class is used to manage mocking functionality. The test runner
module provides a top level `mock` export which is a `MockTracker` instance.
@@ -831,7 +1089,7 @@ Each test also provides its own `MockTracker` instance via the test context's
#### `mock.fn([original[, implementation]][, options])`
-
+
* `original` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) | [`AsyncFunction`](https://tc39.es/ecma262/#sec-async-function-constructor) An optional function to create a mock on.
**Default:** A no-op function.
@@ -878,9 +1136,16 @@ test('mocks a counting function', (t) => {
});
```
+#### `mock.getter(object, methodName[, implementation][, options])`
+
+
+
+This function is syntax sugar for [`MockTracker.method`][] with `options.getter`
+set to `true`.
+
#### `mock.method(object, methodName[, implementation][, options])`
-
+
* `object` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The object whose method is being mocked.
* `methodName` [`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 identifier of the method on `object` to mock.
@@ -932,7 +1197,7 @@ test('spies on an object method', (t) => {
#### `mock.reset()`
-
+
This function restores the default behavior of all mocks that were previously
created by this `MockTracker` and disassociates the mocks from the
@@ -946,54 +1211,129 @@ function manually is recommended.
#### `mock.restoreAll()`
-
+
This function restores the default behavior of all mocks that were previously
created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does
not disassociate the mocks from the `MockTracker` instance.
-### `TapStream`
+#### `mock.setter(object, methodName[, implementation][, options])`
+
+
+
+This function is syntax sugar for [`MockTracker.method`][] with `options.setter`
+set to `true`.
+
+### `TestsStream`
+
+
-
+* Extends [`ReadableStream`](/api/v19/webstreams#readablestream)
-* Extends [`ReadableStream`](/api/webstreams#readablestream)
+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
-A successful call to [`run()`][] method will return a new [`TapStream`](/api/test#tapstream)
-object, streaming a [TAP][] output
-`TapStream` 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.
#### `'test:fail'`
* `data` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `duration` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The test duration.
- * `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The failure casing test to fail.
+ * `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.
#### `'test:pass'`
* `data` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `duration` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The test duration.
+ * `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`
-
+
An instance of `TestContext` is passed to each test function in order to
interact with the test runner. However, the `TestContext` constructor is not
@@ -1001,7 +1341,7 @@ exposed as part of the API.
#### `context.beforeEach([fn][, options])`
-
+
* `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 hook function. The first argument
to this function is a [`TestContext`][] object. If the hook uses callbacks,
@@ -1009,7 +1349,7 @@ exposed as part of the API.
function.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the hook. The following
properties are supported:
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows aborting an in-progress hook.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows aborting an in-progress hook.
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
**Default:** `Infinity`.
@@ -1024,14 +1364,39 @@ test('top level test', async (t) => {
'This is a subtest',
(t) => {
assert.ok('some relevant assertion here');
- }
+ },
);
});
```
+#### `context.after([fn][, options])`
+
+
+
+* `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 hook function. The first argument
+ to this function is a [`TestContext`][] object. If the hook uses callbacks,
+ the callback function is passed as the second argument. **Default:** A no-op
+ function.
+* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the hook. The following
+ properties are supported:
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows aborting an in-progress hook.
+ * `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number of milliseconds the hook will fail after.
+ If unspecified, subtests inherit this value from their parent.
+ **Default:** `Infinity`.
+
+This function is used to create a hook that runs after the current test
+finishes.
+
+```js
+test('top level test', async (t) => {
+ t.after((t) => t.diagnostic(`finished running ${t.name}`));
+ assert.ok('some relevant assertion here');
+});
+```
+
#### `context.afterEach([fn][, options])`
-
+
* `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 hook function. The first argument
to this function is a [`TestContext`][] object. If the hook uses callbacks,
@@ -1039,7 +1404,7 @@ test('top level test', async (t) => {
function.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Configuration options for the hook. The following
properties are supported:
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows aborting an in-progress hook.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows aborting an in-progress hook.
* `timeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A number of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
**Default:** `Infinity`.
@@ -1054,18 +1419,18 @@ test('top level test', async (t) => {
'This is a subtest',
(t) => {
assert.ok('some relevant assertion here');
- }
+ },
);
});
```
#### `context.diagnostic(message)`
-
+
-* `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.
@@ -1077,13 +1442,13 @@ test('top level test', (t) => {
#### `context.name`
-
+
The name of the test.
#### `context.runOnly(shouldRunOnlyTests)`
-
+
* `shouldRunOnlyTests` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Whether or not to run `only` tests.
@@ -1105,9 +1470,9 @@ test('top level test', (t) => {
#### `context.signal`
-
+
-* [`AbortSignal`](/api/globals#abortsignal) Can be used to abort test subtasks when the test has been
+* [`AbortSignal`](/api/v19/globals#abortsignal) Can be used to abort test subtasks when the test has been
aborted.
```js
@@ -1118,12 +1483,12 @@ test('top level test', async (t) => {
#### `context.skip([message])`
-
+
-* `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.
@@ -1136,12 +1501,12 @@ test('top level test', (t) => {
#### `context.todo([message])`
-
+
-* `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
@@ -1153,20 +1518,23 @@ test('top level test', (t) => {
#### `context.test([name][, options][, fn])`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The name of the subtest, 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 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`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows aborting an in-progress test.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows aborting an in-progress test.
* `skip` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If truthy, the test is skipped. If a string is
provided, that string is displayed in the test results as the reason for
skipping the test. **Default:** `false`.
@@ -1192,14 +1560,14 @@ test('top level test', async (t) => {
{ only: false, skip: false, concurrency: 1, todo: false },
(t) => {
assert.ok('some relevant assertion here');
- }
+ },
);
});
```
### `SuiteContext`
-
+
An instance of `SuiteContext` is passed to each suite function in order to
interact with the test runner. However, the `SuiteContext` constructor is not
@@ -1207,30 +1575,40 @@ exposed as part of the API.
#### `context.name`
-
+
The name of the suite.
#### `context.signal`
-
+
-* [`AbortSignal`](/api/globals#abortsignal) Can be used to abort test subtasks when the test has been
+* [`AbortSignal`](/api/v19/globals#abortsignal) Can be used to abort test subtasks when the test has been
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
[`--test-only`]: /api/v19/cli#--test-only
+[`--test-reporter-destination`]: /api/v19/cli#--test-reporter-destination
+[`--test-reporter`]: /api/v19/cli#--test-reporter
[`--test`]: /api/v19/cli#--test
[`MockFunctionContext`]: #class-mockfunctioncontext
+[`MockTracker.method`]: #mockmethodobject-methodname-implementation-options
[`MockTracker`]: #class-mocktracker
+[`NODE_V8_COVERAGE`]: /api/v19/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/v19/stream#streamcomposestreams
+[test reporters]: #test-reporters
[test runner execution model]: #test-runner-execution-model
diff --git a/content/api/v19/timers.en.md b/content/api/v19/timers.en.md
index 6fad373125..470cd13035 100644
--- a/content/api/v19/timers.en.md
+++ b/content/api/v19/timers.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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
@@ -32,7 +36,7 @@ functions that can be used to control this default behavior.
#### `immediate.hasRef()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -40,9 +44,9 @@ If true, the `Immediate` object will keep the Node.js event loop active.
#### `immediate.ref()`
-
+
-* Returns: [`Immediate`](/api/timers#immediate) a reference to `immediate`
+* Returns: [`Immediate`](/api/v19/timers#immediate) a reference to `immediate`
When called, requests that the Node.js event loop _not_ exit so long as the
`Immediate` is active. Calling `immediate.ref()` multiple times will have no
@@ -53,9 +57,9 @@ to call `immediate.ref()` unless `immediate.unref()` had been called previously.
#### `immediate.unref()`
-
+
-* Returns: [`Immediate`](/api/timers#immediate) a reference to `immediate`
+* Returns: [`Immediate`](/api/v19/timers#immediate) a reference to `immediate`
When called, the active `Immediate` object will not require the Node.js event
loop to remain active. If there is no other activity keeping the event loop
@@ -76,17 +80,21 @@ control this default behavior.
#### `timeout.close()`
-
+
+
+
-
+Legacy: Use [`clearTimeout()`][] instead.
-* Returns: [`Timeout`](/api/timers#timeout) a reference to `timeout`
+
+
+* Returns: [`Timeout`](/api/v19/timers#timeout) a reference to `timeout`
Cancels the timeout.
#### `timeout.hasRef()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -94,9 +102,9 @@ If true, the `Timeout` object will keep the Node.js event loop active.
#### `timeout.ref()`
-
+
-* Returns: [`Timeout`](/api/timers#timeout) a reference to `timeout`
+* Returns: [`Timeout`](/api/v19/timers#timeout) a reference to `timeout`
When called, requests that the Node.js event loop _not_ exit so long as the
`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect.
@@ -106,9 +114,9 @@ to call `timeout.ref()` unless `timeout.unref()` had been called previously.
#### `timeout.refresh()`
-
+
-* Returns: [`Timeout`](/api/timers#timeout) a reference to `timeout`
+* Returns: [`Timeout`](/api/v19/timers#timeout) a reference to `timeout`
Sets the timer's start time to the current time, and reschedules the timer to
call its callback at the previously specified duration adjusted to the current
@@ -120,9 +128,9 @@ timer.
#### `timeout.unref()`
-
+
-* Returns: [`Timeout`](/api/timers#timeout) a reference to `timeout`
+* Returns: [`Timeout`](/api/v19/timers#timeout) a reference to `timeout`
When called, the active `Timeout` object will not require the Node.js event loop
to remain active. If there is no other activity keeping the event loop running,
@@ -131,7 +139,7 @@ the process may exit before the `Timeout` object's callback is invoked. Calling
#### `timeout[Symbol.toPrimitive]()`
-
+
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) a number that can be used to reference this `timeout`
@@ -151,12 +159,12 @@ event loop is doing.
#### `setImmediate(callback[, ...args])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to call at the end of this turn of
the Node.js [Event Loop][]
* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional arguments to pass when the `callback` is called.
-* Returns: [`Immediate`](/api/timers#immediate) for use with [`clearImmediate()`][]
+* Returns: [`Immediate`](/api/v19/timers#immediate) for use with [`clearImmediate()`][]
Schedules the "immediate" execution of the `callback` after I/O events'
callbacks.
@@ -174,13 +182,13 @@ This method has a custom variant for promises that is available using
#### `setInterval(callback[, delay[, ...args]])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to call when the timer elapses.
* `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before calling the
`callback`. **Default:** `1`.
* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional arguments to pass when the `callback` is called.
-* Returns: [`Timeout`](/api/timers#timeout) for use with [`clearInterval()`][]
+* Returns: [`Timeout`](/api/v19/timers#timeout) for use with [`clearInterval()`][]
Schedules repeated execution of `callback` every `delay` milliseconds.
@@ -194,13 +202,13 @@ This method has a custom variant for promises that is available using
#### `setTimeout(callback[, delay[, ...args]])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function to call when the timer elapses.
* `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before calling the
`callback`. **Default:** `1`.
* `...args` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional arguments to pass when the `callback` is called.
-* Returns: [`Timeout`](/api/timers#timeout) for use with [`clearTimeout()`][]
+* Returns: [`Timeout`](/api/v19/timers#timeout) for use with [`clearTimeout()`][]
Schedules execution of a one-time `callback` after `delay` milliseconds.
@@ -239,7 +247,7 @@ setImmediatePromise('foobar', { signal })
.then(console.log)
.catch((err) => {
if (err.name === 'AbortError')
- console.log('The immediate was aborted');
+ console.error('The immediate was aborted');
});
ac.abort();
@@ -257,7 +265,7 @@ setTimeoutPromise(1000, 'foobar', { signal })
.then(console.log)
.catch((err) => {
if (err.name === 'AbortError')
- console.log('The timeout was aborted');
+ console.error('The timeout was aborted');
});
ac.abort();
@@ -265,48 +273,46 @@ ac.abort();
#### `clearImmediate(immediate)`
-
+
-* `immediate` [`Immediate`](/api/timers#immediate) An `Immediate` object as returned by
+* `immediate` [`Immediate`](/api/v19/timers#immediate) An `Immediate` object as returned by
[`setImmediate()`][].
Cancels an `Immediate` object created by [`setImmediate()`][].
#### `clearInterval(timeout)`
-
+
-* `timeout` [`Timeout`](/api/timers#timeout) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A `Timeout` object as returned by [`setInterval()`][]
+* `timeout` [`Timeout`](/api/v19/timers#timeout) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A `Timeout` object as returned by [`setInterval()`][]
or the [primitive][] of the `Timeout` object as a string or a number.
Cancels a `Timeout` object created by [`setInterval()`][].
#### `clearTimeout(timeout)`
-
+
-* `timeout` [`Timeout`](/api/timers#timeout) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A `Timeout` object as returned by [`setTimeout()`][]
+* `timeout` [`Timeout`](/api/v19/timers#timeout) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A `Timeout` object as returned by [`setTimeout()`][]
or the [primitive][] of the `Timeout` object as a string or a number.
Cancels a `Timeout` object created by [`setTimeout()`][].
### Timers Promises API
-
+
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,
@@ -316,7 +322,7 @@ const {
#### `timersPromises.setTimeout([delay[, value[, options]]])`
-
+
* `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before fulfilling the
promise. **Default:** `1`.
@@ -325,10 +331,10 @@ const {
* `ref` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `false` to indicate that the scheduled `Timeout`
should not require the Node.js event loop to remain active.
**Default:** `true`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An optional `AbortSignal` that can be used to
+ * `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';
@@ -336,9 +342,7 @@ import {
const res = await setTimeout(100, 'result');
console.log(res); // Prints 'result'
-```
-
-```cjs
+--------------
const {
setTimeout,
} = require('node:timers/promises');
@@ -350,17 +354,17 @@ setTimeout(100, 'result').then((res) => {
#### `timersPromises.setImmediate([value[, options]])`
-
+
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) A value with which the promise is fulfilled.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `ref` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `false` to indicate that the scheduled `Immediate`
should not require the Node.js event loop to remain active.
**Default:** `true`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An optional `AbortSignal` that can be used to
+ * `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';
@@ -368,9 +372,7 @@ import {
const res = await setImmediate('result');
console.log(res); // Prints 'result'
-```
-
-```cjs
+--------------
const {
setImmediate,
} = require('node:timers/promises');
@@ -382,7 +384,7 @@ setImmediate('result').then((res) => {
#### `timersPromises.setInterval([delay[, value[, options]]])`
-
+
Returns an async iterator that generates values in an interval of `delay` ms.
If `ref` is `true`, you need to call `next()` of async iterator explicitly
@@ -396,10 +398,10 @@ or implicitly to keep the event loop alive.
between iterations should not require the Node.js event loop to
remain active.
**Default:** `true`.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An optional `AbortSignal` that can be used to
+ * `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';
@@ -412,9 +414,7 @@ for await (const startTime of setInterval(interval, Date.now())) {
break;
}
console.log(Date.now());
-```
-
-```cjs
+--------------
const {
setInterval,
} = require('node:timers/promises');
@@ -433,14 +433,18 @@ const interval = 100;
#### `timersPromises.scheduler.wait(delay[, options])`
-
+
+
+
+
+Experimental
-
+
* `delay` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of milliseconds to wait before resolving the
promise.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `signal` [`AbortSignal`](/api/globals#abortsignal) An optional `AbortSignal` that can be used to
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) An optional `AbortSignal` that can be used to
cancel waiting.
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
@@ -459,9 +463,13 @@ await scheduler.wait(1000); // Wait one second before continuing
#### `timersPromises.scheduler.yield()`
-
+
+
+
+
+Experimental
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
diff --git a/content/api/v19/tls.en.md b/content/api/v19/tls.en.md
index 6730186911..f0319f6c84 100644
--- a/content/api/v19/tls.en.md
+++ b/content/api/v19/tls.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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.
@@ -32,7 +36,7 @@ let tls;
try {
tls = require('node:tls');
} catch (err) {
- console.log('tls support is disabled!');
+ console.error('tls support is disabled!');
}
```
@@ -50,7 +54,7 @@ let tls;
try {
tls = await import('node:tls');
} catch (err) {
- console.log('tls support is disabled!');
+ console.error('tls support is disabled!');
}
```
@@ -109,7 +113,7 @@ Where:
#### Perfect forward secrecy
-
+
The term _[forward secrecy][]_ or _perfect forward secrecy_ describes a feature
of key-agreement (i.e., key-exchange) methods. That is, the server and client
@@ -126,30 +130,24 @@ 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, but it is not optional for
-TLSv1.3, because all TLSv1.3 cipher suites use ECDHE.
+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).
#### ALPN and SNI
-
+
ALPN (Application-Layer Protocol Negotiation Extension) and
SNI (Server Name Indication) are TLS handshake extensions:
@@ -160,7 +158,7 @@ SNI (Server Name Indication) are TLS handshake extensions:
#### Pre-shared keys
-
+
TLS-PSK support is available as an alternative to normal certificate-based
authentication. It uses a pre-shared key instead of certificates to
@@ -194,7 +192,7 @@ limitations of the underlying OpenSSL API.
#### Client-initiated renegotiation attack mitigation
-
+
The TLS protocol allows clients to renegotiate certain aspects of the TLS
session. Unfortunately, session renegotiation requires a disproportionate amount
@@ -359,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
@@ -446,16 +468,20 @@ has the property `code` which can take one of the following values:
### `tls.CryptoStream`
-
+
-
+
+
+Deprecated: Use [`tls.TLSSocket`][] instead.
+
+
The `tls.CryptoStream` class represents a stream of encrypted data. This class
is deprecated and should no longer be used.
#### `cryptoStream.bytesWritten`
-
+
The `cryptoStream.bytesWritten` property returns the total number of bytes
written to the underlying socket _including_ the bytes required for the
@@ -463,15 +489,19 @@ implementation of the TLS protocol.
### `tls.SecurePair`
-
+
+
+
-
+Deprecated: Use [`tls.TLSSocket`][] instead.
+
+
Returned by [`tls.createSecurePair()`][].
#### `'secure'`
-
+
The `'secure'` event is emitted by the `SecurePair` object once a secure
connection has been established.
@@ -483,17 +513,17 @@ certificate used is properly authorized.
### `tls.Server`
-
+
-* Extends: [`net.Server`](/api/net#netserver)
+* Extends: [`net.Server`](/api/v19/net#netserver)
Accepts encrypted connections using TLS or SSL.
#### `'connection'`
-
+
-* `socket` [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`stream.Duplex`](/api/v19/stream#streamduplex)
This event is emitted when a new TCP stream is established, before the TLS
handshake begins. `socket` is typically an object of type [`net.Socket`][] but
@@ -505,10 +535,10 @@ into the TLS server. In that case, any [`Duplex`][] stream can be passed.
#### `'keylog'`
-
+
-* `line` [`Buffer`](/api/buffer#buffer) Line of ASCII text, in NSS `SSLKEYLOGFILE` format.
-* `tlsSocket` [`tls.TLSSocket`](/api/tls#tlstlssocket) The `tls.TLSSocket` instance on which it was
+* `line` [`Buffer`](/api/v19/buffer#buffer) Line of ASCII text, in NSS `SSLKEYLOGFILE` format.
+* `tlsSocket` [`tls.TLSSocket`](/api/v19/tls#tlstlssocket) The `tls.TLSSocket` instance on which it was
generated.
The `keylog` event is emitted when key material is generated or received by
@@ -532,7 +562,7 @@ server.on('keylog', (line, tlsSocket) => {
#### `'newSession'`
-
+
The `'newSession'` event is emitted upon creation of a new TLS session. This may
be used to store sessions in external storage. The data should be provided to
@@ -540,8 +570,8 @@ the [`'resumeSession'`][] callback.
The listener callback is passed three arguments when called:
-* `sessionId` [`Buffer`](/api/buffer#buffer) The TLS session identifier
-* `sessionData` [`Buffer`](/api/buffer#buffer) The TLS session data
+* `sessionId` [`Buffer`](/api/v19/buffer#buffer) The TLS session identifier
+* `sessionData` [`Buffer`](/api/v19/buffer#buffer) The TLS session data
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function taking no arguments that must be
invoked in order for data to be sent or received over the secure connection.
@@ -550,13 +580,13 @@ after the addition of the event listener.
#### `'OCSPRequest'`
-
+
The `'OCSPRequest'` event is emitted when the client sends a certificate status
request. The listener callback is passed three arguments when called:
-* `certificate` [`Buffer`](/api/buffer#buffer) The server certificate
-* `issuer` [`Buffer`](/api/buffer#buffer) The issuer's certificate
+* `certificate` [`Buffer`](/api/v19/buffer#buffer) The server certificate
+* `issuer` [`Buffer`](/api/v19/buffer#buffer) The issuer's certificate
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function that must be invoked to provide
the results of the OCSP request.
@@ -596,17 +626,17 @@ An npm module like [asn1.js][] may be used to parse the certificates.
#### `'resumeSession'`
-
+
The `'resumeSession'` event is emitted when the client requests to resume a
previous TLS session. The listener callback is passed two arguments when
called:
-* `sessionId` [`Buffer`](/api/buffer#buffer) The TLS session identifier
+* `sessionId` [`Buffer`](/api/v19/buffer#buffer) The TLS session identifier
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A callback function to be called when the prior session
has been recovered: `callback([err[, sessionData]])`
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
- * `sessionData` [`Buffer`](/api/buffer#buffer)
+ * `sessionData` [`Buffer`](/api/v19/buffer#buffer)
The event listener should perform a lookup in external storage for the
`sessionData` saved by the [`'newSession'`][] event handler using the given
@@ -634,13 +664,13 @@ server.on('resumeSession', (id, cb) => {
#### `'secureConnection'`
-
+
The `'secureConnection'` event is emitted after the handshaking process for a
new connection has successfully completed. The listener callback is passed a
single argument when called:
-* `tlsSocket` [`tls.TLSSocket`](/api/tls#tlstlssocket) The established TLS socket.
+* `tlsSocket` [`tls.TLSSocket`](/api/v19/tls#tlstlssocket) The established TLS socket.
The `tlsSocket.authorized` property is a `boolean` indicating whether the
client has been verified by one of the supplied Certificate Authorities for the
@@ -657,19 +687,19 @@ requested via SNI.
#### `'tlsClientError'`
-
+
The `'tlsClientError'` event is emitted when an error occurs before a secure
connection is established. The listener callback is passed two arguments when
called:
* `exception` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) The `Error` object describing the error
-* `tlsSocket` [`tls.TLSSocket`](/api/tls#tlstlssocket) The `tls.TLSSocket` instance from which the
+* `tlsSocket` [`tls.TLSSocket`](/api/v19/tls#tlstlssocket) The `tls.TLSSocket` instance from which the
error originated.
#### `server.addContext(hostname, context)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A SNI host name or wildcard (e.g. `'*'`)
* `context` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object containing any of the possible properties
@@ -684,7 +714,7 @@ used.
#### `server.address()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -694,11 +724,11 @@ more information.
#### `server.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A listener callback that will be registered to listen
for the server instance's `'close'` event.
-* Returns: [`tls.Server`](/api/tls#tlsserver)
+* Returns: [`tls.Server`](/api/v19/tls#tlsserver)
The `server.close()` method stops the server from accepting new connections.
@@ -707,9 +737,9 @@ when the server has no more open connections.
#### `server.getTicketKeys()`
-
+
-* Returns: [`Buffer`](/api/buffer#buffer) A 48-byte buffer containing the session ticket keys.
+* Returns: [`Buffer`](/api/v19/buffer#buffer) A 48-byte buffer containing the session ticket keys.
Returns the session ticket keys.
@@ -722,7 +752,7 @@ This method is identical to [`server.listen()`][] from [`net.Server`][].
#### `server.setSecureContext(options)`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object containing any of the possible properties from
the [`tls.createSecureContext()`][] `options` arguments (e.g. `key`, `cert`,
@@ -733,9 +763,9 @@ existing server. Existing connections to the server are not interrupted.
#### `server.setTicketKeys(keys)`
-
+
-* `keys` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A 48-byte buffer containing the session
+* `keys` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A 48-byte buffer containing the session
ticket keys.
Sets the session ticket keys.
@@ -747,9 +777,9 @@ See [Session Resumption][] for more information.
### `tls.TLSSocket`
-
+
-* Extends: [`net.Socket`](/api/net#netsocket)
+* Extends: [`net.Socket`](/api/v19/net#netsocket)
Performs transparent encryption of written data and all required TLS
negotiation.
@@ -762,9 +792,9 @@ connection is open.
#### `new tls.TLSSocket(socket[, options])`
-
+
-* `socket` [`net.Socket`](/api/net#netsocket) | [`stream.Duplex`](/api/stream#streamduplex)
+* `socket` [`net.Socket`](/api/v19/net#netsocket) | [`stream.Duplex`](/api/v19/stream#streamduplex)
On the server side, any `Duplex` stream. On the client side, any
instance of [`net.Socket`][] (for generic `Duplex` stream support
on the client side, [`tls.connect()`][] must be used).
@@ -773,7 +803,7 @@ connection is open.
* `isServer`: The SSL/TLS protocol is asymmetrical, TLSSockets must know if
they are to behave as a server or a client. If `true` the TLS socket will be
instantiated as a server. **Default:** `false`.
- * `server` [`net.Server`](/api/net#netserver) A [`net.Server`][] instance.
+ * `server` [`net.Server`](/api/v19/net#netserver) A [`net.Server`][] instance.
* `requestCert`: Whether to authenticate the remote peer by requesting a
certificate. Clients always request a server certificate. Servers
(`isServer` is true) may set `requestCert` to true to request a client
@@ -781,7 +811,7 @@ connection is open.
* `rejectUnauthorized`: See [`tls.createServer()`][]
* `ALPNProtocols`: See [`tls.createServer()`][]
* `SNICallback`: See [`tls.createServer()`][]
- * `session` [`Buffer`](/api/buffer#buffer) A `Buffer` instance containing a TLS session.
+ * `session` [`Buffer`](/api/v19/buffer#buffer) A `Buffer` instance containing a TLS session.
* `requestOCSP` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, specifies that the OCSP status request
extension will be added to the client hello and an `'OCSPResponse'` event
will be emitted on the socket before establishing a secure communication
@@ -796,9 +826,9 @@ Construct a new `tls.TLSSocket` object from an existing TCP socket.
#### `'keylog'`
-
+
-* `line` [`Buffer`](/api/buffer#buffer) Line of ASCII text, in NSS `SSLKEYLOGFILE` format.
+* `line` [`Buffer`](/api/v19/buffer#buffer) Line of ASCII text, in NSS `SSLKEYLOGFILE` format.
The `keylog` event is emitted on a `tls.TLSSocket` when key material
is generated or received by the socket. This keying material can be stored
@@ -816,20 +846,20 @@ tlsSocket.on('keylog', (line) => logFile.write(line));
#### `'OCSPResponse'`
-
+
The `'OCSPResponse'` event is emitted if the `requestOCSP` option was set
when the `tls.TLSSocket` was created and an OCSP response has been received.
The listener callback is passed a single argument when called:
-* `response` [`Buffer`](/api/buffer#buffer) The server's OCSP response
+* `response` [`Buffer`](/api/v19/buffer#buffer) The server's OCSP response
Typically, the `response` is a digitally signed object from the server's CA that
contains information about server's certificate revocation status.
#### `'secureConnect'`
-
+
The `'secureConnect'` event is emitted after the handshaking process for a new
connection has successfully completed. The listener callback will be called
@@ -841,14 +871,14 @@ determine if the server certificate was signed by one of the specified CAs. If
`tlsSocket.alpnProtocol` property can be checked to determine the negotiated
protocol.
-The `'secureConnect'` event is not emitted when a [`tls.TLSSocket`](/api/tls#tlstlssocket) is created
+The `'secureConnect'` event is not emitted when a [`tls.TLSSocket`](/api/v19/tls#tlstlssocket) is created
using the `new tls.TLSSocket()` constructor.
#### `'session'`
-
+
-* `session` [`Buffer`](/api/buffer#buffer)
+* `session` [`Buffer`](/api/v19/buffer#buffer)
The `'session'` event is emitted on a client `tls.TLSSocket` when a new session
or TLS ticket is available. This may or may not be before the handshake is
@@ -884,7 +914,7 @@ tlsSocket.once('session', (session) => {
#### `tlsSocket.address()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -894,14 +924,14 @@ underlying socket as reported by the operating system:
#### `tlsSocket.authorizationError`
-
+
Returns the reason why the peer's certificate was not been verified. This
property is set only when `tlsSocket.authorized === false`.
#### `tlsSocket.authorized`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -910,14 +940,14 @@ specified when creating the `tls.TLSSocket` instance, otherwise `false`.
#### `tlsSocket.disableRenegotiation()`
-
+
Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts
to renegotiate will trigger an `'error'` event on the `TLSSocket`.
#### `tlsSocket.enableTrace()`
-
+
When enabled, TLS packet trace information is written to `stderr`. This can be
used to debug TLS connection problems.
@@ -929,14 +959,14 @@ without notice, and should not be relied on.
#### `tlsSocket.encrypted`
-
+
Always returns `true`. This may be used to distinguish TLS sockets from regular
`net.Socket` instances.
#### `tlsSocket.exportKeyingMaterial(length, label[, context])`
-
+
* `length` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) number of bytes to retrieve from keying material
@@ -944,9 +974,9 @@ Always returns `true`. This may be used to distinguish TLS sockets from regular
value from the
[IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels).
-* `context` [`Buffer`](/api/buffer#buffer) Optionally provide a context.
+* `context` [`Buffer`](/api/v19/buffer#buffer) Optionally provide a context.
-* Returns: [`Buffer`](/api/buffer#buffer) requested bytes of the keying material
+* Returns: [`Buffer`](/api/v19/buffer#buffer) requested bytes of the keying material
Keying material is used for validations to prevent different kind of attacks in
network protocols, for example in the specifications of IEEE 802.1X.
@@ -971,7 +1001,7 @@ information.
#### `tlsSocket.getCertificate()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -986,7 +1016,7 @@ socket has been destroyed, `null` will be returned.
#### `tlsSocket.getCipher()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) OpenSSL name for the cipher suite.
@@ -1012,7 +1042,7 @@ for more information.
#### `tlsSocket.getEphemeralKeyInfo()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1027,9 +1057,9 @@ For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`.
#### `tlsSocket.getFinished()`
-
+
-* Returns: [`Buffer`](/api/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The latest `Finished` message that has been
+* Returns: [`Buffer`](/api/v19/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The latest `Finished` message that has been
sent to the socket as part of a SSL/TLS handshake, or `undefined` if
no `Finished` message has been sent yet.
@@ -1043,7 +1073,7 @@ to implement the `tls-unique` channel binding from [RFC 5929][].
#### `tlsSocket.getPeerCertificate([detailed])`
-
+
* `detailed` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Include the full certificate chain if `true`, otherwise
include just the peer's certificate.
@@ -1059,13 +1089,13 @@ certificate.
##### Certificate object
-
+
A certificate object has properties corresponding to the fields of the
certificate.
* `ca` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if a Certificate Authority (CA), `false` otherwise.
-* `raw` [`Buffer`](/api/buffer#buffer) The DER encoded X.509 certificate data.
+* `raw` [`Buffer`](/api/v19/buffer#buffer) The DER encoded X.509 certificate data.
* `subject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The certificate subject, described in terms of
Country (`C`), StateOrProvince (`ST`), Locality (`L`), Organization (`O`),
OrganizationalUnit (`OU`), and CommonName (`CN`). The CommonName is typically
@@ -1103,11 +1133,11 @@ For RSA keys, the following properties may be defined:
notation. Example: `'0x010001'`.
* `modulus` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The RSA modulus, as a hexadecimal string. Example:
`'B56CE45CB7...'`.
-* `pubkey` [`Buffer`](/api/buffer#buffer) The public key.
+* `pubkey` [`Buffer`](/api/v19/buffer#buffer) The public key.
For EC keys, the following properties may be defined:
-* `pubkey` [`Buffer`](/api/buffer#buffer) The public key.
+* `pubkey` [`Buffer`](/api/v19/buffer#buffer) The public key.
* `bits` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The key size in bits. Example: `256`.
* `asn1Curve` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) (Optional) The ASN.1 name of the OID of the elliptic
curve. Well-known curves are identified by an OID. While it is unusual, it is
@@ -1149,9 +1179,9 @@ Example certificate:
#### `tlsSocket.getPeerFinished()`
-
+
-* Returns: [`Buffer`](/api/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The latest `Finished` message that is expected
+* Returns: [`Buffer`](/api/v19/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type) The latest `Finished` message that is expected
or has actually been received from the socket as part of a SSL/TLS handshake,
or `undefined` if there is no `Finished` message so far.
@@ -1165,18 +1195,18 @@ to implement the `tls-unique` channel binding from [RFC 5929][].
#### `tlsSocket.getPeerX509Certificate()`
-
+
-* Returns: [`X509Certificate`](/api/crypto#x509certificate)
+* Returns: [`X509Certificate`](/api/v19/crypto#x509certificate)
-Returns the peer certificate as an [`X509Certificate`](/api/crypto#x509certificate) object.
+Returns the peer certificate as an [`X509Certificate`](/api/v19/crypto#x509certificate) object.
If there is no peer certificate, or the socket has been destroyed,
`undefined` will be returned.
#### `tlsSocket.getProtocol()`
-
+
* Returns: [`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)
@@ -1197,9 +1227,9 @@ See the OpenSSL [`SSL_get_version`][] documentation for more information.
#### `tlsSocket.getSession()`
-
+
-* [`Buffer`](/api/buffer#buffer)
+* [`Buffer`](/api/v19/buffer#buffer)
Returns the TLS session data or `undefined` if no session was
negotiated. On the client, the data can be provided to the `session` option of
@@ -1213,7 +1243,7 @@ must use the [`'session'`][] event (it also works for TLSv1.2 and below).
#### `tlsSocket.getSharedSigalgs()`
-
+
* Returns: [`Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) List of signature algorithms shared between the server and
the client in the order of decreasing preference.
@@ -1224,9 +1254,9 @@ for more information.
#### `tlsSocket.getTLSTicket()`
-
+
-* [`Buffer`](/api/buffer#buffer)
+* [`Buffer`](/api/v19/buffer#buffer)
For a client, returns the TLS session ticket if one is available, or
`undefined`. For a server, always returns `undefined`.
@@ -1237,18 +1267,18 @@ See [Session Resumption][] for more information.
#### `tlsSocket.getX509Certificate()`
-
+
-* Returns: [`X509Certificate`](/api/crypto#x509certificate)
+* Returns: [`X509Certificate`](/api/v19/crypto#x509certificate)
-Returns the local certificate as an [`X509Certificate`](/api/crypto#x509certificate) object.
+Returns the local certificate as an [`X509Certificate`](/api/v19/crypto#x509certificate) object.
If there is no local certificate, or the socket has been destroyed,
`undefined` will be returned.
#### `tlsSocket.isSessionReused()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the session was reused, `false` otherwise.
@@ -1256,7 +1286,7 @@ See [Session Resumption][] for more information.
#### `tlsSocket.localAddress`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1264,7 +1294,7 @@ Returns the string representation of the local IP address.
#### `tlsSocket.localPort`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1272,7 +1302,7 @@ Returns the numeric representation of the local port.
#### `tlsSocket.remoteAddress`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1281,7 +1311,7 @@ Returns the string representation of the remote IP address. For example,
#### `tlsSocket.remoteFamily`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1289,7 +1319,7 @@ Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
#### `tlsSocket.remotePort`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1297,7 +1327,7 @@ Returns the numeric representation of the remote port. For example, `443`.
#### `tlsSocket.renegotiate(options, callback)`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `rejectUnauthorized` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If not `false`, the server certificate is
@@ -1329,7 +1359,7 @@ protocol.
#### `tlsSocket.setMaxSendFragment(size)`
-
+
* `size` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The maximum TLS fragment size. The maximum value is `16384`.
**Default:** `16384`.
@@ -1347,7 +1377,7 @@ decrease overall server throughput.
### `tls.checkServerIdentity(hostname, cert)`
-
+
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The host name or IP address to verify the certificate
against.
@@ -1380,7 +1410,7 @@ was present (see [CVE-2021-44531][]). Applications that wish to accept
### `tls.connect(options[, callback])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `enableTrace`: See [`tls.createServer()`][]
@@ -1389,7 +1419,7 @@ was present (see [CVE-2021-44531][]). Applications that wish to accept
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Port the client should connect to.
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Creates Unix socket connection to path. If this option is
specified, `host` and `port` are ignored.
- * `socket` [`stream.Duplex`](/api/stream#streamduplex) Establish secure connection on a given socket
+ * `socket` [`stream.Duplex`](/api/v19/stream#streamduplex) Establish secure connection on a given socket
rather than creating a new socket. Typically, this is an instance of
[`net.Socket`][], but any `Duplex` stream is allowed.
If this option is specified, `path`, `host`, and `port` are ignored,
@@ -1425,7 +1455,7 @@ was present (see [CVE-2021-44531][]). Applications that wish to accept
of the server against the certificate but that's not applicable for PSK
because there won't be a certificate present.
More information can be found in the [RFC 4279][].
- * `ALPNProtocols`: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+ * `ALPNProtocols`: [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
An array of strings, `Buffer`s, `TypedArray`s, or `DataView`s, or a
single `Buffer`, `TypedArray`, or `DataView` containing the supported ALPN
protocols. `Buffer`s should have the format `[len][name][len][name]...`
@@ -1444,7 +1474,7 @@ was present (see [CVE-2021-44531][]). Applications that wish to accept
explicitly set) against the certificate. This should return an [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) if
verification fails. The method should return `undefined` if the `servername`
and `cert` are verified.
- * `session` [`Buffer`](/api/buffer#buffer) A `Buffer` instance, containing TLS session.
+ * `session` [`Buffer`](/api/v19/buffer#buffer) A `Buffer` instance, containing TLS session.
* `minDHSize` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Minimum size of the DH parameter in bits to accept a
TLS connection. When a server offers a DH parameter with a size less
than `minDHSize`, the TLS connection is destroyed and an error is thrown.
@@ -1463,7 +1493,7 @@ was present (see [CVE-2021-44531][]). Applications that wish to accept
`secureContext` option is missing, otherwise they are ignored.
* ...: Any [`socket.connect()`][] option not already listed.
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`tls.TLSSocket`](/api/tls#tlstlssocket)
+* Returns: [`tls.TLSSocket`](/api/v19/tls#tlstlssocket)
The `callback` function, if specified, will be added as a listener for the
[`'secureConnect'`][] event.
@@ -1513,12 +1543,12 @@ socket.on('end', () => {
### `tls.connect(path[, options][, callback])`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Default value for `options.path`.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) See [`tls.connect()`][].
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) See [`tls.connect()`][].
-* Returns: [`tls.TLSSocket`](/api/tls#tlstlssocket)
+* Returns: [`tls.TLSSocket`](/api/v19/tls#tlstlssocket)
Same as [`tls.connect()`][] except that `path` can be provided
as an argument instead of an option.
@@ -1527,13 +1557,13 @@ A path option, if specified, will take precedence over the path argument.
### `tls.connect(port[, host][, options][, callback])`
-
+
* `port` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Default value for `options.port`.
* `host` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Default value for `options.host`.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) See [`tls.connect()`][].
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) See [`tls.connect()`][].
-* Returns: [`tls.TLSSocket`](/api/tls#tlstlssocket)
+* Returns: [`tls.TLSSocket`](/api/v19/tls#tlstlssocket)
Same as [`tls.connect()`][] except that `port` and `host` can be provided
as arguments instead of options.
@@ -1543,10 +1573,10 @@ 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/buffer#buffer) Optionally override the trusted CA
+ * `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
certificates. Default is to trust the well-known CAs curated by Mozilla.
Mozilla's CAs are completely replaced when CAs are explicitly specified
using this option. The value can be a string or `Buffer`, or an `Array` of
@@ -1564,7 +1594,7 @@ argument.
For PEM encoded certificates, supported types are "TRUSTED CERTIFICATE",
"X509 CERTIFICATE", and "CERTIFICATE".
See also [`tls.rootCertificates`][].
- * `cert` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) Cert chains in PEM format. One
+ * `cert` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) Cert chains in PEM format. One
cert chain should be provided per private key. Each cert chain should
consist of the PEM formatted certificate for a provided private `key`,
followed by the PEM formatted intermediate certificates (if any), in order,
@@ -1585,14 +1615,12 @@ argument.
uppercased in order for OpenSSL to accept them.
* `clientCertEngine` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Name of an OpenSSL engine which can provide the
client certificate.
- * `crl` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) PEM formatted CRLs (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/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
@@ -1604,7 +1632,7 @@ argument.
preferences instead of the client's. When `true`, causes
`SSL_OP_CIPHER_SERVER_PREFERENCE` to be set in `secureOptions`, see
[OpenSSL Options][] for more information.
- * `key` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) Private keys in PEM
+ * `key` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) Private keys in PEM
format. PEM allows the option of private keys being encrypted. Encrypted
keys will be decrypted with `options.passphrase`. Multiple keys using
different algorithms can be provided either as an array of unencrypted key
@@ -1631,7 +1659,7 @@ argument.
**Default:** [`tls.DEFAULT_MIN_VERSION`][].
* `passphrase` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Shared passphrase used for a single private key and/or
a PFX.
- * `pfx` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/buffer#buffer) PFX or PKCS12 encoded
+ * `pfx` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Buffer`](/api/v19/buffer#buffer) PFX or PKCS12 encoded
private key and certificate chain. `pfx` is an alternative to providing
`key` and `cert` individually. PFX is usually encrypted, if it is,
`passphrase` will be used to decrypt it. Multiple PFX can be provided either
@@ -1655,7 +1683,7 @@ argument.
**Default:** none, see `minVersion`.
* `sessionIdContext` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Opaque identifier used by servers to ensure
session state is not shared between applications. Unused by clients.
- * `ticketKeys`: [`Buffer`](/api/buffer#buffer) 48-bytes of cryptographically strong pseudorandom
+ * `ticketKeys`: [`Buffer`](/api/v19/buffer#buffer) 48-bytes of cryptographically strong pseudorandom
data. See [Session Resumption][] for more information.
* `sessionTimeout` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of seconds after which a TLS session
created by the server will no longer be resumable. See
@@ -1669,8 +1697,9 @@ from `process.argv` as the default value of the `sessionIdContext` option, other
APIs that create secure contexts have no default value.
The `tls.createSecureContext()` method creates a `SecureContext` object. It is
-usable as an argument to several `tls` APIs, such as [`tls.createServer()`][]
-and [`server.addContext()`][], but has no public methods.
+usable as an argument to several `tls` APIs, such as [`server.addContext()`][],
+but has no public methods. The [`tls.Server`][] constructor and the
+[`tls.createServer()`][] method do not support the `secureContext` option.
A key is _required_ for ciphers that use certificates. Either `key` or
`pfx` can be used to provide it.
@@ -1678,11 +1707,22 @@ 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])`
-
+
+
+
+
+Deprecated: Use [`tls.TLSSocket`][] instead.
-
+
* `context` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A secure context object as returned by
`tls.createSecureContext()`
@@ -1697,12 +1737,12 @@ If the `ca` option is not given, then Node.js will default to using
* `secureContext`: A TLS context object from [`tls.createSecureContext()`][]
* `isServer`: If `true` the TLS socket will be instantiated in server-mode.
**Default:** `false`.
- * `server` [`net.Server`](/api/net#netserver) A [`net.Server`][] instance
+ * `server` [`net.Server`](/api/v19/net#netserver) A [`net.Server`][] instance
* `requestCert`: See [`tls.createServer()`][]
* `rejectUnauthorized`: See [`tls.createServer()`][]
* `ALPNProtocols`: See [`tls.createServer()`][]
* `SNICallback`: See [`tls.createServer()`][]
- * `session` [`Buffer`](/api/buffer#buffer) A `Buffer` instance containing a TLS session.
+ * `session` [`Buffer`](/api/v19/buffer#buffer) A `Buffer` instance containing a TLS session.
* `requestOCSP` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, specifies that the OCSP status request
extension will be added to the client hello and an `'OCSPResponse'` event
will be emitted on the socket before establishing a secure communication.
@@ -1737,10 +1777,10 @@ where `secureSocket` has the same API as `pair.cleartext`.
### `tls.createServer([options][, secureConnectionListener])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `ALPNProtocols`: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+ * `ALPNProtocols`: [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
An array of strings, `Buffer`s, `TypedArray`s, or `DataView`s, or a single
`Buffer`, `TypedArray`, or `DataView` containing the supported ALPN
protocols. `Buffer`s should have the format `[len][name][len][name]...`
@@ -1775,14 +1815,14 @@ where `secureSocket` has the same API as `pair.cleartext`.
If `callback` is called with a falsy `ctx` argument, the default secure
context of the server will be used. If `SNICallback` wasn't provided the
default callback with high-level API will be used (see below).
- * `ticketKeys`: [`Buffer`](/api/buffer#buffer) 48-bytes of cryptographically strong pseudorandom
+ * `ticketKeys`: [`Buffer`](/api/v19/buffer#buffer) 48-bytes of cryptographically strong pseudorandom
data. See [Session Resumption][] for more information.
* `pskCallback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
- * socket: [`tls.TLSSocket`](/api/tls#tlstlssocket) the server [`tls.TLSSocket`][] instance for
+ * socket: [`tls.TLSSocket`](/api/v19/tls#tlstlssocket) the server [`tls.TLSSocket`][] instance for
this connection.
* identity: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) identity parameter sent from the client.
- * Returns: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) pre-shared key that must either be
+ * Returns: [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) pre-shared key that must either be
a buffer or `null` to stop the negotiation process. Returned PSK must be
compatible with the selected cipher's digest.
@@ -1805,7 +1845,7 @@ where `secureSocket` has the same API as `pair.cleartext`.
are usually required.
* ...: Any [`net.createServer()`][] option can be provided.
* `secureConnectionListener` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
-* Returns: [`tls.Server`](/api/tls#tlsserver)
+* Returns: [`tls.Server`](/api/v19/tls#tlsserver)
Creates a new [`tls.Server`][]. The `secureConnectionListener`, if provided, is
automatically set as a listener for the [`'secureConnection'`][] event.
@@ -1827,7 +1867,7 @@ const options = {
requestCert: true,
// This is necessary only if the client uses a self-signed certificate.
- ca: [ fs.readFileSync('client-cert.pem') ]
+ ca: [ fs.readFileSync('client-cert.pem') ],
};
const server = tls.createServer(options, (socket) => {
@@ -1847,7 +1887,7 @@ The server can be tested by connecting to it using the example client from
### `tls.getCiphers()`
-
+
* Returns: string\[]
@@ -1867,7 +1907,7 @@ console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
### `tls.rootCertificates`
-
+
* string\[]
@@ -1879,7 +1919,7 @@ that is fixed at release time. It is identical on all supported platforms.
### `tls.DEFAULT_ECDH_CURVE`
-
+
The default curve name to use for ECDH key agreement in a tls server. The
default value is `'auto'`. See [`tls.createSecureContext()`][] for further
@@ -1887,7 +1927,7 @@ information.
### `tls.DEFAULT_MAX_VERSION`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The default value of the `maxVersion` option of
[`tls.createSecureContext()`][]. It can be assigned any of the supported TLS
@@ -1899,7 +1939,7 @@ information.
### `tls.DEFAULT_MIN_VERSION`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The default value of the `minVersion` option of
[`tls.createSecureContext()`][]. It can be assigned any of the supported TLS
@@ -1910,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 7ae915ed38..4a9ab6d550 100644
--- a/content/api/v19/tracing.en.md
+++ b/content/api/v19/tracing.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Experimental
+
+
+
+
The `node:trace_events` module provides a mechanism to centralize tracing
information generated by V8, Node.js core, and userspace code.
@@ -116,11 +120,11 @@ The features from this module are not available in [`Worker`][] threads.
### The `node:trace_events` module
-
+
#### `Tracing` object
-
+
The `Tracing` object is used to enable or disable tracing for sets of
categories. Instances are created using the `trace_events.createTracing()`
@@ -133,7 +137,7 @@ set of enabled trace event categories.
##### `tracing.categories`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -142,7 +146,7 @@ A comma-separated list of the trace event categories covered by this
##### `tracing.disable()`
-
+
Disables this `Tracing` object.
@@ -167,26 +171,26 @@ console.log(trace_events.getEnabledCategories());
##### `tracing.enable()`
-
+
Enables this `Tracing` object for the set of categories covered by the
`Tracing` object.
##### `tracing.enabled`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` only if the `Tracing` object has been enabled.
#### `trace_events.createTracing(options)`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `categories` string\[] An array of trace category names. Values included
in the array are coerced to a string when possible. An error will be
thrown if the value cannot be coerced.
-* Returns: [`Tracing`](/api/tracing#tracing-object).
+* Returns: [`Tracing`](/api/v19/tracing#tracing-object).
Creates and returns a `Tracing` object for the given set of `categories`.
@@ -201,7 +205,7 @@ tracing.disable();
#### `trace_events.getEnabledCategories()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
diff --git a/content/api/v19/tty.en.md b/content/api/v19/tty.en.md
index 13d6a42d12..347034cd12 100644
--- a/content/api/v19/tty.en.md
+++ b/content/api/v19/tty.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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
@@ -39,9 +43,9 @@ classes.
### `tty.ReadStream`
-
+
-* Extends: [`net.Socket`](/api/net#netsocket)
+* Extends: [`net.Socket`](/api/v19/net#netsocket)
Represents the readable side of a TTY. In normal circumstances
[`process.stdin`][] will be the only `tty.ReadStream` instance in a Node.js
@@ -49,20 +53,20 @@ process and there should be no reason to create additional instances.
#### `readStream.isRaw`
-
+
A `boolean` that is `true` if the TTY is currently configured to operate as a
raw device. Defaults to `false`.
#### `readStream.isTTY`
-
+
A `boolean` that is always `true` for `tty.ReadStream` instances.
#### `readStream.setRawMode(mode)`
-
+
* `mode` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, configures the `tty.ReadStream` to operate as a
raw device. If `false`, configures the `tty.ReadStream` to operate in its
@@ -80,9 +84,9 @@ in this mode.
### `tty.WriteStream`
-
+
-* Extends: [`net.Socket`](/api/net#netsocket)
+* Extends: [`net.Socket`](/api/v19/net#netsocket)
Represents the writable side of a TTY. In normal circumstances,
[`process.stdout`][] and [`process.stderr`][] will be the only
@@ -91,7 +95,7 @@ should be no reason to create additional instances.
#### `'resize'`
-
+
The `'resize'` event is emitted whenever either of the `writeStream.columns`
or `writeStream.rows` properties have changed. No arguments are passed to the
@@ -106,7 +110,7 @@ process.stdout.on('resize', () => {
#### `writeStream.clearLine(dir[, callback])`
-
+
* `dir` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `-1`: to the left from cursor
@@ -122,7 +126,7 @@ direction identified by `dir`.
#### `writeStream.clearScreenDown([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked once the operation completes.
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `false` if the stream wishes for the calling code to wait
@@ -134,14 +138,14 @@ cursor down.
#### `writeStream.columns`
-
+
A `number` specifying the number of columns the TTY currently has. This property
is updated whenever the `'resize'` event is emitted.
#### `writeStream.cursorTo(x[, y][, callback])`
-
+
* `x` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `y` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -155,7 +159,7 @@ position.
#### `writeStream.getColorDepth([env])`
-
+
* `env` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object containing the environment variables to check. This
enables simulating the usage of a specific terminal. **Default:**
@@ -188,7 +192,7 @@ Disabling color support is also possible by using the `NO_COLOR` and
#### `writeStream.getWindowSize()`
-
+
* Returns: number\[]
@@ -199,7 +203,7 @@ of columns and rows in the corresponding TTY.
#### `writeStream.hasColors([count][, env])`
-
+
* `count` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of colors that are requested (minimum 2).
**Default:** 16.
@@ -227,13 +231,13 @@ process.stdout.hasColors(2 ** 24, { TMUX: '1' });
#### `writeStream.isTTY`
-
+
A `boolean` that is always `true`.
#### `writeStream.moveCursor(dx, dy[, callback])`
-
+
* `dx` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `dy` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -247,14 +251,14 @@ current position.
#### `writeStream.rows`
-
+
A `number` specifying the number of rows the TTY currently has. This property
is updated whenever the `'resize'` event is emitted.
### `tty.isatty(fd)`
-
+
* `fd` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) A numeric file descriptor
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
diff --git a/content/api/v19/url.en.md b/content/api/v19/url.en.md
index a2c95d1200..a64c82d3f3 100644
--- a/content/api/v19/url.en.md
+++ b/content/api/v19/url.en.md
@@ -5,20 +5,22 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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');
```
@@ -70,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');
@@ -87,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';
@@ -111,7 +109,7 @@ console.log(myURL.href);
#### `URL`
-
+
Browser-compatible `URL` class, implemented by following the WHATWG URL
Standard. [Examples of parsed URLs][] may be found in the Standard itself.
@@ -143,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'.
```
@@ -249,7 +245,7 @@ console.log(myURL.hostname);
// Prints example.org
// Setting the hostname does not change the port
-myURL.hostname = 'example.com:82';
+myURL.hostname = 'example.com';
console.log(myURL.href);
// Prints https://example.com:81/foo
@@ -289,19 +285,17 @@ will be thrown.
##### `url.origin`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
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
@@ -323,7 +317,7 @@ console.log(myURL.password);
myURL.password = '123';
console.log(myURL.href);
-// Prints https://abc:123@example.com
+// Prints https://abc:123@example.com/
```
Invalid URL characters included in the value assigned to the `password` property
@@ -354,7 +348,7 @@ to percent-encode may vary somewhat from what the [`url.parse()`][] and
##### `url.port`
-
+
* [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -457,7 +451,7 @@ Invalid URL protocol values assigned to the `protocol` property are ignored.
###### Special schemes
-
+
The [WHATWG URL Standard][] considers a handful of URL protocol schemes to be
_special_ in terms of how they are parsed and serialized. When a URL is
@@ -471,7 +465,7 @@ For instance, changing from `http` to `https` works:
const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
-// https://example.org
+// https://example.org/
```
However, changing from `http` to a hypothetical `fish` protocol does not
@@ -481,7 +475,7 @@ because the new protocol is not special.
const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
-// http://example.org
+// http://example.org/
```
Likewise, changing from a non-special protocol to a special protocol is also
@@ -520,7 +514,7 @@ and [`url.format()`][] methods would produce.
##### `url.searchParams`
-* [`URLSearchParams`](/api/url#urlsearchparams)
+* [`URLSearchParams`](/api/v19/url#urlsearchparams)
Gets the [`URLSearchParams`][] object representing the query parameters of the
URL. This property is read-only but the `URLSearchParams` object it provides
@@ -535,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`
@@ -595,14 +589,18 @@ console.log(JSON.stringify(myURLs));
##### `URL.createObjectURL(blob)`
-
+
+
+
-
+Experimental
-* `blob` [`Blob`](/api/buffer#blob)
+
+
+* `blob` [`Blob`](/api/v19/buffer#blob)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-Creates a `'blob:nodedata:...'` URL string that represents the given [`Blob`](/api/buffer#blob)
+Creates a `'blob:nodedata:...'` URL string that represents the given [`Blob`](/api/v19/buffer#blob)
object and can be used to retrieve the `Blob` later.
```js
@@ -620,7 +618,7 @@ const otherBlob = resolveObjectURL(id);
console.log(otherBlob.size);
```
-The data stored by the registered [`Blob`](/api/buffer#blob) will be retained in memory until
+The data stored by the registered [`Blob`](/api/v19/buffer#blob) will be retained in memory until
`URL.revokeObjectURL()` is called to remove it.
`Blob` objects are registered within the current thread. If using Worker
@@ -629,19 +627,23 @@ to other workers or the main thread.
##### `URL.revokeObjectURL(id)`
-
+
+
+
+
+Experimental
-
+
* `id` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A `'blob:nodedata:...` URL string returned by a prior call to
`URL.createObjectURL()`.
-Removes the stored [`Blob`](/api/buffer#blob) identified by the given ID. Attempting to revoke a
+Removes the stored [`Blob`](/api/v19/buffer#blob) identified by the given ID. Attempting to revoke a
ID that isn't registered will silently fail.
#### `URLSearchParams`
-
+
The `URLSearchParams` API provides read and write access to the query of a
`URL`. The `URLSearchParams` class can also be used standalone with one of the
@@ -713,7 +715,7 @@ console.log(params.toString());
##### `new URLSearchParams(obj)`
-
+
* `obj` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object representing a collection of key-value pairs
@@ -727,7 +729,7 @@ joins all array elements with commas.
```js
const params = new URLSearchParams({
user: 'abc',
- query: ['first', 'second']
+ query: ['first', 'second'],
});
console.log(params.getAll('query'));
// Prints [ 'first,second' ]
@@ -737,7 +739,7 @@ console.log(params.toString());
##### `new URLSearchParams(iterable)`
-
+
* `iterable` [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) An iterable object whose elements are key-value pairs
@@ -813,7 +815,7 @@ Alias for [`urlSearchParams[@@iterator]()`][`urlSearchParams@@iterator()`].
##### `urlSearchParams.forEach(fn[, thisArg])`
-
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked for each name-value pair in the query
* `thisArg` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) To be used as `this` value for when `fn` is called
@@ -894,9 +896,15 @@ console.log(params.toString());
// Prints foo=def&abc=def&xyz=opq
```
+##### `urlSearchParams.size`
+
+
+
+The total number of parameter entries.
+
##### `urlSearchParams.sort()`
-
+
Sort all existing name-value pairs in-place by their names. Sorting is done
with a [stable sorting algorithm][], so relative order between name-value pairs
@@ -946,7 +954,7 @@ for (const [name, value] of params) {
#### `url.domainToASCII(domain)`
-
+
* `domain` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -959,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'));
@@ -968,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'));
@@ -983,7 +989,7 @@ console.log(url.domainToASCII('xn--iñvalid.com'));
#### `url.domainToUnicode(domain)`
-
+
* `domain` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -996,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'));
@@ -1005,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'));
@@ -1020,15 +1024,15 @@ console.log(url.domainToUnicode('xn--iñvalid.com'));
#### `url.fileURLToPath(url)`
-
+
-* `url` [`URL`](/api/url#the-whatwg-url-api) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The file URL string or URL object to convert to a path.
+* `url` [`URL`](/api/v19/url#the-whatwg-url-api) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The file URL string or URL object to convert to a path.
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The fully-resolved platform-specific Node.js file path.
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);
@@ -1044,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)
@@ -1063,9 +1065,9 @@ fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
#### `url.format(URL[, options])`
-
+
-* `URL` [`URL`](/api/url#the-whatwg-url-api) A [WHATWG URL][] object
+* `URL` [`URL`](/api/v19/url#the-whatwg-url-api) A [WHATWG URL][] object
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `auth` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) `true` if the serialized URL string should include the
username and password, `false` otherwise. **Default:** `true`.
@@ -1086,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');
@@ -1098,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');
@@ -1116,15 +1116,15 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
#### `url.pathToFileURL(path)`
-
+
* `path` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The path to convert to a File URL.
-* Returns: [`URL`](/api/url#the-whatwg-url-api) The file URL object.
+* Returns: [`URL`](/api/v19/url#the-whatwg-url-api) The file URL object.
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
@@ -1132,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)
@@ -1150,9 +1148,9 @@ pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSI
#### `url.urlToHttpOptions(url)`
-
+
-* `url` [`URL`](/api/url#the-whatwg-url-api) The [WHATWG URL][] object to convert to an options object.
+* `url` [`URL`](/api/v19/url#the-whatwg-url-api) The [WHATWG URL][] object to convert to an options object.
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Options object
* `protocol` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Protocol to use.
* `hostname` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A domain name or IP address of the server to issue the
@@ -1172,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');
@@ -1189,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:',
@@ -1212,15 +1208,23 @@ console.log(urlToHttpOptions(myUrl));
### Legacy URL API
-
+
+
+
+
+Legacy: Use the WHATWG URL API instead.
-
+
#### Legacy `urlObject`
-
+
-
+
+
+Legacy: Use the WHATWG URL API instead.
+
+
The legacy `urlObject` (`require('node:url').Url` or
`import { Url } from 'node:url'`) is
@@ -1325,9 +1329,13 @@ forward-slash characters (`/`) are required following the colon in the
#### `url.format(urlObject)`
-
+
+
+
-
+Legacy: Use the WHATWG URL API instead.
+
+
* `urlObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A URL object (as returned by `url.parse()` or
constructed otherwise). If a string, it is converted to an object by passing
@@ -1344,8 +1352,8 @@ url.format({
pathname: '/some/path',
query: {
page: 1,
- format: 'json'
- }
+ format: 'json',
+ },
});
// => 'https://example.com/some/path?page=1&format=json'
@@ -1408,9 +1416,13 @@ The formatting process operates as follows:
#### `url.parse(urlString[, parseQueryString[, slashesDenoteHost]])`
-
+
+
+
-
+Deprecated: Use the WHATWG URL API instead.
+
+
* `urlString` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The URL string to parse.
* `parseQueryString` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If `true`, the `query` property will always
@@ -1438,9 +1450,13 @@ input. CVEs are not issued for `url.parse()` vulnerabilities. Use the
#### `url.resolve(from, to)`
-
+
+
+
+
+Legacy: Use the WHATWG URL API instead.
-
+
* `from` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The base URL to use if `to` is a relative URL.
* `to` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The target URL to resolve.
diff --git a/content/api/v19/util.en.md b/content/api/v19/util.en.md
index 5d6d68ffc6..c24041679a 100644
--- a/content/api/v19/util.en.md
+++ b/content/api/v19/util.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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
@@ -21,7 +25,7 @@ const util = require('node:util');
### `util.callbackify(original)`
-
+
* `original` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) An `async` function
* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) a callback style function
@@ -76,7 +80,7 @@ callbackFunction((err, ret) => {
### `util.debuglog(section[, callback])`
-
+
* `section` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A string identifying the portion of the application for
which the `debuglog` function is being created.
@@ -141,7 +145,7 @@ let debuglog = util.debuglog('internals', (debug) => {
#### `debuglog().enabled`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -168,14 +172,14 @@ hello from foo [123]
### `util.debug(section)`
-
+
Alias for `util.debuglog`. Usage allows for readability of that doesn't imply
logging when only using `util.debuglog().enabled`.
### `util.deprecate(fn, msg[, code])`
-
+
* `fn` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The function that is being deprecated.
* `msg` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A warning message to display when the deprecated function is
@@ -232,7 +236,7 @@ property take precedence over `--trace-deprecation` and
### `util.format(format[, ...args])`
-
+
* `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) A `printf`-like format string.
@@ -304,7 +308,7 @@ event loop. Use this function with care and never in a hot code path.
### `util.formatWithOptions(inspectOptions, format[, ...args])`
-
+
* `inspectOptions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -321,7 +325,7 @@ util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
### `util.getSystemErrorName(err)`
-
+
* `err` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -339,7 +343,7 @@ fs.access('file/that/does/not/exist', (err) => {
### `util.getSystemErrorMap()`
-
+
* Returns: [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
@@ -357,9 +361,13 @@ fs.access('file/that/does/not/exist', (err) => {
### `util.inherits(constructor, superConstructor)`
-
+
+
+
+
+Legacy: Use ES2015 class syntax and `extends` keyword instead.
-
+
* `constructor` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* `superConstructor` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -425,7 +433,7 @@ stream.write('With ES6');
### `util.inspect(object[, showHidden[, depth[, colors]]])`
-
+
* `object` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Any JavaScript primitive or `Object`.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -537,7 +545,7 @@ const o = {
'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.',
'test',
'foo']], 4],
- b: new Map([['za', 1], ['zb', 'test']])
+ b: new Map([['za', 1], ['zb', 'test']]),
};
console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));
@@ -605,7 +613,7 @@ const assert = require('node:assert');
const o1 = {
b: [2, 3, 1],
a: '`a` comes before `b`',
- c: new Set([2, 3, 1])
+ c: new Set([2, 3, 1]),
};
console.log(inspect(o1, { sorted: true }));
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }
@@ -615,11 +623,11 @@ console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
const o2 = {
c: new Set([2, 1, 3]),
a: '`a` comes before `b`',
- b: [2, 3, 1]
+ b: [2, 3, 1],
};
assert.strict.equal(
inspect(o1, { sorted: true }),
- inspect(o2, { sorted: true })
+ inspect(o2, { sorted: true }),
);
```
@@ -644,7 +652,7 @@ be truncated.
#### Customizing `util.inspect` colors
-
+
Color output (if enabled) of `util.inspect` is customizable globally
via the `util.inspect.styles` and `util.inspect.colors` properties.
@@ -735,9 +743,9 @@ ignored, if not supported.
#### Custom inspection functions on objects
-
+
-
+
Objects may also define their own
[`[util.inspect.custom](depth, opts, inspect)`][util.inspect.custom] function,
@@ -758,7 +766,7 @@ class Box {
}
const newOptions = Object.assign({}, options, {
- depth: options.depth === null ? null : options.depth - 1
+ depth: options.depth === null ? null : options.depth - 1,
});
// Five space padding because that's the size of "Box< ".
@@ -793,7 +801,7 @@ util.inspect(obj);
#### `util.inspect.custom`
-
+
* [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) that can be used to declare custom inspect functions.
@@ -832,7 +840,7 @@ See [Custom inspection functions on Objects][] for more details.
#### `util.inspect.defaultOptions`
-
+
The `defaultOptions` value allows customization of the default options used by
`util.inspect`. This is useful for functions like `console.log` or
@@ -851,7 +859,7 @@ console.log(arr); // logs the full array
### `util.isDeepStrictEqual(val1, val2)`
-
+
* `val1` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
* `val2` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -865,9 +873,13 @@ equality.
### `util.MIMEType`
-
+
+
+
+
+Experimental
-
+
An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/).
@@ -885,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');
@@ -901,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));
@@ -921,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');
@@ -932,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');
@@ -944,7 +950,7 @@ myMIME.type = 'application';
console.log(myMIME.type);
// Prints: application
console.log(String(myMIME));
-// Prints: application/javascript/javascript
+// Prints: application/javascript
```
##### `mime.subtype`
@@ -953,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');
@@ -964,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');
@@ -986,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');
@@ -997,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');
@@ -1038,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 = [
@@ -1047,9 +1049,7 @@ const myMIMES = [
];
console.log(JSON.stringify(myMIMES));
// Prints: ["image/png", "image/gif"]
-```
-
-```cjs
+--------------
const { MIMEType } = require('node:util');
const myMIMES = [
@@ -1062,7 +1062,7 @@ console.log(JSON.stringify(myMIMES));
#### `util.MIMEParams`
-
+
The `MIMEParams` API provides read and write access to the parameters of a
`MIMEType`.
@@ -1071,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();
@@ -1119,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');
@@ -1129,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');
@@ -1152,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');
@@ -1160,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');
@@ -1184,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');
@@ -1194,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');
@@ -1210,9 +1202,13 @@ for (const [name, value] of params) {
### `util.parseArgs([config])`
-
+
+
+
-
+Experimental
+
+
* `config` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) Used to provide arguments for parsing and to configure
the parser. `config` supports the following properties:
@@ -1252,41 +1248,39 @@ 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 = {
foo: {
type: 'boolean',
- short: 'f'
+ short: 'f',
},
bar: {
- type: 'string'
- }
+ type: 'string',
+ },
};
const {
values,
- positionals
+ positionals,
} = 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 = {
foo: {
type: 'boolean',
- short: 'f'
+ short: 'f',
},
bar: {
- type: 'string'
- }
+ type: 'string',
+ },
};
const {
values,
- positionals
+ positionals,
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
@@ -1325,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 = {
@@ -1355,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 = {
@@ -1405,7 +1397,7 @@ $ node negate.js --no-logfile --logfile=test.log --color --no-color
### `util.promisify(original)`
-
+
* `original` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -1517,7 +1509,7 @@ throw an error.
#### `util.promisify.custom`
-
+
* [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type) that can be used to declare custom promisified variants of functions,
see [Custom promisified functions][].
@@ -1541,7 +1533,7 @@ doSomething[kCustomPromisifiedSymbol] = (foo) => {
### `util.stripVTControlCharacters(str)`
-
+
* `str` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1555,7 +1547,7 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
### `util.TextDecoder`
-
+
An implementation of the [WHATWG Encoding Standard][] `TextDecoder` API.
@@ -1633,7 +1625,7 @@ is not supported.
#### `new TextDecoder([encoding[, options]])`
-
+
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Identifies the `encoding` that this `TextDecoder` instance
supports. **Default:** `'utf-8'`.
@@ -1689,7 +1681,7 @@ mark.
### `util.TextEncoder`
-
+
An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All
instances of `TextEncoder` only support UTF-8 encoding.
@@ -1735,7 +1727,7 @@ The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`.
### `util.toUSVString(string)`
-
+
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1745,23 +1737,31 @@ Unicode "replacement character" U+FFFD.
### `util.transferableAbortController()`
-
+
-
+
-Creates and returns an [`AbortController`](/api/globals#abortcontroller) instance whose [`AbortSignal`](/api/globals#abortsignal) is marked
+Experimental
+
+
+
+Creates and returns an [`AbortController`](/api/v19/globals#abortcontroller) instance whose [`AbortSignal`](/api/v19/globals#abortsignal) is marked
as transferable and can be used with `structuredClone()` or `postMessage()`.
### `util.transferableAbortSignal(signal)`
-
+
+
+
-
+Experimental
-* `signal` [`AbortSignal`](/api/globals#abortsignal)
-* Returns: [`AbortSignal`](/api/globals#abortsignal)
+
-Marks the given [`AbortSignal`](/api/globals#abortsignal) as transferable so that it can be used with
+* `signal` [`AbortSignal`](/api/v19/globals#abortsignal)
+* Returns: [`AbortSignal`](/api/v19/globals#abortsignal)
+
+Marks the given [`AbortSignal`](/api/v19/globals#abortsignal) as transferable so that it can be used with
`structuredClone()` and `postMessage()`.
```js
@@ -1770,9 +1770,54 @@ const channel = new MessageChannel();
channel.port2.postMessage(signal, [signal]);
```
+### `util.aborted(signal, resource)`
+
+
+
+
+
+Experimental
+
+
+
+* `signal` [`AbortSignal`](/api/v19/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`
-
+
`util.types` provides type checks for different kinds of built-in objects.
Unlike `instanceof` or `Object.prototype.toString.call(value)`, these checks do
@@ -1787,7 +1832,7 @@ The API is accessible via `require('node:util').types` or `require('node:util/ty
#### `util.types.isAnyArrayBuffer(value)`
-
+
* `value` [`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)
@@ -1805,7 +1850,7 @@ util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true
#### `util.types.isArrayBufferView(value)`
-
+
* `value` [`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)
@@ -1823,7 +1868,7 @@ util.types.isArrayBufferView(new ArrayBuffer()); // false
#### `util.types.isArgumentsObject(value)`
-
+
* `value` [`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)
@@ -1838,7 +1883,7 @@ function foo() {
#### `util.types.isArrayBuffer(value)`
-
+
* `value` [`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)
@@ -1854,7 +1899,7 @@ util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false
#### `util.types.isAsyncFunction(value)`
-
+
* `value` [`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)
@@ -1871,7 +1916,7 @@ util.types.isAsyncFunction(async function foo() {}); // Returns true
#### `util.types.isBigInt64Array(value)`
-
+
* `value` [`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)
@@ -1885,7 +1930,7 @@ util.types.isBigInt64Array(new BigUint64Array()); // Returns false
#### `util.types.isBigUint64Array(value)`
-
+
* `value` [`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)
@@ -1899,7 +1944,7 @@ util.types.isBigUint64Array(new BigUint64Array()); // Returns true
#### `util.types.isBooleanObject(value)`
-
+
* `value` [`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)
@@ -1918,7 +1963,7 @@ util.types.isBooleanObject(Boolean(true)); // Returns false
#### `util.types.isBoxedPrimitive(value)`
-
+
* `value` [`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)
@@ -1938,16 +1983,16 @@ util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
#### `util.types.isCryptoKey(value)`
-
+
* `value` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if `value` is a [`CryptoKey`](/api/webcrypto#cryptokey), `false` otherwise.
+Returns `true` if `value` is a [`CryptoKey`](/api/v19/webcrypto#cryptokey), `false` otherwise.
#### `util.types.isDataView(value)`
-
+
* `value` [`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)
@@ -1964,7 +2009,7 @@ See also [`ArrayBuffer.isView()`][].
#### `util.types.isDate(value)`
-
+
* `value` [`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)
@@ -1977,7 +2022,7 @@ util.types.isDate(new Date()); // Returns true
#### `util.types.isExternal(value)`
-
+
* `value` [`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)
@@ -1990,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;
@@ -2006,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
@@ -2021,7 +2064,7 @@ For further information on `napi_create_external`, refer to
#### `util.types.isFloat32Array(value)`
-
+
* `value` [`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)
@@ -2036,7 +2079,7 @@ util.types.isFloat32Array(new Float64Array()); // Returns false
#### `util.types.isFloat64Array(value)`
-
+
* `value` [`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)
@@ -2051,7 +2094,7 @@ util.types.isFloat64Array(new Float64Array()); // Returns true
#### `util.types.isGeneratorFunction(value)`
-
+
* `value` [`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)
@@ -2068,7 +2111,7 @@ util.types.isGeneratorFunction(function* foo() {}); // Returns true
#### `util.types.isGeneratorObject(value)`
-
+
* `value` [`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)
@@ -2087,7 +2130,7 @@ util.types.isGeneratorObject(generator); // Returns true
#### `util.types.isInt8Array(value)`
-
+
* `value` [`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)
@@ -2102,7 +2145,7 @@ util.types.isInt8Array(new Float64Array()); // Returns false
#### `util.types.isInt16Array(value)`
-
+
* `value` [`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)
@@ -2117,7 +2160,7 @@ util.types.isInt16Array(new Float64Array()); // Returns false
#### `util.types.isInt32Array(value)`
-
+
* `value` [`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)
@@ -2132,16 +2175,16 @@ util.types.isInt32Array(new Float64Array()); // Returns false
#### `util.types.isKeyObject(value)`
-
+
* `value` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Returns `true` if `value` is a [`KeyObject`](/api/crypto#keyobject), `false` otherwise.
+Returns `true` if `value` is a [`KeyObject`](/api/v19/crypto#keyobject), `false` otherwise.
#### `util.types.isMap(value)`
-
+
* `value` [`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)
@@ -2154,7 +2197,7 @@ util.types.isMap(new Map()); // Returns true
#### `util.types.isMapIterator(value)`
-
+
* `value` [`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)
@@ -2172,7 +2215,7 @@ util.types.isMapIterator(map[Symbol.iterator]()); // Returns true
#### `util.types.isModuleNamespaceObject(value)`
-
+
* `value` [`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)
@@ -2187,7 +2230,7 @@ util.types.isModuleNamespaceObject(ns); // Returns true
#### `util.types.isNativeError(value)`
-
+
* `value` [`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)
@@ -2202,7 +2245,7 @@ util.types.isNativeError(new RangeError()); // Returns true
#### `util.types.isNumberObject(value)`
-
+
* `value` [`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)
@@ -2217,7 +2260,7 @@ util.types.isNumberObject(new Number(0)); // Returns true
#### `util.types.isPromise(value)`
-
+
* `value` [`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)
@@ -2230,7 +2273,7 @@ util.types.isPromise(Promise.resolve(42)); // Returns true
#### `util.types.isProxy(value)`
-
+
* `value` [`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)
@@ -2246,7 +2289,7 @@ util.types.isProxy(proxy); // Returns true
#### `util.types.isRegExp(value)`
-
+
* `value` [`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)
@@ -2260,7 +2303,7 @@ util.types.isRegExp(new RegExp('abc')); // Returns true
#### `util.types.isSet(value)`
-
+
* `value` [`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)
@@ -2273,7 +2316,7 @@ util.types.isSet(new Set()); // Returns true
#### `util.types.isSetIterator(value)`
-
+
* `value` [`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)
@@ -2291,7 +2334,7 @@ util.types.isSetIterator(set[Symbol.iterator]()); // Returns true
#### `util.types.isSharedArrayBuffer(value)`
-
+
* `value` [`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)
@@ -2307,7 +2350,7 @@ util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true
#### `util.types.isStringObject(value)`
-
+
* `value` [`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)
@@ -2322,7 +2365,7 @@ util.types.isStringObject(new String('foo')); // Returns true
#### `util.types.isSymbolObject(value)`
-
+
* `value` [`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)
@@ -2338,7 +2381,7 @@ util.types.isSymbolObject(Object(symbol)); // Returns true
#### `util.types.isTypedArray(value)`
-
+
* `value` [`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)
@@ -2355,7 +2398,7 @@ See also [`ArrayBuffer.isView()`][].
#### `util.types.isUint8Array(value)`
-
+
* `value` [`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)
@@ -2370,7 +2413,7 @@ util.types.isUint8Array(new Float64Array()); // Returns false
#### `util.types.isUint8ClampedArray(value)`
-
+
* `value` [`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)
@@ -2385,7 +2428,7 @@ util.types.isUint8ClampedArray(new Float64Array()); // Returns false
#### `util.types.isUint16Array(value)`
-
+
* `value` [`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)
@@ -2400,7 +2443,7 @@ util.types.isUint16Array(new Float64Array()); // Returns false
#### `util.types.isUint32Array(value)`
-
+
* `value` [`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)
@@ -2415,7 +2458,7 @@ util.types.isUint32Array(new Float64Array()); // Returns false
#### `util.types.isWeakMap(value)`
-
+
* `value` [`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)
@@ -2428,7 +2471,7 @@ util.types.isWeakMap(new WeakMap()); // Returns true
#### `util.types.isWeakSet(value)`
-
+
* `value` [`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)
@@ -2441,9 +2484,13 @@ util.types.isWeakSet(new WeakSet()); // Returns true
#### `util.types.isWebAssemblyCompiledModule(value)`
-
+
+
+
+
+Deprecated: Use `value instanceof WebAssembly.Module` instead.
-
+
* `value` [`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)
@@ -2462,9 +2509,13 @@ applications and modules should be updated to find alternative approaches.
#### `util._extend(target, source)`
-
+
-
+
+
+Deprecated: Use [`Object.assign()`][] instead.
+
+
* `target` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `source` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -2477,9 +2528,13 @@ similar built-in functionality through [`Object.assign()`][].
#### `util.isArray(object)`
-
+
+
+
-
+Deprecated: Use [`Array.isArray()`][] instead.
+
+
* `object` [`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)
@@ -2501,9 +2556,13 @@ util.isArray({});
#### `util.isBoolean(object)`
-
+
+
+
+
+Deprecated: Use `typeof value === 'boolean'` instead.
-
+
* `object` [`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)
@@ -2523,9 +2582,13 @@ util.isBoolean(false);
#### `util.isBuffer(object)`
-
+
-
+
+
+Deprecated: Use [`Buffer.isBuffer()`][] instead.
+
+
* `object` [`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)
@@ -2545,9 +2608,13 @@ util.isBuffer(Buffer.from('hello world'));
#### `util.isDate(object)`
-
+
+
+
-
+Deprecated: Use [`util.types.isDate()`][] instead.
+
+
* `object` [`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)
@@ -2567,9 +2634,13 @@ util.isDate({});
#### `util.isError(object)`
-
+
+
+
-
+Deprecated: Use [`util.types.isNativeError()`][] instead.
+
+
* `object` [`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)
@@ -2605,9 +2676,13 @@ util.isError(obj);
#### `util.isFunction(object)`
-
+
+
+
-
+Deprecated: Use `typeof value === 'function'` instead.
+
+
* `object` [`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)
@@ -2631,9 +2706,13 @@ util.isFunction(Bar);
#### `util.isNull(object)`
-
+
+
+
+
+Deprecated: Use `value === null` instead.
-
+
* `object` [`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)
@@ -2654,9 +2733,13 @@ util.isNull(null);
#### `util.isNullOrUndefined(object)`
-
+
-
+
+
+Deprecated: Use `value === undefined || value === null` instead.
+
+
* `object` [`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)
@@ -2677,9 +2760,13 @@ util.isNullOrUndefined(null);
#### `util.isNumber(object)`
-
+
+
+
-
+Deprecated: Use `typeof value === 'number'` instead.
+
+
* `object` [`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)
@@ -2701,9 +2788,13 @@ util.isNumber(NaN);
#### `util.isObject(object)`
-
+
+
+
+
+Deprecated: Use `value !== null && typeof value === 'object'` instead.
-
+
* `object` [`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)
@@ -2727,9 +2818,13 @@ util.isObject(() => {});
#### `util.isPrimitive(object)`
-
+
- instead."}}} />
+
+
+Deprecated: Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead.
+
+
* `object` [`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)
@@ -2762,9 +2857,13 @@ util.isPrimitive(new Date());
#### `util.isRegExp(object)`
-
+
+
+
-
+Deprecated
+
+
* `object` [`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)
@@ -2784,9 +2883,13 @@ util.isRegExp({});
#### `util.isString(object)`
-
+
+
+
+
+Deprecated: Use `typeof value === 'string'` instead.
-
+
* `object` [`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)
@@ -2808,9 +2911,13 @@ util.isString(5);
#### `util.isSymbol(object)`
-
+
-
+
+
+Deprecated: Use `typeof value === 'symbol'` instead.
+
+
* `object` [`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)
@@ -2830,9 +2937,13 @@ util.isSymbol(Symbol('foo'));
#### `util.isUndefined(object)`
-
+
+
+
-
+Deprecated: Use `value === undefined` instead.
+
+
* `object` [`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)
@@ -2853,9 +2964,13 @@ util.isUndefined(null);
#### `util.log(string)`
-
+
+
+
+
+Deprecated: Use a third party module instead.
-
+
* `string` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
diff --git a/content/api/v19/v8.en.md b/content/api/v19/v8.en.md
index 5a5239341b..1de3c2d053 100644
--- a/content/api/v19/v8.en.md
+++ b/content/api/v19/v8.en.md
@@ -5,9 +5,9 @@ category: 'api'
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:
@@ -18,7 +18,7 @@ const v8 = require('node:v8');
### `v8.cachedDataVersionTag()`
-
+
* Returns: [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -38,7 +38,7 @@ console.log(v8.cachedDataVersionTag()); // 183726201
### `v8.getHeapCodeStatistics()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -62,7 +62,7 @@ following properties:
### `v8.getHeapSnapshot([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `exposeInternals` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If true, expose internals in the heap snapshot.
@@ -70,7 +70,7 @@ following properties:
* `exposeNumericValues` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If true, expose numeric values in
artificial fields. **Default:** `false`.
-* Returns: [`stream.Readable`](/api/stream#streamreadable) A Readable containing the V8 heap snapshot.
+* Returns: [`stream.Readable`](/api/v19/stream#streamreadable) A Readable containing the V8 heap snapshot.
Generates a snapshot of the current V8 heap and returns a Readable
Stream that may be used to read the JSON serialized representation.
@@ -94,7 +94,7 @@ stream.pipe(process.stdout);
### `v8.getHeapSpaceStatistics()`
-
+
* Returns: Object\[]
@@ -154,7 +154,7 @@ The value returned is an array of objects containing the following properties:
### `v8.getHeapStatistics()`
-
+
* Returns: [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -219,7 +219,7 @@ buffers and external strings.
### `v8.setFlagsFromString(flags)`
-
+
* `flags` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -242,7 +242,7 @@ setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
### `v8.stopCoverage()`
-
+
The `v8.stopCoverage()` method allows the user to stop the coverage collection
started by [`NODE_V8_COVERAGE`][], so that V8 can release the execution count
@@ -251,7 +251,7 @@ records and optimize code. This can be used in conjunction with
### `v8.takeCoverage()`
-
+
The `v8.takeCoverage()` method allows the user to write the coverage started by
[`NODE_V8_COVERAGE`][] to disk on demand. This method can be invoked multiple
@@ -264,7 +264,7 @@ disk unless [`v8.stopCoverage()`][] is invoked before the process exits.
### `v8.writeHeapSnapshot([filename[,options]])`
-
+
* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The file path where the V8 heap snapshot is to be
saved. If not specified, a file name with the pattern
@@ -300,7 +300,7 @@ const { writeHeapSnapshot } = require('node:v8');
const {
Worker,
isMainThread,
- parentPort
+ parentPort,
} = require('node:worker_threads');
if (isMainThread) {
@@ -327,9 +327,13 @@ if (isMainThread) {
### `v8.setHeapSnapshotNearHeapLimit(limit)`
-
+
-
+
+
+Experimental
+
+
* `limit` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -347,10 +351,10 @@ Equal JavaScript values may result in different serialized output.
#### `v8.serialize(value)`
-
+
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
-* Returns: [`Buffer`](/api/buffer#buffer)
+* Returns: [`Buffer`](/api/v19/buffer#buffer)
Uses a [`DefaultSerializer`][] to serialize `value` into a buffer.
@@ -360,16 +364,16 @@ larger than [`buffer.constants.MAX_LENGTH`][].
#### `v8.deserialize(buffer)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer returned by [`serialize()`][].
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer returned by [`serialize()`][].
Uses a [`DefaultDeserializer`][] with default options to read a JS value
from a buffer.
#### `v8.Serializer`
-
+
##### `new Serializer()`
@@ -390,7 +394,7 @@ This throws an error if `value` cannot be serialized.
##### `serializer.releaseBuffer()`
-* Returns: [`Buffer`](/api/buffer#buffer)
+* Returns: [`Buffer`](/api/v19/buffer#buffer)
Returns the stored internal buffer. This serializer should not be used once
the buffer is released. Calling this method results in undefined behavior
@@ -429,7 +433,7 @@ For use inside of a custom [`serializer._writeHostObject()`][].
##### `serializer.writeRawBytes(buffer)`
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
Write raw bytes into the serializer's internal buffer. The deserializer
will require a way to compute the length of the buffer.
@@ -480,11 +484,11 @@ host objects, i.e. pass them to [`serializer._writeHostObject()`][].
#### `v8.Deserializer`
-
+
##### `new Deserializer(buffer)`
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer returned by
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) A buffer returned by
[`serializer.releaseBuffer()`][].
Creates a new `Deserializer` object.
@@ -542,7 +546,7 @@ For use inside of a custom [`deserializer._readHostObject()`][].
##### `deserializer.readRawBytes(length)`
* `length` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-* Returns: [`Buffer`](/api/buffer#buffer)
+* Returns: [`Buffer`](/api/v19/buffer#buffer)
Read raw bytes from the deserializer's internal buffer. The `length` parameter
must correspond to the length of the buffer that was passed to
@@ -560,7 +564,7 @@ provided by subclasses.
#### `v8.DefaultSerializer`
-
+
A subclass of [`Serializer`][] that serializes `TypedArray`
(in particular [`Buffer`][]) and `DataView` objects as host objects, and only
@@ -568,7 +572,7 @@ stores the part of their underlying `ArrayBuffer`s that they are referring to.
#### `v8.DefaultDeserializer`
-
+
A subclass of [`Deserializer`][] corresponding to the format written by
[`DefaultSerializer`][].
@@ -624,7 +628,7 @@ const stopHookSet = promiseHooks.createHook({
init,
settled,
before,
- after
+ after,
});
// To stop a hook, call the function returned at its creation.
@@ -637,7 +641,7 @@ stopHookSet();
#### `promiseHooks.onInit(init)`
-
+
* `init` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`init` callback][] to call when a promise is created.
* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Call to stop the hook.
@@ -645,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) => {});
@@ -659,7 +661,7 @@ const stop = promiseHooks.onInit((promise, parent) => {});
#### `promiseHooks.onSettled(settled)`
-
+
* `settled` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`settled` callback][] to call when a promise
is resolved or rejected.
@@ -668,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) => {});
@@ -682,7 +682,7 @@ const stop = promiseHooks.onSettled((promise) => {});
#### `promiseHooks.onBefore(before)`
-
+
* `before` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`before` callback][] to call before a promise
continuation executes.
@@ -691,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) => {});
@@ -705,7 +703,7 @@ const stop = promiseHooks.onBefore((promise) => {});
#### `promiseHooks.onAfter(after)`
-
+
* `after` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`after` callback][] to call after a promise
continuation executes.
@@ -714,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) => {});
@@ -728,7 +724,7 @@ const stop = promiseHooks.onAfter((promise) => {});
#### `promiseHooks.createHook(callbacks)`
-
+
* `callbacks` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The [Hook Callbacks][] to register
* `init` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) The [`init` callback][].
@@ -750,19 +746,17 @@ 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) {}
+ init(promise, parent) {},
});
-```
-
-```cjs
+--------------
const { promiseHooks } = require('node:v8');
const stopAll = promiseHooks.createHook({
- init(promise, parent) {}
+ init(promise, parent) {},
});
```
@@ -827,9 +821,13 @@ occur synchronously in the case of `Promise.resolve()` or `Promise.reject()`.
### Startup Snapshot API
-
+
+
+
-
+Experimental
+
+
The `v8.startupSnapshot` interface can be used to add serialization and
deserialization hooks for custom startup snapshots. Currently the startup
@@ -861,7 +859,7 @@ const {
isBuildingSnapshot,
addSerializeCallback,
addDeserializeCallback,
- setDeserializeMainFunction
+ setDeserializeMainFunction,
} = require('node:v8').startupSnapshot;
const filePath = path.resolve(__dirname, '../x1024.txt');
@@ -896,7 +894,7 @@ snapshot cannot use these APIs again.
#### `v8.startupSnapshot.addSerializeCallback(callback[, data])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback to be invoked before serialization.
* `data` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Optional data that will be passed to the `callback` when it
@@ -909,7 +907,7 @@ into a form more suitable for serialization.
#### `v8.startupSnapshot.addDeserializeCallback(callback[, data])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback to be invoked after the snapshot is
deserialized.
@@ -924,7 +922,7 @@ when the application is restarted from the snapshot.
#### `v8.startupSnapshot.setDeserializeMainFunction(callback[, data])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Callback to be invoked as the entry point after the
snapshot is deserialized.
@@ -940,12 +938,110 @@ needs to be provided to the deserialized application.
#### `v8.startupSnapshot.isBuildingSnapshot()`
-
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
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/v19/vm.en.md b/content/api/v19/vm.en.md
index 27576f2353..64049fdb00 100644
--- a/content/api/v19/vm.en.md
+++ b/content/api/v19/vm.en.md
@@ -5,13 +5,17 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
-
+
+
+
+
+
The `node:vm` module enables compiling and running code within V8 Virtual
Machine contexts.
@@ -51,14 +55,14 @@ console.log(x); // 1; y is not defined.
### `vm.Script`
-
+
Instances of the `vm.Script` class contain precompiled scripts that can be
executed in specific contexts.
#### `new vm.Script(code[, options])`
-
+
* `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The JavaScript code to compile.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -68,7 +72,7 @@ executed in specific contexts.
in stack traces produced by this script. **Default:** `0`.
* `columnOffset` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Specifies the first-line column number offset that
is displayed in stack traces produced by this script. **Default:** `0`.
- * `cachedData` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
+ * `cachedData` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
`TypedArray`, or `DataView` with V8's code cache data for the supplied
source. When supplied, the `cachedDataRejected` value will be set to
either `true` or `false` depending on acceptance of the data by V8.
@@ -86,11 +90,11 @@ executed in specific contexts.
This option is part of the experimental modules API. We do not recommend
using it in a production environment.
* `specifier` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) specifier passed to `import()`
- * `script` [`vm.Script`](/api/vm#vmscript)
+ * `script` [`vm.Script`](/api/v19/vm#vmscript)
* `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the
[`optionsExpression`][] optional parameter, or an empty object if no value
was provided.
- * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is
+ * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/v19/vm#vmmodule) Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
@@ -102,7 +106,7 @@ any global object; rather, it is bound before each run, just for that run.
#### `script.cachedDataRejected`
-
+
* [`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)
@@ -112,9 +116,9 @@ Otherwise the value is `undefined`.
#### `script.createCachedData()`
-
+
-* Returns: [`Buffer`](/api/buffer#buffer)
+* Returns: [`Buffer`](/api/v19/buffer#buffer)
Creates a code cache that can be used with the `Script` constructor's
`cachedData` option. Returns a `Buffer`. This method may be called at any
@@ -151,7 +155,7 @@ const cacheWithAdd = script.createCachedData();
#### `script.runInContext(contextifiedObject[, options])`
-
+
* `contextifiedObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A [contextified][] object as returned by the
`vm.createContext()` method.
@@ -182,7 +186,7 @@ const vm = require('node:vm');
const context = {
animal: 'cat',
- count: 2
+ count: 2,
};
const script = new vm.Script('count += 1; name = "kitty";');
@@ -202,7 +206,7 @@ overhead.
#### `script.runInNewContext([contextObject[, options]])`
-
+
* `contextObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object that will be [contextified][]. If
`undefined`, a new object will be created.
@@ -263,7 +267,7 @@ console.log(contexts);
#### `script.runInThisContext([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `displayErrors` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, if an [`Error`][] occurs
@@ -304,14 +308,14 @@ console.log(globalVar);
#### `script.sourceMapURL`
-
+
* [`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)
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(`
@@ -321,9 +325,7 @@ function myFunc() {}
console.log(script.sourceMapURL);
// Prints: sourcemap.json
-```
-
-```cjs
+--------------
const vm = require('node:vm');
const script = new vm.Script(`
@@ -337,9 +339,13 @@ console.log(script.sourceMapURL);
### `vm.Module`
-
+
+
+
-
+Experimental
+
+
This feature is only available with the `--experimental-vm-modules` command
flag enabled.
@@ -362,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({
@@ -431,9 +437,7 @@ await bar.link(linker);
// Prints 42.
await bar.evaluate();
-```
-
-```cjs
+--------------
const vm = require('node:vm');
const contextifiedObject = vm.createContext({
@@ -572,7 +576,7 @@ The identifier of the current module, as set in the constructor.
// ^^^^^ the module specifier
```
- * `referencingModule` [`vm.Module`](/api/vm#vmmodule) The `Module` object `link()` is called on.
+ * `referencingModule` [`vm.Module`](/api/v19/vm#vmmodule) The `Module` object `link()` is called on.
* `extra` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `assert` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The data from the assertion:
@@ -585,7 +589,7 @@ The identifier of the current module, as set in the constructor.
support, as opposed to, for example, triggering an error if an
unsupported assertion is present.
- * Returns: [`vm.Module`](/api/vm#vmmodule) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+ * Returns: [`vm.Module`](/api/v19/vm#vmmodule) | [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
Link module dependencies. This method must be called before evaluation, and
@@ -660,28 +664,32 @@ value that is not `undefined`.
### `vm.SourceTextModule`
-
+
+
+
+
+Experimental
-
+
This feature is only available with the `--experimental-vm-modules` command
flag enabled.
-* Extends: [`vm.Module`](/api/vm#vmmodule)
+* Extends: [`vm.Module`](/api/v19/vm#vmmodule)
The `vm.SourceTextModule` class provides the [Source Text Module Record][] as
defined in the ECMAScript specification.
#### `new vm.SourceTextModule(code[, options])`
-
+
* `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) JavaScript Module code to parse
* `options`
* `identifier` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) String used in stack traces.
**Default:** `'vm:module(i)'` where `i` is a context-specific ascending
index.
- * `cachedData` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
+ * `cachedData` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
`TypedArray`, or `DataView` with V8's code cache data for the supplied
source. The `code` must be the same as the module from which this
`cachedData` was created.
@@ -693,17 +701,17 @@ defined in the ECMAScript specification.
is displayed in stack traces produced by this `Module`. **Default:** `0`.
* `initializeImportMeta` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called during evaluation of this `Module`
to initialize the `import.meta`.
- * `meta` [`import.meta`](/api/esm#importmeta)
- * `module` [`vm.SourceTextModule`](/api/vm#vmsourcetextmodule)
+ * `meta` [`import.meta`](/api/v19/esm#importmeta)
+ * `module` [`vm.SourceTextModule`](/api/v19/vm#vmsourcetextmodule)
* `importModuleDynamically` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called during evaluation of this module
when `import()` is called. If this option is not specified, calls to
`import()` will reject with [`ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`][].
* `specifier` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) specifier passed to `import()`
- * `module` [`vm.Module`](/api/vm#vmmodule)
+ * `module` [`vm.Module`](/api/v19/vm#vmmodule)
* `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the
[`optionsExpression`][] optional parameter, or an empty object if no value
was provided.
- * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is
+ * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/v19/vm#vmmodule) Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
@@ -713,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 });
@@ -727,7 +735,7 @@ const module = new vm.SourceTextModule(
// Object.prototype in the top context rather than that in
// the contextified object.
meta.prop = {};
- }
+ },
});
// Since module has no dependencies, the linker function will never be called.
await module.link(() => {});
@@ -739,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 () => {
@@ -754,7 +760,7 @@ const contextifiedObject = vm.createContext({ secret: 42 });
// Object.prototype in the top context rather than that in
// the contextified object.
meta.prop = {};
- }
+ },
});
// Since module has no dependencies, the linker function will never be called.
await module.link(() => {});
@@ -770,9 +776,9 @@ const contextifiedObject = vm.createContext({ secret: 42 });
#### `sourceTextModule.createCachedData()`
-
+
-* Returns: [`Buffer`](/api/buffer#buffer)
+* Returns: [`Buffer`](/api/v19/buffer#buffer)
Creates a code cache that can be used with the `SourceTextModule` constructor's
`cachedData` option. Returns a `Buffer`. This method may be called any number
@@ -801,14 +807,18 @@ const module2 = new vm.SourceTextModule('const a = 1;', { cachedData });
### `vm.SyntheticModule`
-
+
+
+
+
+Experimental
-
+
This feature is only available with the `--experimental-vm-modules` command
flag enabled.
-* Extends: [`vm.Module`](/api/vm#vmmodule)
+* Extends: [`vm.Module`](/api/v19/vm#vmmodule)
The `vm.SyntheticModule` class provides the [Synthetic Module Record][] as
defined in the WebIDL specification. The purpose of synthetic modules is to
@@ -829,7 +839,7 @@ const module = new vm.SyntheticModule(['default'], function() {
#### `new vm.SyntheticModule(exportNames, evaluateCallback[, options])`
-
+
* `exportNames` string\[] Array of names that will be exported from the
module.
@@ -849,7 +859,7 @@ the module to access information outside the specified `context`. Use
#### `syntheticModule.setExport(name, value)`
-
+
* `name` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Name of the export to set.
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The value to set the export to.
@@ -858,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'], () => {
@@ -869,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'], () => {
@@ -885,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
@@ -897,7 +905,7 @@ const vm = require('node:vm');
in stack traces produced by this script. **Default:** `0`.
* `columnOffset` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Specifies the first-line column number offset that
is displayed in stack traces produced by this script. **Default:** `0`.
- * `cachedData` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
+ * `cachedData` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
`TypedArray`, or `DataView` with V8's code cache data for the supplied
source.
* `produceCachedData` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Specifies whether to produce new cache data.
@@ -917,7 +925,7 @@ const vm = require('node:vm');
* `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the
[`optionsExpression`][] optional parameter, or an empty object if no value
was provided.
- * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is
+ * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/v19/vm#vmmodule) Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
* Returns: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -928,7 +936,7 @@ function with the given `params`.
### `vm.createContext([contextObject[, options]])`
-
+
* `contextObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -992,7 +1000,7 @@ Inspector API.
### `vm.isContext(object)`
-
+
* `object` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1002,9 +1010,13 @@ Returns `true` if the given `object` object has been [contextified][] using
### `vm.measureMemory([options])`
-
+
+
+
+
+Experimental
-
+
Measure the memory known to V8 and used by all contexts known to the
current V8 isolate, or the main context.
@@ -1076,7 +1088,7 @@ vm.measureMemory({ mode: 'detailed', execution: 'eager' })
### `vm.runInContext(code, contextifiedObject[, options])`
-
+
* `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The JavaScript code to compile and run.
* `contextifiedObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The [contextified][] object that will be used
@@ -1099,7 +1111,7 @@ vm.measureMemory({ mode: 'detailed', execution: 'eager' })
[`Error`][]. Existing handlers for the event that have been attached via
`process.on('SIGINT')` are disabled during script execution, but continue to
work after that. **Default:** `false`.
- * `cachedData` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
+ * `cachedData` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
`TypedArray`, or `DataView` with V8's code cache data for the supplied
source.
* `importModuleDynamically` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called during evaluation of this module
@@ -1108,11 +1120,11 @@ vm.measureMemory({ mode: 'detailed', execution: 'eager' })
This option is part of the experimental modules API. We do not recommend
using it in a production environment.
* `specifier` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) specifier passed to `import()`
- * `script` [`vm.Script`](/api/vm#vmscript)
+ * `script` [`vm.Script`](/api/v19/vm#vmscript)
* `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the
[`optionsExpression`][] optional parameter, or an empty object if no value
was provided.
- * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is
+ * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/v19/vm#vmmodule) Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
* Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) the result of the very last statement executed in the script.
@@ -1142,7 +1154,7 @@ console.log(contextObject);
### `vm.runInNewContext(code[, contextObject[, options]])`
-
+
* `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The JavaScript code to compile and run.
* `contextObject` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) An object that will be [contextified][]. If
@@ -1180,7 +1192,7 @@ console.log(contextObject);
`EvalError`. **Default:** `true`.
* `wasm` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If set to false any attempt to compile a WebAssembly
module will throw a `WebAssembly.CompileError`. **Default:** `true`.
- * `cachedData` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
+ * `cachedData` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
`TypedArray`, or `DataView` with V8's code cache data for the supplied
source.
* `importModuleDynamically` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called during evaluation of this module
@@ -1189,11 +1201,11 @@ console.log(contextObject);
This option is part of the experimental modules API. We do not recommend
using it in a production environment.
* `specifier` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) specifier passed to `import()`
- * `script` [`vm.Script`](/api/vm#vmscript)
+ * `script` [`vm.Script`](/api/v19/vm#vmscript)
* `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the
[`optionsExpression`][] optional parameter, or an empty object if no value
was provided.
- * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is
+ * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/v19/vm#vmmodule) Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
* `microtaskMode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) If set to `afterEvaluate`, microtasks (tasks
@@ -1217,7 +1229,7 @@ const vm = require('node:vm');
const contextObject = {
animal: 'cat',
- count: 2
+ count: 2,
};
vm.runInNewContext('count += 1; name = "kitty"', contextObject);
@@ -1227,7 +1239,7 @@ console.log(contextObject);
### `vm.runInThisContext(code[, options])`
-
+
* `code` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) The JavaScript code to compile and run.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1248,7 +1260,7 @@ console.log(contextObject);
[`Error`][]. Existing handlers for the event that have been attached via
`process.on('SIGINT')` are disabled during script execution, but continue to
work after that. **Default:** `false`.
- * `cachedData` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
+ * `cachedData` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) Provides an optional `Buffer` or
`TypedArray`, or `DataView` with V8's code cache data for the supplied
source.
* `importModuleDynamically` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Called during evaluation of this module
@@ -1257,11 +1269,11 @@ console.log(contextObject);
This option is part of the experimental modules API. We do not recommend
using it in a production environment.
* `specifier` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) specifier passed to `import()`
- * `script` [`vm.Script`](/api/vm#vmscript)
+ * `script` [`vm.Script`](/api/v19/vm#vmscript)
* `importAssertions` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The `"assert"` value passed to the
[`optionsExpression`][] optional parameter, or an empty object if no value
was provided.
- * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/vm#vmmodule) Returning a `vm.Module` is
+ * Returns: [`Module Namespace Object`](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects) | [`vm.Module`](/api/v19/vm#vmmodule) Returning a `vm.Module` is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain `then` function exports.
* Returns: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) the result of the very last statement executed in the script.
@@ -1367,7 +1379,7 @@ function loop() {
vm.runInNewContext(
'Promise.resolve().then(() => loop());',
{ loop, console },
- { timeout: 5 }
+ { timeout: 5 },
);
// This is printed *before* 'entering loop' (!)
console.log('done executing');
@@ -1386,7 +1398,7 @@ function loop() {
vm.runInNewContext(
'Promise.resolve().then(() => loop());',
{ loop, console },
- { timeout: 5, microtaskMode: 'afterEvaluate' }
+ { timeout: 5, microtaskMode: 'afterEvaluate' },
);
```
diff --git a/content/api/v19/wasi.en.md b/content/api/v19/wasi.en.md
index 68a9af5740..7b4ef79a7f 100644
--- a/content/api/v19/wasi.en.md
+++ b/content/api/v19/wasi.en.md
@@ -5,42 +5,41 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+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: {
- '/sandbox': '/some/real/path/that/wasm/can/access'
- }
+ '/sandbox': '/some/real/path/that/wasm/can/access',
+ },
});
-// 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))
+ 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');
@@ -48,22 +47,19 @@ const { argv, env } = require('node:process');
const { join } = require('node:path');
const wasi = new WASI({
+ version: 'preview1',
args: argv,
env,
preopens: {
- '/sandbox': '/some/real/path/that/wasm/can/access'
- }
+ '/sandbox': '/some/real/path/that/wasm/can/access',
+ },
});
-// 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'))
+ await readFile(join(__dirname, 'demo.wasm')),
);
- const instance = await WebAssembly.instantiate(wasm, importObject);
+ const instance = await WebAssembly.instantiate(wasm, wasi.getImportObject());
wasi.start(instance);
})();
@@ -113,7 +109,7 @@ example to run.
### `WASI`
-
+
The `WASI` class provides the WASI system call API and additional convenience
methods for working with WASI-based applications. Each `WASI` instance
@@ -123,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
@@ -145,10 +141,32 @@ 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)`
-
+
* `instance` [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance)
@@ -163,7 +181,7 @@ If `start()` is called more than once, an exception is thrown.
#### `wasi.initialize(instance)`
-
+
* `instance` [`WebAssembly.Instance`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance)
@@ -178,7 +196,7 @@ If `initialize()` is called more than once, an exception is thrown.
#### `wasi.wasiImport`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
diff --git a/content/api/v19/webcrypto.en.md b/content/api/v19/webcrypto.en.md
index c8312f0afe..6805e728ce 100644
--- a/content/api/v19/webcrypto.en.md
+++ b/content/api/v19/webcrypto.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
+
+Stable
+
+
Node.js provides an implementation of the standard [Web Crypto API][].
@@ -24,14 +28,14 @@ const { subtle } = globalThis.crypto;
const key = await subtle.generateKey({
name: 'HMAC',
hash: 'SHA-256',
- length: 256
+ length: 256,
}, true, ['sign', 'verify']);
const enc = new TextEncoder();
const message = enc.encode('I love cupcakes');
const digest = await subtle.sign({
- name: 'HMAC'
+ name: 'HMAC',
}, key, message);
})();
@@ -41,7 +45,7 @@ const { subtle } = globalThis.crypto;
#### Generating keys
-The [`SubtleCrypto`](/api/webcrypto#subtlecrypto) class can be used to generate symmetric (secret) keys
+The [`SubtleCrypto`](/api/v19/webcrypto#subtlecrypto) class can be used to generate symmetric (secret) keys
or asymmetric key pairs (public key and private key).
##### AES keys
@@ -52,7 +56,7 @@ const { subtle } = globalThis.crypto;
async function generateAesKey(length = 256) {
const key = await subtle.generateKey({
name: 'AES-CBC',
- length
+ length,
}, true, ['encrypt', 'decrypt']);
return key;
@@ -67,7 +71,7 @@ const { subtle } = globalThis.crypto;
async function generateEcKey(namedCurve = 'P-521') {
const {
publicKey,
- privateKey
+ privateKey,
} = await subtle.generateKey({
name: 'ECDSA',
namedCurve,
@@ -79,7 +83,11 @@ async function generateEcKey(namedCurve = 'P-521') {
##### Ed25519/Ed448/X25519/X448 key pairs
-
+
+
+Experimental
+
+
```js
const { subtle } = globalThis.crypto;
@@ -105,7 +113,7 @@ const { subtle } = globalThis.crypto;
async function generateHmacKey(hash = 'SHA-256') {
const key = await subtle.generateKey({
name: 'HMAC',
- hash
+ hash,
}, true, ['sign', 'verify']);
return key;
@@ -121,7 +129,7 @@ const publicExponent = new Uint8Array([1, 0, 1]);
async function generateRsaKey(modulusLength = 2048, hash = 'SHA-256') {
const {
publicKey,
- privateKey
+ privateKey,
} = await subtle.generateKey({
name: 'RSASSA-PKCS1-v1_5',
modulusLength,
@@ -151,7 +159,7 @@ async function aesEncrypt(plaintext) {
return {
key,
iv,
- ciphertext
+ ciphertext,
};
}
@@ -174,7 +182,7 @@ const { subtle } = globalThis.crypto;
async function generateAndExportHmacKey(format = 'jwk', hash = 'SHA-512') {
const key = await subtle.generateKey({
name: 'HMAC',
- hash
+ hash,
}, true, ['sign', 'verify']);
return subtle.exportKey(format, key);
@@ -183,7 +191,7 @@ async function generateAndExportHmacKey(format = 'jwk', hash = 'SHA-512') {
async function importHmacKey(keyData, format = 'jwk', hash = 'SHA-512') {
const key = await subtle.importKey(format, keyData, {
name: 'HMAC',
- hash
+ hash,
}, true, ['sign', 'verify']);
return key;
@@ -201,11 +209,11 @@ async function generateAndWrapHmacKey(format = 'jwk', hash = 'SHA-512') {
wrappingKey,
] = await Promise.all([
subtle.generateKey({
- name: 'HMAC', hash
+ name: 'HMAC', hash,
}, true, ['sign', 'verify']),
subtle.generateKey({
name: 'AES-KW',
- length: 256
+ length: 256,
}, true, ['wrapKey', 'unwrapKey']),
]);
@@ -274,7 +282,7 @@ async function pbkdf2(pass, salt, iterations = 1000, length = 256) {
name: 'PBKDF2',
hash: 'SHA-512',
salt: ec.encode(salt),
- iterations
+ iterations,
}, key, length);
return bits;
}
@@ -291,10 +299,10 @@ async function pbkdf2Key(pass, salt, iterations = 1000, length = 256) {
name: 'PBKDF2',
hash: 'SHA-512',
salt: ec.encode(salt),
- iterations
+ iterations,
}, keyMaterial, {
name: 'AES-GCM',
- length: 256
+ length: 256,
}, true, ['encrypt', 'decrypt']);
return key;
}
@@ -342,7 +350,7 @@ implementation and the APIs supported for each:
### `Crypto`
-
+
`globalThis.crypto` is an instance of the `Crypto`
class. `Crypto` is a singleton that provides access to the remainder of the
@@ -350,18 +358,18 @@ crypto API.
#### `crypto.subtle`
-
+
-* Type: [`SubtleCrypto`](/api/webcrypto#subtlecrypto)
+* Type: [`SubtleCrypto`](/api/v19/webcrypto#subtlecrypto)
Provides access to the `SubtleCrypto` API.
#### `crypto.getRandomValues(typedArray)`
-
+
-* `typedArray` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)
-* Returns: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)
+* `typedArray` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)
+* Returns: [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)
Generates cryptographically strong random values. The given `typedArray` is
filled with random values, and a reference to `typedArray` is returned.
@@ -373,7 +381,7 @@ An error will be thrown if the given `typedArray` is larger than 65,536 bytes.
#### `crypto.randomUUID()`
-
+
* Returns: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -382,13 +390,13 @@ cryptographic pseudorandom number generator.
### `CryptoKey`
-
+
#### `cryptoKey.algorithm`
-
+
-* Type: [`AesKeyGenParams`](/api/webcrypto#aeskeygenparams) | [`RsaHashedKeyGenParams`](/api/webcrypto#rsahashedkeygenparams) | [`EcKeyGenParams`](/api/webcrypto#eckeygenparams) | [`HmacKeyGenParams`](/api/webcrypto#hmackeygenparams)
+* Type: [`AesKeyGenParams`](/api/v19/webcrypto#aeskeygenparams) | [`RsaHashedKeyGenParams`](/api/v19/webcrypto#rsahashedkeygenparams) | [`EcKeyGenParams`](/api/v19/webcrypto#eckeygenparams) | [`HmacKeyGenParams`](/api/v19/webcrypto#hmackeygenparams)
An object detailing the algorithm for which the key can be used along with
additional algorithm-specific parameters.
@@ -397,18 +405,18 @@ Read-only.
#### `cryptoKey.extractable`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-When `true`, the [`CryptoKey`](/api/webcrypto#cryptokey) can be extracted using either
+When `true`, the [`CryptoKey`](/api/v19/webcrypto#cryptokey) can be extracted using either
`subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`.
Read-only.
#### `cryptoKey.type`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) One of `'secret'`, `'private'`, or `'public'`.
@@ -417,7 +425,7 @@ asymmetric (`'private'` or `'public'`) key.
#### `cryptoKey.usages`
-
+
* Type: string\[]
@@ -459,34 +467,34 @@ Valid key usages depend on the key algorithm (identified by
### `CryptoKeyPair`
-
+
The `CryptoKeyPair` is a simple dictionary object with `publicKey` and
`privateKey` properties, representing an asymmetric key pair.
#### `cryptoKeyPair.privateKey`
-
+
-* Type: [`CryptoKey`](/api/webcrypto#cryptokey) A [`CryptoKey`](/api/webcrypto#cryptokey) whose `type` will be `'private'`.
+* Type: [`CryptoKey`](/api/v19/webcrypto#cryptokey) A [`CryptoKey`](/api/v19/webcrypto#cryptokey) whose `type` will be `'private'`.
#### `cryptoKeyPair.publicKey`
-
+
-* Type: [`CryptoKey`](/api/webcrypto#cryptokey) A [`CryptoKey`](/api/webcrypto#cryptokey) whose `type` will be `'public'`.
+* Type: [`CryptoKey`](/api/v19/webcrypto#cryptokey) A [`CryptoKey`](/api/v19/webcrypto#cryptokey) whose `type` will be `'public'`.
### `SubtleCrypto`
-
+
#### `subtle.decrypt(algorithm, key, data)`
-
+
-* `algorithm`: [`RsaOaepParams`](/api/webcrypto#rsaoaepparams) | [`AesCtrParams`](/api/webcrypto#aesctrparams) | [`AesCbcParams`](/api/webcrypto#aescbcparams) | [`AesGcmParams`](/api/webcrypto#aesgcmparams)
-* `key`: [`CryptoKey`](/api/webcrypto#cryptokey)
-* `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* `algorithm`: [`RsaOaepParams`](/api/v19/webcrypto#rsaoaepparams) | [`AesCtrParams`](/api/v19/webcrypto#aesctrparams) | [`AesCbcParams`](/api/v19/webcrypto#aescbcparams) | [`AesGcmParams`](/api/v19/webcrypto#aesgcmparams)
+* `key`: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
+* `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
Using the method and parameters specified in `algorithm` and the keying
@@ -503,10 +511,10 @@ The algorithms currently supported include:
#### `subtle.deriveBits(algorithm, baseKey, length)`
-
+
-* `algorithm`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`EcdhKeyDeriveParams`](/api/webcrypto#ecdhkeyderiveparams) | [`HkdfParams`](/api/webcrypto#hkdfparams) | [`Pbkdf2Params`](/api/webcrypto#pbkdf2params)
-* `baseKey`: [`CryptoKey`](/api/webcrypto#cryptokey)
+* `algorithm`: [`AlgorithmIdentifier`](/api/v19/webcrypto#algorithmidentifier) | [`EcdhKeyDeriveParams`](/api/v19/webcrypto#ecdhkeyderiveparams) | [`HkdfParams`](/api/v19/webcrypto#hkdfparams) | [`Pbkdf2Params`](/api/v19/webcrypto#pbkdf2params)
+* `baseKey`: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
* `length`: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
@@ -534,18 +542,18 @@ The algorithms currently supported include:
#### `subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)`
-
+
-* `algorithm`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`EcdhKeyDeriveParams`](/api/webcrypto#ecdhkeyderiveparams) | [`HkdfParams`](/api/webcrypto#hkdfparams) | [`Pbkdf2Params`](/api/webcrypto#pbkdf2params)
-* `baseKey`: [`CryptoKey`](/api/webcrypto#cryptokey)
-* `derivedKeyAlgorithm`: [`HmacKeyGenParams`](/api/webcrypto#hmackeygenparams) | [`AesKeyGenParams`](/api/webcrypto#aeskeygenparams)
+* `algorithm`: [`AlgorithmIdentifier`](/api/v19/webcrypto#algorithmidentifier) | [`EcdhKeyDeriveParams`](/api/v19/webcrypto#ecdhkeyderiveparams) | [`HkdfParams`](/api/v19/webcrypto#hkdfparams) | [`Pbkdf2Params`](/api/v19/webcrypto#pbkdf2params)
+* `baseKey`: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
+* `derivedKeyAlgorithm`: [`HmacKeyGenParams`](/api/v19/webcrypto#hmackeygenparams) | [`AesKeyGenParams`](/api/v19/webcrypto#aeskeygenparams)
* `extractable`: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `keyUsages`: string\[] See [Key usages][].
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`CryptoKey`](/api/webcrypto#cryptokey)
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`CryptoKey`](/api/v19/webcrypto#cryptokey)
Using the method and parameters specified in `algorithm`, and the keying
material provided by `baseKey`, `subtle.deriveKey()` attempts to generate
-a new [`CryptoKey`](/api/webcrypto#cryptokey) based on the method and parameters in `derivedKeyAlgorithm`.
+a new [`CryptoKey`](/api/v19/webcrypto#cryptokey) based on the method and parameters in `derivedKeyAlgorithm`.
Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to
generate raw keying material, then passing the result into the
@@ -562,10 +570,10 @@ The algorithms currently supported include:
#### `subtle.digest(algorithm, data)`
-
+
* `algorithm`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
-* `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
Using the method identified by `algorithm`, `subtle.digest()` attempts to
@@ -584,10 +592,10 @@ whose value is one of the above.
#### `subtle.encrypt(algorithm, key, data)`
-
+
-* `algorithm`: [`RsaOaepParams`](/api/webcrypto#rsaoaepparams) | [`AesCtrParams`](/api/webcrypto#aesctrparams) | [`AesCbcParams`](/api/webcrypto#aescbcparams) | [`AesGcmParams`](/api/webcrypto#aesgcmparams)
-* `key`: [`CryptoKey`](/api/webcrypto#cryptokey)
+* `algorithm`: [`RsaOaepParams`](/api/v19/webcrypto#rsaoaepparams) | [`AesCtrParams`](/api/v19/webcrypto#aesctrparams) | [`AesCbcParams`](/api/v19/webcrypto#aescbcparams) | [`AesGcmParams`](/api/v19/webcrypto#aesgcmparams)
+* `key`: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
Using the method and parameters specified by `algorithm` and the keying
@@ -604,15 +612,15 @@ The algorithms currently supported include:
#### `subtle.exportKey(format, key)`
-
+
* `format`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
-* `key`: [`CryptoKey`](/api/webcrypto#cryptokey)
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
+* `key`: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object).
Exports the given key into the specified format, if supported.
-If the [`CryptoKey`](/api/webcrypto#cryptokey) is not extractable, the returned promise will reject.
+If the [`CryptoKey`](/api/v19/webcrypto#cryptokey) is not extractable, the returned promise will reject.
When `format` is either `'pkcs8'` or `'spki'` and the export is successful,
the returned promise will be resolved with an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing the
@@ -641,19 +649,19 @@ specification.
#### `subtle.generateKey(algorithm, extractable, keyUsages)`
-
+
-* `algorithm`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`RsaHashedKeyGenParams`](/api/webcrypto#rsahashedkeygenparams) | [`EcKeyGenParams`](/api/webcrypto#eckeygenparams) | [`HmacKeyGenParams`](/api/webcrypto#hmackeygenparams) | [`AesKeyGenParams`](/api/webcrypto#aeskeygenparams)
+* `algorithm`: [`AlgorithmIdentifier`](/api/v19/webcrypto#algorithmidentifier) | [`RsaHashedKeyGenParams`](/api/v19/webcrypto#rsahashedkeygenparams) | [`EcKeyGenParams`](/api/v19/webcrypto#eckeygenparams) | [`HmacKeyGenParams`](/api/v19/webcrypto#hmackeygenparams) | [`AesKeyGenParams`](/api/v19/webcrypto#aeskeygenparams)
* `extractable`: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `keyUsages`: string\[] See [Key usages][].
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`CryptoKey`](/api/webcrypto#cryptokey) | [`CryptoKeyPair`](/api/webcrypto#cryptokeypair)
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`CryptoKey`](/api/v19/webcrypto#cryptokey) | [`CryptoKeyPair`](/api/v19/webcrypto#cryptokeypair)
Using the method and parameters provided in `algorithm`, `subtle.generateKey()`
attempts to generate new keying material. Depending the method used, the method
-may generate either a single [`CryptoKey`](/api/webcrypto#cryptokey) or a [`CryptoKeyPair`](/api/webcrypto#cryptokeypair).
+may generate either a single [`CryptoKey`](/api/v19/webcrypto#cryptokey) or a [`CryptoKeyPair`](/api/v19/webcrypto#cryptokeypair).
-The [`CryptoKeyPair`](/api/webcrypto#cryptokeypair) (public and private key) generating algorithms supported
+The [`CryptoKeyPair`](/api/v19/webcrypto#cryptokeypair) (public and private key) generating algorithms supported
include:
* `'RSASSA-PKCS1-v1_5'`
@@ -666,7 +674,7 @@ include:
* `'X25519'` [^1]
* `'X448'` [^1]
-The [`CryptoKey`](/api/webcrypto#cryptokey) (secret key) generating algorithms supported include:
+The [`CryptoKey`](/api/v19/webcrypto#cryptokey) (secret key) generating algorithms supported include:
* `'HMAC'`
* `'AES-CTR'`
@@ -676,21 +684,21 @@ The [`CryptoKey`](/api/webcrypto#cryptokey) (secret key) generating algorithms s
#### `subtle.importKey(format, keyData, algorithm, extractable, keyUsages)`
-
+
* `format`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
-* `keyData`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) | [`KeyObject`](/api/crypto#keyobject)
+* `keyData`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
-* `algorithm`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`RsaHashedImportParams`](/api/webcrypto#rsahashedimportparams) | [`EcKeyImportParams`](/api/webcrypto#eckeyimportparams) | [`HmacImportParams`](/api/webcrypto#hmacimportparams)
+* `algorithm`: [`AlgorithmIdentifier`](/api/v19/webcrypto#algorithmidentifier) | [`RsaHashedImportParams`](/api/v19/webcrypto#rsahashedimportparams) | [`EcKeyImportParams`](/api/v19/webcrypto#eckeyimportparams) | [`HmacImportParams`](/api/v19/webcrypto#hmacimportparams)
* `extractable`: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `keyUsages`: string\[] See [Key usages][].
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`CryptoKey`](/api/webcrypto#cryptokey)
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`CryptoKey`](/api/v19/webcrypto#cryptokey)
The `subtle.importKey()` method attempts to interpret the provided `keyData`
-as the given `format` to create a [`CryptoKey`](/api/webcrypto#cryptokey) instance using the provided
+as the given `format` to create a [`CryptoKey`](/api/v19/webcrypto#cryptokey) instance using the provided
`algorithm`, `extractable`, and `keyUsages` arguments. If the import is
-successful, the returned promise will be resolved with the created [`CryptoKey`](/api/webcrypto#cryptokey).
+successful, the returned promise will be resolved with the created [`CryptoKey`](/api/v19/webcrypto#cryptokey).
If importing a `'PBKDF2'` key, `extractable` must be `false`.
@@ -717,11 +725,11 @@ The algorithms currently supported include:
#### `subtle.sign(algorithm, key, data)`
-
+
-* `algorithm`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`RsaPssParams`](/api/webcrypto#rsapssparams) | [`EcdsaParams`](/api/webcrypto#ecdsaparams) | [`Ed448Params`](/api/webcrypto#ed448params)
-* `key`: [`CryptoKey`](/api/webcrypto#cryptokey)
-* `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* `algorithm`: [`AlgorithmIdentifier`](/api/v19/webcrypto#algorithmidentifier) | [`RsaPssParams`](/api/v19/webcrypto#rsapssparams) | [`EcdsaParams`](/api/v19/webcrypto#ecdsaparams) | [`Ed448Params`](/api/v19/webcrypto#ed448params)
+* `key`: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
+* `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
Using the method and parameters given by `algorithm` and the keying material
@@ -740,27 +748,27 @@ The algorithms currently supported include:
#### `subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)`
-
+
* `format`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
-* `wrappedKey`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
-* `unwrappingKey`: [`CryptoKey`](/api/webcrypto#cryptokey)
+* `wrappedKey`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
+* `unwrappingKey`: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
-* `unwrapAlgo`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`RsaOaepParams`](/api/webcrypto#rsaoaepparams) | [`AesCtrParams`](/api/webcrypto#aesctrparams) | [`AesCbcParams`](/api/webcrypto#aescbcparams) | [`AesGcmParams`](/api/webcrypto#aesgcmparams)
-* `unwrappedKeyAlgo`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`RsaHashedImportParams`](/api/webcrypto#rsahashedimportparams) | [`EcKeyImportParams`](/api/webcrypto#eckeyimportparams) | [`HmacImportParams`](/api/webcrypto#hmacimportparams)
+* `unwrapAlgo`: [`AlgorithmIdentifier`](/api/v19/webcrypto#algorithmidentifier) | [`RsaOaepParams`](/api/v19/webcrypto#rsaoaepparams) | [`AesCtrParams`](/api/v19/webcrypto#aesctrparams) | [`AesCbcParams`](/api/v19/webcrypto#aescbcparams) | [`AesGcmParams`](/api/v19/webcrypto#aesgcmparams)
+* `unwrappedKeyAlgo`: [`AlgorithmIdentifier`](/api/v19/webcrypto#algorithmidentifier) | [`RsaHashedImportParams`](/api/v19/webcrypto#rsahashedimportparams) | [`EcKeyImportParams`](/api/v19/webcrypto#eckeyimportparams) | [`HmacImportParams`](/api/v19/webcrypto#hmacimportparams)
* `extractable`: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
* `keyUsages`: string\[] See [Key usages][].
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`CryptoKey`](/api/webcrypto#cryptokey)
+* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`CryptoKey`](/api/v19/webcrypto#cryptokey)
In cryptography, "wrapping a key" refers to exporting and then encrypting the
keying material. The `subtle.unwrapKey()` method attempts to decrypt a wrapped
-key and create a [`CryptoKey`](/api/webcrypto#cryptokey) instance. It is equivalent to calling
+key and create a [`CryptoKey`](/api/v19/webcrypto#cryptokey) instance. It is equivalent to calling
`subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`,
`unwrapAlgo`, and `unwrappingKey` arguments as input) then passing the results
in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`,
`extractable`, and `keyUsages` arguments as inputs. If successful, the returned
-promise is resolved with a [`CryptoKey`](/api/webcrypto#cryptokey) object.
+promise is resolved with a [`CryptoKey`](/api/v19/webcrypto#cryptokey) object.
The wrapping algorithms currently supported include:
@@ -789,12 +797,12 @@ The unwrapped key algorithms supported include:
#### `subtle.verify(algorithm, key, signature, data)`
-
+
-* `algorithm`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`RsaPssParams`](/api/webcrypto#rsapssparams) | [`EcdsaParams`](/api/webcrypto#ecdsaparams) | [`Ed448Params`](/api/webcrypto#ed448params)
-* `key`: [`CryptoKey`](/api/webcrypto#cryptokey)
-* `signature`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
-* `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* `algorithm`: [`AlgorithmIdentifier`](/api/v19/webcrypto#algorithmidentifier) | [`RsaPssParams`](/api/v19/webcrypto#rsapssparams) | [`EcdsaParams`](/api/v19/webcrypto#ecdsaparams) | [`Ed448Params`](/api/v19/webcrypto#ed448params)
+* `key`: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
+* `signature`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
+* `data`: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
Using the method and parameters given in `algorithm` and the keying material
@@ -813,12 +821,12 @@ The algorithms currently supported include:
#### `subtle.wrapKey(format, key, wrappingKey, wrapAlgo)`
-
+
* `format`: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
-* `key`: [`CryptoKey`](/api/webcrypto#cryptokey)
-* `wrappingKey`: [`CryptoKey`](/api/webcrypto#cryptokey)
-* `wrapAlgo`: [`AlgorithmIdentifier`](/api/webcrypto#algorithmidentifier) | [`RsaOaepParams`](/api/webcrypto#rsaoaepparams) | [`AesCtrParams`](/api/webcrypto#aesctrparams) | [`AesCbcParams`](/api/webcrypto#aescbcparams) | [`AesGcmParams`](/api/webcrypto#aesgcmparams)
+* `key`: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
+* `wrappingKey`: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
+* `wrapAlgo`: [`AlgorithmIdentifier`](/api/v19/webcrypto#algorithmidentifier) | [`RsaOaepParams`](/api/v19/webcrypto#rsaoaepparams) | [`AesCtrParams`](/api/v19/webcrypto#aesctrparams) | [`AesCbcParams`](/api/v19/webcrypto#aescbcparams) | [`AesGcmParams`](/api/v19/webcrypto#aesgcmparams)
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) containing [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
In cryptography, "wrapping a key" refers to exporting and then encrypting the
@@ -842,47 +850,47 @@ The wrapping algorithms currently supported include:
### Algorithm parameters
The algorithm parameter objects define the methods and parameters used by
-the various [`SubtleCrypto`](/api/webcrypto#subtlecrypto) methods. While described here as "classes", they
+the various [`SubtleCrypto`](/api/v19/webcrypto#subtlecrypto) methods. While described here as "classes", they
are simple JavaScript dictionary objects.
#### `AlgorithmIdentifier`
-
+
##### `algorithmIdentifier.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
#### `AesCbcParams`
-
+
##### `aesCbcParams.iv`
-
+
-* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
Provides the initialization vector. It must be exactly 16-bytes in length
and should be unpredictable and cryptographically random.
##### `aesCbcParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'AES-CBC'`.
#### `AesCtrParams`
-
+
##### `aesCtrParams.counter`
-
+
-* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
The initial value of the counter block. This must be exactly 16 bytes long.
@@ -891,26 +899,26 @@ counter and the remaining bits as the nonce.
##### `aesCtrParams.length`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The number of bits in the `aesCtrParams.counter` that are
to be used as the counter.
##### `aesCtrParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'AES-CTR'`.
#### `AesGcmParams`
-
+
##### `aesGcmParams.additionalData`
-
+
-* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
With the AES-GCM method, the `additionalData` is extra input that is not
encrypted but is included in the authentication of the data. The use of
@@ -918,9 +926,9 @@ encrypted but is included in the authentication of the data. The use of
##### `aesGcmParams.iv`
-
+
-* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
The initialization vector must be unique for every encryption operation using a
given key.
@@ -933,13 +941,13 @@ initialization vectors for AES-GCM, refer to Section 8 of [NIST SP 800-38D][].
##### `aesGcmParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'AES-GCM'`.
##### `aesGcmParams.tagLength`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) The size in bits of the generated authentication tag.
This values must be one of `32`, `64`, `96`, `104`, `112`, `120`, or
@@ -947,11 +955,11 @@ initialization vectors for AES-GCM, refer to Section 8 of [NIST SP 800-38D][].
#### `AesKeyGenParams`
-
+
##### `aesKeyGenParams.length`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -960,26 +968,26 @@ or `256`.
##### `aesKeyGenParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'AES-CBC'`, `'AES-CTR'`, `'AES-GCM'`, or
`'AES-KW'`
#### `EcdhKeyDeriveParams`
-
+
##### `ecdhKeyDeriveParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'ECDH'`, `'X25519'`, or `'X448'`.
##### `ecdhKeyDeriveParams.public`
-
+
-* Type: [`CryptoKey`](/api/webcrypto#cryptokey)
+* Type: [`CryptoKey`](/api/v19/webcrypto#cryptokey)
ECDH key derivation operates by taking as input one parties private key and
another parties public key -- using both to generate a common shared secret.
@@ -988,11 +996,11 @@ key.
#### `EcdsaParams`
-
+
##### `ecdsaParams.hash`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1008,57 +1016,57 @@ whose value is one of the above listed values.
##### `ecdsaParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'ECDSA'`.
#### `EcKeyGenParams`
-
+
##### `ecKeyGenParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'ECDSA'` or `'ECDH'`.
##### `ecKeyGenParams.namedCurve`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'P-256'`, `'P-384'`, `'P-521'`.
#### `EcKeyImportParams`
-
+
##### `ecKeyImportParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'ECDSA'` or `'ECDH'`.
##### `ecKeyImportParams.namedCurve`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'P-256'`, `'P-384'`, `'P-521'`.
#### `Ed448Params`
-
+
##### `ed448Params.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'Ed448'`.
##### `ed448Params.context`
-
+
-* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
+* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer) | [`undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type)
The `context` member represents the optional context data to associate with
the message.
@@ -1067,11 +1075,11 @@ which is equivalent to not providing context at all.
#### `HkdfParams`
-
+
##### `hkdfParams.hash`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1087,24 +1095,24 @@ whose value is one of the above listed values.
##### `hkdfParams.info`
-
+
-* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
Provides application-specific contextual input to the HKDF algorithm.
This can be zero-length but must be provided.
##### `hkdfParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'HKDF'`.
##### `hkdfParams.salt`
-
+
-* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
The salt value significantly improves the strength of the HKDF algorithm.
It should be random or pseudorandom and should be the same length as the
@@ -1113,11 +1121,11 @@ digest, the salt should be 256-bits of random data).
#### `HmacImportParams`
-
+
##### `hmacImportParams.hash`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1133,7 +1141,7 @@ whose value is one of the above listed values.
##### `hmacImportParams.length`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1142,17 +1150,17 @@ be omitted for most cases.
##### `hmacImportParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'HMAC'`.
#### `HmacKeyGenParams`
-
+
##### `hmacKeyGenParams.hash`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1168,7 +1176,7 @@ whose value is one of the above listed values.
##### `hmacKeyGenParams.length`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1178,17 +1186,17 @@ This is optional and should be omitted for most cases.
##### `hmacKeyGenParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'HMAC'`.
#### `Pbkdf2Params`
-
+
##### `pbkdb2Params.hash`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1204,7 +1212,7 @@ whose value is one of the above listed values.
##### `pbkdf2Params.iterations`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1212,25 +1220,25 @@ The number of iterations the PBKDF2 algorithm should make when deriving bits.
##### `pbkdf2Params.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'PBKDF2'`.
##### `pbkdf2Params.salt`
-
+
-* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
Should be at least 16 random or pseudorandom bytes.
#### `RsaHashedImportParams`
-
+
##### `rsaHashedImportParams.hash`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1246,18 +1254,18 @@ whose value is one of the above listed values.
##### `rsaHashedImportParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'RSASSA-PKCS1-v1_5'`, `'RSA-PSS'`, or
`'RSA-OAEP'`.
#### `RsaHashedKeyGenParams`
-
+
##### `rsaHashedKeyGenParams.hash`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
@@ -1273,7 +1281,7 @@ whose value is one of the above listed values.
##### `rsaHashedKeyGenParams.modulusLength`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1282,14 +1290,14 @@ at least `2048`.
##### `rsaHashedKeyGenParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be one of `'RSASSA-PKCS1-v1_5'`, `'RSA-PSS'`, or
`'RSA-OAEP'`.
##### `rsaHashedKeyGenParams.publicExponent`
-
+
* Type: [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
@@ -1301,38 +1309,38 @@ there is reason to use a different value, use `new Uint8Array([1, 0, 1])`
#### `RsaOaepParams`
-
+
-##### rsaOaepParams.label
+##### `rsaOaepParams.label`
-
+
-* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/buffer#buffer)
+* Type: [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`Buffer`](/api/v19/buffer#buffer)
An additional collection of bytes that will not be encrypted, but will be bound
to the generated ciphertext.
The `rsaOaepParams.label` parameter is optional.
-##### rsaOaepParams.name
+##### `rsaOaepParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) must be `'RSA-OAEP'`.
#### `RsaPssParams`
-
+
##### `rsaPssParams.name`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Must be `'RSA-PSS'`.
##### `rsaPssParams.saltLength`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
diff --git a/content/api/v19/webstreams.en.md b/content/api/v19/webstreams.en.md
index 2fda904af1..e11c21e140 100644
--- a/content/api/v19/webstreams.en.md
+++ b/content/api/v19/webstreams.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+
+
+Experimental.
+
+
An implementation of the [WHATWG Streams Standard][].
@@ -32,17 +36,17 @@ 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
+ ReadableStream,
} from 'node:stream/web';
import {
- setInterval as every
+ setInterval as every,
} from 'node:timers/promises';
import {
- performance
+ performance,
} from 'node:perf_hooks';
const SECOND = 1000;
@@ -51,24 +55,22 @@ const stream = new ReadableStream({
async start(controller) {
for await (const _ of every(SECOND))
controller.enqueue(performance.now());
- }
+ },
});
for await (const value of stream)
console.log(value);
-```
-
-```cjs
+--------------
const {
- ReadableStream
+ ReadableStream,
} = require('node:stream/web');
const {
- setInterval: every
+ setInterval: every,
} = require('node:timers/promises');
const {
- performance
+ performance,
} = require('node:perf_hooks');
const SECOND = 1000;
@@ -77,7 +79,7 @@ const stream = new ReadableStream({
async start(controller) {
for await (const _ of every(SECOND))
controller.enqueue(performance.now());
- }
+ },
});
(async () => {
@@ -90,22 +92,22 @@ const stream = new ReadableStream({
#### `ReadableStream`
-
+
##### `new ReadableStream([underlyingSource [, strategy]])`
-
+
* `underlyingSource` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `start` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that is invoked immediately when
the `ReadableStream` is created.
- * `controller` [`ReadableStreamDefaultController`](/api/webstreams#readablestreamdefaultcontroller) | [`ReadableByteStreamController`](/api/webstreams#readablebytestreamcontroller)
+ * `controller` [`ReadableStreamDefaultController`](/api/v19/webstreams#readablestreamdefaultcontroller) | [`ReadableByteStreamController`](/api/v19/webstreams#readablebytestreamcontroller)
* Returns: `undefined` or a promise fulfilled with `undefined`.
* `pull` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that is called repeatedly when the
`ReadableStream` internal queue is not full. The operation may be sync or
async. If async, the function will not be called again until the previously
returned promise is fulfilled.
- * `controller` [`ReadableStreamDefaultController`](/api/webstreams#readablestreamdefaultcontroller) | [`ReadableByteStreamController`](/api/webstreams#readablebytestreamcontroller)
+ * `controller` [`ReadableStreamDefaultController`](/api/v19/webstreams#readablestreamdefaultcontroller) | [`ReadableByteStreamController`](/api/v19/webstreams#readablebytestreamcontroller)
* Returns: A promise fulfilled with `undefined`.
* `cancel` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that is called when the
`ReadableStream` is canceled.
@@ -124,10 +126,10 @@ const stream = new ReadableStream({
##### `readableStream.locked`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) Set to `true` if there is an active reader for this
- [`ReadableStream`](/api/webstreams#readablestream).
+ [`ReadableStream`](/api/v19/webstreams#readablestream).
The `readableStream.locked` property is `false` by default, and is
switched to `true` while there is an active reader consuming the
@@ -135,7 +137,7 @@ stream's data.
##### `readableStream.cancel([reason])`
-
+
* `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
* Returns: A promise fulfilled with `undefined` once cancelation has
@@ -143,13 +145,13 @@ stream's data.
##### `readableStream.getReader([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `mode` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) `'byob'` or `undefined`
-* Returns: [`ReadableStreamDefaultReader`](/api/webstreams#readablestreamdefaultreader) | [`ReadableStreamBYOBReader`](/api/webstreams#readablestreambyobreader)
+* Returns: [`ReadableStreamDefaultReader`](/api/v19/webstreams#readablestreamdefaultreader) | [`ReadableStreamBYOBReader`](/api/v19/webstreams#readablestreambyobreader)
-```mjs
+```mjs|cjs
import { ReadableStream } from 'node:stream/web';
const stream = new ReadableStream();
@@ -157,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();
@@ -173,13 +173,13 @@ Causes the `readableStream.locked` to be `true`.
##### `readableStream.pipeThrough(transform[, options])`
-
+
* `transform` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `readable` [`ReadableStream`](/api/webstreams#readablestream) The `ReadableStream` to which
+ * `readable` [`ReadableStream`](/api/v19/webstreams#readablestream) The `ReadableStream` to which
`transform.writable` will push the potentially modified data
is receives from this `ReadableStream`.
- * `writable` [`WritableStream`](/api/webstreams#writablestream) The `WritableStream` to which this
+ * `writable` [`WritableStream`](/api/v19/webstreams#writablestream) The `WritableStream` to which this
`ReadableStream`'s data will be written.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `preventAbort` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, errors in this `ReadableStream`
@@ -189,20 +189,20 @@ Causes the `readableStream.locked` to be `true`.
canceled.
* `preventClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, closing this `ReadableStream`
does not cause `transform.writable` to be closed.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows the transfer of data to be canceled
- using an [`AbortController`](/api/globals#abortcontroller).
-* Returns: [`ReadableStream`](/api/webstreams#readablestream) From `transform.readable`.
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows the transfer of data to be canceled
+ using an [`AbortController`](/api/v19/globals#abortcontroller).
+* Returns: [`ReadableStream`](/api/v19/webstreams#readablestream) From `transform.readable`.
-Connects this [`ReadableStream`](/api/webstreams#readablestream) to the pair of [`ReadableStream`](/api/webstreams#readablestream) and
-[`WritableStream`](/api/webstreams#writablestream) provided in the `transform` argument such that the
-data from this [`ReadableStream`](/api/webstreams#readablestream) is written in to `transform.writable`,
+Connects this [`ReadableStream`](/api/v19/webstreams#readablestream) to the pair of [`ReadableStream`](/api/v19/webstreams#readablestream) and
+[`WritableStream`](/api/v19/webstreams#writablestream) provided in the `transform` argument such that the
+data from this [`ReadableStream`](/api/v19/webstreams#readablestream) is written in to `transform.writable`,
possibly transformed, then pushed to `transform.readable`. Once the
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,
@@ -217,16 +217,14 @@ const stream = new ReadableStream({
const transform = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
- }
+ },
});
const transformedStream = stream.pipeThrough(transform);
for await (const chunk of transformedStream)
console.log(chunk);
-```
-
-```cjs
+--------------
const {
ReadableStream,
TransformStream,
@@ -241,7 +239,7 @@ const stream = new ReadableStream({
const transform = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
- }
+ },
});
const transformedStream = stream.pipeThrough(transform);
@@ -252,11 +250,11 @@ const transformedStream = stream.pipeThrough(transform);
})();
```
-##### `readableStream.pipeTo(destination, options)`
+##### `readableStream.pipeTo(destination[, options])`
-
+
-* `destination` [`WritableStream`](/api/webstreams#writablestream) A [`WritableStream`](/api/webstreams#writablestream) to which this
+* `destination` [`WritableStream`](/api/v19/webstreams#writablestream) A [`WritableStream`](/api/v19/webstreams#writablestream) to which this
`ReadableStream`'s data will be written.
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `preventAbort` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, errors in this `ReadableStream`
@@ -265,8 +263,8 @@ const transformedStream = stream.pipeThrough(transform);
will not cause this `ReadableStream` to be canceled.
* `preventClose` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, closing this `ReadableStream`
does not cause `destination` to be closed.
- * `signal` [`AbortSignal`](/api/globals#abortsignal) Allows the transfer of data to be canceled
- using an [`AbortController`](/api/globals#abortcontroller).
+ * `signal` [`AbortSignal`](/api/v19/globals#abortsignal) Allows the transfer of data to be canceled
+ using an [`AbortController`](/api/v19/globals#abortcontroller).
* Returns: A promise fulfilled with `undefined`
Causes the `readableStream.locked` to be `true` while the pipe operation
@@ -274,11 +272,11 @@ is active.
##### `readableStream.tee()`
-
+
* Returns: ReadableStream\[]
-Returns a pair of new [`ReadableStream`](/api/webstreams#readablestream) instances to which this
+Returns a pair of new [`ReadableStream`](/api/v19/webstreams#readablestream) instances to which this
`ReadableStream`'s data will be forwarded. Each will receive the
same data.
@@ -286,10 +284,10 @@ Causes the `readableStream.locked` to be `true`.
##### `readableStream.values([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- * `preventCancel` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, prevents the [`ReadableStream`](/api/webstreams#readablestream)
+ * `preventCancel` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) When `true`, prevents the [`ReadableStream`](/api/v19/webstreams#readablestream)
from being closed when the async iterator abruptly terminates.
**Default**: `false`.
@@ -310,7 +308,7 @@ for await (const chunk of stream.values({ preventCancel: true }))
##### Async Iteration
-The [`ReadableStream`](/api/webstreams#readablestream) object supports the async iterator protocol using
+The [`ReadableStream`](/api/v19/webstreams#readablestream) object supports the async iterator protocol using
`for await` syntax.
```mjs
@@ -322,20 +320,20 @@ for await (const chunk of stream)
console.log(Buffer.from(chunk).toString());
```
-The async iterator will consume the [`ReadableStream`](/api/webstreams#readablestream) until it terminates.
+The async iterator will consume the [`ReadableStream`](/api/v19/webstreams#readablestream) until it terminates.
By default, if the async iterator exits early (via either a `break`,
-`return`, or a `throw`), the [`ReadableStream`](/api/webstreams#readablestream) will be closed. To prevent
-automatic closing of the [`ReadableStream`](/api/webstreams#readablestream), use the `readableStream.values()`
+`return`, or a `throw`), the [`ReadableStream`](/api/v19/webstreams#readablestream) will be closed. To prevent
+automatic closing of the [`ReadableStream`](/api/v19/webstreams#readablestream), use the `readableStream.values()`
method to acquire the async iterator and set the `preventCancel` option to
`true`.
-The [`ReadableStream`](/api/webstreams#readablestream) must not be locked (that is, it must not have an existing
-active reader). During the async iteration, the [`ReadableStream`](/api/webstreams#readablestream) will be locked.
+The [`ReadableStream`](/api/v19/webstreams#readablestream) must not be locked (that is, it must not have an existing
+active reader). During the async iteration, the [`ReadableStream`](/api/v19/webstreams#readablestream) will be locked.
##### Transferring with `postMessage()`
-A [`ReadableStream`](/api/webstreams#readablestream) instance can be transferred using a [`MessagePort`](/api/worker_threads#messageport).
+A [`ReadableStream`](/api/v19/webstreams#readablestream) instance can be transferred using a [`MessagePort`](/api/v19/worker_threads#messageport).
```js
const stream = new ReadableStream(getReadableSourceSomehow());
@@ -353,65 +351,65 @@ port2.postMessage(stream, [stream]);
#### `ReadableStreamDefaultReader`
-
+
By default, calling `readableStream.getReader()` with no arguments
will return an instance of `ReadableStreamDefaultReader`. The default
reader treats the chunks of data passed through the stream as opaque
-values, which allows the [`ReadableStream`](/api/webstreams#readablestream) to work with generally any
+values, which allows the [`ReadableStream`](/api/v19/webstreams#readablestream) to work with generally any
JavaScript value.
##### `new ReadableStreamDefaultReader(stream)`
-
+
-* `stream` [`ReadableStream`](/api/webstreams#readablestream)
+* `stream` [`ReadableStream`](/api/v19/webstreams#readablestream)
-Creates a new [`ReadableStreamDefaultReader`](/api/webstreams#readablestreamdefaultreader) that is locked to the
-given [`ReadableStream`](/api/webstreams#readablestream).
+Creates a new [`ReadableStreamDefaultReader`](/api/v19/webstreams#readablestreamdefaultreader) that is locked to the
+given [`ReadableStream`](/api/v19/webstreams#readablestream).
##### `readableStreamDefaultReader.cancel([reason])`
-
+
* `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
* Returns: A promise fulfilled with `undefined`.
-Cancels the [`ReadableStream`](/api/webstreams#readablestream) and returns a promise that is fulfilled
+Cancels the [`ReadableStream`](/api/v19/webstreams#readablestream) and returns a promise that is fulfilled
when the underlying stream has been canceled.
##### `readableStreamDefaultReader.closed`
-
+
* Type: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfilled with `undefined` when the associated
- [`ReadableStream`](/api/webstreams#readablestream) is closed or rejected if the stream errors or the reader's
+ [`ReadableStream`](/api/v19/webstreams#readablestream) is closed or rejected if the stream errors or the reader's
lock is released before the stream finishes closing.
##### `readableStreamDefaultReader.read()`
-
+
* Returns: A promise fulfilled with an object:
* `value` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
* `done` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Requests the next chunk of data from the underlying [`ReadableStream`](/api/webstreams#readablestream)
+Requests the next chunk of data from the underlying [`ReadableStream`](/api/v19/webstreams#readablestream)
and returns a promise that is fulfilled with the data once it is
available.
##### `readableStreamDefaultReader.releaseLock()`
-
+
-Releases this reader's lock on the underlying [`ReadableStream`](/api/webstreams#readablestream).
+Releases this reader's lock on the underlying [`ReadableStream`](/api/v19/webstreams#readablestream).
#### `ReadableStreamBYOBReader`
-
+
The `ReadableStreamBYOBReader` is an alternative consumer for
-byte-oriented [`ReadableStream`](/api/webstreams#readablestream)s (those that are created with
+byte-oriented [`ReadableStream`](/api/v19/webstreams#readablestream)s (those that are created with
`underlyingSource.type` set equal to `'bytes'` when the
`ReadableStream` was created).
@@ -421,11 +419,11 @@ data that avoids extraneous copying.
```mjs
import {
- open
+ open,
} from 'node:fs/promises';
import {
- ReadableStream
+ ReadableStream,
} from 'node:stream/web';
import { Buffer } from 'node:buffer';
@@ -446,7 +444,7 @@ class Source {
} = await this.file.read({
buffer: view,
offset: view.byteOffset,
- length: view.byteLength
+ length: view.byteLength,
});
if (bytesRead === 0) {
@@ -479,45 +477,45 @@ console.log(Buffer.from(data).toString());
##### `new ReadableStreamBYOBReader(stream)`
-
+
-* `stream` [`ReadableStream`](/api/webstreams#readablestream)
+* `stream` [`ReadableStream`](/api/v19/webstreams#readablestream)
Creates a new `ReadableStreamBYOBReader` that is locked to the
-given [`ReadableStream`](/api/webstreams#readablestream).
+given [`ReadableStream`](/api/v19/webstreams#readablestream).
##### `readableStreamBYOBReader.cancel([reason])`
-
+
* `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
* Returns: A promise fulfilled with `undefined`.
-Cancels the [`ReadableStream`](/api/webstreams#readablestream) and returns a promise that is fulfilled
+Cancels the [`ReadableStream`](/api/v19/webstreams#readablestream) and returns a promise that is fulfilled
when the underlying stream has been canceled.
##### `readableStreamBYOBReader.closed`
-
+
* Type: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfilled with `undefined` when the associated
- [`ReadableStream`](/api/webstreams#readablestream) is closed or rejected if the stream errors or the reader's
+ [`ReadableStream`](/api/v19/webstreams#readablestream) is closed or rejected if the stream errors or the reader's
lock is released before the stream finishes closing.
##### `readableStreamBYOBReader.read(view)`
-
+
-* `view` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `view` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
* Returns: A promise fulfilled with an object:
* `value` [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
* `done` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
-Requests the next chunk of data from the underlying [`ReadableStream`](/api/webstreams#readablestream)
+Requests the next chunk of data from the underlying [`ReadableStream`](/api/v19/webstreams#readablestream)
and returns a promise that is fulfilled with the data once it is
available.
-Do not pass a pooled [`Buffer`](/api/buffer#buffer) object instance in to this method.
+Do not pass a pooled [`Buffer`](/api/v19/buffer#buffer) object instance in to this method.
Pooled `Buffer` objects are created using `Buffer.allocUnsafe()`,
or `Buffer.from()`, or are often returned by various `node:fs` module
callbacks. These types of `Buffer`s use a shared underlying
@@ -530,98 +528,98 @@ can have disastrous consequences for your application.
##### `readableStreamBYOBReader.releaseLock()`
-
+
-Releases this reader's lock on the underlying [`ReadableStream`](/api/webstreams#readablestream).
+Releases this reader's lock on the underlying [`ReadableStream`](/api/v19/webstreams#readablestream).
#### `ReadableStreamDefaultController`
-
+
-Every [`ReadableStream`](/api/webstreams#readablestream) has a controller that is responsible for
+Every [`ReadableStream`](/api/v19/webstreams#readablestream) has a controller that is responsible for
the internal state and management of the stream's queue. The
`ReadableStreamDefaultController` is the default controller
implementation for `ReadableStream`s that are not byte-oriented.
##### `readableStreamDefaultController.close()`
-
+
-Closes the [`ReadableStream`](/api/webstreams#readablestream) to which this controller is associated.
+Closes the [`ReadableStream`](/api/v19/webstreams#readablestream) to which this controller is associated.
##### `readableStreamDefaultController.desiredSize`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-Returns the amount of data remaining to fill the [`ReadableStream`](/api/webstreams#readablestream)'s
+Returns the amount of data remaining to fill the [`ReadableStream`](/api/v19/webstreams#readablestream)'s
queue.
-##### `readableStreamDefaultController.enqueue(chunk)`
+##### `readableStreamDefaultController.enqueue([chunk])`
-
+
* `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
-Appends a new chunk of data to the [`ReadableStream`](/api/webstreams#readablestream)'s queue.
+Appends a new chunk of data to the [`ReadableStream`](/api/v19/webstreams#readablestream)'s queue.
-##### `readableStreamDefaultController.error(error)`
+##### `readableStreamDefaultController.error([error])`
-
+
* `error` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
-Signals an error that causes the [`ReadableStream`](/api/webstreams#readablestream) to error and close.
+Signals an error that causes the [`ReadableStream`](/api/v19/webstreams#readablestream) to error and close.
#### `ReadableByteStreamController`
-
+
-Every [`ReadableStream`](/api/webstreams#readablestream) has a controller that is responsible for
+Every [`ReadableStream`](/api/v19/webstreams#readablestream) has a controller that is responsible for
the internal state and management of the stream's queue. The
`ReadableByteStreamController` is for byte-oriented `ReadableStream`s.
##### `readableByteStreamController.byobRequest`
-
+
-* Type: [`ReadableStreamBYOBRequest`](/api/webstreams#readablestreambyobrequest)
+* Type: [`ReadableStreamBYOBRequest`](/api/v19/webstreams#readablestreambyobrequest)
##### `readableByteStreamController.close()`
-
+
-Closes the [`ReadableStream`](/api/webstreams#readablestream) to which this controller is associated.
+Closes the [`ReadableStream`](/api/v19/webstreams#readablestream) to which this controller is associated.
##### `readableByteStreamController.desiredSize`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-Returns the amount of data remaining to fill the [`ReadableStream`](/api/webstreams#readablestream)'s
+Returns the amount of data remaining to fill the [`ReadableStream`](/api/v19/webstreams#readablestream)'s
queue.
##### `readableByteStreamController.enqueue(chunk)`
-
+
-* `chunk`: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `chunk`: [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
-Appends a new chunk of data to the [`ReadableStream`](/api/webstreams#readablestream)'s queue.
+Appends a new chunk of data to the [`ReadableStream`](/api/v19/webstreams#readablestream)'s queue.
-##### `readableByteStreamController.error(error)`
+##### `readableByteStreamController.error([error])`
-
+
* `error` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
-Signals an error that causes the [`ReadableStream`](/api/webstreams#readablestream) to error and close.
+Signals an error that causes the [`ReadableStream`](/api/v19/webstreams#readablestream) to error and close.
#### `ReadableStreamBYOBRequest`
-
+
When using `ReadableByteStreamController` in byte-oriented
streams, and when using the `ReadableStreamBYOBReader`,
@@ -635,7 +633,7 @@ been provided.
##### `readableStreamBYOBRequest.respond(bytesWritten)`
-
+
* `bytesWritten` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -644,34 +642,34 @@ to `readableStreamBYOBRequest.view`.
##### `readableStreamBYOBRequest.respondWithNewView(view)`
-
+
-* `view` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* `view` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
Signals that the request has been fulfilled with bytes written
to a new `Buffer`, `TypedArray`, or `DataView`.
##### `readableStreamBYOBRequest.view`
-
+
-* Type: [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
+* Type: [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
#### `WritableStream`
-
+
The `WritableStream` is a destination to which stream data is sent.
```mjs
import {
- WritableStream
+ WritableStream,
} from 'node:stream/web';
const stream = new WritableStream({
write(chunk) {
console.log(chunk);
- }
+ },
});
await stream.getWriter().write('Hello World');
@@ -679,17 +677,17 @@ await stream.getWriter().write('Hello World');
##### `new WritableStream([underlyingSink[, strategy]])`
-
+
* `underlyingSink` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `start` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that is invoked immediately when
the `WritableStream` is created.
- * `controller` [`WritableStreamDefaultController`](/api/webstreams#writablestreamdefaultcontroller)
+ * `controller` [`WritableStreamDefaultController`](/api/v19/webstreams#writablestreamdefaultcontroller)
* Returns: `undefined` or a promise fulfilled with `undefined`.
* `write` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that is invoked when a chunk of
data has been written to the `WritableStream`.
* `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
- * `controller` [`WritableStreamDefaultController`](/api/webstreams#writablestreamdefaultcontroller)
+ * `controller` [`WritableStreamDefaultController`](/api/v19/webstreams#writablestreamdefaultcontroller)
* Returns: A promise fulfilled with `undefined`.
* `close` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that is called when the
`WritableStream` is closed.
@@ -710,7 +708,7 @@ await stream.getWriter().write('Hello World');
##### `writableStream.abort([reason])`
-
+
* `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
* Returns: A promise fulfilled with `undefined`.
@@ -720,7 +718,7 @@ canceled with their associated promises rejected.
##### `writableStream.close()`
-
+
* Returns: A promise fulfilled with `undefined`.
@@ -728,16 +726,16 @@ Closes the `WritableStream` when no additional writes are expected.
##### `writableStream.getWriter()`
-
+
-* Returns: [`WritableStreamDefaultWriter`](/api/webstreams#writablestreamdefaultwriter)
+* Returns: [`WritableStreamDefaultWriter`](/api/v19/webstreams#writablestreamdefaultwriter)
Creates and creates a new writer instance that can be used to write
data into the `WritableStream`.
##### `writableStream.locked`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -747,7 +745,7 @@ switched to `true` while there is an active writer attached to this
##### Transferring with postMessage()
-A [`WritableStream`](/api/webstreams#writablestream) instance can be transferred using a [`MessagePort`](/api/worker_threads#messageport).
+A [`WritableStream`](/api/v19/webstreams#writablestream) instance can be transferred using a [`MessagePort`](/api/v19/worker_threads#messageport).
```js
const stream = new WritableStream(getWritableSinkSomehow());
@@ -763,20 +761,20 @@ port2.postMessage(stream, [stream]);
#### `WritableStreamDefaultWriter`
-
+
##### `new WritableStreamDefaultWriter(stream)`
-
+
-* `stream` [`WritableStream`](/api/webstreams#writablestream)
+* `stream` [`WritableStream`](/api/v19/webstreams#writablestream)
Creates a new `WritableStreamDefaultWriter` that is locked to the given
`WritableStream`.
##### `writableStreamDefaultWriter.abort([reason])`
-
+
* `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
* Returns: A promise fulfilled with `undefined`.
@@ -786,7 +784,7 @@ canceled with their associated promises rejected.
##### `writableStreamDefaultWriter.close()`
-
+
* Returns: A promise fulfilled with `undefined`.
@@ -794,82 +792,82 @@ Closes the `WritableStream` when no additional writes are expected.
##### `writableStreamDefaultWriter.closed`
-
+
* Type: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfilled with `undefined` when the associated
- [`WritableStream`](/api/webstreams#writablestream) is closed or rejected if the stream errors or the writer's
+ [`WritableStream`](/api/v19/webstreams#writablestream) is closed or rejected if the stream errors or the writer's
lock is released before the stream finishes closing.
##### `writableStreamDefaultWriter.desiredSize`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
-The amount of data required to fill the [`WritableStream`](/api/webstreams#writablestream)'s queue.
+The amount of data required to fill the [`WritableStream`](/api/v19/webstreams#writablestream)'s queue.
##### `writableStreamDefaultWriter.ready`
-
+
* type: A promise that is fulfilled with `undefined` when the
writer is ready to be used.
##### `writableStreamDefaultWriter.releaseLock()`
-
+
-Releases this writer's lock on the underlying [`ReadableStream`](/api/webstreams#readablestream).
+Releases this writer's lock on the underlying [`ReadableStream`](/api/v19/webstreams#readablestream).
##### `writableStreamDefaultWriter.write([chunk])`
-
+
* `chunk`: [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
* Returns: A promise fulfilled with `undefined`.
-Appends a new chunk of data to the [`WritableStream`](/api/webstreams#writablestream)'s queue.
+Appends a new chunk of data to the [`WritableStream`](/api/v19/webstreams#writablestream)'s queue.
#### `WritableStreamDefaultController`
-
+
-The `WritableStreamDefaultController` manage's the [`WritableStream`](/api/webstreams#writablestream)'s
+The `WritableStreamDefaultController` manage's the [`WritableStream`](/api/v19/webstreams#writablestream)'s
internal state.
-##### `writableStreamDefaultController.error(error)`
+##### `writableStreamDefaultController.error([error])`
-
+
* `error` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
Called by user-code to signal that an error has occurred while processing
-the `WritableStream` data. When called, the [`WritableStream`](/api/webstreams#writablestream) will be aborted,
+the `WritableStream` data. When called, the [`WritableStream`](/api/v19/webstreams#writablestream) will be aborted,
with currently pending writes canceled.
##### `writableStreamDefaultController.signal`
-* Type: [`AbortSignal`](/api/globals#abortsignal) An `AbortSignal` that can be used to cancel pending
- write or close operations when a [`WritableStream`](/api/webstreams#writablestream) is aborted.
+* Type: [`AbortSignal`](/api/v19/globals#abortsignal) An `AbortSignal` that can be used to cancel pending
+ write or close operations when a [`WritableStream`](/api/v19/webstreams#writablestream) is aborted.
#### `TransformStream`
-
+
-A `TransformStream` consists of a [`ReadableStream`](/api/webstreams#readablestream) and a [`WritableStream`](/api/webstreams#writablestream) that
+A `TransformStream` consists of a [`ReadableStream`](/api/v19/webstreams#readablestream) and a [`WritableStream`](/api/v19/webstreams#writablestream) that
are connected such that the data written to the `WritableStream` is received,
and potentially transformed, before being pushed into the `ReadableStream`'s
queue.
```mjs
import {
- TransformStream
+ TransformStream,
} from 'node:stream/web';
const transform = new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
- }
+ },
});
await Promise.all([
@@ -880,23 +878,23 @@ await Promise.all([
##### `new TransformStream([transformer[, writableStrategy[, readableStrategy]]])`
-
+
* `transformer` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `start` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that is invoked immediately when
the `TransformStream` is created.
- * `controller` [`TransformStreamDefaultController`](/api/webstreams#transformstreamdefaultcontroller)
+ * `controller` [`TransformStreamDefaultController`](/api/v19/webstreams#transformstreamdefaultcontroller)
* Returns: `undefined` or a promise fulfilled with `undefined`
* `transform` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that receives, and
potentially modifies, a chunk of data written to `transformStream.writable`,
before forwarding that on to `transformStream.readable`.
* `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
- * `controller` [`TransformStreamDefaultController`](/api/webstreams#transformstreamdefaultcontroller)
+ * `controller` [`TransformStreamDefaultController`](/api/v19/webstreams#transformstreamdefaultcontroller)
* Returns: A promise fulfilled with `undefined`.
* `flush` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) A user-defined function that is called immediately before
the writable side of the `TransformStream` is closed, signaling the end of
the transformation process.
- * `controller` [`TransformStreamDefaultController`](/api/webstreams#transformstreamdefaultcontroller)
+ * `controller` [`TransformStreamDefaultController`](/api/v19/webstreams#transformstreamdefaultcontroller)
* Returns: A promise fulfilled with `undefined`.
* `readableType` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) the `readableType` option is reserved for future use
and _must_ be `undefined`.
@@ -919,19 +917,19 @@ await Promise.all([
##### `transformStream.readable`
-
+
-* Type: [`ReadableStream`](/api/webstreams#readablestream)
+* Type: [`ReadableStream`](/api/v19/webstreams#readablestream)
##### `transformStream.writable`
-
+
-* Type: [`WritableStream`](/api/webstreams#writablestream)
+* Type: [`WritableStream`](/api/v19/webstreams#writablestream)
##### Transferring with postMessage()
-A [`TransformStream`](/api/webstreams#transformstream) instance can be transferred using a [`MessagePort`](/api/worker_threads#messageport).
+A [`TransformStream`](/api/v19/webstreams#transformstream) instance can be transferred using a [`MessagePort`](/api/v19/worker_threads#messageport).
```js
const stream = new TransformStream();
@@ -948,14 +946,14 @@ port2.postMessage(stream, [stream]);
#### `TransformStreamDefaultController`
-
+
The `TransformStreamDefaultController` manages the internal state
of the `TransformStream`.
##### `transformStreamDefaultController.desiredSize`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -963,7 +961,7 @@ The amount of data required to fill the readable side's queue.
##### `transformStreamDefaultController.enqueue([chunk])`
-
+
* `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -971,7 +969,7 @@ Appends a chunk of data to the readable side's queue.
##### `transformStreamDefaultController.error([reason])`
-
+
* `reason` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -981,31 +979,31 @@ closed.
##### `transformStreamDefaultController.terminate()`
-
+
Closes the readable side of the transport and causes the writable side
to be abruptly closed with an error.
#### `ByteLengthQueuingStrategy`
-
+
##### `new ByteLengthQueuingStrategy(options)`
-
+
* `options` [`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)
##### `byteLengthQueuingStrategy.highWaterMark`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
##### `byteLengthQueuingStrategy.size`
-
+
* Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -1013,24 +1011,24 @@ to be abruptly closed with an error.
#### `CountQueuingStrategy`
-
+
##### `new CountQueuingStrategy(options)`
-
+
* `options` [`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)
##### `countQueuingStrategy.highWaterMark`
-
+
* Type: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
##### `countQueuingStrategy.size`
-
+
* Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
* `chunk` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
@@ -1038,17 +1036,17 @@ to be abruptly closed with an error.
#### `TextEncoderStream`
-
+
##### `new TextEncoderStream()`
-
+
Creates a new `TextEncoderStream` instance.
##### `textEncoderStream.encoding`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1056,23 +1054,23 @@ The encoding supported by the `TextEncoderStream` instance.
##### `textEncoderStream.readable`
-
+
-* Type: [`ReadableStream`](/api/webstreams#readablestream)
+* Type: [`ReadableStream`](/api/v19/webstreams#readablestream)
##### `textEncoderStream.writable`
-
+
-* Type: [`WritableStream`](/api/webstreams#writablestream)
+* Type: [`WritableStream`](/api/v19/webstreams#writablestream)
#### `TextDecoderStream`
-
+
##### `new TextDecoderStream([encoding[, options]])`
-
+
* `encoding` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) Identifies the `encoding` that this `TextDecoder` instance
supports. **Default:** `'utf-8'`.
@@ -1087,7 +1085,7 @@ Creates a new `TextDecoderStream` instance.
##### `textDecoderStream.encoding`
-
+
* Type: [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
@@ -1095,7 +1093,7 @@ The encoding supported by the `TextDecoderStream` instance.
##### `textDecoderStream.fatal`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1104,7 +1102,7 @@ thrown.
##### `textDecoderStream.ignoreBOM`
-
+
* Type: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -1113,70 +1111,70 @@ mark.
##### `textDecoderStream.readable`
-
+
-* Type: [`ReadableStream`](/api/webstreams#readablestream)
+* Type: [`ReadableStream`](/api/v19/webstreams#readablestream)
##### `textDecoderStream.writable`
-
+
-* Type: [`WritableStream`](/api/webstreams#writablestream)
+* Type: [`WritableStream`](/api/v19/webstreams#writablestream)
#### `CompressionStream`
-
+
##### `new CompressionStream(format)`
-
+
* `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) One of either `'deflate'` or `'gzip'`.
##### `compressionStream.readable`
-
+
-* Type: [`ReadableStream`](/api/webstreams#readablestream)
+* Type: [`ReadableStream`](/api/v19/webstreams#readablestream)
##### `compressionStream.writable`
-
+
-* Type: [`WritableStream`](/api/webstreams#writablestream)
+* Type: [`WritableStream`](/api/v19/webstreams#writablestream)
#### `DecompressionStream`
-
+
##### `new DecompressionStream(format)`
-
+
* `format` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) One of either `'deflate'` or `'gzip'`.
##### `decompressionStream.readable`
-
+
-* Type: [`ReadableStream`](/api/webstreams#readablestream)
+* Type: [`ReadableStream`](/api/v19/webstreams#readablestream)
##### `decompressionStream.writable`
-
+
-* Type: [`WritableStream`](/api/webstreams#writablestream)
+* Type: [`WritableStream`](/api/v19/webstreams#writablestream)
#### Utility Consumers
-
+
The utility consumer functions provide common options for consuming
streams.
They are accessed using:
-```mjs
+```mjs|cjs
import {
arrayBuffer,
blob,
@@ -1184,9 +1182,7 @@ import {
json,
text,
} from 'node:stream/consumers';
-```
-
-```cjs
+--------------
const {
arrayBuffer,
blob,
@@ -1198,13 +1194,13 @@ const {
##### `streamConsumers.arrayBuffer(stream)`
-
+
-* `stream` [`ReadableStream`](/api/webstreams#readablestream) | [`stream.Readable`](/api/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
+* `stream` [`ReadableStream`](/api/v19/webstreams#readablestream) | [`stream.Readable`](/api/v19/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
* 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';
@@ -1215,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}`);
@@ -1232,13 +1226,13 @@ arrayBuffer(readable).then((data) => {
##### `streamConsumers.blob(stream)`
-
+
-* `stream` [`ReadableStream`](/api/webstreams#readablestream) | [`stream.Readable`](/api/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`Blob`](/api/buffer#blob) containing the full contents
+* `stream` [`ReadableStream`](/api/v19/webstreams#readablestream) | [`stream.Readable`](/api/v19/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
+* 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!']);
@@ -1246,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!']);
@@ -1261,13 +1253,13 @@ blob(readable).then((data) => {
##### `streamConsumers.buffer(stream)`
-
+
-* `stream` [`ReadableStream`](/api/webstreams#readablestream) | [`stream.Readable`](/api/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
-* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) Fulfills with a [`Buffer`](/api/buffer#buffer) containing the full
+* `stream` [`ReadableStream`](/api/v19/webstreams#readablestream) | [`stream.Readable`](/api/v19/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
+* 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';
@@ -1277,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');
@@ -1294,41 +1284,39 @@ buffer(readable).then((data) => {
##### `streamConsumers.json(stream)`
-
+
-* `stream` [`ReadableStream`](/api/webstreams#readablestream) | [`stream.Readable`](/api/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
+* `stream` [`ReadableStream`](/api/v19/webstreams#readablestream) | [`stream.Readable`](/api/v19/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
* 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';
const items = Array.from(
{
- length: 100
+ length: 100,
},
() => ({
- message: 'hello world from consumers!'
- })
+ message: 'hello world from consumers!',
+ }),
);
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');
const items = Array.from(
{
- length: 100
+ length: 100,
},
() => ({
- message: 'hello world from consumers!'
- })
+ message: 'hello world from consumers!',
+ }),
);
const readable = Readable.from(JSON.stringify(items));
@@ -1339,22 +1327,20 @@ json(readable).then((data) => {
##### `streamConsumers.text(stream)`
-
+
-* `stream` [`ReadableStream`](/api/webstreams#readablestream) | [`stream.Readable`](/api/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
+* `stream` [`ReadableStream`](/api/v19/webstreams#readablestream) | [`stream.Readable`](/api/v19/stream#streamreadable) | [`AsyncIterator`](https://tc39.github.io/ecma262/#sec-asynciterator-interface)
* 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/v19/worker_threads.en.md b/content/api/v19/worker_threads.en.md
index a87a18b119..54c1f6f5c7 100644
--- a/content/api/v19/worker_threads.en.md
+++ b/content/api/v19/worker_threads.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
The `node:worker_threads` module enables the use of threads that execute
JavaScript in parallel. To access it:
@@ -28,14 +32,14 @@ instances.
```js
const {
- Worker, isMainThread, parentPort, workerData
+ Worker, isMainThread, parentPort, workerData,
} = require('node:worker_threads');
if (isMainThread) {
module.exports = function parseJSAsync(script) {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, {
- workerData: script
+ workerData: script,
});
worker.on('message', resolve);
worker.on('error', reject);
@@ -68,7 +72,7 @@ specifically `argv` and `execArgv` options.
### `worker.getEnvironmentData(key)`
-
+
* `key` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Any arbitrary, cloneable JavaScript value that can be used as a
[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) key.
@@ -97,7 +101,7 @@ if (isMainThread) {
### `worker.isMainThread`
-
+
* [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -117,7 +121,7 @@ if (isMainThread) {
### `worker.markAsUntransferable(object)`
-
+
Mark an object as not transferable. If `object` occurs in the transfer list of
a [`port.postMessage()`][] call, it is ignored.
@@ -153,14 +157,14 @@ There is no equivalent to this API in browsers.
### `worker.moveMessagePortToContext(port, contextifiedSandbox)`
-
+
-* `port` [`MessagePort`](/api/worker_threads#messageport) The message port to transfer.
+* `port` [`MessagePort`](/api/v19/worker_threads#messageport) The message port to transfer.
* `contextifiedSandbox` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) A [contextified][] object as returned by the
`vm.createContext()` method.
-* Returns: [`MessagePort`](/api/worker_threads#messageport)
+* Returns: [`MessagePort`](/api/v19/worker_threads#messageport)
Transfer a `MessagePort` to a different [`vm`][] Context. The original `port`
object is rendered unusable, and the returned `MessagePort` instance
@@ -177,9 +181,9 @@ events using it.
### `worker.parentPort`
-
+
-* [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`MessagePort`](/api/worker_threads#messageport)
+* [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`MessagePort`](/api/v19/worker_threads#messageport)
If this thread is a [`Worker`][], this is a [`MessagePort`][]
allowing communication with the parent thread. Messages sent using
@@ -207,9 +211,9 @@ if (isMainThread) {
### `worker.receiveMessageOnPort(port)`
-
+
-* `port` [`MessagePort`](/api/worker_threads#messageport) | [`BroadcastChannel`](/api/worker_threads#broadcastchannel-extends-eventtarget)
+* `port` [`MessagePort`](/api/v19/worker_threads#messageport) | [`BroadcastChannel`](/api/v19/worker_threads#broadcastchannel-extends-eventtarget)
* Returns: [`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)
@@ -234,7 +238,7 @@ When this function is used, no `'message'` event is emitted and the
### `worker.resourceLimits`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `maxYoungGenerationSizeMb` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -250,7 +254,7 @@ If this is used in the main thread, its value is an empty object.
### `worker.SHARE_ENV`
-
+
* [`symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type)
@@ -268,7 +272,7 @@ new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
### `worker.setEnvironmentData(key[, value])`
-
+
* `key` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Any arbitrary, cloneable JavaScript value that can be used as a
[`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) key.
@@ -282,7 +286,7 @@ instances spawned from the current context.
### `worker.threadId`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -292,7 +296,7 @@ This value is unique for each [`Worker`][] instance inside a single process.
### `worker.workerData`
-
+
An arbitrary JavaScript value that contains a clone of the data passed
to this thread's `Worker` constructor.
@@ -312,7 +316,7 @@ if (isMainThread) {
### `BroadcastChannel extends EventTarget`
-
+
Instances of `BroadcastChannel` allow asynchronous one-to-many communication
with all other `BroadcastChannel` instances bound to the same channel name.
@@ -323,7 +327,7 @@ with all other `BroadcastChannel` instances bound to the same channel name.
const {
isMainThread,
BroadcastChannel,
- Worker
+ Worker,
} = require('node:worker_threads');
const bc = new BroadcastChannel('hello');
@@ -344,40 +348,40 @@ if (isMainThread) {
#### `new BroadcastChannel(name)`
-
+
* `name` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The name of the channel to connect to. Any JavaScript value
that can be converted to a string using `` `$name` `` is permitted.
#### `broadcastChannel.close()`
-
+
Closes the `BroadcastChannel` connection.
#### `broadcastChannel.onmessage`
-
+
* Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked with a single `MessageEvent` argument
when a message is received.
#### `broadcastChannel.onmessageerror`
-
+
* Type: [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) Invoked with a received message cannot be
deserialized.
#### `broadcastChannel.postMessage(message)`
-
+
* `message` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) Any cloneable JavaScript value.
#### `broadcastChannel.ref()`
-
+
Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed
BroadcastChannel does _not_ let the program exit if it's the only active handle
@@ -386,7 +390,7 @@ has no effect.
#### `broadcastChannel.unref()`
-
+
Calling `unref()` on a BroadcastChannel allows the thread to exit if this
is the only active handle in the event system. If the BroadcastChannel is
@@ -394,7 +398,7 @@ already `unref()`ed calling `unref()` again has no effect.
### `MessageChannel`
-
+
Instances of the `worker.MessageChannel` class represent an asynchronous,
two-way communications channel.
@@ -413,9 +417,9 @@ port2.postMessage({ foo: 'bar' });
### `MessagePort`
-
+
-* Extends: [`EventTarget`](/api/events#eventtarget)
+* Extends: [`EventTarget`](/api/v19/events#eventtarget)
Instances of the `worker.MessagePort` class represent one end of an
asynchronous, two-way communications channel. It can be used to transfer
@@ -426,7 +430,7 @@ This implementation matches [browser `MessagePort`][]s.
#### `'close'`
-
+
The `'close'` event is emitted once either side of the channel has been
disconnected.
@@ -447,7 +451,7 @@ port1.close();
#### `'message'`
-
+
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The transmitted value
@@ -459,7 +463,7 @@ to `postMessage()` and no further arguments.
#### `'messageerror'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) An Error object
@@ -473,7 +477,7 @@ unavailable).
#### `port.close()`
-
+
Disables further sending of messages on either side of the connection.
This method can be called when no further communication will happen over this
@@ -484,7 +488,7 @@ are part of the channel.
#### `port.postMessage(value[, transferList])`
-
+
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
* `transferList` Object\[]
@@ -502,14 +506,14 @@ In particular, the significant differences to `JSON` are:
and `SharedArrayBuffer`s.
* `value` may contain [`WebAssembly.Module`][] instances.
* `value` may not contain native (C++-backed) objects other than:
- * [`CryptoKey`](/api/webcrypto#cryptokey)s,
- * [`FileHandle`](/api/fs#filehandle)s,
- * [`Histogram`](/api/perf_hooks#histogram)s,
- * [`KeyObject`](/api/crypto#keyobject)s,
- * [`MessagePort`](/api/worker_threads#messageport)s,
- * [`net.BlockList`](/api/net#netblocklist)s,
- * [`net.SocketAddress`](/api/net#netsocketaddress)es,
- * [`X509Certificate`](/api/crypto#x509certificate)s.
+ * [`CryptoKey`](/api/v19/webcrypto#cryptokey)s,
+ * [`FileHandle`](/api/v19/fs#filehandle)s,
+ * [`Histogram`](/api/v19/perf_hooks#histogram)s,
+ * [`KeyObject`](/api/v19/crypto#keyobject)s,
+ * [`MessagePort`](/api/v19/worker_threads#messageport)s,
+ * [`net.BlockList`](/api/v19/net#netblocklist)s,
+ * [`net.SocketAddress`](/api/v19/net#netsocketaddress)es,
+ * [`X509Certificate`](/api/v19/crypto#x509certificate)s.
```js
const { MessageChannel } = require('node:worker_threads');
@@ -659,9 +663,13 @@ port2.postMessage(new URL('https://example.org'));
#### `port.hasRef()`
-
+
+
+
-
+Experimental
+
+
* Returns: [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
@@ -669,7 +677,7 @@ If true, the `MessagePort` object will keep the Node.js event loop active.
#### `port.ref()`
-
+
Opposite of `unref()`. Calling `ref()` on a previously `unref()`ed port does
_not_ let the program exit if it's the only active handle left (the default
@@ -681,7 +689,7 @@ listeners for the event exist.
#### `port.start()`
-
+
Starts receiving messages on this `MessagePort`. When using this port
as an event emitter, this is called automatically once `'message'`
@@ -695,7 +703,7 @@ until a new handler is set or the port is discarded.
#### `port.unref()`
-
+
Calling `unref()` on a port allows the thread to exit if this is the only
active handle in the event system. If the port is already `unref()`ed calling
@@ -707,9 +715,9 @@ listeners for the event exist.
### `Worker`
-
+
-* Extends: [`EventEmitter`](/api/events#eventemitter)
+* Extends: [`EventEmitter`](/api/v19/events#eventemitter)
The `Worker` class represents an independent JavaScript execution thread.
Most Node.js APIs are available inside of it.
@@ -761,7 +769,7 @@ the thread barrier.
```js
const assert = require('node:assert');
const {
- Worker, MessageChannel, MessagePort, isMainThread, parentPort
+ Worker, MessageChannel, MessagePort, isMainThread, parentPort,
} = require('node:worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
@@ -781,9 +789,9 @@ if (isMainThread) {
#### `new Worker(filename[, options])`
-
+
-* `filename` [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | [`URL`](/api/url#the-whatwg-url-api) The path to the Worker's main script or module. Must
+* `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
current working directory) starting with `./` or `../`, or a WHATWG `URL`
object using `file:` or `data:` protocol.
@@ -846,10 +854,13 @@ 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'`
-
+
* `err` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
@@ -858,7 +869,7 @@ exception. In that case, the worker is terminated.
#### `'exit'`
-
+
* `exitCode` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -871,7 +882,7 @@ This is the final event emitted by any `Worker` instance.
#### `'message'`
-
+
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types) The transmitted value
@@ -884,7 +895,7 @@ All messages sent from the worker thread are emitted before the
#### `'messageerror'`
-
+
* `error` [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) An Error object
@@ -892,14 +903,14 @@ The `'messageerror'` event is emitted when deserializing a message failed.
#### `'online'`
-
+
The `'online'` event is emitted when the worker thread has started executing
JavaScript code.
#### `worker.getHeapSnapshot([options])`
-
+
* `options` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `exposeInternals` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) If true, expose internals in the heap snapshot.
@@ -918,14 +929,14 @@ immediately with an [`ERR_WORKER_NOT_RUNNING`][] error.
#### `worker.performance`
-
+
An object that can be used to query performance information from a worker
instance. Similar to [`perf_hooks.performance`][].
##### `performance.eventLoopUtilization([utilization1[, utilization2]])`
-
+
* `utilization1` [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) The result of a previous call to
`eventLoopUtilization()`.
@@ -975,7 +986,7 @@ event][], then all properties have the value of `0`.
#### `worker.postMessage(value[, transferList])`
-
+
* `value` [`any`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types)
* `transferList` Object\[]
@@ -986,7 +997,7 @@ See [`port.postMessage()`][] for more details.
#### `worker.ref()`
-
+
Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does
_not_ let the program exit if it's the only active handle left (the default
@@ -995,7 +1006,7 @@ no effect.
#### `worker.resourceLimits`
-
+
* [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
* `maxYoungGenerationSizeMb` [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1011,9 +1022,9 @@ If the worker has stopped, the return value is an empty object.
#### `worker.stderr`
-
+
-* [`stream.Readable`](/api/stream#streamreadable)
+* [`stream.Readable`](/api/v19/stream#streamreadable)
This is a readable stream which contains data written to [`process.stderr`][]
inside the worker thread. If `stderr: true` was not passed to the
@@ -1022,9 +1033,9 @@ inside the worker thread. If `stderr: true` was not passed to the
#### `worker.stdin`
-
+
-* [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`stream.Writable`](/api/stream#streamwritable)
+* [`null`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type) | [`stream.Writable`](/api/v19/stream#streamwritable)
If `stdin: true` was passed to the [`Worker`][] constructor, this is a
writable stream. The data written to this stream will be made available in
@@ -1032,9 +1043,9 @@ the worker thread as [`process.stdin`][].
#### `worker.stdout`
-
+
-* [`stream.Readable`](/api/stream#streamreadable)
+* [`stream.Readable`](/api/v19/stream#streamreadable)
This is a readable stream which contains data written to [`process.stdout`][]
inside the worker thread. If `stdout: true` was not passed to the
@@ -1043,7 +1054,7 @@ inside the worker thread. If `stdout: true` was not passed to the
#### `worker.terminate()`
-
+
* Returns: [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
@@ -1053,7 +1064,7 @@ Returns a Promise for the exit code that is fulfilled when the
#### `worker.threadId`
-
+
* [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -1063,7 +1074,7 @@ This value is unique for each `Worker` instance inside a single process.
#### `worker.unref()`
-
+
Calling `unref()` on a worker allows the thread to exit if this is the only
active handle in the event system. If the worker is already `unref()`ed calling
@@ -1073,12 +1084,12 @@ active handle in the event system. If the worker is already `unref()`ed calling
#### Synchronous blocking of stdio
-`Worker`s utilize message passing via [`MessagePort`](/api/worker_threads#messageport) to implement interactions
+`Worker`s utilize message passing via [`MessagePort`](/api/v19/worker_threads#messageport) to implement interactions
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,
@@ -1093,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 204f1d9b61..87dd25460e 100644
--- a/content/api/v19/zlib.en.md
+++ b/content/api/v19/zlib.en.md
@@ -5,11 +5,15 @@ category: 'api'
version: 'v19'
---
-
+
-
+
-
+Stable
+
+
+
+
The `node:zlib` module provides compression functionality implemented using
Gzip, Deflate/Inflate, and Brotli.
@@ -31,7 +35,7 @@ const { createGzip } = require('node:zlib');
const { pipeline } = require('node:stream');
const {
createReadStream,
- createWriteStream
+ createWriteStream,
} = require('node:fs');
const gzip = createGzip();
@@ -143,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');
@@ -180,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.
@@ -261,7 +263,7 @@ decompressed result is valid.
### Memory usage tuning
-
+
#### For zlib-based streams
@@ -359,9 +361,9 @@ http.createServer((request, response) => {
### Constants
-
+
-
+
#### zlib constants
@@ -416,7 +418,7 @@ Compression strategy.
#### Brotli constants
-
+
There are several options and other constants available for Brotli-based
streams:
@@ -486,9 +488,9 @@ These advanced options are available for controlling decompression:
### `Options`
-
+
-
+
Each zlib-based class takes an `options` object. No options are required.
@@ -502,7 +504,7 @@ ignored by the decompression classes.
* `level` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) (compression only)
* `memLevel` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) (compression only)
* `strategy` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) (compression only)
-* `dictionary` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) (deflate/inflate only,
+* `dictionary` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) (deflate/inflate only,
empty dictionary by default)
* `info` [`boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) (If `true`, returns an object with `buffer` and `engine`.)
* `maxOutputLength` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) Limits output size when using
@@ -513,9 +515,9 @@ information.
### `BrotliOptions`
-
+
-
+
Each Brotli-based class takes an `options` object. All options are optional.
@@ -534,69 +536,69 @@ const stream = zlib.createBrotliCompress({
params: {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
[zlib.constants.BROTLI_PARAM_QUALITY]: 4,
- [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size
- }
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size,
+ },
});
```
### `zlib.BrotliCompress`
-
+
Compress data using the Brotli algorithm.
### `zlib.BrotliDecompress`
-
+
Decompress data using the Brotli algorithm.
### `zlib.Deflate`
-
+
Compress data using deflate.
### `zlib.DeflateRaw`
-
+
Compress data using deflate, and do not append a `zlib` header.
### `zlib.Gunzip`
-
+
Decompress a gzip stream.
### `zlib.Gzip`
-
+
Compress data using gzip.
### `zlib.Inflate`
-
+
Decompress a deflate stream.
### `zlib.InflateRaw`
-
+
Decompress a raw deflate stream.
### `zlib.Unzip`
-
+
Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
the header.
### `zlib.ZlibBase`
-
+
Not exported by the `node:zlib` module. It is documented here because it is the
base class of the compressor/decompressor classes.
@@ -606,9 +608,13 @@ be used in pipes and similar stream operations.
#### `zlib.bytesRead`
-
+
+
+
+
+Deprecated: Use [`zlib.bytesWritten`][] instead.
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -619,7 +625,7 @@ expose values under these names.
#### `zlib.bytesWritten`
-
+
* [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -629,7 +635,7 @@ as appropriate for the derived class).
#### `zlib.close([callback])`
-
+
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
@@ -637,7 +643,7 @@ Close the underlying handle.
#### `zlib.flush([kind, ]callback)`
-
+
* `kind` **Default:** `zlib.constants.Z_FULL_FLUSH` for zlib-based streams,
`zlib.constants.BROTLI_OPERATION_FLUSH` for Brotli-based streams.
@@ -653,7 +659,7 @@ writes and will only produce output when data is being read from the stream.
#### `zlib.params(level, strategy, callback)`
-
+
* `level` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
* `strategy` [`integer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
@@ -666,46 +672,46 @@ Only applicable to deflate algorithm.
#### `zlib.reset()`
-
+
Reset the compressor/decompressor to factory defaults. Only applicable to
the inflate and deflate algorithms.
### `zlib.constants`
-
+
Provides an object enumerating Zlib-related constants.
### `zlib.createBrotliCompress([options])`
-
+
-* `options` [`brotli options`](/api/zlib#brotlioptions)
+* `options` [`brotli options`](/api/v19/zlib#brotlioptions)
Creates and returns a new [`BrotliCompress`][] object.
### `zlib.createBrotliDecompress([options])`
-
+
-* `options` [`brotli options`](/api/zlib#brotlioptions)
+* `options` [`brotli options`](/api/v19/zlib#brotlioptions)
Creates and returns a new [`BrotliDecompress`][] object.
### `zlib.createDeflate([options])`
-
+
-* `options` [`zlib options`](/api/zlib#options)
+* `options` [`zlib options`](/api/v19/zlib#options)
Creates and returns a new [`Deflate`][] object.
### `zlib.createDeflateRaw([options])`
-
+
-* `options` [`zlib options`](/api/zlib#options)
+* `options` [`zlib options`](/api/v19/zlib#options)
Creates and returns a new [`DeflateRaw`][] object.
@@ -718,48 +724,48 @@ that effectively uses an 8-bit window only.
### `zlib.createGunzip([options])`
-
+
-* `options` [`zlib options`](/api/zlib#options)
+* `options` [`zlib options`](/api/v19/zlib#options)
Creates and returns a new [`Gunzip`][] object.
### `zlib.createGzip([options])`
-
+
-* `options` [`zlib options`](/api/zlib#options)
+* `options` [`zlib options`](/api/v19/zlib#options)
Creates and returns a new [`Gzip`][] object.
See [example][zlib.createGzip example].
### `zlib.createInflate([options])`
-
+
-* `options` [`zlib options`](/api/zlib#options)
+* `options` [`zlib options`](/api/v19/zlib#options)
Creates and returns a new [`Inflate`][] object.
### `zlib.createInflateRaw([options])`
-
+
-* `options` [`zlib options`](/api/zlib#options)
+* `options` [`zlib options`](/api/v19/zlib#options)
Creates and returns a new [`InflateRaw`][] object.
### `zlib.createUnzip([options])`
-
+
-* `options` [`zlib options`](/api/zlib#options)
+* `options` [`zlib options`](/api/v19/zlib#options)
Creates and returns a new [`Unzip`][] object.
### Convenience methods
-
+
All of these take a [`Buffer`][], [`TypedArray`][], [`DataView`][],
[`ArrayBuffer`][] or string as the first argument, an optional second argument
@@ -771,154 +777,154 @@ without a callback.
#### `zlib.brotliCompress(buffer[, options], callback)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`brotli options`](/api/zlib#brotlioptions)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`brotli options`](/api/v19/zlib#brotlioptions)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
#### `zlib.brotliCompressSync(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`brotli options`](/api/zlib#brotlioptions)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`brotli options`](/api/v19/zlib#brotlioptions)
Compress a chunk of data with [`BrotliCompress`][].
#### `zlib.brotliDecompress(buffer[, options], callback)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`brotli options`](/api/zlib#brotlioptions)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`brotli options`](/api/v19/zlib#brotlioptions)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
#### `zlib.brotliDecompressSync(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`brotli options`](/api/zlib#brotlioptions)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`brotli options`](/api/v19/zlib#brotlioptions)
Decompress a chunk of data with [`BrotliDecompress`][].
#### `zlib.deflate(buffer[, options], callback)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
#### `zlib.deflateSync(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
Compress a chunk of data with [`Deflate`][].
#### `zlib.deflateRaw(buffer[, options], callback)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
#### `zlib.deflateRawSync(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
Compress a chunk of data with [`DeflateRaw`][].
#### `zlib.gunzip(buffer[, options], callback)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
#### `zlib.gunzipSync(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
Decompress a chunk of data with [`Gunzip`][].
#### `zlib.gzip(buffer[, options], callback)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
#### `zlib.gzipSync(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
Compress a chunk of data with [`Gzip`][].
#### `zlib.inflate(buffer[, options], callback)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
#### `zlib.inflateSync(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
Decompress a chunk of data with [`Inflate`][].
#### `zlib.inflateRaw(buffer[, options], callback)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
#### `zlib.inflateRawSync(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
Decompress a chunk of data with [`InflateRaw`][].
#### `zlib.unzip(buffer[, options], callback)`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
* `callback` [`Function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
#### `zlib.unzipSync(buffer[, options])`
-
+
-* `buffer` [`Buffer`](/api/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
-* `options` [`zlib options`](/api/zlib#options)
+* `buffer` [`Buffer`](/api/v19/buffer#buffer) | [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) | [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) | [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | [`string`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
+* `options` [`zlib options`](/api/v19/zlib#options)
Decompress a chunk of data with [`Unzip`][].
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