From 621266afc7530854ab61012b7380b2408fa945a4 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 10 Oct 2021 21:55:04 -0700 Subject: [PATCH] doc: format doc/api/*.md with markdown formatter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/40403 Backport-PR-URL: https://github.com/nodejs/node/pull/40530 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Zijian Liu Reviewed-By: Michaël Zasso Reviewed-By: Antoine du Hamel --- doc/api/addons.md | 1 + doc/api/assert.md | 26 ++ doc/api/async_context.md | 13 + doc/api/async_hooks.md | 14 +- doc/api/buffer.md | 172 ++++++++--- doc/api/child_process.md | 64 ++-- doc/api/cli.md | 146 ++++++++- doc/api/cluster.md | 39 ++- doc/api/console.md | 36 ++- doc/api/crypto.md | 186 +++++++++++- doc/api/debugger.md | 1 + doc/api/deprecations.md | 163 +++++++++- doc/api/dgram.md | 45 ++- doc/api/dns.md | 161 ++++++---- doc/api/documentation.md | 2 + doc/api/domain.md | 1 + doc/api/embedding.md | 1 + doc/api/errors.md | 445 ++++++++++++++++++++++++++-- doc/api/esm.md | 380 ++++++++++++------------ doc/api/events.md | 116 ++++++-- doc/api/fs.md | 281 +++++++++++++++--- doc/api/globals.md | 31 ++ doc/api/http.md | 196 ++++++++++-- doc/api/http2.md | 219 ++++++++++++-- doc/api/https.md | 16 + doc/api/index.md | 14 +- doc/api/inspector.md | 12 +- doc/api/intl.md | 4 +- doc/api/module.md | 15 +- doc/api/modules.md | 47 ++- doc/api/n-api.md | 606 ++++++++++++++++++++++++-------------- doc/api/net.md | 101 ++++++- doc/api/os.md | 29 +- doc/api/packages.md | 105 ++++--- doc/api/path.md | 15 + doc/api/perf_hooks.md | 69 ++++- doc/api/process.md | 162 +++++++--- doc/api/punycode.md | 11 +- doc/api/querystring.md | 11 +- doc/api/readline.md | 49 ++- doc/api/repl.md | 50 ++-- doc/api/report.md | 1 + doc/api/stream.md | 163 +++++++--- doc/api/string_decoder.md | 9 +- doc/api/synopsis.md | 3 +- doc/api/timers.md | 25 +- doc/api/tls.md | 202 +++++++++---- doc/api/tracing.md | 18 +- doc/api/tty.md | 26 +- doc/api/url.md | 58 ++-- doc/api/util.md | 170 ++++++++--- doc/api/v8.md | 24 +- doc/api/vm.md | 59 ++-- doc/api/wasi.md | 5 + doc/api/webcrypto.md | 322 ++++++++++++++------ doc/api/webstreams.md | 102 ++++++- doc/api/worker_threads.md | 73 ++++- doc/api/zlib.md | 55 +++- 58 files changed, 4225 insertions(+), 1145 deletions(-) diff --git a/doc/api/addons.md b/doc/api/addons.md index a906306b2cd1bc..3635d5bd54d8fb 100644 --- a/doc/api/addons.md +++ b/doc/api/addons.md @@ -235,6 +235,7 @@ NODE_MODULE_INIT(/* exports, module, context */) { ``` #### Worker support + @@ -216,6 +218,7 @@ try { ``` ## Class: `assert.CallTracker` + @@ -453,6 +461,7 @@ added: v0.5.9 An alias of [`assert.ok()`][]. ## `assert.deepEqual(actual, expected[, message])` + @@ -999,6 +1011,7 @@ assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) ``` ## `assert.doesNotThrow(fn[, error][, message])` + @@ -1223,6 +1238,7 @@ Using `assert.fail()` with more than two arguments is possible but deprecated. See below for further details. ## `assert.fail(actual, expected[, message[, operator[, stackStartFn]]])` + @@ -1974,6 +1998,7 @@ example in [`assert.throws()`][] carefully if using a string as the second argument gets considered. ## `assert.strictEqual(actual, expected[, message])` + ## Introduction + These classes are used to associate state and propagate it throughout callbacks and promise chains. They allow storing data throughout the lifetime of a web request @@ -25,6 +26,7 @@ const async_hooks = require('async_hooks'); ``` ## Class: `AsyncLocalStorage` + @@ -507,6 +519,7 @@ never be called. `AsyncResource` constructor. + ### Using `AsyncResource` for a `Worker` thread pool The following example shows how to use the `AsyncResource` class to properly diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md index 132f2a6bb2e910..c3170f8162f49b 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -190,7 +190,7 @@ const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); Because promises are asynchronous resources whose lifecycle is tracked via the async hooks mechanism, the `init()`, `before()`, `after()`, and -`destroy()` callbacks *must not* be async functions that return promises. +`destroy()` callbacks _must not_ be async functions that return promises. ### Error handling @@ -350,8 +350,8 @@ listening to the hooks. `triggerAsyncId` is the `asyncId` of the resource that caused (or "triggered") the new resource to initialize and that caused `init` to call. This is different -from `async_hooks.executionAsyncId()` that only shows *when* a resource was -created, while `triggerAsyncId` shows *why* a resource was created. +from `async_hooks.executionAsyncId()` that only shows _when_ a resource was +created, while `triggerAsyncId` shows _why_ a resource was created. The following is a simple demonstration of `triggerAsyncId`: @@ -499,13 +499,13 @@ TickObject(6) The `TCPSERVERWRAP` is not part of this graph, even though it was the reason for `console.log()` being called. This is because binding to a port without a host -name is a *synchronous* operation, but to maintain a completely asynchronous +name is a _synchronous_ operation, but to maintain a completely asynchronous API the user's callback is placed in a `process.nextTick()`. Which is why `TickObject` is present in the output and is a 'parent' for `.listen()` callback. -The graph only shows *when* a resource was created, not *why*, so to track -the *why* use `triggerAsyncId`. Which can be represented with the following +The graph only shows _when_ a resource was created, not _why_, so to track +the _why_ use `triggerAsyncId`. Which can be represented with the following graph: ```console @@ -545,7 +545,7 @@ it only once. Called immediately after the callback specified in `before` is completed. If an uncaught exception occurs during execution of the callback, then `after` -will run *after* the `'uncaughtException'` event is emitted or a `domain`'s +will run _after_ the `'uncaughtException'` event is emitted or a `domain`'s handler runs. #### `destroy(asyncId)` diff --git a/doc/api/buffer.md b/doc/api/buffer.md index c6f403a60b78a4..af34991256cf01 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -83,6 +83,7 @@ const buf7 = Buffer.from('tést', 'latin1'); ``` ## Buffers and character encodings + @@ -457,6 +460,7 @@ A [`Blob`][] encapsulates immutable, raw data that can be safely shared across multiple worker threads. ### `new buffer.Blob([sources[, options]])` + -* `sources` {string[]|ArrayBuffer[]|TypedArray[]|DataView[]|Blob[]} An array - of string, {ArrayBuffer}, {TypedArray}, {DataView}, or {Blob} objects, or - any mix of such objects, that will be stored within the `Blob`. +* `sources` {string\[]|ArrayBuffer\[]|TypedArray\[]|DataView\[]|Blob\[]} An + array of string, {ArrayBuffer}, {TypedArray}, {DataView}, or {Blob} objects, + or any mix of such objects, that will be stored within the `Blob`. * `options` {Object} * `endings` {string} One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be converted to @@ -487,6 +491,7 @@ Unmatched surrogate pairs within each string part will be replaced by Unicode U+FFFD replacement characters. ### `blob.arrayBuffer()` + @@ -497,6 +502,7 @@ Returns a promise that fulfills with an {ArrayBuffer} containing a copy of the `Blob` data. ### `blob.size` + @@ -504,6 +510,7 @@ added: v15.7.0 The total size of the `Blob` in bytes. ### `blob.slice([start, [end, [type]]])` + @@ -516,6 +523,7 @@ Creates and returns a new `Blob` containing a subset of this `Blob` objects data. The original `Blob` is not altered. ### `blob.stream()` + @@ -525,6 +533,7 @@ added: v16.7.0 Returns a new `ReadableStream` that allows the content of the `Blob` to be read. ### `blob.text()` + @@ -535,6 +544,7 @@ Returns a promise that fulfills with the contents of the `Blob` decoded as a UTF-8 string. ### `blob.type` + @@ -610,6 +620,7 @@ The `Buffer` class is a global type for dealing with binary data directly. It can be constructed in a variety of ways. ### Static method: `Buffer.alloc(size[, fill[, encoding]])` + -* `list` {Buffer[] | Uint8Array[]} List of `Buffer` or [`Uint8Array`][] +* `list` {Buffer\[] | Uint8Array\[]} List of `Buffer` or [`Uint8Array`][] instances to concatenate. * `totalLength` {integer} Total length of the `Buffer` instances in `list` when concatenated. @@ -1023,11 +1039,12 @@ console.log(bufA.length); [`Buffer.allocUnsafe()`][] does. ### Static method: `Buffer.from(array)` + -* `array` {integer[]} +* `array` {integer\[]} Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. Array entries outside that range will be truncated to fit into it. @@ -1053,6 +1070,7 @@ appropriate for `Buffer.from()` variants. `Buffer` pool like [`Buffer.allocUnsafe()`][] does. ### Static method: `Buffer.from(arrayBuffer[, byteOffset[, length]])` + @@ -1168,6 +1186,7 @@ console.log(buf); ``` ### Static method: `Buffer.from(buffer)` + @@ -1209,6 +1228,7 @@ A `TypeError` will be thrown if `buffer` is not a `Buffer` or another type appropriate for `Buffer.from()` variants. ### Static method: `Buffer.from(object[, offsetOrEncoding[, length]])` + @@ -1267,6 +1287,7 @@ A `TypeError` will be thrown if `object` does not have the mentioned methods or is not of another type appropriate for `Buffer.from()` variants. ### Static method: `Buffer.from(string[, encoding])` + @@ -1309,6 +1330,7 @@ A `TypeError` will be thrown if `string` is not a string or another type appropriate for `Buffer.from()` variants. ### Static method: `Buffer.isBuffer(obj)` + @@ -1339,6 +1361,7 @@ Buffer.isBuffer(new Uint8Array(1024)); // false ``` ### Static method: `Buffer.isEncoding(encoding)` + @@ -1382,6 +1405,7 @@ console.log(Buffer.isEncoding('')); ``` ### Class property: `Buffer.poolSize` + @@ -1509,6 +1533,7 @@ new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length); ``` ### `buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])` + @@ -1721,6 +1747,7 @@ console.log(buf.toString()); ``` ### `buf.entries()` + @@ -1769,6 +1796,7 @@ for (const pair of buf.entries()) { ``` ### `buf.equals(otherBuffer)` + @@ -1979,6 +2009,7 @@ console.log(buf.includes('this', 4)); ``` ### `buf.indexOf(value[, byteOffset][, encoding])` + @@ -2155,6 +2187,7 @@ for (const key of buf.keys()) { ``` ### `buf.lastIndexOf(value[, byteOffset][, encoding])` + @@ -2326,6 +2360,7 @@ console.log(buf.length); ``` ### `buf.parent` + @@ -2335,6 +2370,7 @@ deprecated: v8.0.0 The `buf.parent` property is a deprecated alias for `buf.buffer`. ### `buf.readBigInt64BE([offset])` + @@ -3309,6 +3367,7 @@ console.log(buf.subarray(-5, -2).toString()); ``` ### `buf.slice([start[, end]])` + @@ -3374,7 +3434,7 @@ added: v5.10.0 * Returns: {Buffer} A reference to `buf`. Interprets `buf` as an array of unsigned 16-bit integers and swaps the -byte order *in-place*. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] +byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 2. ```mjs @@ -3433,6 +3493,7 @@ buf.swap16(); // Convert to big-endian UTF-16 text. ``` ### `buf.swap32()` + @@ -3440,7 +3501,7 @@ added: v5.10.0 * Returns: {Buffer} A reference to `buf`. Interprets `buf` as an array of unsigned 32-bit integers and swaps the -byte order *in-place*. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] +byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 4. ```mjs @@ -3482,13 +3543,14 @@ buf2.swap32(); ``` ### `buf.swap64()` + * Returns: {Buffer} A reference to `buf`. -Interprets `buf` as an array of 64-bit numbers and swaps byte order *in-place*. +Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. Throws [`ERR_INVALID_BUFFER_SIZE`][] if [`buf.length`][] is not a multiple of 8. ```mjs @@ -3530,6 +3592,7 @@ buf2.swap64(); ``` ### `buf.toJSON()` + @@ -3581,6 +3644,7 @@ console.log(copy); ``` ### `buf.toString([encoding[, start[, end]]])` + @@ -3651,6 +3715,7 @@ console.log(buf2.toString(undefined, 0, 3)); ``` ### `buf.values()` + @@ -3717,6 +3782,7 @@ for (const value of buf) { ``` ### `buf.write(string[, offset[, length]][, encoding])` + @@ -3771,6 +3837,7 @@ console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); ``` ### `buf.writeBigInt64BE(value[, offset])` + @@ -4907,6 +5001,7 @@ and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** ### `buffer.btoa(data)` + @@ -4928,6 +5023,7 @@ and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** ### `buffer.INSPECT_MAX_BYTES` + @@ -4939,6 +5035,7 @@ Returns the maximum number of bytes that will be returned when [`util.inspect()`][] for more details on `buf.inspect()` behavior. ### `buffer.kMaxLength` + @@ -4948,6 +5045,7 @@ added: v3.0.0 An alias for [`buffer.constants.MAX_LENGTH`][]. ### `buffer.kStringMaxLength` + @@ -4957,6 +5055,7 @@ added: v3.0.0 An alias for [`buffer.constants.MAX_STRING_LENGTH`][]. ### `buffer.resolveObjectURL(id)` + @@ -4971,6 +5070,7 @@ Resolves a `'blob:nodedata:...'` an associated {Blob} object registered using a prior call to `URL.createObjectURL()`. ### `buffer.transcode(source, fromEnc, toEnc)` + @@ -5027,6 +5128,7 @@ the constructor always returned a `Buffer` instance, rather than a `SlowBuffer` instance. #### `new SlowBuffer(size)` + @@ -5038,11 +5140,13 @@ deprecated: v6.0.0 See [`Buffer.allocUnsafeSlow()`][]. ### Buffer constants + #### `buffer.constants.MAX_LENGTH` + @@ -5087,11 +5192,11 @@ differently based on what arguments are provided: * Passing a number as the first argument to `Buffer()` (e.g. `new Buffer(10)`) allocates a new `Buffer` object of the specified size. Prior to Node.js 8.0.0, - the memory allocated for such `Buffer` instances is *not* initialized and - *can contain sensitive data*. Such `Buffer` instances *must* be subsequently + the memory allocated for such `Buffer` instances is _not_ initialized and + _can contain sensitive data_. Such `Buffer` instances _must_ be subsequently initialized by using either [`buf.fill(0)`][`buf.fill()`] or by writing to the entire `Buffer` before reading data from the `Buffer`. - While this behavior is *intentional* to improve performance, + While this behavior is _intentional_ to improve performance, development experience has demonstrated that a more explicit distinction is required between creating a fast-but-uninitialized `Buffer` versus creating a slower-but-safer `Buffer`. Since Node.js 8.0.0, `Buffer(num)` and `new @@ -5125,18 +5230,18 @@ the various forms of the `new Buffer()` constructor have been **deprecated** and replaced by separate `Buffer.from()`, [`Buffer.alloc()`][], and [`Buffer.allocUnsafe()`][] methods. -*Developers should migrate all existing uses of the `new Buffer()` constructors -to one of these new APIs.* +_Developers should migrate all existing uses of the `new Buffer()` constructors +to one of these new APIs._ -* [`Buffer.from(array)`][] returns a new `Buffer` that *contains a copy* of the +* [`Buffer.from(array)`][] returns a new `Buffer` that _contains a copy_ of the provided octets. * [`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`] - returns a new `Buffer` that *shares the same allocated memory* as the given + returns a new `Buffer` that _shares the same allocated memory_ as the given [`ArrayBuffer`][]. -* [`Buffer.from(buffer)`][] returns a new `Buffer` that *contains a copy* of the +* [`Buffer.from(buffer)`][] returns a new `Buffer` that _contains a copy_ of the contents of the given `Buffer`. * [`Buffer.from(string[, encoding])`][`Buffer.from(string)`] returns a new - `Buffer` that *contains a copy* of the provided string. + `Buffer` that _contains a copy_ of the provided string. * [`Buffer.alloc(size[, fill[, encoding]])`][`Buffer.alloc()`] returns a new initialized `Buffer` of the specified size. This method is slower than [`Buffer.allocUnsafe(size)`][`Buffer.allocUnsafe()`] but guarantees that newly @@ -5149,12 +5254,13 @@ to one of these new APIs.* potentially sensitive. `Buffer` instances returned by [`Buffer.allocUnsafe()`][] and -[`Buffer.from(array)`][] *may* be allocated off a shared internal memory pool +[`Buffer.from(array)`][] _may_ be allocated off a shared internal memory pool if `size` is less than or equal to half [`Buffer.poolSize`][]. Instances -returned by [`Buffer.allocUnsafeSlow()`][] *never* use the shared internal +returned by [`Buffer.allocUnsafeSlow()`][] _never_ use the shared internal memory pool. ### The `--zero-fill-buffers` command-line option + @@ -5176,14 +5282,14 @@ $ node --zero-fill-buffers ### What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` "unsafe"? When calling [`Buffer.allocUnsafe()`][] and [`Buffer.allocUnsafeSlow()`][], the -segment of allocated memory is *uninitialized* (it is not zeroed-out). While +segment of allocated memory is _uninitialized_ (it is not zeroed-out). While this design makes the allocation of memory quite fast, the allocated segment of memory might contain old data that is potentially sensitive. Using a `Buffer` -created by [`Buffer.allocUnsafe()`][] without *completely* overwriting the +created by [`Buffer.allocUnsafe()`][] without _completely_ overwriting the memory can allow this old data to be leaked when the `Buffer` memory is read. While there are clear performance advantages to using -[`Buffer.allocUnsafe()`][], extra care *must* be taken in order to avoid +[`Buffer.allocUnsafe()`][], extra care _must_ be taken in order to avoid introducing security vulnerabilities into an application. [ASCII]: https://en.wikipedia.org/wiki/ASCII diff --git a/doc/api/child_process.md b/doc/api/child_process.md index 4170bbb5296ae0..9674590d057c2c 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -143,6 +143,7 @@ exec('"my script.cmd" a b', (err, stdout, stderr) => { ``` ### `child_process.exec(command[, options][, callback])` + * `file` {string} The name or path of the executable file to run. -* `args` {string[]} List of string arguments. +* `args` {string\[]} List of string arguments. * `options` {Object} * `cwd` {string|URL} Current working directory of the child process. * `env` {Object} Environment key-value pairs. **Default:** `process.env`. @@ -379,6 +381,7 @@ controller.abort(); ``` ### `child_process.fork(modulePath[, args][, options])` + * `modulePath` {string} The module to run in the child. -* `args` {string[]} List of string arguments. +* `args` {string\[]} List of string arguments. * `options` {Object} * `cwd` {string|URL} Current working directory of the child process. * `detached` {boolean} Prepare child to run independently of its parent @@ -417,7 +420,7 @@ changes: [`options.detached`][]). * `env` {Object} Environment key-value pairs. **Default:** `process.env`. * `execPath` {string} Executable used to create the child process. - * `execArgv` {string[]} List of string arguments passed to the executable. + * `execArgv` {string\[]} List of string arguments passed to the executable. **Default:** `process.execArgv`. * `gid` {number} Sets the group identity of the process (see setgid(2)). * `serialization` {string} Specify the kind of serialization used for sending @@ -492,6 +495,7 @@ if (process.argv[2] === 'child') { ``` ### `child_process.spawn(command[, args][, options])` + * `command` {string} The command to run. -* `args` {string[]} List of string arguments. +* `args` {string\[]} List of string arguments. * `options` {Object} * `cwd` {string|URL} Current working directory of the child process. * `env` {Object} Environment key-value pairs. **Default:** `process.env`. @@ -556,7 +560,6 @@ changes: is allowed to run. **Default:** `undefined`. * `killSignal` {string|integer} The signal value to be used when the spawned process will be killed by timeout or abort signal. **Default:** `'SIGTERM'`. - * Returns: {ChildProcess} The `child_process.spawn()` method spawns a new process using the given @@ -679,6 +682,7 @@ controller.abort(); // Stops the child process ``` #### `options.detached` + @@ -737,6 +741,7 @@ subprocess.unref(); ``` #### `options.stdio` + * `file` {string} The name or path of the executable file to run. -* `args` {string[]} List of string arguments. +* `args` {string\[]} List of string arguments. * `options` {Object} * `cwd` {string|URL} Current working directory of the child process. * `input` {string|Buffer|TypedArray|DataView} The value which will be passed @@ -925,6 +931,7 @@ function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.** ### `child_process.execSync(command[, options])` + * `command` {string} The command to run. -* `args` {string[]} List of string arguments. +* `args` {string\[]} List of string arguments. * `options` {Object} * `cwd` {string|URL} Current working directory of the child process. * `input` {string|Buffer|TypedArray|DataView} The value which will be passed @@ -1072,6 +1080,7 @@ function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.** ## Class: `ChildProcess` + @@ -1086,6 +1095,7 @@ use the [`child_process.spawn()`][], [`child_process.exec()`][], instances of `ChildProcess`. ### Event: `'close'` + @@ -1117,6 +1127,7 @@ ls.on('exit', (code) => { ``` ### Event: `'disconnect'` + @@ -1144,6 +1155,7 @@ against accidentally invoking handler functions multiple times. See also [`subprocess.kill()`][] and [`subprocess.send()`][]. ### Event: `'exit'` + @@ -1167,6 +1179,7 @@ re-raise the handled signal. See waitpid(2). ### Event: `'message'` + @@ -1187,6 +1200,7 @@ to represent. See [Advanced serialization][] for more details. ### Event: `'spawn'` + @@ -1204,6 +1218,7 @@ the `'spawn'` event will fire, though `bash` may fail to spawn `some-command`. This caveat also applies when using `{ shell: true }`. ### `subprocess.channel` + @@ -1226,6 +1242,7 @@ This method makes the IPC channel keep the event loop of the parent process running if `.unref()` has been called before. #### `subprocess.channel.unref()` + @@ -1234,6 +1251,7 @@ This method makes the IPC channel not keep the event loop of the parent process running, and lets it finish even while the channel is open. ### `subprocess.connected` + @@ -1245,6 +1263,7 @@ send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. ### `subprocess.disconnect()` + @@ -1271,6 +1290,7 @@ The `subprocess.exitCode` property indicates the exit code of the child process. If the child process is still running, the field will be `null`. ### `subprocess.kill([signal])` + @@ -1338,6 +1358,7 @@ setTimeout(() => { ``` ### `subprocess.killed` + @@ -1350,6 +1371,7 @@ successfully received a signal from `subprocess.kill()`. The `killed` property does not indicate that the child process has been terminated. ### `subprocess.pid` + @@ -1369,6 +1391,7 @@ grep.stdin.end(); ``` ### `subprocess.ref()` + @@ -1390,6 +1413,7 @@ subprocess.ref(); ``` ### `subprocess.send(message[, sendHandle[, options]][, callback])` + @@ -1615,6 +1640,7 @@ The `subprocess.stderr` property can be `null` if the child process could not be successfully spawned. ### `subprocess.stdin` + @@ -1636,6 +1662,7 @@ The `subprocess.stdin` property can be `undefined` if the child process could not be successfully spawned. ### `subprocess.stdio` + @@ -1679,6 +1706,7 @@ The `subprocess.stdio` property can be `undefined` if the child process could not be successfully spawned. ### `subprocess.stdout` + @@ -1707,6 +1735,7 @@ The `subprocess.stdout` property can be `null` if the child process could not be successfully spawned. ### `subprocess.unref()` + @@ -1752,6 +1781,7 @@ spawned, `'cmd.exe'` is used as a fallback if `process.env.ComSpec` is unavailable. ## Advanced serialization + @@ -49,6 +51,7 @@ meaning that the script is read from stdin, and the rest of the options are passed to that script. ### `--` + @@ -58,6 +61,7 @@ If no script filename or eval/print script is supplied prior to this, then the next argument is used as a script filename. ### `--abort-on-uncaught-exception` + @@ -70,6 +74,7 @@ If this flag is passed, the behavior can still be set to not abort through `domain` module that uses it). ### `--completion-bash` + @@ -82,6 +87,7 @@ $ source node_bash_completion ``` ### `-C=condition`, `--conditions=condition` + @@ -127,6 +134,7 @@ CPU.20190409.202950.15293.0.0.cpuprofile ``` ### `--cpu-prof-dir` + @@ -140,6 +148,7 @@ The default value is controlled by the [`--diagnostic-dir`][] command-line option. ### `--cpu-prof-interval` + @@ -150,6 +159,7 @@ Specify the sampling interval in microseconds for the CPU profiles generated by `--cpu-prof`. The default is 1000 microseconds. ### `--cpu-prof-name` + @@ -164,11 +174,13 @@ Set the directory to which all diagnostic output files are written. Defaults to current working directory. Affects the default output directory of: + * [`--cpu-prof-dir`][] * [`--heap-prof-dir`][] * [`--redirect-warnings`][] ### `--disable-proto=mode` + @@ -189,12 +202,14 @@ code from strings throw an exception instead. This does not affect the Node.js `vm` module. ### `--dns-result-order=order` + Set the default value of `verbatim` in [`dns.lookup()`][] and [`dnsPromises.lookup()`][]. The value could be: + * `ipv4first`: sets default `verbatim` `false`. * `verbatim`: sets default `verbatim` `true`. @@ -202,6 +217,7 @@ The default is `ipv4first` and [`dns.setDefaultResultOrder()`][] have higher priority than `--dns-result-order`. ### `--enable-fips` + @@ -210,6 +226,7 @@ Enable FIPS-compliant crypto at startup. (Requires Node.js to be built against FIPS-compatible OpenSSL.) ### `--enable-source-maps` + @@ -257,6 +277,7 @@ added: v12.9.0 Enable experimental JSON support for the ES Module loader. ### `--experimental-loader=module` + @@ -265,6 +286,7 @@ Specify the `module` of a custom experimental [ECMAScript Module loader][]. `module` may be either a path to a file, or an ECMAScript Module name. ### `--experimental-modules` + @@ -272,6 +294,7 @@ added: v8.5.0 Enable latest experimental modules features (deprecated). ### `--experimental-policy` + @@ -279,12 +302,15 @@ added: v11.8.0 Use the specified file as a security policy. ### `--no-experimental-repl-await` + - Use this flag to disable top-level await in REPL. + +Use this flag to disable top-level await in REPL. ### `--experimental-specifier-resolution=mode` + @@ -308,6 +335,7 @@ added: v9.6.0 Enable experimental ES Module support in the `vm` module. ### `--experimental-wasi-unstable-preview1` + @@ -329,6 +358,7 @@ added: v12.3.0 Enable experimental WebAssembly module support. ### `--force-context-aware` + @@ -336,6 +366,7 @@ added: v12.12.0 Disable loading native addons that are not [context-aware][]. ### `--force-fips` + @@ -344,6 +375,7 @@ Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.) (Same requirements as `--enable-fips`.) ### `--frozen-intrinsics` + @@ -360,6 +392,7 @@ reference. Code may break under this flag. be added. ### `--heapsnapshot-near-heap-limit=max_count` + @@ -406,6 +439,7 @@ FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaS ``` ### `--heapsnapshot-signal=signal` + @@ -425,6 +459,7 @@ Heap.20190718.133405.15554.0.001.heapsnapshot ``` ### `--heap-prof` + @@ -447,6 +482,7 @@ Heap.20190409.202950.15293.0.001.heapprofile ``` ### `--heap-prof-dir` + @@ -460,6 +496,7 @@ The default value is controlled by the [`--diagnostic-dir`][] command-line option. ### `--heap-prof-interval` + @@ -467,9 +504,10 @@ added: v12.4.0 > Stability: 1 - Experimental Specify the average sampling interval in bytes for the heap profiles generated -by `--heap-prof`. The default is 512 * 1024 bytes. +by `--heap-prof`. The default is 512 \* 1024 bytes. ### `--heap-prof-name` + @@ -479,6 +517,7 @@ added: v12.4.0 Specify the file name of the heap profile generated by `--heap-prof`. ### `--icu-data-dir=file` + @@ -486,6 +525,7 @@ added: v0.11.15 Specify ICU data load path. (Overrides `NODE_ICU_DATA`.) ### `--input-type=type` + @@ -496,6 +536,7 @@ module. String input is input via `--eval`, `--print`, or `STDIN`. Valid values are `"commonjs"` and `"module"`. The default is `"commonjs"`. ### `--inspect-brk[=[host:]port]` + @@ -504,6 +545,7 @@ Activate inspector on `host:port` and break at start of user script. Default `host:port` is `127.0.0.1:9229`. ### `--inspect-port=[host:]port` + @@ -517,6 +559,7 @@ See the [security warning][] below regarding the `host` parameter usage. ### `--inspect[=[host:]port]` + @@ -528,7 +571,9 @@ and profile Node.js instances. The tools attach to Node.js instances via a tcp port and communicate using the [Chrome DevTools Protocol][]. + + #### Warning: binding inspector to a public IP:port combination is insecure Binding the inspector to a public IP (including `0.0.0.0`) with an open port is @@ -553,6 +598,7 @@ By default inspector websocket url is available in stderr and under `/json/list` endpoint on `http://host:port/json/list`. ### `--insecure-http-parser` + @@ -578,6 +625,7 @@ This flag is inherited from V8 and is subject to change upstream. It may disappear in a non-semver-major release. ### `--max-http-header-size=size` + @@ -598,6 +647,7 @@ added: v7.10.0 This option is a no-op. It is kept for compatibility. ### `--no-addons` + @@ -607,6 +657,7 @@ native addons. When `--no-addons` is specified, calling `process.dlopen` or requiring a native C++ addon will fail and throw an exception. ### `--no-deprecation` + @@ -614,6 +665,7 @@ added: v0.8.0 Silence deprecation warnings. ### `--no-force-async-hooks-checks` + @@ -622,6 +674,7 @@ Disables runtime checks for `async_hooks`. These will still be enabled dynamically when `async_hooks` is enabled. ### `--no-global-search-paths` + @@ -630,6 +683,7 @@ Do not search modules from global paths like `$HOME/.node_modules` and `$NODE_PATH`. ### `--no-warnings` + @@ -637,6 +691,7 @@ added: v6.0.0 Silence all process warnings (including deprecations). ### `--node-memory-debug` + @@ -645,6 +700,7 @@ Enable extra debug checks for memory leaks in Node.js internals. This is usually only useful for developers debugging Node.js itself. ### `--openssl-config=file` + @@ -654,6 +710,7 @@ used to enable FIPS-compliant crypto if Node.js is built against FIPS-enabled OpenSSL. ### `--pending-deprecation` + @@ -661,13 +718,14 @@ added: v8.0.0 Emit pending deprecation warnings. Pending deprecations are generally identical to a runtime deprecation with the -notable exception that they are turned *off* by default and will not be emitted +notable exception that they are turned _off_ by default and will not be emitted unless either the `--pending-deprecation` command-line flag, or the `NODE_PENDING_DEPRECATION=1` environment variable, is set. Pending deprecations are used to provide a kind of selective "early warning" mechanism that developers may leverage to detect deprecated API usage. ### `--policy-integrity=sri` + @@ -679,6 +737,7 @@ the specified integrity. It expects a [Subresource Integrity][] string as a parameter. ### `--preserve-symlinks` + @@ -713,7 +772,7 @@ symlink path for modules as opposed to the real path, allowing symbolically linked peer dependencies to be found. Note, however, that using `--preserve-symlinks` can have other side effects. -Specifically, symbolically linked *native* modules can fail to load if those +Specifically, symbolically linked _native_ modules can fail to load if those are linked from more than one location in the dependency tree (Node.js would see those as two separate modules and would attempt to load the module multiple times, causing an exception to be thrown). @@ -723,6 +782,7 @@ The `--preserve-symlinks` flag does not apply to the main module, which allows behavior for the main module, also use `--preserve-symlinks-main`. ### `--preserve-symlinks-main` + @@ -742,6 +802,7 @@ resolving relative paths. See `--preserve-symlinks` for more information. ### `--prof` + @@ -749,6 +810,7 @@ added: v2.0.0 Generate V8 profiler output. ### `--prof-process` + @@ -756,6 +818,7 @@ added: v5.2.0 Process V8 profiler output generated using the V8 option `--prof`. ### `--redirect-warnings=file` + @@ -770,6 +833,7 @@ will be written to is controlled by the [`--diagnostic-dir`]() command-line option. ### `--report-compact` + @@ -917,6 +988,7 @@ The secure heap is not available on Windows. See [`CRYPTO_secure_malloc_init`][] for more details. ### `--secure-heap-min=n` + @@ -927,6 +999,7 @@ The maximum value is the lesser of `--secure-heap` or `2147483647`. The value given must be a power of two. ### `--throw-deprecation` + @@ -934,6 +1007,7 @@ added: v0.11.14 Throw errors for deprecations. ### `--title=title` + @@ -941,6 +1015,7 @@ added: v10.7.0 Set `process.title` on startup. ### `--tls-cipher-list=list` + @@ -949,6 +1024,7 @@ Specify an alternative default TLS cipher list. Requires Node.js to be built with crypto support (default). ### `--tls-keylog=file` + @@ -978,6 +1056,7 @@ Set default [`tls.DEFAULT_MAX_VERSION`][] to 'TLSv1.3'. Use to enable support for TLSv1.3. ### `--tls-min-v1.0` + @@ -1017,6 +1099,7 @@ Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.3'. Use to disable support for TLSv1.2, which is not as secure as TLSv1.3. ### `--trace-atomics-wait` + @@ -1044,6 +1127,7 @@ The fields here correspond to: * The timeout passed to `Atomics.wait` ### `--trace-deprecation` + @@ -1051,6 +1135,7 @@ added: v0.8.0 Print stack traces for deprecations. ### `--trace-event-categories` + @@ -1059,6 +1144,7 @@ A comma separated list of categories that should be traced when trace event tracing is enabled using `--trace-events-enabled`. ### `--trace-event-file-pattern` + @@ -1067,6 +1153,7 @@ Template string specifying the filepath for the trace event data, it supports `${rotation}` and `${pid}`. ### `--trace-events-enabled` + @@ -1074,6 +1161,7 @@ added: v7.7.0 Enables the collection of trace event tracing information. ### `--trace-exit` + @@ -1101,6 +1191,7 @@ Prints a stack trace whenever synchronous I/O is detected after the first turn of the event loop. ### `--trace-tls` + @@ -1109,6 +1200,7 @@ Prints TLS packet trace information to `stderr`. This can be used to debug TLS connection problems. ### `--trace-uncaught` + @@ -1121,6 +1213,7 @@ to be an `Error` instance). Enabling this option may affect garbage collection behavior negatively. ### `--trace-warnings` + @@ -1128,6 +1221,7 @@ added: v6.0.0 Print stack traces for process warnings (including deprecations). ### `--track-heap-objects` + @@ -1135,6 +1229,7 @@ added: v2.4.0 Track heap object allocations for heap snapshots. ### `--unhandled-rejections=mode` + @@ -1179,6 +1275,7 @@ environment variables. See `SSL_CERT_DIR` and `SSL_CERT_FILE`. ### `--use-largepages=mode` + @@ -1204,6 +1303,7 @@ added: v0.1.3 Print V8 command-line options. ### `--v8-pool-size=num` + @@ -1217,6 +1317,7 @@ If the value provided is larger than V8's maximum, then the largest value will be chosen. ### `--zero-fill-buffers` + @@ -1225,6 +1326,7 @@ Automatically zero-fills all newly allocated [`Buffer`][] and [`SlowBuffer`][] instances. ### `-c`, `--check` + @@ -1262,6 +1366,7 @@ Print node command-line options. The output of this option is less detailed than this document. ### `-i`, `--interactive` + @@ -1269,6 +1374,7 @@ added: v0.7.7 Opens the REPL even if stdin does not appear to be a terminal. ### `-p`, `--print "script"` + @@ -1293,6 +1400,7 @@ Only CommonJS modules are supported. Attempting to preload a ES6 Module using `--require` will fail with an error. ### `-v`, `--version` + @@ -1314,7 +1422,9 @@ When `FORCE_COLOR` is used and set to a supported value, both the `NO_COLOR`, and `NODE_DISABLE_COLORS` environment variables are ignored. Any other value will result in colorized output being disabled. + ### `NODE_DEBUG=module[,…]` + @@ -1326,6 +1436,7 @@ added: v0.1.32 `','`-separated list of core C++ modules that should print debug information. ### `NODE_DISABLE_COLORS=1` + @@ -1333,6 +1444,7 @@ added: v0.3.0 When set, colors will not be used in the REPL. ### `NODE_EXTRA_CA_CERTS=file` + @@ -1354,6 +1466,7 @@ process is first launched. Changing the value at runtime using `process.env.NODE_EXTRA_CA_CERTS` has no effect on the current process. ### `NODE_ICU_DATA=file` + @@ -1362,6 +1475,7 @@ Data path for ICU (`Intl` object) data. Will extend linked-in data when compiled with small-icu support. ### `NODE_NO_WARNINGS=1` + @@ -1369,6 +1483,7 @@ added: v6.11.0 When set to `1`, process warnings are silenced. ### `NODE_OPTIONS=options...` + @@ -1404,7 +1519,9 @@ node --require "./a.js" --require "./b.js" ``` Node.js options that are allowed are: + + * `--conditions`, `-C` * `--diagnostic-dir` * `--disable-proto` @@ -1489,10 +1606,13 @@ Node.js options that are allowed are: * `--use-openssl-ca` * `--v8-pool-size` * `--zero-fill-buffers` + V8 options that are allowed are: + + * `--abort-on-uncaught-exception` * `--disallow-code-generation-from-strings` * `--huge-max-old-generation-size` @@ -1504,12 +1624,14 @@ V8 options that are allowed are: * `--perf-prof-unwinding-info` * `--perf-prof` * `--stack-trace-limit` + `--perf-basic-prof-only-functions`, `--perf-basic-prof`, `--perf-prof-unwinding-info`, and `--perf-prof` are only available on Linux. ### `NODE_PATH=path[:…]` + @@ -1519,6 +1641,7 @@ added: v0.1.32 On Windows, this is a `';'`-separated list instead. ### `NODE_PENDING_DEPRECATION=1` + @@ -1526,7 +1649,7 @@ added: v8.0.0 When set to `1`, emit pending deprecation warnings. Pending deprecations are generally identical to a runtime deprecation with the -notable exception that they are turned *off* by default and will not be emitted +notable exception that they are turned _off_ by default and will not be emitted unless either the `--pending-deprecation` command-line flag, or the `NODE_PENDING_DEPRECATION=1` environment variable, is set. Pending deprecations are used to provide a kind of selective "early warning" mechanism that @@ -1538,6 +1661,7 @@ Set the number of pending pipe instance handles when the pipe server is waiting for connections. This setting applies to Windows only. ### `NODE_PRESERVE_SYMLINKS=1` + @@ -1546,6 +1670,7 @@ When set to `1`, instructs the module loader to preserve symbolic links when resolving and caching modules. ### `NODE_REDIRECT_WARNINGS=file` + @@ -1557,6 +1682,7 @@ warning to the file, the warning will be written to stderr instead. This is equivalent to using the `--redirect-warnings=file` command-line flag. ### `NODE_REPL_HISTORY=file` + @@ -1566,6 +1692,7 @@ Path to the file used to store the persistent REPL history. The default path is to an empty string (`''` or `' '`) disables persistent REPL history. ### `NODE_REPL_EXTERNAL_MODULE=file` + @@ -1672,18 +1800,20 @@ and the line lengths of the source file (in the key `lineLengths`). environment variable is arbitrary. ### `OPENSSL_CONF=file` + Load an OpenSSL configuration file on startup. Among other uses, this can be -used to enable FIPS-compliant crypto if Node.js is built with `./configure ---openssl-fips`. +used to enable FIPS-compliant crypto if Node.js is built with +`./configure --openssl-fips`. If the [`--openssl-config`][] command-line option is used, the environment variable is ignored. ### `SSL_CERT_DIR=dir` + @@ -1696,6 +1826,7 @@ variable will be inherited by any child processes, and if they use OpenSSL, it may cause them to trust the same CAs as node. ### `SSL_CERT_FILE=file` + @@ -1708,6 +1839,7 @@ variable will be inherited by any child processes, and if they use OpenSSL, it may cause them to trust the same CAs as node. ### `TZ` + @@ -157,6 +158,7 @@ In the primary it can be obtained using `cluster.workers`. In a worker it can be obtained using `cluster.worker`. ### Event: `'disconnect'` + @@ -170,6 +172,7 @@ cluster.fork().on('disconnect', () => { ``` ### Event: `'error'` + @@ -179,6 +182,7 @@ This event is the same as the one provided by [`child_process.fork()`][]. Within a worker, `process.on('error')` may also be used. ### Event: `'exit'` + @@ -220,6 +224,7 @@ worker.on('exit', (code, signal) => { ``` ### Event: `'listening'` + @@ -247,6 +252,7 @@ cluster.fork().on('listening', (address) => { It is not emitted in the worker. ### Event: `'message'` + @@ -351,6 +357,7 @@ if (cluster.isPrimary) { ``` ### Event: `'online'` + @@ -366,6 +373,7 @@ cluster.fork().on('online', () => { It is not emitted in the worker. ### `worker.disconnect()` + @@ -462,6 +471,7 @@ worker.kill(); ``` ### `worker.id` + @@ -475,6 +485,7 @@ While a worker is alive, this is the key that indexes it in `cluster.workers`. ### `worker.isConnected()` + @@ -484,6 +495,7 @@ IPC channel, `false` otherwise. A worker is connected to its primary after it has been created. It is disconnected after the `'disconnect'` event is emitted. ### `worker.isDead()` + @@ -556,6 +568,7 @@ if (cluster.isPrimary) { ``` ### `worker.kill([signal])` + @@ -581,6 +594,7 @@ In a worker, `process.kill()` exists, but it is not this function; it is [`kill()`][]. ### `worker.process` + @@ -598,6 +612,7 @@ on `process` and `.exitedAfterDisconnect` is not `true`. This protects against accidental disconnection. ### `worker.send(message[, sendHandle[, options]][, callback])` + @@ -661,6 +677,7 @@ cluster.on('disconnect', (worker) => { ``` ## Event: `'exit'` + @@ -685,6 +702,7 @@ cluster.on('exit', (worker, code, signal) => { See [`child_process` event: `'exit'`][]. ## Event: `'fork'` + @@ -713,6 +731,7 @@ cluster.on('exit', (worker, code, signal) => { ``` ## Event: `'listening'` + @@ -744,6 +763,7 @@ The `addressType` is one of: * `'udp4'` or `'udp6'` (UDP v4 or v6) ## Event: `'message'` + @@ -779,6 +800,7 @@ cluster.on('online', (worker) => { ``` ## Event: `'setup'` + @@ -794,6 +816,7 @@ The `settings` object is the `cluster.settings` object at the time If accuracy is important, use `cluster.settings`. ## `cluster.disconnect([callback])` + @@ -812,6 +835,7 @@ finished. This can only be called from the primary process. ## `cluster.fork([env])` + @@ -824,6 +848,7 @@ Spawn a new worker process. This can only be called from the primary process. ## `cluster.isMaster` + @@ -844,6 +870,7 @@ by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` is undefined, then `isPrimary` is `true`. ## `cluster.isWorker` + @@ -853,6 +880,7 @@ added: v0.6.0 True if the process is not a primary (it is the negation of `cluster.isPrimary`). ## `cluster.schedulingPolicy` + @@ -871,6 +899,7 @@ distribute IOCP handles without incurring a large performance hit. values are `'rr'` and `'none'`. ## `cluster.settings` + * {Object} - * `execArgv` {string[]} List of string arguments passed to the Node.js + * `execArgv` {string\[]} List of string arguments passed to the Node.js executable. **Default:** `process.execArgv`. * `exec` {string} File path to worker file. **Default:** `process.argv[1]`. - * `args` {string[]} String arguments passed to worker. + * `args` {string\[]} String arguments passed to worker. **Default:** `process.argv.slice(2)`. * `cwd` {string} Current working directory of the worker process. **Default:** `undefined` (inherits from parent process). @@ -925,6 +954,7 @@ contain the settings, including the default values. This object is not intended to be changed or set manually. ## `cluster.setupMaster([settings])` + @@ -990,6 +1021,7 @@ cluster.fork(); // http worker This can only be called from the primary process. ## `cluster.worker` + @@ -1023,6 +1055,7 @@ if (cluster.isPrimary) { ``` ## `cluster.workers` + diff --git a/doc/api/console.md b/doc/api/console.md index 411366ab2f6842..5c8b4ecc64d9b4 100644 --- a/doc/api/console.md +++ b/doc/api/console.md @@ -17,7 +17,7 @@ The module exports two specific components: [`process.stderr`][]. The global `console` can be used without calling `require('console')`. -***Warning***: The global console object's methods are neither consistently +_**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [note on process I/O][] for more information. @@ -65,6 +65,7 @@ myConsole.warn(`Danger ${name}! Danger!`); ``` ## Class: `Console` + @@ -192,6 +197,7 @@ will clear only the output in the current terminal viewport for the Node.js binary. ### `console.count([label])` + @@ -202,6 +208,7 @@ Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + ```js > console.count() default: 1 @@ -225,6 +232,7 @@ undefined ``` ### `console.countReset([label])` + @@ -234,6 +242,7 @@ added: v8.3.0 Resets the internal counter specific to `label`. + ```js > console.count('abc'); abc: 1 @@ -247,6 +256,7 @@ undefined ``` ### `console.debug(data[, ...args])` + @@ -273,13 +284,14 @@ added: v0.1.101 formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass `null`. **Default:** `2`. * `colors` {boolean} If `true`, then the output will be styled with ANSI color - codes. Colors are customizable; - see [customizing `util.inspect()` colors][]. **Default:** `false`. + codes. Colors are customizable; + see [customizing `util.inspect()` colors][]. **Default:** `false`. Uses [`util.inspect()`][] on `obj` and prints the resulting string to `stdout`. This function bypasses any custom `inspect()` function defined on `obj`. ### `console.dirxml(...data)` + @@ -319,6 +332,7 @@ If formatting elements (e.g. `%d`) are not found in the first string then values are concatenated. See [`util.format()`][] for more information. ### `console.group([...label])` + @@ -332,6 +346,7 @@ If one or more `label`s are provided, those are printed first without the additional indentation. ### `console.groupCollapsed()` + @@ -339,6 +354,7 @@ additional indentation. An alias for [`console.group()`][]. ### `console.groupEnd()` + @@ -347,6 +363,7 @@ Decreases indentation of subsequent lines by spaces for `groupIndentation` length. ### `console.info([data][, ...args])` + @@ -357,6 +374,7 @@ added: v0.1.100 The `console.info()` function is an alias for [`console.log()`][]. ### `console.log([data][, ...args])` + @@ -380,12 +398,13 @@ console.log('count:', count); See [`util.format()`][] for more information. ### `console.table(tabularData[, properties])` + * `tabularData` {any} -* `properties` {string[]} Alternate properties for constructing the table. +* `properties` {string\[]} Alternate properties for constructing the table. Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just @@ -417,6 +436,7 @@ console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); ``` ### `console.time([label])` + @@ -430,6 +450,7 @@ suitable time units to `stdout`. For example, if the elapsed time is 3869ms, `console.timeEnd()` displays "3.869s". ### `console.timeEnd([label])` + @@ -475,6 +497,7 @@ console.timeEnd('process'); ``` ### `console.trace([message][, ...args])` + @@ -502,6 +525,7 @@ console.trace('Show me'); ``` ### `console.warn([data][, ...args])` + @@ -512,11 +536,13 @@ added: v0.1.100 The `console.warn()` function is an alias for [`console.error()`][]. ## Inspector only methods + The following methods are exposed by the V8 engine in the general API but do not display anything unless used in conjunction with the [inspector][] (`--inspect` flag). ### `console.profile([label])` + @@ -536,6 +562,7 @@ console.profileEnd('MyLabel'); ``` ### `console.profileEnd([label])` + @@ -551,6 +578,7 @@ If this method is called without a label, the most recently started profile is stopped. ### `console.timeStamp([label])` + diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 139a669c03efe6..b23bee42e95bc6 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -52,7 +52,7 @@ try { When using the lexical ESM `import` keyword, the error can only be caught if a handler for `process.on('uncaughtException')` is registered -*before* any attempt to load the module is made -- using, for instance, +_before_ any attempt to load the module is made -- using, for instance, a preload module. When using ESM, if there is a chance that the code may be run on a build @@ -69,6 +69,7 @@ try { ``` ## Class: `Certificate` + @@ -84,6 +85,7 @@ data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC implementation][] internally. ### Static method: `Certificate.exportChallenge(spkac[, encoding])` + @@ -234,6 +239,7 @@ console.log(challenge.toString('utf8')); ``` #### `certificate.exportPublicKey(spkac[, encoding])` + @@ -262,6 +268,7 @@ console.log(publicKey); ``` #### `certificate.verifySpkac(spkac[, encoding])` + @@ -292,6 +299,7 @@ console.log(cert.verifySpkac(Buffer.from(spkac))); ``` ## Class: `Cipher` + @@ -515,6 +523,7 @@ scrypt(password, 'salt', 24, (err, key) => { ``` ### `cipher.final([outputEncoding])` + @@ -529,6 +538,7 @@ longer be used to encrypt data. Attempts to call `cipher.final()` more than once will result in an error being thrown. ### `cipher.getAuthTag()` + @@ -542,6 +552,7 @@ The `cipher.getAuthTag()` method should only be called after encryption has been completed using the [`cipher.final()`][] method. ### `cipher.setAAD(buffer[, options])` + @@ -563,6 +574,7 @@ length of the plaintext in bytes. See [CCM mode][]. The `cipher.setAAD()` method must be called before [`cipher.update()`][]. ### `cipher.setAutoPadding([autoPadding])` + @@ -583,6 +595,7 @@ The `cipher.setAutoPadding()` method must be called before [`cipher.final()`][]. ### `cipher.update(data[, inputEncoding][, outputEncoding])` + @@ -812,6 +826,7 @@ console.log(decrypted); ``` ### `decipher.final([outputEncoding])` + @@ -826,6 +841,7 @@ no longer be used to decrypt data. Attempts to call `decipher.final()` more than once will result in an error being thrown. ### `decipher.setAAD(buffer[, options])` + @@ -911,6 +929,7 @@ The `decipher.setAutoPadding()` method must be called before [`decipher.final()`][]. ### `decipher.update(data[, inputEncoding][, outputEncoding])` + @@ -997,6 +1017,7 @@ assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); ``` ### `diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])` + @@ -1018,6 +1039,7 @@ If `outputEncoding` is given a string is returned; otherwise, a [`Buffer`][] is returned. ### `diffieHellman.generateKeys([encoding])` + @@ -1032,6 +1054,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `diffieHellman.getGenerator([encoding])` + @@ -1044,6 +1067,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `diffieHellman.getPrime([encoding])` + @@ -1056,6 +1080,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `diffieHellman.getPrivateKey([encoding])` + @@ -1068,6 +1093,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `diffieHellman.getPublicKey([encoding])` + @@ -1080,6 +1106,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `diffieHellman.setPrivateKey(privateKey[, encoding])` + @@ -1093,6 +1120,7 @@ to be a string. If no `encoding` is provided, `privateKey` is expected to be a [`Buffer`][], `TypedArray`, or `DataView`. ### `diffieHellman.setPublicKey(publicKey[, encoding])` + @@ -1106,6 +1134,7 @@ to be a string. If no `encoding` is provided, `publicKey` is expected to be a [`Buffer`][], `TypedArray`, or `DataView`. ### `diffieHellman.verifyError` + @@ -1122,6 +1151,7 @@ module): * `DH_NOT_SUITABLE_GENERATOR` ## Class: `DiffieHellmanGroup` + @@ -1157,6 +1187,7 @@ modp18 ``` ## Class: `ECDH` + @@ -1214,6 +1245,7 @@ assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); ``` ### Static method: `ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])` + @@ -1286,6 +1318,7 @@ console.log(uncompressedKey === ecdh.getPublicKey('hex')); ``` ### `ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])` + @@ -1341,6 +1375,7 @@ If `encoding` is provided a string is returned; otherwise a [`Buffer`][] is returned. ### `ecdh.getPrivateKey([encoding])` + @@ -1352,6 +1387,7 @@ If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is returned. ### `ecdh.getPublicKey([encoding][, format])` + @@ -1369,6 +1405,7 @@ If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is returned. ### `ecdh.setPrivateKey(privateKey[, encoding])` + @@ -1386,6 +1423,7 @@ created, an error is thrown. Upon setting the private key, the associated public point (key) is also generated and set in the `ECDH` object. ### `ecdh.setPublicKey(publicKey[, encoding])` + @@ -1580,6 +1619,7 @@ console.log(hash.digest('hex')); ``` ### `hash.copy([options])` + @@ -1638,6 +1678,7 @@ console.log(hash.copy().digest('hex')); ``` ### `hash.digest([encoding])` + @@ -1654,6 +1695,7 @@ The `Hash` object can not be used again after `hash.digest()` method has been called. Multiple calls will cause an error to be thrown. ### `hash.update(data[, inputEncoding])` + @@ -1796,6 +1839,7 @@ console.log(hmac.digest('hex')); ``` ### `hmac.digest([encoding])` + @@ -1811,6 +1855,7 @@ The `Hmac` object can not be used again after `hmac.digest()` has been called. Multiple calls to `hmac.digest()` will result in an error being thrown. ### `hmac.update(data[, inputEncoding])` + @@ -1906,6 +1953,7 @@ const { ``` ### `keyObject.asymmetricKeyDetails` + @@ -2038,6 +2089,7 @@ For secret keys, this property represents the size of the key in bytes. This property is `undefined` for asymmetric keys. ### `keyObject.type` + @@ -2049,6 +2101,7 @@ Depending on the type of this `KeyObject`, this property is either or `'private'` for private (asymmetric) keys. ## Class: `Sign` + @@ -2164,6 +2217,7 @@ console.log(verify.verify(publicKey, signature)); ``` ### `sign.sign(privateKey[, outputEncoding])` + + * `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `dsaEncoding` {string} * `padding` {integer} * `saltLength` {integer} * `outputEncoding` {string} The [encoding][] of the return value. * Returns: {Buffer | string} + Calculates the signature on all the data passed through using either @@ -2207,6 +2263,7 @@ object, the following additional properties can be passed: * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`. * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363. * `padding` {integer} Optional padding value for RSA, one of the following: + * `crypto.constants.RSA_PKCS1_PADDING` (default) * `crypto.constants.RSA_PKCS1_PSS_PADDING` @@ -2227,6 +2284,7 @@ The `Sign` object can not be again used after `sign.sign()` method has been called. Multiple calls to `sign.sign()` will result in an error being thrown. ### `sign.update(data[, inputEncoding])` + @@ -2267,6 +2326,7 @@ The [`crypto.createVerify()`][] method is used to create `Verify` instances. See [`Sign`][] for examples. ### `verify.update(data[, inputEncoding])` + + * `object` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `dsaEncoding` {string} * `padding` {integer} @@ -2318,6 +2380,7 @@ changes: * `signatureEncoding` {string} The [encoding][] of the `signature` string. * Returns: {boolean} `true` or `false` depending on the validity of the signature for the data and public key. + Verifies the provided data using the given `object` and `signature`. @@ -2331,6 +2394,7 @@ object, the following additional properties can be passed: * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`. * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363. * `padding` {integer} Optional padding value for RSA, one of the following: + * `crypto.constants.RSA_PKCS1_PADDING` (default) * `crypto.constants.RSA_PKCS1_PSS_PADDING` @@ -2358,6 +2422,7 @@ Because public keys can be derived from private keys, a private key may be passed instead of a public key. ## Class: `X509Certificate` + @@ -2382,6 +2447,7 @@ console.log(x509.subject); ``` ### `new X509Certificate(buffer)` + @@ -2390,6 +2456,7 @@ added: v15.6.0 X509 Certificate. ### `x509.ca` + @@ -2398,6 +2465,7 @@ added: v15.6.0 certificate. ### `x509.checkEmail(email[, options])` + @@ -2415,6 +2483,7 @@ added: v15.6.0 Checks whether the certificate matches the given email address. ### `x509.checkHost(name[, options])` + @@ -2432,6 +2501,7 @@ added: v15.6.0 Checks whether the certificate matches the given host name. ### `x509.checkIP(ip[, options])` + @@ -2449,6 +2519,7 @@ added: v15.6.0 Checks whether the certificate matches the given IP address (IPv4 or IPv6). ### `x509.checkIssued(otherCert)` + @@ -2459,6 +2530,7 @@ added: v15.6.0 Checks whether this certificate was issued by the given `otherCert`. ### `x509.checkPrivateKey(privateKey)` + @@ -2470,6 +2542,7 @@ Checks whether the public key for this certificate is consistent with the given private key. ### `x509.fingerprint` + @@ -2479,6 +2552,7 @@ added: v15.6.0 The SHA-1 fingerprint of this certificate. ### `x509.fingerprint256` + @@ -2488,6 +2562,7 @@ added: v15.6.0 The SHA-256 fingerprint of this certificate. ### `x509.infoAccess` + @@ -2497,6 +2572,7 @@ added: v15.6.0 The information access content of this certificate. ### `x509.issuer` + @@ -2506,6 +2582,7 @@ added: v15.6.0 The issuer identification included in this certificate. ### `x509.issuerCertificate` + @@ -2516,15 +2593,17 @@ The issuer certificate or `undefined` if the issuer certificate is not available. ### `x509.keyUsage` + -* Type: {string[]} +* Type: {string\[]} An array detailing the key usages for this certificate. ### `x509.publicKey` + @@ -2534,6 +2613,7 @@ added: v15.6.0 The public key {KeyObject} for this certificate. ### `x509.raw` + @@ -2543,6 +2623,7 @@ added: v15.6.0 A `Buffer` containing the DER encoding of this certificate. ### `x509.serialNumber` + @@ -2552,6 +2633,7 @@ added: v15.6.0 The serial number of this certificate. ### `x509.subject` + @@ -2561,6 +2643,7 @@ added: v15.6.0 The complete subject of this certificate. ### `x509.subjectAltName` + @@ -2570,6 +2653,7 @@ added: v15.6.0 The subject alternative name specified for this certificate. ### `x509.toJSON()` + @@ -2581,6 +2665,7 @@ There is no standard JSON encoding for X509 certificates. The certificate. ### `x509.toLegacyObject()` + @@ -2591,6 +2676,7 @@ Returns information about this certificate using the legacy [certificate object][] encoding. ### `x509.toString()` + @@ -2600,6 +2686,7 @@ added: v15.6.0 Returns the PEM-encoded certificate. ### `x509.validFrom` + @@ -2609,6 +2696,7 @@ added: v15.6.0 The date/time from which this certificate is considered valid. ### `x509.validTo` + @@ -2618,6 +2706,7 @@ added: v15.6.0 The date/time until which this certificate is considered valid. ### `x509.verify(publicKey)` + @@ -2631,6 +2720,7 @@ Does not perform any other validation checks on the certificate. ## `crypto` module methods and properties ### `crypto.constants` + @@ -2640,6 +2730,7 @@ added: v6.3.0 described in [Crypto constants][]. ### `crypto.DEFAULT_ENCODING` + @@ -2695,6 +2788,7 @@ added: v15.8.0 Checks the primality of the `candidate`. ### `crypto.checkPrimeSync(candidate[, options])` + @@ -2715,6 +2809,7 @@ added: v15.8.0 Checks the primality of the `candidate`. ### `crypto.createCipher(algorithm, password[, options])` + @@ -2988,6 +3088,7 @@ Creates a `DiffieHellman` key exchange object and generates a prime of If `generator` is not specified, the value `2` is used. ### `crypto.createDiffieHellmanGroup(name)` + @@ -2998,6 +3099,7 @@ added: v0.9.3 An alias for [`crypto.getDiffieHellman()`][] ### `crypto.createECDH(curveName)` + @@ -3012,6 +3114,7 @@ OpenSSL releases, `openssl ecparam -list_curves` will also display the name and description of each available elliptic curve. ### `crypto.createHash(algorithm[, options])` + + * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView} * `key`: {string|ArrayBuffer|Buffer|TypedArray|DataView|Object} The key material, either in PEM, DER, or JWK format. * `format`: {string} Must be `'pem'`, `'der'`, or '`'jwk'`. **Default:** `'pem'`. * `type`: {string} Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is - required only if the `format` is `'der'` and ignored otherwise. + required only if the `format` is `'der'` and ignored otherwise. * `passphrase`: {string | Buffer} The passphrase to use for decryption. * `encoding`: {string} The string encoding to use when `key` is a string. * Returns: {KeyObject} + Creates and returns a new key object containing a private key. If `key` is a @@ -3209,6 +3316,7 @@ If the private key is encrypted, a `passphrase` must be specified. The length of the passphrase is limited to 1024 bytes. ### `crypto.createPublicKey(key)` + + * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView} * `key`: {string|ArrayBuffer|Buffer|TypedArray|DataView|Object} The key material, either in PEM, DER, or JWK format. * `format`: {string} Must be `'pem'`, `'der'`, or `'jwk'`. **Default:** `'pem'`. * `type`: {string} Must be `'pkcs1'` or `'spki'`. This option is - required only if the `format` is `'der'` and ignored otherwise. + required only if the `format` is `'der'` and ignored otherwise. * `encoding` {string} The string encoding to use when `key` is a string. * Returns: {KeyObject} + Creates and returns a new key object containing a public key. If `key` is a @@ -3256,6 +3366,7 @@ extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type and it will be impossible to extract the private key from the returned object. ### `crypto.createSecretKey(key[, encoding])` + @@ -3293,6 +3405,7 @@ algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest algorithm names. ### `crypto.createVerify(algorithm[, options])` + @@ -3313,6 +3426,7 @@ algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest algorithm names. ### `crypto.diffieHellman(options)` + @@ -3372,6 +3487,7 @@ generateKey('hmac', { length: 64 }, (err, key) => { ``` ### `crypto.generateKeyPair(type, options, callback)` + @@ -3630,6 +3748,7 @@ console.log(key.export().toString('hex')); // e89..........41e ``` ### `crypto.generatePrime(size[, options[, callback]])` + @@ -3672,6 +3791,7 @@ in an {ArrayBuffer}. If the `bigint` option is `true`, then a {bigint} is provided. ### `crypto.generatePrimeSync(size[, options])` + @@ -3712,6 +3832,7 @@ in an {ArrayBuffer}. If the `bigint` option is `true`, then a {bigint} is provided. ### `crypto.getCipherInfo(nameOrNid[, options])` + @@ -3741,11 +3862,12 @@ cipher, use the `keyLength` and `ivLength` options. If the given values are unacceptable, `undefined` will be returned. ### `crypto.getCiphers()` + -* Returns: {string[]} An array with the names of the supported cipher +* Returns: {string\[]} An array with the names of the supported cipher algorithms. ```mjs @@ -3765,11 +3887,12 @@ console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] ``` ### `crypto.getCurves()` + -* Returns: {string[]} An array with the names of the supported elliptic curves. +* Returns: {string\[]} An array with the names of the supported elliptic curves. ```mjs const { @@ -3788,6 +3911,7 @@ console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] ``` ### `crypto.getDiffieHellman(groupName)` + @@ -3844,6 +3968,7 @@ console.log(aliceSecret === bobSecret); ``` ### `crypto.getFips()` + @@ -3853,11 +3978,12 @@ added: v10.0.0 the return type of this API to a {boolean}. ### `crypto.getHashes()` + -* Returns: {string[]} An array of the names of the supported hash algorithms, +* Returns: {string\[]} An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. ```mjs @@ -3877,6 +4003,7 @@ console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] ``` ### `crypto.hkdf(digest, ikm, salt, info, keylen, callback)` + @@ -3930,6 +4057,7 @@ hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { ``` ### `crypto.hkdfSync(digest, ikm, salt, info, keylen)` + @@ -3977,6 +4105,7 @@ console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' ``` ### `crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)` + + * `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `oaepHash` {string} The hash function to use for OAEP padding and MGF1. **Default:** `'sha1'` * `oaepLabel` {string|ArrayBuffer|Buffer|TypedArray|DataView} The label to - use for OAEP padding. If not specified, no label is used. + use for OAEP padding. If not specified, no label is used. * `padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`. * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView} * Returns: {Buffer} A new `Buffer` with the decrypted content. + Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using @@ -4214,6 +4347,7 @@ object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. ### `crypto.privateEncrypt(privateKey, buffer)` + + * `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} A PEM encoded private key. @@ -4241,6 +4376,7 @@ changes: or `passphrase` are strings. * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView} * Returns: {Buffer} A new `Buffer` with the encrypted content. + Encrypts `buffer` with `privateKey`. The returned data can be decrypted using @@ -4252,6 +4388,7 @@ object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. ### `crypto.publicDecrypt(key, buffer)` + + * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `passphrase` {string|ArrayBuffer|Buffer|TypedArray|DataView} An optional passphrase for the private key. @@ -4277,6 +4415,7 @@ changes: or `passphrase` are strings. * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView} * Returns: {Buffer} A new `Buffer` with the decrypted content. + Decrypts `buffer` with `key`.`buffer` was previously encrypted using @@ -4291,6 +4430,7 @@ Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key. ### `crypto.publicEncrypt(key, buffer)` + + * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} * `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} A PEM encoded public or private key, {KeyObject}, or {CryptoKey}. @@ -4329,6 +4470,7 @@ changes: `oaepLabel`, or `passphrase` are strings. * `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView} * Returns: {Buffer} A new `Buffer` with the encrypted content. + Encrypts the content of `buffer` with `key` and returns a new @@ -4344,6 +4486,7 @@ Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key. ### `crypto.randomBytes(size[, callback])` + @@ -4756,6 +4903,7 @@ Generates a random [RFC 4122][] version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator. ### `crypto.scrypt(password, salt, keylen[, options], callback)` + @@ -4930,6 +5080,7 @@ added: v15.6.0 allocated bytes. ### `crypto.setEngine(engine[, flags])` + @@ -4964,6 +5115,7 @@ The flags below are deprecated in OpenSSL-1.1.0. * `crypto.constants.ENGINE_METHOD_STORE` ### `crypto.setFips(bool)` + @@ -4974,6 +5126,7 @@ Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available. ### `crypto.sign(algorithm, data, key[, callback])` + + * `algorithm` {string | null | undefined} * `data` {ArrayBuffer|Buffer|TypedArray|DataView} * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} @@ -4995,6 +5149,7 @@ changes: * `err` {Error} * `signature` {Buffer} * Returns: {Buffer} if the `callback` function is not provided. + Calculates and returns the signature for `data` using the given private key and @@ -5010,6 +5165,7 @@ additional properties can be passed: * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`. * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363. * `padding` {integer} Optional padding value for RSA, one of the following: + * `crypto.constants.RSA_PKCS1_PADDING` (default) * `crypto.constants.RSA_PKCS1_PSS_PADDING` @@ -5024,6 +5180,7 @@ additional properties can be passed: If the `callback` function is provided this function uses libuv's threadpool. ### `crypto.timingSafeEqual(a, b)` + + * `algorithm` {string|null|undefined} * `data` {ArrayBuffer| Buffer|TypedArray|DataView} * `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey} @@ -5081,6 +5240,7 @@ changes: * Returns: {boolean} `true` or `false` depending on the validity of the signature for the data and public key if the `callback` function is not provided. + Verifies the given signature for `data` using the given key and algorithm. If @@ -5096,6 +5256,7 @@ additional properties can be passed: * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`. * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363. * `padding` {integer} Optional padding value for RSA, one of the following: + * `crypto.constants.RSA_PKCS1_PADDING` (default) * `crypto.constants.RSA_PKCS1_PSS_PADDING` @@ -5115,6 +5276,7 @@ key may be passed for `key`. If the `callback` function is provided this function uses libuv's threadpool. ### `crypto.webcrypto` + @@ -5242,7 +5404,7 @@ mode must adhere to certain restrictions when using the cipher API: * As CCM processes the whole message at once, `update()` must be called exactly once. * Even though calling `update()` is sufficient to encrypt/decrypt the message, - applications *must* call `final()` to compute or verify the + applications _must_ call `final()` to compute or verify the authentication tag. ```mjs diff --git a/doc/api/debugger.md b/doc/api/debugger.md index b155738b073165..c5e019e5412278 100644 --- a/doc/api/debugger.md +++ b/doc/api/debugger.md @@ -32,6 +32,7 @@ Inserting the statement `debugger;` into the source code of a script will enable a breakpoint at that position in the code: + ```js // myscript.js global.x = 5; diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index 8beb77603ab8fc..0d9d00582bb66b 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -42,6 +42,7 @@ However, the deprecation identifier will not be modified. ## List of deprecated APIs ### DEP0001: `http.OutgoingMessage.prototype.flush` + + Type: Documentation-only (supports [`--pending-deprecation`][]) The `process._tickCallback` property was never documented as an officially supported API. ### DEP0135: `WriteStream.open()` and `ReadStream.open()` are internal + + Type: Runtime `Transform._transformState` will be removed in future versions where it is no longer required due to simplification of the implementation. ### DEP0144: `module.parent` + @@ -68,6 +69,7 @@ New instances of `dgram.Socket` are created using [`dgram.createSocket()`][]. The `new` keyword is not to be used to create `dgram.Socket` instances. ### Event: `'close'` + @@ -76,6 +78,7 @@ The `'close'` event is emitted after a socket is closed with [`close()`][]. Once triggered, no new `'message'` events will be emitted on this socket. ### Event: `'connect'` + @@ -84,6 +87,7 @@ The `'connect'` event is emitted after a socket is associated to a remote address as a result of a successful [`connect()`][] call. ### Event: `'error'` + @@ -94,6 +98,7 @@ The `'error'` event is emitted whenever any error occurs. The event handler function is passed a single `Error` object. ### Event: `'listening'` + @@ -105,6 +110,7 @@ Until the `dgram.Socket` is listening, the underlying system resources do not exist and calls such as `socket.address()` and `socket.setTTL()` will fail. ### Event: `'message'` + @@ -126,6 +132,7 @@ address field set to `'fe80::2618:1234:ab11:3b9c%en0'`, where `'%en0'` is the interface name as a zone ID suffix. ### `socket.addMembership(multicastAddress[, multicastInterface])` + @@ -177,11 +184,13 @@ if (cluster.isPrimary) { ``` ### `socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])` + + * `sourceAddress` {string} * `groupAddress` {string} * `multicastInterface` {string} @@ -197,6 +206,7 @@ When called on an unbound socket, this method will implicitly bind to a random port, listening on all interfaces. ### `socket.address()` + @@ -210,6 +220,7 @@ properties. This method throws `EBADF` if called on an unbound socket. ### `socket.bind([port][, address][, callback])` + @@ -343,6 +355,7 @@ socket.bind({ ``` ### `socket.close([callback])` + @@ -353,6 +366,7 @@ Close the underlying socket and stop listening for data on it. If a callback is provided, it is added as a listener for the [`'close'`][] event. ### `socket.connect(port[, address][, callback])` + @@ -372,6 +386,7 @@ is emitted and the optional `callback` function is called. In case of failure, the `callback` is called or, failing this, an `'error'` event is emitted. ### `socket.disconnect()` + @@ -382,6 +397,7 @@ disconnected socket will result in an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] exception. ### `socket.dropMembership(multicastAddress[, multicastInterface])` + @@ -398,6 +414,7 @@ If `multicastInterface` is not specified, the operating system will attempt to drop membership on all valid interfaces. ### `socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])` + @@ -427,6 +445,7 @@ added: v8.7.0 This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. ### `socket.getSendBufferSize()` + @@ -436,6 +455,7 @@ added: v8.7.0 This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. ### `socket.ref()` + @@ -454,6 +474,7 @@ The `socket.ref()` method returns a reference to the socket so calls can be chained. ### `socket.remoteAddress()` + @@ -465,6 +486,7 @@ endpoint. This method throws an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][] exception if the socket is not connected. ### `socket.send(msg[, offset, length][, port][, address][, callback])` + @@ -665,16 +688,17 @@ packets may be sent to a local interface's broadcast address. This method throws `EBADF` if called on an unbound socket. ### `socket.setMulticastInterface(multicastInterface)` + * `multicastInterface` {string} -*All references to scope in this section are referring to +_All references to scope in this section are referring to [IPv6 Zone Indices][], which are defined by [RFC 4007][]. In string form, an IP with a scope index is written as `'IP%scope'` where scope is an interface name -or interface number.* +or interface number._ Sets the default outgoing multicast interface of the socket to a chosen interface or back to system interface selection. The `multicastInterface` must @@ -715,6 +739,7 @@ socket.bind(1234, () => { ``` #### Example: IPv4 outgoing multicast interface + All systems use an IP of the host on the desired physical interface: ```js @@ -727,10 +752,10 @@ socket.bind(1234, () => { #### Call results -A call on a socket that is not ready to send or no longer open may throw a *Not -running* [`Error`][]. +A call on a socket that is not ready to send or no longer open may throw a _Not +running_ [`Error`][]. -If `multicastInterface` can not be parsed into an IP then an *EINVAL* +If `multicastInterface` can not be parsed into an IP then an _EINVAL_ [`System Error`][] is thrown. On IPv4, if `multicastInterface` is a valid address but does not match any @@ -745,6 +770,7 @@ used to return control of the sockets default outgoing interface to the system for future multicast packets. ### `socket.setMulticastLoopback(flag)` + @@ -757,6 +783,7 @@ multicast packets will also be received on the local interface. This method throws `EBADF` if called on an unbound socket. ### `socket.setMulticastTTL(ttl)` + @@ -774,6 +801,7 @@ The `ttl` argument may be between 0 and 255. The default on most systems is `1`. This method throws `EBADF` if called on an unbound socket. ### `socket.setRecvBufferSize(size)` + @@ -786,6 +814,7 @@ in bytes. This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. ### `socket.setSendBufferSize(size)` + @@ -798,6 +827,7 @@ in bytes. This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket. ### `socket.setTTL(ttl)` + @@ -816,6 +846,7 @@ is 64. This method throws `EBADF` if called on an unbound socket. ### `socket.unref()` + @@ -836,6 +867,7 @@ chained. ## `dgram` module functions ### `dgram.createSocket(options[, callback])` + diff --git a/doc/api/dns.md b/doc/api/dns.md index ac7f7156043184..48796f9c846f30 100644 --- a/doc/api/dns.md +++ b/doc/api/dns.md @@ -52,6 +52,7 @@ dns.resolve4('archive.org', (err, addresses) => { See the [Implementation considerations section][] for more information. ## Class: `dns.Resolver` + @@ -94,6 +95,7 @@ The following methods from the `dns` module are available: * [`resolver.setServers()`][`dns.setServers()`] ### `Resolver([options])` + @@ -123,6 +126,7 @@ 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])` + @@ -144,17 +148,19 @@ servers, and the v6 local address when making requests to IPv6 DNS servers. The `rrtype` of resolution requests has no impact on the local address used. ## `dns.getServers()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array of IP address strings, formatted according to [RFC 5952][], that are currently configured for DNS resolution. A string will include a port section if a custom port is used. + ```js [ '4.4.4.4', @@ -165,6 +171,7 @@ section if a custom port is used. ``` ## `dns.lookup(hostname[, options], callback)` + @@ -297,6 +306,7 @@ If this method is invoked as its [`util.promisify()`][]ed version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. ## `dns.resolve(hostname[, rrtype], callback)` + @@ -305,15 +315,15 @@ added: v0.1.27 * `rrtype` {string} Resource record type. **Default:** `'A'`. * `callback` {Function} * `err` {Error} - * `records` {string[] | Object[] | Object} + * `records` {string\[] | Object\[] | Object} Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource records. The type and structure of individual results varies based on `rrtype`: -| `rrtype` | `records` contains | Result type | Shorthand method | -|-----------|--------------------------------|-------------|--------------------------| +| `rrtype` | `records` contains | Result type | Shorthand method | +| --------- | ------------------------------ | ----------- | ------------------------ | | `'A'` | IPv4 addresses (default) | {string} | [`dns.resolve4()`][] | | `'AAAA'` | IPv6 addresses | {string} | [`dns.resolve6()`][] | | `'ANY'` | any records | {Object} | [`dns.resolveAny()`][] | @@ -325,12 +335,13 @@ records. The type and structure of individual results varies based on `rrtype`: | `'PTR'` | pointer records | {string} | [`dns.resolvePtr()`][] | | `'SOA'` | start of authority records | {Object} | [`dns.resolveSoa()`][] | | `'SRV'` | service records | {Object} | [`dns.resolveSrv()`][] | -| `'TXT'` | text records | {string[]} | [`dns.resolveTxt()`][] | +| `'TXT'` | text records | {string\[]} | [`dns.resolveTxt()`][] | On error, `err` is an [`Error`][] object, where `err.code` is one of the [DNS error codes](). ## `dns.resolve4(hostname[, options], callback)` + + ```js [ { type: 'A', address: '127.0.0.1', ttl: 299 }, { type: 'CNAME', value: 'example.com' }, @@ -429,6 +442,7 @@ queries. It may be better to call individual methods like [`dns.resolve4()`][], [`dns.resolveMx()`][], and so on. For more details, see [RFC 8482][]. ## `dns.resolveCname(hostname, callback)` + @@ -436,7 +450,7 @@ added: v0.3.2 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {string[]} + * `addresses` {string\[]} Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function @@ -444,6 +458,7 @@ will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). ## `dns.resolveCaa(hostname, callback)` + @@ -451,7 +466,7 @@ added: v15.0.0 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `records` {Object[]} + * `records` {Object\[]} Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function @@ -460,6 +475,7 @@ available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). ## `dns.resolveMx(hostname, callback)` + @@ -467,7 +483,7 @@ added: v0.1.27 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {Object[]} + * `addresses` {Object\[]} Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will @@ -475,6 +491,7 @@ contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). ## `dns.resolveNaptr(hostname, callback)` + @@ -482,7 +499,7 @@ added: v0.9.12 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {Object[]} + * `addresses` {Object\[]} Uses the DNS protocol to resolve regular expression based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` @@ -496,6 +513,7 @@ function will contain an array of objects with the following properties: * `preference` + ```js { flags: 's', @@ -508,6 +526,7 @@ function will contain an array of objects with the following properties: ``` ## `dns.resolveNs(hostname, callback)` + @@ -515,7 +534,7 @@ added: v0.1.90 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {string[]} + * `addresses` {string\[]} Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will @@ -523,6 +542,7 @@ contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). ## `dns.resolvePtr(hostname, callback)` + @@ -530,13 +550,14 @@ added: v6.0.0 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {string[]} + * `addresses` {string\[]} Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will be an array of strings containing the reply records. ## `dns.resolveSoa(hostname, callback)` + @@ -559,6 +580,7 @@ be an object with the following properties: * `minttl` + ```js { nsname: 'ns.example.com', @@ -572,6 +594,7 @@ be an object with the following properties: ``` ## `dns.resolveSrv(hostname, callback)` + @@ -579,7 +602,7 @@ added: v0.1.27 * `hostname` {string} * `callback` {Function} * `err` {Error} - * `addresses` {Object[]} + * `addresses` {Object\[]} Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will @@ -591,6 +614,7 @@ be an array of objects with the following properties: * `name` + ```js { priority: 10, @@ -601,15 +625,18 @@ be an array of objects with the following properties: ``` ## `dns.resolveTxt(hostname, callback)` + + * `hostname` {string} * `callback` {Function} * `err` {Error} - * `records` <string[][]> + * `records` \ + Uses the DNS protocol to resolve text queries (`TXT` records) for the @@ -620,6 +647,7 @@ one record. Depending on the use case, these could be either joined together or treated separately. ## `dns.reverse(ip, callback)` + @@ -627,7 +655,7 @@ added: v0.1.16 * `ip` {string} * `callback` {Function} * `err` {Error} - * `hostnames` {string[]} + * `hostnames` {string\[]} Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of host names. @@ -636,6 +664,7 @@ On error, `err` is an [`Error`][] object, where `err.code` is one of the [DNS error codes][]. ## `dns.setDefaultResultOrder(order)` + @@ -644,6 +673,7 @@ added: v16.4.0 Set the default value of `verbatim` in [`dns.lookup()`][] and [`dnsPromises.lookup()`][]. The value could be: + * `ipv4first`: sets default `verbatim` `false`. * `verbatim`: sets default `verbatim` `true`. @@ -653,11 +683,12 @@ priority than [`--dns-result-order`][]. When using [worker threads][], dns orders in workers. ## `dns.setServers(servers)` + -* `servers` {string[]} array of [RFC 5952][] formatted addresses +* `servers` {string\[]} array of [RFC 5952][] formatted addresses Sets the IP address and port of servers to be used when performing DNS resolution. The `servers` argument is an array of [RFC 5952][] formatted @@ -678,17 +709,18 @@ The `dns.setServers()` method must not be called while a DNS query is in progress. The [`dns.setServers()`][] method affects only [`dns.resolve()`][], -`dns.resolve*()` and [`dns.reverse()`][] (and specifically *not* +`dns.resolve*()` and [`dns.reverse()`][] (and specifically _not_ [`dns.lookup()`][]). This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). That is, if attempting to resolve with the first server provided results in a -`NOTFOUND` error, the `resolve()` method will *not* attempt to resolve with +`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with subsequent servers provided. Fallback DNS servers will only be used if the earlier ones time out or result in some other error. ## DNS promises API + @@ -754,6 +787,7 @@ The following methods from the `dnsPromises` API are available: * [`resolver.setServers()`][`dnsPromises.setServers()`] ### `resolver.cancel()` + @@ -762,17 +796,19 @@ Cancel all outstanding DNS queries made by this resolver. The corresponding promises will be rejected with an error with code `ECANCELLED`. ### `dnsPromises.getServers()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array of IP address strings, formatted according to [RFC 5952][], that are currently configured for DNS resolution. A string will include a port section if a custom port is used. + ```js [ '4.4.4.4', @@ -783,6 +819,7 @@ section if a custom port is used. ``` ### `dnsPromises.lookup(hostname[, options])` + @@ -849,6 +886,7 @@ dnsPromises.lookup('example.com', options).then((result) => { ``` ### `dnsPromises.lookupService(address, port)` + @@ -875,6 +913,7 @@ dnsPromises.lookupService('127.0.0.1', 22).then((result) => { ``` ### `dnsPromises.resolve(hostname[, rrtype])` + @@ -887,12 +926,12 @@ of the resource records. When successful, the `Promise` is resolved with an array of resource records. The type and structure of individual results vary based on `rrtype`: -| `rrtype` | `records` contains | Result type | Shorthand method | -|-----------|--------------------------------|-------------|--------------------------| +| `rrtype` | `records` contains | Result type | Shorthand method | +| --------- | ------------------------------ | ----------- | -------------------------------- | | `'A'` | IPv4 addresses (default) | {string} | [`dnsPromises.resolve4()`][] | | `'AAAA'` | IPv6 addresses | {string} | [`dnsPromises.resolve6()`][] | | `'ANY'` | any records | {Object} | [`dnsPromises.resolveAny()`][] | -| `'CAA'` | CA authorization records | {Object} | [`dnsPromises.resolveCaa()`][] | +| `'CAA'` | CA authorization records | {Object} | [`dnsPromises.resolveCaa()`][] | | `'CNAME'` | canonical name records | {string} | [`dnsPromises.resolveCname()`][] | | `'MX'` | mail exchange records | {Object} | [`dnsPromises.resolveMx()`][] | | `'NAPTR'` | name authority pointer records | {Object} | [`dnsPromises.resolveNaptr()`][] | @@ -900,12 +939,13 @@ based on `rrtype`: | `'PTR'` | pointer records | {string} | [`dnsPromises.resolvePtr()`][] | | `'SOA'` | start of authority records | {Object} | [`dnsPromises.resolveSoa()`][] | | `'SRV'` | service records | {Object} | [`dnsPromises.resolveSrv()`][] | -| `'TXT'` | text records | {string[]} | [`dnsPromises.resolveTxt()`][] | +| `'TXT'` | text records | {string\[]} | [`dnsPromises.resolveTxt()`][] | On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` is one of the [DNS error codes](). ### `dnsPromises.resolve4(hostname[, options])` + @@ -922,6 +962,7 @@ Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). ### `dnsPromises.resolve6(hostname[, options])` + @@ -938,6 +979,7 @@ Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the addresses. ### `dnsPromises.resolveAny(hostname)` + @@ -950,22 +992,23 @@ records. Each object has a property `type` that indicates the type of the current record. And depending on the `type`, additional properties will be present on the object: -| Type | Properties | -|------|------------| -| `'A'` | `address`/`ttl` | -| `'AAAA'` | `address`/`ttl` | -| `'CNAME'` | `value` | -| `'MX'` | Refer to [`dnsPromises.resolveMx()`][] | -| `'NAPTR'` | Refer to [`dnsPromises.resolveNaptr()`][] | -| `'NS'` | `value` | -| `'PTR'` | `value` | -| `'SOA'` | Refer to [`dnsPromises.resolveSoa()`][] | -| `'SRV'` | Refer to [`dnsPromises.resolveSrv()`][] | -| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dnsPromises.resolveTxt()`][], e.g. `{ entries: ['...'], type: 'TXT' }` | +| Type | Properties | +| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `'A'` | `address`/`ttl` | +| `'AAAA'` | `address`/`ttl` | +| `'CNAME'` | `value` | +| `'MX'` | Refer to [`dnsPromises.resolveMx()`][] | +| `'NAPTR'` | Refer to [`dnsPromises.resolveNaptr()`][] | +| `'NS'` | `value` | +| `'PTR'` | `value` | +| `'SOA'` | Refer to [`dnsPromises.resolveSoa()`][] | +| `'SRV'` | Refer to [`dnsPromises.resolveSrv()`][] | +| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dnsPromises.resolveTxt()`][], e.g. `{ entries: ['...'], type: 'TXT' }` | Here is an example of the result object: + ```js [ { type: 'A', address: '127.0.0.1', ttl: 299 }, { type: 'CNAME', value: 'example.com' }, @@ -983,6 +1026,7 @@ Here is an example of the result object: ``` ### `dnsPromises.resolveCaa(hostname)` + @@ -996,6 +1040,7 @@ certification authority authorization records available for the `hostname` 'pki.example.com'}]`). ### `dnsPromises.resolveCname(hostname)` + @@ -1007,6 +1052,7 @@ the `Promise` is resolved with an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). ### `dnsPromises.resolveMx(hostname)` + @@ -1019,6 +1065,7 @@ containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). ### `dnsPromises.resolveNaptr(hostname)` + @@ -1037,6 +1084,7 @@ of objects with the following properties: * `preference` + ```js { flags: 's', @@ -1049,6 +1097,7 @@ of objects with the following properties: ``` ### `dnsPromises.resolveNs(hostname)` + @@ -1061,6 +1110,7 @@ records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). ### `dnsPromises.resolvePtr(hostname)` + @@ -1072,6 +1122,7 @@ Uses the DNS protocol to resolve pointer records (`PTR` records) for the containing the reply records. ### `dnsPromises.resolveSoa(hostname)` + @@ -1091,6 +1142,7 @@ following properties: * `minttl` + ```js { nsname: 'ns.example.com', @@ -1104,6 +1156,7 @@ following properties: ``` ### `dnsPromises.resolveSrv(hostname)` + @@ -1120,6 +1173,7 @@ the following properties: * `name` + ```js { priority: 10, @@ -1130,6 +1184,7 @@ the following properties: ``` ### `dnsPromises.resolveTxt(hostname)` + @@ -1144,6 +1199,7 @@ one record. Depending on the use case, these could be either joined together or treated separately. ### `dnsPromises.reverse(ip)` + @@ -1157,6 +1213,7 @@ On error, the `Promise` is rejected with an [`Error`][] object, where `err.code` is one of the [DNS error codes](). ### `dnsPromises.setDefaultResultOrder(order)` + @@ -1165,6 +1222,7 @@ added: v16.4.0 Set the default value of `verbatim` in [`dns.lookup()`][] and [`dnsPromises.lookup()`][]. The value could be: + * `ipv4first`: sets default `verbatim` `false`. * `verbatim`: sets default `verbatim` `true`. @@ -1174,11 +1232,12 @@ higher priority than [`--dns-result-order`][]. When using [worker threads][], default dns orders in workers. ### `dnsPromises.setServers(servers)` + -* `servers` {string[]} array of [RFC 5952][] formatted addresses +* `servers` {string\[]} array of [RFC 5952][] formatted addresses Sets the IP address and port of servers to be used when performing DNS resolution. The `servers` argument is an array of [RFC 5952][] formatted @@ -1201,7 +1260,7 @@ progress. This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). That is, if attempting to resolve with the first server provided results in a -`NOTFOUND` error, the `resolve()` method will *not* attempt to resolve with +`NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with subsequent servers provided. Fallback DNS servers will only be used if the earlier ones time out or result in some other error. diff --git a/doc/api/documentation.md b/doc/api/documentation.md index 9100354b361644..be5e7671f8d18c 100644 --- a/doc/api/documentation.md +++ b/doc/api/documentation.md @@ -51,11 +51,13 @@ modifications occur. To avoid surprises, use of an Experimental feature may need a command-line flag. Experimental features may also emit a [warning][]. ## Stability overview + ## JSON output + diff --git a/doc/api/domain.md b/doc/api/domain.md index 02833e36e7ba1c..9552b3bbcd478c 100644 --- a/doc/api/domain.md +++ b/doc/api/domain.md @@ -1,4 +1,5 @@ # Domain + + + ```js const fs = require('fs'); fs.readFile('a file that does not exist', (err, data) => { @@ -101,7 +102,7 @@ and [event emitter-based][] APIs, which themselves represent a series of asynchronous operations over time (as opposed to a single operation that may pass or fail). -For *all* [`EventEmitter`][] objects, if an `'error'` event handler is not +For _all_ [`EventEmitter`][] objects, if an `'error'` event handler is not provided, the error will be thrown, causing the Node.js process to report an uncaught exception and crash unless either: The [`domain`][domains] module is used appropriately or a handler has been registered for the @@ -118,8 +119,8 @@ setImmediate(() => { }); ``` -Errors generated in this way *cannot* be intercepted using `try…catch` as -they are thrown *after* the calling code has already exited. +Errors generated in this way _cannot_ be intercepted using `try…catch` as +they are thrown _after_ the calling code has already exited. Developers must refer to the documentation for each method to determine exactly how errors raised by those methods are propagated. @@ -199,7 +200,7 @@ provided text message. If an object is passed as `message`, the text message is generated by calling `message.toString()`. The `error.stack` property will represent the point in the code at which `new Error()` was called. Stack traces are dependent on [V8's stack trace API][]. Stack traces extend only to either -(a) the beginning of *synchronous code execution*, or (b) the number of frames +(a) the beginning of _synchronous code execution_, or (b) the number of frames given by the property `Error.stackTraceLimit`, whichever is smaller. ### `Error.captureStackTrace(targetObject[, constructorOpt])` @@ -247,7 +248,7 @@ collected by a stack trace (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`). The default value is `10` but may be set to any valid JavaScript number. Changes -will affect any stack trace captured *after* the value has been changed. +will affect any stack trace captured _after_ the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames. @@ -269,7 +270,7 @@ about specific codes. The `error.message` property is the string description of the error as set by calling `new Error(message)`. The `message` passed to the constructor will also appear in the first line of the stack trace of the `Error`, however changing -this property after the `Error` object is created *may not* change the first +this property after the `Error` object is created _may not_ change the first line of the stack trace (for example, when `error.stack` is read before this property is changed). @@ -341,7 +342,7 @@ The location information will be one of: * `native`, if the frame represents a call internal to V8 (as in `[].forEach`). * `plain-filename.js:line:column`, if the frame represents a call internal - to Node.js. + to Node.js. * `/absolute/path/to/file.js:line:column`, if the frame represents a call in a user program, or its dependencies. @@ -372,7 +373,7 @@ require('net').connect(-1); // Throws "RangeError: "port" option should be >= 0 and < 65536: -1" ``` -Node.js will generate and throw `RangeError` instances *immediately* as a form +Node.js will generate and throw `RangeError` instances _immediately_ as a form of argument validation. ## Class: `ReferenceError` @@ -570,7 +571,7 @@ require('url').parse(() => { }); // Throws TypeError, since it expected a string. ``` -Node.js will generate and throw `TypeError` instances *immediately* as a form +Node.js will generate and throw `TypeError` instances _immediately_ as a form of argument validation. ## Exceptions vs. errors @@ -580,11 +581,11 @@ of argument validation. 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 that these values are instances of `Error` or classes which inherit from -`Error`, all exceptions thrown by Node.js or the JavaScript runtime *will* be +`Error`, all exceptions thrown by Node.js or the JavaScript runtime _will_ be instances of `Error`. -Some exceptions are *unrecoverable* at the JavaScript layer. Such exceptions -will *always* cause the Node.js process to crash. Examples include `assert()` +Some exceptions are _unrecoverable_ at the JavaScript layer. Such exceptions +will _always_ cause the Node.js process to crash. Examples include `assert()` checks or `abort()` calls in the C++ layer. ## OpenSSL errors @@ -611,13 +612,17 @@ The OpenSSL library the error originates in. A human-readable string describing the reason for the error. + ## Node.js error codes + ### `ABORT_ERR` + + Used when an operation has been aborted (typically using an `AbortController`). APIs _not_ using `AbortSignal`s typically do not raise an error with this code. @@ -626,6 +631,7 @@ This code does not use the regular `ERR_*` convention Node.js errors use in order to be compatible with the web platform's `AbortError`. + ### `ERR_AMBIGUOUS_ARGUMENT` A function argument is being used in a way that suggests that the function @@ -636,12 +642,14 @@ is the expected message rather than the message the `AssertionError` will display if `block` does not throw. + ### `ERR_ARG_NOT_ITERABLE` An iterable argument (i.e. a value that works with `for...of` loops) was required, but not provided to a Node.js API. + ### `ERR_ASSERTION` A special type of error that can be triggered whenever Node.js detects an @@ -649,28 +657,33 @@ exceptional logic violation that should never occur. These are raised typically by the `assert` module. + ### `ERR_ASYNC_CALLBACK` An attempt was made to register something that is not a function as an `AsyncHooks` callback. + ### `ERR_ASYNC_TYPE` The type of an asynchronous resource was invalid. Users are also able to define their own types if using the public embedder API. + ### `ERR_BROTLI_COMPRESSION_FAILED` Data passed to a Brotli stream was not successfully compressed. + ### `ERR_BROTLI_INVALID_PARAM` An invalid parameter key was passed during construction of a Brotli stream. + ### `ERR_BUFFER_CONTEXT_NOT_AVAILABLE` An attempt was made to create a Node.js `Buffer` instance from addon or embedder @@ -684,39 +697,47 @@ prototype of the resulting object. `Uint8Array`s are generally accepted in all Node.js core APIs where `Buffer`s are; they are available in all Contexts. + ### `ERR_BUFFER_OUT_OF_BOUNDS` An operation outside the bounds of a `Buffer` was attempted. + ### `ERR_BUFFER_TOO_LARGE` An attempt has been made to create a `Buffer` larger than the maximum allowed size. + ### `ERR_CANNOT_WATCH_SIGINT` Node.js was unable to watch for the `SIGINT` signal. + ### `ERR_CHILD_CLOSED_BEFORE_REPLY` A child process was closed before the parent received a reply. + ### `ERR_CHILD_PROCESS_IPC_REQUIRED` Used when a child process is being forked without specifying an IPC channel. + ### `ERR_CHILD_PROCESS_STDIO_MAXBUFFER` Used when the main process is trying to read data from the child process's STDERR/STDOUT, and the data's length is longer than the `maxBuffer` option. + ### `ERR_CLOSED_MESSAGE_PORT` + @@ -746,11 +770,13 @@ added: v12.5.0 A class constructor was called that is not callable. + ### `ERR_CONSTRUCT_CALL_REQUIRED` A constructor for a class was called without `new`. + ### `ERR_CONTEXT_NOT_INITIALIZED` The vm context passed into the API is not yet initialized. This could happen @@ -759,18 +785,21 @@ context, for example, when the allocation fails or the maximum call stack size is reached when the context is created. + ### `ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED` A client certificate engine was requested that is not supported by the version of OpenSSL being used. + ### `ERR_CRYPTO_ECDH_INVALID_FORMAT` An invalid value for the `format` argument was passed to the `crypto.ECDH()` class `getPublicKey()` method. + ### `ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` An invalid value for the `key` argument has been passed to the @@ -778,46 +807,55 @@ An invalid value for the `key` argument has been passed to the key lies outside of the elliptic curve. + ### `ERR_CRYPTO_ENGINE_UNKNOWN` An invalid crypto engine identifier was passed to [`require('crypto').setEngine()`][]. + ### `ERR_CRYPTO_FIPS_FORCED` The [`--force-fips`][] command-line argument was used but there was an attempt to enable or disable FIPS mode in the `crypto` module. + ### `ERR_CRYPTO_FIPS_UNAVAILABLE` An attempt was made to enable or disable FIPS mode, but FIPS mode was not available. + ### `ERR_CRYPTO_HASH_FINALIZED` [`hash.digest()`][] was called multiple times. The `hash.digest()` method must be called no more than one time per instance of a `Hash` object. + ### `ERR_CRYPTO_HASH_UPDATE_FAILED` [`hash.update()`][] failed for any reason. This should rarely, if ever, happen. + ### `ERR_CRYPTO_INCOMPATIBLE_KEY` The given crypto keys are incompatible with the attempted operation. + ### `ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS` The selected public or private key encoding is incompatible with other options. + ### `ERR_CRYPTO_INITIALIZATION_FAILED` + @@ -825,7 +863,9 @@ added: v15.0.0 Initialization of the crypto subsystem failed. + ### `ERR_CRYPTO_INVALID_AUTH_TAG` + @@ -833,7 +873,9 @@ added: v15.0.0 An invalid authentication tag was provided. + ### `ERR_CRYPTO_INVALID_COUNTER` + @@ -841,7 +883,9 @@ added: v15.0.0 An invalid counter was provided for a counter-mode cipher. + ### `ERR_CRYPTO_INVALID_CURVE` + @@ -849,12 +893,15 @@ added: v15.0.0 An invalid elliptic-curve was provided. + ### `ERR_CRYPTO_INVALID_DIGEST` An invalid [crypto digest algorithm][] was specified. + ### `ERR_CRYPTO_INVALID_IV` + @@ -862,7 +909,9 @@ added: v15.0.0 An invalid initialization vector was provided. + ### `ERR_CRYPTO_INVALID_JWK` + @@ -870,12 +919,15 @@ added: v15.0.0 An invalid JSON Web Key was provided. + ### `ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE` The given crypto key object's type is invalid for the attempted operation. + ### `ERR_CRYPTO_INVALID_KEYLEN` + @@ -883,7 +935,9 @@ added: v15.0.0 An invalid key length was provided. + ### `ERR_CRYPTO_INVALID_KEYPAIR` + @@ -891,7 +945,9 @@ added: v15.0.0 An invalid key pair was provided. + ### `ERR_CRYPTO_INVALID_KEYTYPE` + @@ -899,7 +955,9 @@ added: v15.0.0 An invalid key type was provided. + ### `ERR_CRYPTO_INVALID_MESSAGELEN` + @@ -907,7 +965,9 @@ added: v15.0.0 An invalid message length was provided. + ### `ERR_CRYPTO_INVALID_SCRYPT_PARAMS` + @@ -915,13 +975,16 @@ added: v15.0.0 Invalid scrypt algorithm parameters were provided. + ### `ERR_CRYPTO_INVALID_STATE` A crypto method was used on an object that was in an invalid state. For instance, calling [`cipher.getAuthTag()`][] before calling `cipher.final()`. + ### `ERR_CRYPTO_INVALID_TAG_LENGTH` + @@ -929,7 +992,9 @@ added: v15.0.0 An invalid authentication tag length was provided. + ### `ERR_CRYPTO_JOB_INIT_FAILED` + @@ -937,19 +1002,23 @@ added: v15.0.0 Initialization of an asynchronous crypto operation failed. + ### `ERR_CRYPTO_JWK_UNSUPPORTED_CURVE` Key's Elliptic Curve is not registered for use in the [JSON Web Key Elliptic Curve Registry][]. + ### `ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE` Key's Asymmetric Key Type is not registered for use in the [JSON Web Key Types Registry][]. + ### `ERR_CRYPTO_OPERATION_FAILED` + @@ -957,47 +1026,56 @@ added: v15.0.0 A crypto operation failed for an otherwise unspecified reason. + ### `ERR_CRYPTO_PBKDF2_ERROR` The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide more details and therefore neither does Node.js. + ### `ERR_CRYPTO_SCRYPT_INVALID_PARAMETER` One or more [`crypto.scrypt()`][] or [`crypto.scryptSync()`][] parameters are outside their legal range. + ### `ERR_CRYPTO_SCRYPT_NOT_SUPPORTED` Node.js was compiled without `scrypt` support. Not possible with the official release binaries but can happen with custom builds, including distro builds. + ### `ERR_CRYPTO_SIGN_KEY_REQUIRED` A signing `key` was not provided to the [`sign.sign()`][] method. + ### `ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH` [`crypto.timingSafeEqual()`][] was called with `Buffer`, `TypedArray`, or `DataView` arguments of different lengths. + ### `ERR_CRYPTO_UNKNOWN_CIPHER` An unknown cipher was specified. + ### `ERR_CRYPTO_UNKNOWN_DH_GROUP` An unknown Diffie-Hellman group name was given. See [`crypto.getDiffieHellman()`][] for a list of valid group names. + ### `ERR_CRYPTO_UNSUPPORTED_OPERATION` + @@ -1005,7 +1083,9 @@ added: v15.0.0 An attempt to invoke an unsupported crypto operation was made. + ### `ERR_DEBUGGER_ERROR` + @@ -1013,7 +1093,9 @@ added: v16.4.0 An error occurred with the [debugger][]. + ### `ERR_DEBUGGER_STARTUP_ERROR` + @@ -1021,7 +1103,9 @@ added: v16.4.0 The [debugger][] timed out waiting for the required host/port to be free. + ### `ERR_DLOPEN_DISABLED` + @@ -1029,7 +1113,9 @@ added: v16.10.0 Loading native addons has been disabled using [`--no-addons`][]. + ### `ERR_DLOPEN_FAILED` + @@ -1037,12 +1123,15 @@ added: v15.0.0 A call to `process.dlopen()` failed. + ### `ERR_DIR_CLOSED` The [`fs.Dir`][] was previously closed. + ### `ERR_DIR_CONCURRENT_OPERATION` + @@ -1051,11 +1140,13 @@ A synchronous read or close call was attempted on an [`fs.Dir`][] which has ongoing asynchronous operations. + ### `ERR_DNS_SET_SERVERS_FAILED` `c-ares` failed to set the DNS server. + ### `ERR_DOMAIN_CALLBACK_NOT_AVAILABLE` The `domain` module was not usable since it could not establish the required @@ -1064,6 +1155,7 @@ error handling hooks, because earlier point in time. + ### `ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE` [`process.setUncaughtExceptionCaptureCallback()`][] could not be called @@ -1073,28 +1165,33 @@ The stack trace is extended to include the point in time at which the `domain` module had been loaded. + ### `ERR_ENCODING_INVALID_ENCODED_DATA` Data provided to `TextDecoder()` API was invalid according to the encoding provided. + ### `ERR_ENCODING_NOT_SUPPORTED` Encoding provided to `TextDecoder()` API was not one of the [WHATWG Supported Encodings][]. + ### `ERR_EVAL_ESM_CANNOT_PRINT` `--print` cannot be used with ESM input. + ### `ERR_EVENT_RECURSION` Thrown when an attempt is made to recursively dispatch an event on `EventTarget`. + ### `ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE` The JS execution context is not associated with a Node.js environment. @@ -1102,13 +1199,16 @@ This may occur when Node.js is used as an embedded library and some hooks for the JS engine are not set up properly. + ### `ERR_FALSY_VALUE_REJECTION` A `Promise` that was callbackified via `util.callbackify()` was rejected with a falsy value. + ### `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` + @@ -1117,7 +1217,9 @@ Used when a feature that is not available to the current platform which is running Node.js is used. + ### `ERR_FS_CP_DIR_TO_NON_DIR` + @@ -1126,7 +1228,9 @@ An attempt was made to copy a directory to a non-directory (file, symlink, etc.) using [`fs.cp()`][]. + ### `ERR_FS_CP_EEXIST` + @@ -1135,7 +1239,9 @@ An attempt was made to copy over a file that already existed with [`fs.cp()`][], with the `force` and `errorOnExist` set to `true`. + ### `ERR_FS_CP_EINVAL` + @@ -1143,7 +1249,9 @@ added: v16.7.0 When using [`fs.cp()`][], `src` or `dest` pointed to an invalid path. + ### `ERR_FS_CP_FIFO_PIPE` + @@ -1151,7 +1259,9 @@ added: v16.7.0 An attempt was made to copy a named pipe with [`fs.cp()`][]. + ### `ERR_FS_CP_NON_DIR_TO_DIR` + @@ -1160,7 +1270,9 @@ An attempt was made to copy a non-directory (file, symlink, etc.) to a directory using [`fs.cp()`][]. + ### `ERR_FS_CP_SOCKET` + @@ -1168,7 +1280,9 @@ added: v16.7.0 An attempt was made to copy to a socket with [`fs.cp()`][]. + ### `ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY` + @@ -1177,7 +1291,9 @@ When using [`fs.cp()`][], a symlink in `dest` pointed to a subdirectory of `src`. + ### `ERR_FS_CP_UNKNOWN` + @@ -1185,137 +1301,162 @@ added: v16.7.0 An attempt was made to copy to an unknown file type with [`fs.cp()`][]. + ### `ERR_FS_EISDIR` Path is a directory. + ### `ERR_FS_FILE_TOO_LARGE` An attempt has been made to read a file whose size is larger than the maximum allowed size for a `Buffer`. + ### `ERR_FS_INVALID_SYMLINK_TYPE` An invalid symlink type was passed to the [`fs.symlink()`][] or [`fs.symlinkSync()`][] methods. + ### `ERR_HTTP_HEADERS_SENT` An attempt was made to add more headers after the headers had already been sent. + ### `ERR_HTTP_INVALID_HEADER_VALUE` An invalid HTTP header value was specified. + ### `ERR_HTTP_INVALID_STATUS_CODE` Status code was outside the regular status code range (100-999). + ### `ERR_HTTP_REQUEST_TIMEOUT` The client has not sent the entire request within the allowed time. + ### `ERR_HTTP_SOCKET_ENCODING` Changing the socket encoding is not allowed per [RFC 7230 Section 3][]. + ### `ERR_HTTP_TRAILER_INVALID` The `Trailer` header was set even though the transfer encoding does not support that. + ### `ERR_HTTP2_ALTSVC_INVALID_ORIGIN` HTTP/2 ALTSVC frames require a valid origin. + ### `ERR_HTTP2_ALTSVC_LENGTH` HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes. + ### `ERR_HTTP2_CONNECT_AUTHORITY` For HTTP/2 requests using the `CONNECT` method, the `:authority` pseudo-header is required. + ### `ERR_HTTP2_CONNECT_PATH` For HTTP/2 requests using the `CONNECT` method, the `:path` pseudo-header is forbidden. + ### `ERR_HTTP2_CONNECT_SCHEME` For HTTP/2 requests using the `CONNECT` method, the `:scheme` pseudo-header is forbidden. + ### `ERR_HTTP2_ERROR` A non-specific HTTP/2 error has occurred. + ### `ERR_HTTP2_GOAWAY_SESSION` New HTTP/2 Streams may not be opened after the `Http2Session` has received a `GOAWAY` frame from the connected peer. + ### `ERR_HTTP2_HEADER_SINGLE_VALUE` Multiple values were provided for an HTTP/2 header field that was required to have only a single value. + ### `ERR_HTTP2_HEADERS_AFTER_RESPOND` An additional headers was specified after an HTTP/2 response was initiated. + ### `ERR_HTTP2_HEADERS_SENT` An attempt was made to send multiple response headers. + ### `ERR_HTTP2_INFO_STATUS_NOT_ALLOWED` Informational HTTP status codes (`1xx`) may not be set as the response status code on HTTP/2 responses. + ### `ERR_HTTP2_INVALID_CONNECTION_HEADERS` HTTP/1 connection specific headers are forbidden to be used in HTTP/2 requests and responses. + ### `ERR_HTTP2_INVALID_HEADER_VALUE` An invalid HTTP/2 header value was specified. + ### `ERR_HTTP2_INVALID_INFO_STATUS` An invalid HTTP informational status code has been specified. Informational status codes must be an integer between `100` and `199` (inclusive). + ### `ERR_HTTP2_INVALID_ORIGIN` HTTP/2 `ORIGIN` frames require a valid origin. + ### `ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH` Input `Buffer` and `Uint8Array` instances passed to the @@ -1323,28 +1464,33 @@ Input `Buffer` and `Uint8Array` instances passed to the six. + ### `ERR_HTTP2_INVALID_PSEUDOHEADER` Only valid HTTP/2 pseudoheaders (`:status`, `:path`, `:authority`, `:scheme`, and `:method`) may be used. + ### `ERR_HTTP2_INVALID_SESSION` An action was performed on an `Http2Session` object that had already been destroyed. + ### `ERR_HTTP2_INVALID_SETTING_VALUE` An invalid value has been specified for an HTTP/2 setting. + ### `ERR_HTTP2_INVALID_STREAM` An operation was performed on a stream that had already been destroyed. + ### `ERR_HTTP2_MAX_PENDING_SETTINGS_ACK` Whenever an HTTP/2 `SETTINGS` frame is sent to a connected peer, the peer is @@ -1354,68 +1500,80 @@ be sent at any given time. This error code is used when that limit has been reached. + ### `ERR_HTTP2_NESTED_PUSH` An attempt was made to initiate a new push stream from within a push stream. Nested push streams are not permitted. + ### `ERR_HTTP2_NO_MEM` Out of memory when using the `http2session.setLocalWindowSize(windowSize)` API. + ### `ERR_HTTP2_NO_SOCKET_MANIPULATION` An attempt was made to directly manipulate (read, write, pause, resume, etc.) a socket attached to an `Http2Session`. + ### `ERR_HTTP2_ORIGIN_LENGTH` HTTP/2 `ORIGIN` frames are limited to a length of 16382 bytes. + ### `ERR_HTTP2_OUT_OF_STREAMS` The number of streams created on a single HTTP/2 session reached the maximum limit. + ### `ERR_HTTP2_PAYLOAD_FORBIDDEN` A message payload was specified for an HTTP response code for which a payload is forbidden. + ### `ERR_HTTP2_PING_CANCEL` An HTTP/2 ping was canceled. + ### `ERR_HTTP2_PING_LENGTH` HTTP/2 ping payloads must be exactly 8 bytes in length. + ### `ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED` An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header key names that begin with the `:` prefix. + ### `ERR_HTTP2_PUSH_DISABLED` An attempt was made to create a push stream, which had been disabled by the client. + ### `ERR_HTTP2_SEND_FILE` An attempt was made to use the `Http2Stream.prototype.responseWithFile()` API to send a directory. + ### `ERR_HTTP2_SEND_FILE_NOSEEK` An attempt was made to use the `Http2Stream.prototype.responseWithFile()` API to @@ -1423,50 +1581,59 @@ send something other than a regular file, but `offset` or `length` options were provided. + ### `ERR_HTTP2_SESSION_ERROR` The `Http2Session` closed with a non-zero error code. + ### `ERR_HTTP2_SETTINGS_CANCEL` The `Http2Session` settings canceled. + ### `ERR_HTTP2_SOCKET_BOUND` An attempt was made to connect a `Http2Session` object to a `net.Socket` or `tls.TLSSocket` that had already been bound to another `Http2Session` object. + ### `ERR_HTTP2_SOCKET_UNBOUND` An attempt was made to use the `socket` property of an `Http2Session` that has already been closed. + ### `ERR_HTTP2_STATUS_101` Use of the `101` Informational status code is forbidden in HTTP/2. + ### `ERR_HTTP2_STATUS_INVALID` An invalid HTTP status code has been specified. Status codes must be an integer between `100` and `599` (inclusive). + ### `ERR_HTTP2_STREAM_CANCEL` An `Http2Stream` was destroyed before any data was transmitted to the connected peer. + ### `ERR_HTTP2_STREAM_ERROR` A non-zero error code was been specified in an `RST_STREAM` frame. + ### `ERR_HTTP2_STREAM_SELF_DEPENDENCY` When setting the priority for an HTTP/2 stream, the stream may be marked as @@ -1474,7 +1641,9 @@ a dependency for a parent stream. This error code is used when an attempt is made to mark a stream and dependent of itself. + ### `ERR_HTTP2_TOO_MANY_INVALID_FRAMES` + @@ -1483,11 +1652,13 @@ The limit of acceptable invalid HTTP/2 protocol frames sent by the peer, as specified through the `maxSessionInvalidFrames` option, has been exceeded. + ### `ERR_HTTP2_TRAILERS_ALREADY_SENT` Trailing headers have already been sent on the `Http2Stream`. + ### `ERR_HTTP2_TRAILERS_NOT_READY` The `http2stream.sendTrailers()` method cannot be called until after the @@ -1496,23 +1667,27 @@ The `http2stream.sendTrailers()` method cannot be called until after the is set for the `Http2Stream`. + ### `ERR_HTTP2_UNSUPPORTED_PROTOCOL` `http2.connect()` was passed a URL that uses any protocol other than `http:` or `https:`. + ### `ERR_ILLEGAL_CONSTRUCTOR` An attempt was made to construct an object using a non-public constructor. + ### `ERR_INCOMPATIBLE_OPTION_PAIR` An option pair is incompatible with each other and cannot be used at the same time. + ### `ERR_INPUT_TYPE_NOT_ALLOWED` > Stability: 1 - Experimental @@ -1521,6 +1696,7 @@ 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`. + ### `ERR_INSPECTOR_ALREADY_ACTIVATED` While using the `inspector` module, an attempt was made to activate the @@ -1528,104 +1704,123 @@ inspector when it already started to listen on a port. Use `inspector.close()` before activating it on a different address. + ### `ERR_INSPECTOR_ALREADY_CONNECTED` While using the `inspector` module, an attempt was made to connect when the inspector was already connected. + ### `ERR_INSPECTOR_CLOSED` While using the `inspector` module, an attempt was made to use the inspector after the session had already closed. + ### `ERR_INSPECTOR_COMMAND` An error occurred while issuing a command via the `inspector` module. + ### `ERR_INSPECTOR_NOT_ACTIVE` The `inspector` is not active when `inspector.waitForDebugger()` is called. + ### `ERR_INSPECTOR_NOT_AVAILABLE` The `inspector` module is not available for use. + ### `ERR_INSPECTOR_NOT_CONNECTED` While using the `inspector` module, an attempt was made to use the inspector before it was connected. + ### `ERR_INSPECTOR_NOT_WORKER` An API was called on the main thread that can only be used from the worker thread. + ### `ERR_INTERNAL_ASSERTION` There was a bug in Node.js or incorrect usage of Node.js internals. To fix the error, open an issue at . + ### `ERR_INVALID_ADDRESS_FAMILY` The provided address family is not understood by the Node.js API. + ### `ERR_INVALID_ARG_TYPE` An argument of the wrong type was passed to a Node.js API. + ### `ERR_INVALID_ARG_VALUE` An invalid or unsupported value was passed for a given argument. + ### `ERR_INVALID_ASYNC_ID` An invalid `asyncId` or `triggerAsyncId` was passed using `AsyncHooks`. An id less than -1 should never happen. + ### `ERR_INVALID_BUFFER_SIZE` A swap was performed on a `Buffer` but its size was not compatible with the operation. + ### `ERR_INVALID_CALLBACK` A callback function was required but was not been provided to a Node.js API. + ### `ERR_INVALID_CHAR` Invalid characters were detected in headers. + ### `ERR_INVALID_CURSOR_POS` A cursor on a given stream cannot be moved to a specified row without a specified column. + ### `ERR_INVALID_FD` A file descriptor ('fd') was not valid (e.g. it was a negative value). + ### `ERR_INVALID_FD_TYPE` A file descriptor ('fd') type was not valid. + ### `ERR_INVALID_FILE_URL_HOST` A Node.js API that consumes `file:` URLs (such as certain functions in the @@ -1634,6 +1829,7 @@ situation can only occur on Unix-like systems where only `localhost` or an empty host is supported. + ### `ERR_INVALID_FILE_URL_PATH` A Node.js API that consumes `file:` URLs (such as certain functions in the @@ -1641,6 +1837,7 @@ A Node.js API that consumes `file:` URLs (such as certain functions in the semantics for determining whether a path can be used is platform-dependent. + ### `ERR_INVALID_HANDLE_TYPE` An attempt was made to send an unsupported "handle" over an IPC communication @@ -1648,17 +1845,21 @@ channel to a child process. See [`subprocess.send()`][] and [`process.send()`][] for more information. + ### `ERR_INVALID_HTTP_TOKEN` An invalid HTTP token was supplied. + ### `ERR_INVALID_IP_ADDRESS` An IP address is not valid. + ### `ERR_INVALID_MODULE` + @@ -1667,65 +1868,77 @@ An attempt was made to load a module that does not exist or was otherwise not valid. + ### `ERR_INVALID_MODULE_SPECIFIER` The imported module string is an invalid URL, package name, or package subpath specifier. + ### `ERR_INVALID_PACKAGE_CONFIG` An invalid [`package.json`][] file failed parsing. + ### `ERR_INVALID_PACKAGE_TARGET` The `package.json` [`"exports"`][] field contains an invalid target mapping value for the attempted module resolution. + ### `ERR_INVALID_PERFORMANCE_MARK` While using the Performance Timing API (`perf_hooks`), a performance mark is invalid. + ### `ERR_INVALID_PROTOCOL` An invalid `options.protocol` was passed to `http.request()`. + ### `ERR_INVALID_REPL_EVAL_CONFIG` Both `breakEvalOnSigint` and `eval` options were set in the [`REPL`][] config, which is not supported. + ### `ERR_INVALID_REPL_INPUT` The input may not be used in the [`REPL`][]. The conditions under which this error is used are described in the [`REPL`][] documentation. + ### `ERR_INVALID_RETURN_PROPERTY` Thrown in case a function option does not provide a valid value for one of its returned object properties on execution. + ### `ERR_INVALID_RETURN_PROPERTY_VALUE` Thrown in case a function option does not provide an expected value type for one of its returned object properties on execution. + ### `ERR_INVALID_RETURN_VALUE` Thrown in case a function option does not return an expected value type on execution, such as when a function is expected to return a promise. + ### `ERR_INVALID_STATE` + @@ -1735,6 +1948,7 @@ For instance, an object may have already been destroyed, or may be performing another operation. + ### `ERR_INVALID_SYNC_FORK_INPUT` A `Buffer`, `TypedArray`, `DataView` or `string` was provided as stdio input to @@ -1742,6 +1956,7 @@ an asynchronous fork. See the documentation for the [`child_process`][] module for more information. + ### `ERR_INVALID_THIS` A Node.js API function was called with an incompatible `this` value. @@ -1755,11 +1970,13 @@ urlSearchParams.has.call(buf, 'foo'); ``` + ### `ERR_INVALID_TRANSFER_OBJECT` An invalid transfer object was passed to `postMessage()`. + ### `ERR_INVALID_TUPLE` An element in the `iterable` provided to the [WHATWG][WHATWG URL API] @@ -1768,11 +1985,13 @@ represent a `[name, value]` tuple – that is, if an element is not iterable, or does not consist of exactly two elements. + ### `ERR_INVALID_URI` An invalid URI was passed. + ### `ERR_INVALID_URL` An invalid URL was passed to the [WHATWG][WHATWG URL API] @@ -1781,6 +2000,7 @@ typically has an additional property `'input'` that contains the URL that failed to parse. + ### `ERR_INVALID_URL_SCHEME` An attempt was made to use a URL of an incompatible scheme (protocol) for a @@ -1789,11 +2009,13 @@ specific purpose. It is only used in the [WHATWG URL API][] support in the in other Node.js APIs as well in the future. + ### `ERR_IPC_CHANNEL_CLOSED` An attempt was made to use an IPC communication channel that was already closed. + ### `ERR_IPC_DISCONNECTED` An attempt was made to disconnect an IPC communication channel that was already @@ -1801,6 +2023,7 @@ disconnected. See the documentation for the [`child_process`][] module for more information. + ### `ERR_IPC_ONE_PIPE` An attempt was made to create a child Node.js process using more than one IPC @@ -1808,6 +2031,7 @@ communication channel. See the documentation for the [`child_process`][] module for more information. + ### `ERR_IPC_SYNC_FORK` An attempt was made to open an IPC communication channel with a synchronously @@ -1815,6 +2039,7 @@ forked Node.js process. See the documentation for the [`child_process`][] module for more information. + ### `ERR_MANIFEST_ASSERT_INTEGRITY` An attempt was made to load a resource, but the resource did not match the @@ -1822,6 +2047,7 @@ integrity defined by the policy manifest. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_DEPENDENCY_MISSING` An attempt was made to load a resource, but the resource was not listed as a @@ -1829,6 +2055,7 @@ dependency from the location that attempted to load it. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_INTEGRITY_MISMATCH` An attempt was made to load a policy manifest, but the manifest had multiple @@ -1837,6 +2064,7 @@ entries to match in order to resolve this error. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_INVALID_RESOURCE_FIELD` A policy manifest resource had an invalid value for one of its fields. Update @@ -1844,6 +2072,7 @@ the manifest entry to match in order to resolve this error. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_INVALID_SPECIFIER` A policy manifest resource had an invalid value for one of its dependency @@ -1851,31 +2080,37 @@ mappings. Update the manifest entry to match to resolve this error. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_PARSE_POLICY` An attempt was made to load a policy manifest, but the manifest was unable to be parsed. See the documentation for [policy][] manifests for more information. + ### `ERR_MANIFEST_TDZ` An attempt was made to read from a policy manifest, but the manifest initialization has not yet taken place. This is likely a bug in Node.js. + ### `ERR_MANIFEST_UNKNOWN_ONERROR` A policy manifest was loaded, but had an unknown value for its "onerror" behavior. See the documentation for [policy][] manifests for more information. + ### `ERR_MEMORY_ALLOCATION_FAILED` An attempt was made to allocate memory (usually in the C++ layer) but it failed. + ### `ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE` + @@ -1935,6 +2177,7 @@ transferable object types has been expanded to cover more types than `MessagePort`. + ### `ERR_MODULE_NOT_FOUND` > Stability: 1 - Experimental @@ -1942,6 +2185,7 @@ transferable object types has been expanded to cover more types than An [ES Module][] could not be resolved. + ### `ERR_MULTIPLE_CALLBACK` A callback was called more than once. @@ -1951,41 +2195,48 @@ can either be fulfilled or rejected but not both at the same time. The latter would be possible by calling a callback more than once. + ### `ERR_NAPI_CONS_FUNCTION` While using `Node-API`, a constructor passed was not a function. + ### `ERR_NAPI_INVALID_DATAVIEW_ARGS` While calling `napi_create_dataview()`, a given `offset` was outside the bounds of the dataview or `offset + length` was larger than a length of given `buffer`. + ### `ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT` While calling `napi_create_typedarray()`, the provided `offset` was not a multiple of the element size. + ### `ERR_NAPI_INVALID_TYPEDARRAY_LENGTH` While calling `napi_create_typedarray()`, `(length * size_of_element) + byte_offset` was larger than the length of given `buffer`. + ### `ERR_NAPI_TSFN_CALL_JS` An error occurred while invoking the JavaScript portion of the thread-safe function. + ### `ERR_NAPI_TSFN_GET_UNDEFINED` An error occurred while attempting to retrieve the JavaScript `undefined` value. + ### `ERR_NAPI_TSFN_START_IDLE_LOOP` On the main thread, values are removed from the queue associated with the @@ -1993,40 +2244,47 @@ thread-safe function in an idle loop. This error indicates that an error has occurred when attempting to start the loop. + ### `ERR_NAPI_TSFN_STOP_IDLE_LOOP` Once no more items are left in the queue, the idle loop must be suspended. This error indicates that the idle loop has failed to stop. + ### `ERR_NO_CRYPTO` An attempt was made to use crypto features while Node.js was not compiled with OpenSSL crypto support. + ### `ERR_NO_ICU` An attempt was made to use features that require [ICU][], but Node.js was not compiled with ICU support. + ### `ERR_NON_CONTEXT_AWARE_DISABLED` A non-context-aware native addon was loaded in a process that disallows them. + ### `ERR_OUT_OF_RANGE` A given value is out of the accepted range. + ### `ERR_PACKAGE_IMPORT_NOT_DEFINED` The `package.json` [`"imports"`][] field does not define the given internal package specifier mapping. + ### `ERR_PACKAGE_PATH_NOT_EXPORTED` The `package.json` [`"exports"`][] field does not export the requested subpath. @@ -2034,16 +2292,19 @@ Because exports are encapsulated, private internal modules that are not exported cannot be imported through the package resolution, unless using an absolute URL. + ### `ERR_PERFORMANCE_INVALID_TIMESTAMP` An invalid timestamp value was provided for a performance mark or measure. + ### `ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS` Invalid options were provided for a performance measure. + ### `ERR_PROTO_ACCESS` Accessing `Object.prototype.__proto__` has been forbidden using @@ -2052,6 +2313,7 @@ Accessing `Object.prototype.__proto__` has been forbidden using object. + ### `ERR_REQUIRE_ESM` > Stability: 1 - Experimental @@ -2059,17 +2321,20 @@ object. An attempt was made to `require()` an [ES Module][]. + ### `ERR_SCRIPT_EXECUTION_INTERRUPTED` -Script execution was interrupted by `SIGINT` (For example, -Ctrl+C was pressed.) +Script execution was interrupted by `SIGINT` (For +example, Ctrl+C was pressed.) + ### `ERR_SCRIPT_EXECUTION_TIMEOUT` Script execution timed out, possibly due to bugs in the script being executed. + ### `ERR_SERVER_ALREADY_LISTEN` The [`server.listen()`][] method was called while a `net.Server` was already @@ -2077,6 +2342,7 @@ listening. This applies to all instances of `net.Server`, including HTTP, HTTPS, and HTTP/2 `Server` instances. + ### `ERR_SERVER_NOT_RUNNING` The [`server.close()`][] method was called when a `net.Server` was not @@ -2084,55 +2350,65 @@ running. This applies to all instances of `net.Server`, including HTTP, HTTPS, and HTTP/2 `Server` instances. + ### `ERR_SOCKET_ALREADY_BOUND` An attempt was made to bind a socket that has already been bound. + ### `ERR_SOCKET_BAD_BUFFER_SIZE` An invalid (negative) size was passed for either the `recvBufferSize` or `sendBufferSize` options in [`dgram.createSocket()`][]. + ### `ERR_SOCKET_BAD_PORT` An API function expecting a port >= 0 and < 65536 received an invalid value. + ### `ERR_SOCKET_BAD_TYPE` An API function expecting a socket type (`udp4` or `udp6`) received an invalid value. + ### `ERR_SOCKET_BUFFER_SIZE` While using [`dgram.createSocket()`][], the size of the receive or send `Buffer` could not be determined. + ### `ERR_SOCKET_CLOSED` An attempt was made to operate on an already closed socket. + ### `ERR_SOCKET_DGRAM_IS_CONNECTED` A [`dgram.connect()`][] call was made on an already connected socket. + ### `ERR_SOCKET_DGRAM_NOT_CONNECTED` A [`dgram.disconnect()`][] or [`dgram.remoteAddress()`][] call was made on a disconnected socket. + ### `ERR_SOCKET_DGRAM_NOT_RUNNING` A call was made and the UDP subsystem was not running. + ### `ERR_SRI_PARSE` A string was provided for a Subresource Integrity check, but was unable to be @@ -2140,46 +2416,54 @@ parsed. Check the format of integrity attributes by looking at the [Subresource Integrity specification][]. + ### `ERR_STREAM_ALREADY_FINISHED` A stream method was called that cannot complete because the stream was finished. + ### `ERR_STREAM_CANNOT_PIPE` An attempt was made to call [`stream.pipe()`][] on a [`Writable`][] stream. + ### `ERR_STREAM_DESTROYED` A stream method was called that cannot complete because the stream was destroyed using `stream.destroy()`. + ### `ERR_STREAM_NULL_VALUES` An attempt was made to call [`stream.write()`][] with a `null` chunk. + ### `ERR_STREAM_PREMATURE_CLOSE` An error returned by `stream.finished()` and `stream.pipeline()`, when a stream or a pipeline ends non gracefully with no explicit error. + ### `ERR_STREAM_PUSH_AFTER_EOF` An attempt was made to call [`stream.push()`][] after a `null`(EOF) had been pushed to the stream. + ### `ERR_STREAM_UNSHIFT_AFTER_END_EVENT` An attempt was made to call [`stream.unshift()`][] after the `'end'` event was emitted. + ### `ERR_STREAM_WRAP` Prevents an abort if a string decoder was set on the Socket or if the decoder @@ -2193,24 +2477,28 @@ instance.setEncoding('utf8'); ``` + ### `ERR_STREAM_WRITE_AFTER_END` An attempt was made to call [`stream.write()`][] after `stream.end()` has been called. + ### `ERR_STRING_TOO_LONG` An attempt has been made to create a string longer than the maximum allowed length. + ### `ERR_SYNTHETIC` An artificial error object used to capture the call stack for diagnostic reports. + ### `ERR_SYSTEM_ERROR` An unspecified or non-specific system error has occurred within the Node.js @@ -2218,12 +2506,14 @@ process. The error object will have an `err.info` object property with additional details. + ### `ERR_TLS_CERT_ALTNAME_INVALID` While using TLS, the host name/IP of the peer did not match any of the `subjectAltNames` in its certificate. + ### `ERR_TLS_DH_PARAM_SIZE` While using TLS, the parameter offered for the Diffie-Hellman (`DH`) @@ -2232,13 +2522,16 @@ than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly recommended to use 2048 bits or larger for stronger security. + ### `ERR_TLS_HANDSHAKE_TIMEOUT` A TLS/SSL handshake timed out. In this case, the server must also abort the connection. + ### `ERR_TLS_INVALID_CONTEXT` + @@ -2246,18 +2539,22 @@ added: v13.3.0 The context must be a `SecureContext`. + ### `ERR_TLS_INVALID_PROTOCOL_METHOD` The specified `secureProtocol` method is invalid. It is either unknown, or disabled because it is insecure. + ### `ERR_TLS_INVALID_PROTOCOL_VERSION` Valid TLS protocol versions are `'TLSv1'`, `'TLSv1.1'`, or `'TLSv1.2'`. + ### `ERR_TLS_INVALID_STATE` + + ```js import './'; // unsupported import './index.js'; // supported @@ -2407,22 +2727,26 @@ import 'package-name'; // supported ``` + ### `ERR_UNSUPPORTED_ESM_URL_SCHEME` `import` with URL schemes other than `file` and `data` is unsupported. + ### `ERR_VALID_PERFORMANCE_ENTRY_TYPE` While using the Performance Timing API (`perf_hooks`), no valid performance entry types are found. + ### `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING` A dynamic import callback was not specified. + ### `ERR_VM_MODULE_ALREADY_LINKED` The module attempted to be linked is not eligible for linking, because of one of @@ -2433,96 +2757,115 @@ the following reasons: * Linking has failed for this module (`linkingStatus` is `'errored'`) + ### `ERR_VM_MODULE_CACHED_DATA_REJECTED` The `cachedData` option passed to a module constructor is invalid. + ### `ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA` Cached data cannot be created for modules which have already been evaluated. + ### `ERR_VM_MODULE_DIFFERENT_CONTEXT` The module being returned from the linker function is from a different context than the parent module. Linked modules must share the same context. + ### `ERR_VM_MODULE_LINKING_ERRORED` The linker function returned a module for which linking has failed. + ### `ERR_VM_MODULE_LINK_FAILURE` The module was unable to be linked due to a failure. + ### `ERR_VM_MODULE_NOT_MODULE` The fulfilled value of a linking promise is not a `vm.Module` object. + ### `ERR_VM_MODULE_STATUS` The current module's status does not allow for this operation. The specific meaning of the error depends on the specific function. + ### `ERR_WASI_ALREADY_STARTED` The WASI instance has already started. + ### `ERR_WASI_NOT_STARTED` The WASI instance has not been started. + ### `ERR_WORKER_INIT_FAILED` The `Worker` initialization failed. + ### `ERR_WORKER_INVALID_EXEC_ARGV` The `execArgv` option passed to the `Worker` constructor contains invalid flags. + ### `ERR_WORKER_NOT_RUNNING` An operation failed because the `Worker` instance is not currently running. + ### `ERR_WORKER_OUT_OF_MEMORY` The `Worker` instance terminated because it reached its memory limit. + ### `ERR_WORKER_PATH` The path for the main script of a worker is neither an absolute path nor a relative path starting with `./` or `../`. + ### `ERR_WORKER_UNSERIALIZABLE_ERROR` All attempts at serializing an uncaught exception from a worker thread failed. + ### `ERR_WORKER_UNSUPPORTED_OPERATION` The requested functionality is not supported in worker threads. + ### `ERR_ZLIB_INITIALIZATION_FAILED` Creation of a [`zlib`][] object failed due to incorrect configuration. + ### `HPE_HEADER_OVERFLOW` + + A module file could not be resolved while attempting a [`require()`][] or `import` operation. @@ -2566,7 +2913,9 @@ A module file could not be resolved while attempting a [`require()`][] or > been removed. + ### `ERR_CANNOT_TRANSFER_OBJECT` + -HTTP/2 informational headers must only be sent *prior* to calling the +HTTP/2 informational headers must only be sent _prior_ to calling the `Http2Stream.prototype.respond()` method. + ### `ERR_HTTP2_STREAM_CLOSED` + + A given index was out of the accepted range (e.g. negative offsets). + ### `ERR_INVALID_OPT_VALUE` + @@ -2682,7 +3054,9 @@ in Node.js v15.0.0, because it is no longer accurate as other types of transferable objects also exist now. + ### `ERR_NAPI_CONS_PROTOTYPE_OBJECT` + @@ -2706,7 +3083,9 @@ An operation failed. This is typically used to signal the general failure of an asynchronous operation. + ### `ERR_OUTOFMEMORY` + diff --git a/doc/api/esm.md b/doc/api/esm.md index c33a53188ca209..46750050ee90d6 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -82,9 +82,8 @@ provides interoperability between them and its original module format, [CommonJS][]. - - - + + ## Enabling @@ -98,20 +97,8 @@ via the `.mjs` file extension, the `package.json` [`"type"`][] field, or the details. - - - - - - - - - - - - - - + + ## Packages @@ -291,6 +278,7 @@ const buffer = readFileSync(new URL('./data.proto', import.meta.url)); ``` ### `import.meta.resolve(specifier[, parent])` + + ```js const dependencyAsset = await import.meta.resolve('component-lib/asset.css'); ``` @@ -323,6 +312,7 @@ const dependencyAsset = await import.meta.resolve('component-lib/asset.css'); from which to resolve from: + ```js await import.meta.resolve('./dep', import.meta.url); ``` @@ -359,6 +349,7 @@ When importing a CommonJS module, it can be reliably imported using the ES module default import or its corresponding sugar syntax: + ```js import { default as cjs } from 'cjs'; @@ -381,6 +372,7 @@ This Module Namespace Exotic Object can be directly observed either when using `import * as m from 'cjs'` or a dynamic import: + ```js import * as m from 'cjs'; console.log(m); @@ -405,6 +397,7 @@ exports.name = 'exported'; The preceding module supports named imports in ES modules: + ```js import { name } from './cjs.cjs'; console.log(name); @@ -458,6 +451,7 @@ JSON imports are still experimental and only supported via the Local JSON files can be loaded relative to `import.meta.url` with `fs` directly: + ```js import { readFile } from 'fs/promises'; const json = JSON.parse(await readFile(new URL('./dat.json', import.meta.url))); @@ -518,6 +512,7 @@ same path. Assuming an `index.mjs` with + ```js import packageConfig from './package.json'; ``` @@ -570,6 +565,7 @@ within modules as per the [ECMAScript Top-Level `await` proposal][]. Assuming an `a.mjs` with + ```js export const five = await Promise.resolve(5); ``` @@ -611,12 +607,12 @@ CommonJS modules loaded. * `specifier` {string} * `context` {Object} - * `conditions` {string[]} + * `conditions` {string\[]} * `parentURL` {string|undefined} * `defaultResolve` {Function} The Node.js default resolver. * Returns: {Object} * `format` {string|null|undefined} - `'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'` + `'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'` * `url` {string} The absolute url to the import target (such as `file://…`) The `resolve` hook returns the resolved file URL for a given module specifier @@ -687,7 +683,7 @@ export async function resolve(specifier, context, defaultResolve) { * `url` {string} * `context` {Object} * `format` {string|null|undefined} The format optionally supplied by the - `resolve` hook. + `resolve` hook. * `defaultLoad` {Function} * Returns: {Object} * `format` {string} @@ -1020,16 +1016,16 @@ The resolver has the following properties: * Relative and absolute URL resolution * No default extensions * No folder mains -* Bare specifier package resolution lookup through node_modules +* Bare specifier package resolution lookup through node\_modules ### Resolver algorithm The algorithm to load an ES module specifier is given through the -**ESM_RESOLVE** method below. It returns the resolved URL for a +**ESM\_RESOLVE** method below. It returns the resolved URL for a module specifier relative to a parentURL. The algorithm to determine the module format of a resolved URL is -provided by **ESM_FORMAT**, which returns the unique module +provided by **ESM\_FORMAT**, which returns the unique module format for any file. The _"module"_ format is returned for an ECMAScript Module, while the _"commonjs"_ format is used to indicate loading through the legacy CommonJS loader. Additional formats such as _"addon"_ can be extended in @@ -1042,6 +1038,7 @@ _defaultConditions_ is the conditional environment name array, `["node", "import"]`. The resolver can throw the following errors: + * _Invalid Module Specifier_: Module specifier is an invalid URL, package name or package subpath specifier. * _Invalid Package Configuration_: package.json configuration is invalid or @@ -1057,286 +1054,286 @@ The resolver can throw the following errors: ### Resolver Algorithm Specification -**ESM_RESOLVE**(_specifier_, _parentURL_) +**ESM\_RESOLVE**(_specifier_, _parentURL_) > 1. Let _resolved_ be **undefined**. -> 1. If _specifier_ is a valid URL, then +> 2. If _specifier_ is a valid URL, then > 1. Set _resolved_ to the result of parsing and reserializing > _specifier_ as a URL. -> 1. Otherwise, if _specifier_ starts with _"/"_, _"./"_ or _"../"_, then +> 3. Otherwise, if _specifier_ starts with _"/"_, _"./"_ or _"../"_, then > 1. Set _resolved_ to the URL resolution of _specifier_ relative to > _parentURL_. -> 1. Otherwise, if _specifier_ starts with _"#"_, then +> 4. Otherwise, if _specifier_ starts with _"#"_, then > 1. Set _resolved_ to the destructured value of the result of -> **PACKAGE_IMPORTS_RESOLVE**(_specifier_, _parentURL_, +> **PACKAGE\_IMPORTS\_RESOLVE**(_specifier_, _parentURL_, > _defaultConditions_). -> 1. Otherwise, +> 5. Otherwise, > 1. Note: _specifier_ is now a bare specifier. -> 1. Set _resolved_ the result of -> **PACKAGE_RESOLVE**(_specifier_, _parentURL_). -> 1. If _resolved_ contains any percent encodings of _"/"_ or _"\\"_ (_"%2f"_ +> 2. Set _resolved_ the result of +> **PACKAGE\_RESOLVE**(_specifier_, _parentURL_). +> 6. If _resolved_ contains any percent encodings of _"/"_ or _"\\"_ (_"%2f"_ > and _"%5C"_ respectively), then > 1. Throw an _Invalid Module Specifier_ error. -> 1. If the file at _resolved_ is a directory, then +> 7. If the file at _resolved_ is a directory, then > 1. Throw an _Unsupported Directory Import_ error. -> 1. If the file at _resolved_ does not exist, then +> 8. If the file at _resolved_ does not exist, then > 1. Throw a _Module Not Found_ error. -> 1. Set _resolved_ to the real path of _resolved_. -> 1. Let _format_ be the result of **ESM_FORMAT**(_resolved_). -> 1. Load _resolved_ as module format, _format_. -> 1. Return _resolved_. +> 9. Set _resolved_ to the real path of _resolved_. +> 10. Let _format_ be the result of **ESM\_FORMAT**(_resolved_). +> 11. Load _resolved_ as module format, _format_. +> 12. Return _resolved_. -**PACKAGE_RESOLVE**(_packageSpecifier_, _parentURL_) +**PACKAGE\_RESOLVE**(_packageSpecifier_, _parentURL_) > 1. Let _packageName_ be **undefined**. -> 1. If _packageSpecifier_ is an empty string, then +> 2. If _packageSpecifier_ is an empty string, then > 1. Throw an _Invalid Module Specifier_ error. -> 1. If _packageSpecifier_ does not start with _"@"_, then +> 3. If _packageSpecifier_ does not start with _"@"_, then > 1. Set _packageName_ to the substring of _packageSpecifier_ until the first > _"/"_ separator or the end of the string. -> 1. Otherwise, +> 4. Otherwise, > 1. If _packageSpecifier_ does not contain a _"/"_ separator, then > 1. Throw an _Invalid Module Specifier_ error. -> 1. Set _packageName_ to the substring of _packageSpecifier_ +> 2. Set _packageName_ to the substring of _packageSpecifier_ > until the second _"/"_ separator or the end of the string. -> 1. If _packageName_ starts with _"."_ or contains _"\\"_ or _"%"_, then +> 5. If _packageName_ starts with _"."_ or contains _"\\"_ or _"%"_, then > 1. Throw an _Invalid Module Specifier_ error. -> 1. Let _packageSubpath_ be _"."_ concatenated with the substring of -> _packageSpecifier_ from the position at the length of _packageName_. -> 1. Let _selfUrl_ be the result of -> **PACKAGE_SELF_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_). -> 1. If _selfUrl_ is not **undefined**, return _selfUrl_. -> 1. If _packageSubpath_ is _"."_ and _packageName_ is a Node.js builtin +> 6. Let _packageSubpath_ be _"."_ concatenated with the substring of +> _packageSpecifier_ from the position at the length of _packageName_. +> 7. Let _selfUrl_ be the result of +> **PACKAGE\_SELF\_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_). +> 8. If _selfUrl_ is not **undefined**, return _selfUrl_. +> 9. If _packageSubpath_ is _"."_ and _packageName_ is a Node.js builtin > module, then > 1. Return the string _"node:"_ concatenated with _packageSpecifier_. -> 1. While _parentURL_ is not the file system root, -> 1. Let _packageURL_ be the URL resolution of _"node_modules/"_ -> concatenated with _packageSpecifier_, relative to _parentURL_. -> 1. Set _parentURL_ to the parent folder URL of _parentURL_. -> 1. If the folder at _packageURL_ does not exist, then -> 1. Set _parentURL_ to the parent URL path of _parentURL_. -> 1. Continue the next loop iteration. -> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_). -> 1. If _pjson_ is not **null** and _pjson_._exports_ is not **null** or -> **undefined**, then -> 1. Let _exports_ be _pjson.exports_. -> 1. Return the _resolved_ destructured value of the result of -> **PACKAGE_EXPORTS_RESOLVE**(_packageURL_, _packageSubpath_, +> 10. While _parentURL_ is not the file system root, +> 1. Let _packageURL_ be the URL resolution of _"node\_modules/"_ +> concatenated with _packageSpecifier_, relative to _parentURL_. +> 2. Set _parentURL_ to the parent folder URL of _parentURL_. +> 3. If the folder at _packageURL_ does not exist, then +> 1. Set _parentURL_ to the parent URL path of _parentURL_. +> 2. Continue the next loop iteration. +> 4. Let _pjson_ be the result of **READ\_PACKAGE\_JSON**(_packageURL_). +> 5. If _pjson_ is not **null** and _pjson_._exports_ is not **null** or +> **undefined**, then +> 1. Let _exports_ be _pjson.exports_. +> 2. Return the _resolved_ destructured value of the result of +> **PACKAGE\_EXPORTS\_RESOLVE**(_packageURL_, _packageSubpath_, > _pjson.exports_, _defaultConditions_). -> 1. Otherwise, if _packageSubpath_ is equal to _"."_, then -> 1. Return the result applying the legacy **LOAD_AS_DIRECTORY** -> CommonJS resolver to _packageURL_, throwing a _Module Not Found_ -> error for no resolution. -> 1. Otherwise, -> 1. Return the URL resolution of _packageSubpath_ in _packageURL_. -> 1. Throw a _Module Not Found_ error. - -**PACKAGE_SELF_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_) - -> 1. Let _packageURL_ be the result of **READ_PACKAGE_SCOPE**(_parentURL_). -> 1. If _packageURL_ is **null**, then +> 6. Otherwise, if _packageSubpath_ is equal to _"."_, then +> 1. Return the result applying the legacy **LOAD\_AS\_DIRECTORY** +> CommonJS resolver to _packageURL_, throwing a _Module Not Found_ +> error for no resolution. +> 7. Otherwise, +> 1. Return the URL resolution of _packageSubpath_ in _packageURL_. +> 11. Throw a _Module Not Found_ error. + +**PACKAGE\_SELF\_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_) + +> 1. Let _packageURL_ be the result of **READ\_PACKAGE\_SCOPE**(_parentURL_). +> 2. If _packageURL_ is **null**, then > 1. Return **undefined**. -> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_). -> 1. If _pjson_ is **null** or if _pjson_._exports_ is **null** or +> 3. Let _pjson_ be the result of **READ\_PACKAGE\_JSON**(_packageURL_). +> 4. If _pjson_ is **null** or if _pjson_._exports_ is **null** or > **undefined**, then > 1. Return **undefined**. -> 1. If _pjson.name_ is equal to _packageName_, then +> 5. If _pjson.name_ is equal to _packageName_, then > 1. Return the _resolved_ destructured value of the result of -> **PACKAGE_EXPORTS_RESOLVE**(_packageURL_, _packageSubpath_, +> **PACKAGE\_EXPORTS\_RESOLVE**(_packageURL_, _packageSubpath_, > _pjson.exports_, _defaultConditions_). -> 1. Otherwise, return **undefined**. +> 6. Otherwise, return **undefined**. -**PACKAGE_EXPORTS_RESOLVE**(_packageURL_, _subpath_, _exports_, _conditions_) +**PACKAGE\_EXPORTS\_RESOLVE**(_packageURL_, _subpath_, _exports_, _conditions_) > 1. If _exports_ is an Object with both a key starting with _"."_ and a key not > starting with _"."_, throw an _Invalid Package Configuration_ error. -> 1. If _subpath_ is equal to _"."_, then +> 2. If _subpath_ is equal to _"."_, then > 1. Let _mainExport_ be **undefined**. -> 1. If _exports_ is a String or Array, or an Object containing no keys +> 2. If _exports_ is a String or Array, or an Object containing no keys > starting with _"."_, then > 1. Set _mainExport_ to _exports_. -> 1. Otherwise if _exports_ is an Object containing a _"."_ property, then -> 1. Set _mainExport_ to _exports_\[_"."_\]. -> 1. If _mainExport_ is not **undefined**, then -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> 3. Otherwise if _exports_ is an Object containing a _"."_ property, then +> 1. Set _mainExport_ to _exports_\[_"."_]. +> 4. If _mainExport_ is not **undefined**, then +> 1. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _mainExport_, _""_, **false**, **false**, > _conditions_). -> 1. If _resolved_ is not **null** or **undefined**, then +> 2. If _resolved_ is not **null** or **undefined**, then > 1. Return _resolved_. -> 1. Otherwise, if _exports_ is an Object and all keys of _exports_ start with +> 3. Otherwise, if _exports_ is an Object and all keys of _exports_ start with > _"."_, then > 1. Let _matchKey_ be the string _"./"_ concatenated with _subpath_. -> 1. Let _resolvedMatch_ be result of **PACKAGE_IMPORTS_EXPORTS_RESOLVE**( +> 2. Let _resolvedMatch_ be result of **PACKAGE\_IMPORTS\_EXPORTS\_RESOLVE**( > _matchKey_, _exports_, _packageURL_, **false**, _conditions_). -> 1. If _resolvedMatch_._resolve_ is not **null** or **undefined**, then +> 3. If _resolvedMatch_._resolve_ is not **null** or **undefined**, then > 1. Return _resolvedMatch_. -> 1. Throw a _Package Path Not Exported_ error. +> 4. Throw a _Package Path Not Exported_ error. -**PACKAGE_IMPORTS_RESOLVE**(_specifier_, _parentURL_, _conditions_) +**PACKAGE\_IMPORTS\_RESOLVE**(_specifier_, _parentURL_, _conditions_) > 1. Assert: _specifier_ begins with _"#"_. -> 1. If _specifier_ is exactly equal to _"#"_ or starts with _"#/"_, then +> 2. If _specifier_ is exactly equal to _"#"_ or starts with _"#/"_, then > 1. Throw an _Invalid Module Specifier_ error. -> 1. Let _packageURL_ be the result of **READ_PACKAGE_SCOPE**(_parentURL_). -> 1. If _packageURL_ is not **null**, then -> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_packageURL_). -> 1. If _pjson.imports_ is a non-null Object, then +> 3. Let _packageURL_ be the result of **READ\_PACKAGE\_SCOPE**(_parentURL_). +> 4. If _packageURL_ is not **null**, then +> 1. Let _pjson_ be the result of **READ\_PACKAGE\_JSON**(_packageURL_). +> 2. If _pjson.imports_ is a non-null Object, then > 1. Let _resolvedMatch_ be the result of -> **PACKAGE_IMPORTS_EXPORTS_RESOLVE**(_specifier_, _pjson.imports_, +> **PACKAGE\_IMPORTS\_EXPORTS\_RESOLVE**(_specifier_, _pjson.imports_, > _packageURL_, **true**, _conditions_). -> 1. If _resolvedMatch_._resolve_ is not **null** or **undefined**, then +> 2. If _resolvedMatch_._resolve_ is not **null** or **undefined**, then > 1. Return _resolvedMatch_. -> 1. Throw a _Package Import Not Defined_ error. +> 5. Throw a _Package Import Not Defined_ error. -**PACKAGE_IMPORTS_EXPORTS_RESOLVE**(_matchKey_, _matchObj_, _packageURL_, +**PACKAGE\_IMPORTS\_EXPORTS\_RESOLVE**(_matchKey_, _matchObj_, _packageURL_, _isImports_, _conditions_) > 1. If _matchKey_ is a key of _matchObj_ and does not end in _"/"_ or contain -> _"*"_, then -> 1. Let _target_ be the value of _matchObj_\[_matchKey_\]. -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> _"\*"_, then +> 1. Let _target_ be the value of _matchObj_\[_matchKey_]. +> 2. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _target_, _""_, **false**, _isImports_, _conditions_). -> 1. Return the object _{ resolved, exact: **true** }_. -> 1. Let _expansionKeys_ be the list of keys of _matchObj_ either ending in -> _"/"_ or containing only a single _"*"_, sorted by the sorting function -> **PATTERN_KEY_COMPARE** which orders in descending order of specificity. -> 1. For each key _expansionKey_ in _expansionKeys_, do +> 3. Return the object _{ resolved, exact: **true** }_. +> 2. Let _expansionKeys_ be the list of keys of _matchObj_ either ending in +> _"/"_ or containing only a single _"\*"_, sorted by the sorting function +> **PATTERN\_KEY\_COMPARE** which orders in descending order of specificity. +> 3. For each key _expansionKey_ in _expansionKeys_, do > 1. Let _patternBase_ be **null**. -> 1. If _expansionKey_ contains _"*"_, set _patternBase_ to the substring of -> _expansionKey_ up to but excluding the first _"*"_ character. -> 1. If _patternBase_ is not **null** and _matchKey_ starts with but is not +> 2. If _expansionKey_ contains _"\*"_, set _patternBase_ to the substring of +> _expansionKey_ up to but excluding the first _"\*"_ character. +> 3. If _patternBase_ is not **null** and _matchKey_ starts with but is not > equal to _patternBase_, then > 1. If _matchKey_ ends with _"/"_, throw an _Invalid Module Specifier_ > error. -> 1. Let _patternTrailer_ be the substring of _expansionKey_ from the -> index after the first _"*"_ character. -> 1. If _patternTrailer_ has zero length, or if _matchKey_ ends with +> 2. Let _patternTrailer_ be the substring of _expansionKey_ from the +> index after the first _"\*"_ character. +> 3. If _patternTrailer_ has zero length, or if _matchKey_ ends with > _patternTrailer_ and the length of _matchKey_ is greater than or > equal to the length of _expansionKey_, then -> 1. Let _target_ be the value of _matchObj_\[_expansionKey_\]. -> 1. Let _subpath_ be the substring of _matchKey_ starting at the +> 1. Let _target_ be the value of _matchObj_\[_expansionKey_]. +> 2. Let _subpath_ be the substring of _matchKey_ starting at the > index of the length of _patternBase_ up to the length of > _matchKey_ minus the length of _patternTrailer_. -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> 3. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _target_, _subpath_, **true**, _isImports_, > _conditions_). -> 1. Return the object _{ resolved, exact: **true** }_. -> 1. Otherwise if _patternBase_ is **null** and _matchKey_ starts with +> 4. Return the object _{ resolved, exact: **true** }_. +> 4. Otherwise if _patternBase_ is **null** and _matchKey_ starts with > _expansionKey_, then -> 1. Let _target_ be the value of _matchObj_\[_expansionKey_\]. -> 1. Let _subpath_ be the substring of _matchKey_ starting at the +> 1. Let _target_ be the value of _matchObj_\[_expansionKey_]. +> 2. Let _subpath_ be the substring of _matchKey_ starting at the > index of the length of _expansionKey_. -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> 3. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _target_, _subpath_, **false**, _isImports_, > _conditions_). -> 1. Return the object _{ resolved, exact: **false** }_. -> 1. Return the object _{ resolved: **null**, exact: **true** }_. - -**PATTERN_KEY_COMPARE**(_keyA_, _keyB_) - -> 1. Assert: _keyA_ ends with _"/"_ or contains only a single _"*"_. -> 1. Assert: _keyB_ ends with _"/"_ or contains only a single _"*"_. -> 1. Let _baseLengthA_ be the index of _"*"_ in _keyA_ plus one, if _keyA_ -> contains _"*"_, or the length of _keyA_ otherwise. -> 1. Let _baseLengthB_ be the index of _"*"_ in _keyB_ plus one, if _keyB_ -> contains _"*"_, or the length of _keyB_ otherwise. -> 1. If _baseLengthA_ is greater than _baseLengthB_, return -1. -> 1. If _baseLengthB_ is greater than _baseLengthA_, return 1. -> 1. If _keyA_ does not contain _"*"_, return 1. -> 1. If _keyB_ does not contain _"*"_, return -1. -> 1. If the length of _keyA_ is greater than the length of _keyB_, return -1. -> 1. If the length of _keyB_ is greater than the length of _keyA_, return 1. -> 1. Return 0. - -**PACKAGE_TARGET_RESOLVE**(_packageURL_, _target_, _subpath_, _pattern_, +> 4. Return the object _{ resolved, exact: **false** }_. +> 4. Return the object _{ resolved: **null**, exact: **true** }_. + +**PATTERN\_KEY\_COMPARE**(_keyA_, _keyB_) + +> 1. Assert: _keyA_ ends with _"/"_ or contains only a single _"\*"_. +> 2. Assert: _keyB_ ends with _"/"_ or contains only a single _"\*"_. +> 3. Let _baseLengthA_ be the index of _"\*"_ in _keyA_ plus one, if _keyA_ +> contains _"\*"_, or the length of _keyA_ otherwise. +> 4. Let _baseLengthB_ be the index of _"\*"_ in _keyB_ plus one, if _keyB_ +> contains _"\*"_, or the length of _keyB_ otherwise. +> 5. If _baseLengthA_ is greater than _baseLengthB_, return -1. +> 6. If _baseLengthB_ is greater than _baseLengthA_, return 1. +> 7. If _keyA_ does not contain _"\*"_, return 1. +> 8. If _keyB_ does not contain _"\*"_, return -1. +> 9. If the length of _keyA_ is greater than the length of _keyB_, return -1. +> 10. If the length of _keyB_ is greater than the length of _keyA_, return 1. +> 11. Return 0. + +**PACKAGE\_TARGET\_RESOLVE**(_packageURL_, _target_, _subpath_, _pattern_, _internal_, _conditions_) > 1. If _target_ is a String, then > 1. If _pattern_ is **false**, _subpath_ has non-zero length and _target_ > does not end with _"/"_, throw an _Invalid Module Specifier_ error. -> 1. If _target_ does not start with _"./"_, then +> 2. If _target_ does not start with _"./"_, then > 1. If _internal_ is **true** and _target_ does not start with _"../"_ or > _"/"_ and is not a valid URL, then > 1. If _pattern_ is **true**, then -> 1. Return **PACKAGE_RESOLVE**(_target_ with every instance of -> _"*"_ replaced by _subpath_, _packageURL_ + _"/"_)_. -> 1. Return **PACKAGE_RESOLVE**(_target_ + _subpath_, -> _packageURL_ + _"/"_)_. -> 1. Otherwise, throw an _Invalid Package Target_ error. -> 1. If _target_ split on _"/"_ or _"\\"_ contains any _"."_, _".."_ or -> _"node_modules"_ segments after the first segment, throw an +> 1. Return **PACKAGE\_RESOLVE**(_target_ with every instance of +> _"\*"_ replaced by _subpath_, _packageURL_ + _"/"_)\_. +> 2. Return **PACKAGE\_RESOLVE**(_target_ + _subpath_, +> _packageURL_ + _"/"_)\_. +> 2. Otherwise, throw an _Invalid Package Target_ error. +> 3. If _target_ split on _"/"_ or _"\\"_ contains any _"."_, _".."_ or +> _"node\_modules"_ segments after the first segment, throw an > _Invalid Package Target_ error. -> 1. Let _resolvedTarget_ be the URL resolution of the concatenation of +> 4. Let _resolvedTarget_ be the URL resolution of the concatenation of > _packageURL_ and _target_. -> 1. Assert: _resolvedTarget_ is contained in _packageURL_. -> 1. If _subpath_ split on _"/"_ or _"\\"_ contains any _"."_, _".."_ or -> _"node_modules"_ segments, throw an _Invalid Module Specifier_ error. -> 1. If _pattern_ is **true**, then +> 5. Assert: _resolvedTarget_ is contained in _packageURL_. +> 6. If _subpath_ split on _"/"_ or _"\\"_ contains any _"."_, _".."_ or +> _"node\_modules"_ segments, throw an _Invalid Module Specifier_ error. +> 7. If _pattern_ is **true**, then > 1. Return the URL resolution of _resolvedTarget_ with every instance of -> _"*"_ replaced with _subpath_. -> 1. Otherwise, +> _"\*"_ replaced with _subpath_. +> 8. Otherwise, > 1. Return the URL resolution of the concatenation of _subpath_ and > _resolvedTarget_. -> 1. Otherwise, if _target_ is a non-null Object, then +> 2. Otherwise, if _target_ is a non-null Object, then > 1. If _exports_ contains any index property keys, as defined in ECMA-262 > [6.1.7 Array Index][], throw an _Invalid Package Configuration_ error. -> 1. For each property _p_ of _target_, in object insertion order as, +> 2. For each property _p_ of _target_, in object insertion order as, > 1. If _p_ equals _"default"_ or _conditions_ contains an entry for _p_, > then > 1. Let _targetValue_ be the value of the _p_ property in _target_. -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> 2. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _targetValue_, _subpath_, _pattern_, _internal_, > _conditions_). -> 1. If _resolved_ is equal to **undefined**, continue the loop. -> 1. Return _resolved_. -> 1. Return **undefined**. -> 1. Otherwise, if _target_ is an Array, then -> 1. If _target.length is zero, return **null**. -> 1. For each item _targetValue_ in _target_, do -> 1. Let _resolved_ be the result of **PACKAGE_TARGET_RESOLVE**( +> 3. If _resolved_ is equal to **undefined**, continue the loop. +> 4. Return _resolved_. +> 3. Return **undefined**. +> 3. Otherwise, if _target_ is an Array, then +> 1. If \_target.length is zero, return **null**. +> 2. For each item _targetValue_ in _target_, do +> 1. Let _resolved_ be the result of **PACKAGE\_TARGET\_RESOLVE**( > _packageURL_, _targetValue_, _subpath_, _pattern_, _internal_, > _conditions_), continuing the loop on any _Invalid Package Target_ > error. -> 1. If _resolved_ is **undefined**, continue the loop. -> 1. Return _resolved_. -> 1. Return or throw the last fallback resolution **null** return or error. -> 1. Otherwise, if _target_ is _null_, return **null**. -> 1. Otherwise throw an _Invalid Package Target_ error. +> 2. If _resolved_ is **undefined**, continue the loop. +> 3. Return _resolved_. +> 3. Return or throw the last fallback resolution **null** return or error. +> 4. Otherwise, if _target_ is _null_, return **null**. +> 5. Otherwise throw an _Invalid Package Target_ error. -**ESM_FORMAT**(_url_) +**ESM\_FORMAT**(_url_) > 1. Assert: _url_ corresponds to an existing file. -> 1. Let _pjson_ be the result of **READ_PACKAGE_SCOPE**(_url_). -> 1. If _url_ ends in _".mjs"_, then +> 2. Let _pjson_ be the result of **READ\_PACKAGE\_SCOPE**(_url_). +> 3. If _url_ ends in _".mjs"_, then > 1. Return _"module"_. -> 1. If _url_ ends in _".cjs"_, then +> 4. If _url_ ends in _".cjs"_, then > 1. Return _"commonjs"_. -> 1. If _pjson?.type_ exists and is _"module"_, then +> 5. If _pjson?.type_ exists and is _"module"_, then > 1. If _url_ ends in _".js"_, then > 1. Return _"module"_. -> 1. Throw an _Unsupported File Extension_ error. -> 1. Otherwise, +> 2. Throw an _Unsupported File Extension_ error. +> 6. Otherwise, > 1. Throw an _Unsupported File Extension_ error. -**READ_PACKAGE_SCOPE**(_url_) +**READ\_PACKAGE\_SCOPE**(_url_) > 1. Let _scopeURL_ be _url_. -> 1. While _scopeURL_ is not the file system root, +> 2. While _scopeURL_ is not the file system root, > 1. Set _scopeURL_ to the parent URL of _scopeURL_. -> 1. If _scopeURL_ ends in a _"node_modules"_ path segment, return **null**. -> 1. Let _pjson_ be the result of **READ_PACKAGE_JSON**(_scopeURL_). -> 1. If _pjson_ is not **null**, then +> 2. If _scopeURL_ ends in a _"node\_modules"_ path segment, return **null**. +> 3. Let _pjson_ be the result of **READ\_PACKAGE\_JSON**(_scopeURL_). +> 4. If _pjson_ is not **null**, then > 1. Return _pjson_. -> 1. Return **null**. +> 3. Return **null**. -**READ_PACKAGE_JSON**(_packageURL_) +**READ\_PACKAGE\_JSON**(_packageURL_) > 1. Let _pjsonURL_ be the resolution of _"package.json"_ within _packageURL_. -> 1. If the file at _pjsonURL_ does not exist, then +> 2. If the file at _pjsonURL_ does not exist, then > 1. Return **null**. -> 1. If the file at _packageURL_ does not parse as valid JSON, then +> 3. If the file at _packageURL_ does not parse as valid JSON, then > 1. Throw an _Invalid Package Configuration_ error. -> 1. Return the parsed JSON source of the file at _pjsonURL_. +> 4. Return the parsed JSON source of the file at _pjsonURL_. ### Customizing ESM specifier resolution algorithm @@ -1363,6 +1360,7 @@ success! ``` + [6.1.7 Array Index]: https://tc39.es/ecma262/#integer-index [CommonJS]: modules.md [Conditional exports]: packages.md#conditional-exports diff --git a/doc/api/events.md b/doc/api/events.md index b6a075f2a77a98..b659f1fd8cbcc5 100644 --- a/doc/api/events.md +++ b/doc/api/events.md @@ -113,7 +113,7 @@ myEmitter.emit('event'); 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. +the listener is unregistered and _then_ called. ```js const myEmitter = new MyEmitter(); @@ -226,6 +226,7 @@ do not have a catch handler to avoid infinite error loops: the recommendation is to **not use `async` functions as `'error'` event handlers**. ## Class: `EventEmitter` + @@ -259,15 +261,15 @@ added: v0.1.26 * `eventName` {string|symbol} The name of the event being listened for * `listener` {Function} The event handler function -The `EventEmitter` instance will emit its own `'newListener'` event *before* +The `EventEmitter` instance will emit its own `'newListener'` event _before_ a listener is added to its internal array of listeners. Listeners registered for the `'newListener'` event are passed the event name and a reference to the listener being added. The fact that the event is triggered before adding the listener has a subtle -but important side effect: any *additional* listeners registered to the same -`name` *within* the `'newListener'` callback are inserted *before* the +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 @@ -293,6 +295,7 @@ myEmitter.emit('event'); ``` ### Event: `'removeListener'` + @@ -320,6 +324,7 @@ added: v0.1.26 Alias for `emitter.on(eventName, listener)`. ### `emitter.emit(eventName[, ...args])` + @@ -368,6 +373,7 @@ myEmitter.emit('event', 1, 2, 3, 4, 5); ``` ### `emitter.eventNames()` + @@ -391,6 +397,7 @@ console.log(myEE.eventNames()); ``` ### `emitter.getMaxListeners()` + @@ -402,6 +409,7 @@ set by [`emitter.setMaxListeners(n)`][] or defaults to [`events.defaultMaxListeners`][]. ### `emitter.listenerCount(eventName)` + @@ -412,6 +420,7 @@ added: v3.2.0 Returns the number of listeners listening to the event named `eventName`. ### `emitter.listeners(eventName)` + * `eventName` {string|symbol} -* Returns: {Function[]} +* Returns: {Function\[]} Returns a copy of the array of listeners for the event named `eventName`. @@ -435,6 +444,7 @@ console.log(util.inspect(server.listeners('connection'))); ``` ### `emitter.off(eventName, listener)` + @@ -446,6 +456,7 @@ added: v10.0.0 Alias for [`emitter.removeListener()`][]. ### `emitter.on(eventName, listener)` + @@ -483,6 +494,7 @@ myEE.emit('foo'); ``` ### `emitter.once(eventName, listener)` + @@ -517,6 +529,7 @@ myEE.emit('foo'); ``` ### `emitter.prependListener(eventName, listener)` + @@ -525,7 +538,7 @@ added: v6.0.0 * `listener` {Function} The callback function * Returns: {EventEmitter} -Adds the `listener` function to the *beginning* of the listeners array for the +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 already been added. Multiple calls passing the same combination of `eventName` and `listener` will result in the `listener` being added, and called, multiple @@ -540,6 +553,7 @@ server.prependListener('connection', (stream) => { Returns a reference to the `EventEmitter`, so that calls can be chained. ### `emitter.prependOnceListener(eventName, listener)` + @@ -549,7 +563,7 @@ added: v6.0.0 * Returns: {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 +_beginning_ of the listeners array. The next time `eventName` is triggered, this listener is removed, and then invoked. ```js @@ -561,6 +575,7 @@ server.prependOnceListener('connection', (stream) => { Returns a reference to the `EventEmitter`, so that calls can be chained. ### `emitter.removeAllListeners([eventName])` + @@ -577,6 +592,7 @@ component or module (e.g. sockets or file streams). Returns a reference to the `EventEmitter`, so that calls can be chained. ### `emitter.removeListener(eventName, listener)` + @@ -604,8 +620,8 @@ called multiple times to remove each instance. Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any -`removeListener()` or `removeAllListeners()` calls *after* emitting and -*before* the last listener finishes execution will not remove them from +`removeListener()` or `removeAllListeners()` calls _after_ emitting and +_before_ the last listener finishes execution will not remove them from `emit()` in progress. Subsequent events behave as expected. ```js @@ -639,7 +655,7 @@ myEmitter.emit('event'); ``` Because listeners are managed using an internal array, calling this will -change the position indices of any listener registered *after* the listener +change the position indices of any listener registered _after_ the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the `emitter.listeners()` method will need to be recreated. @@ -667,6 +683,7 @@ ee.emit('ping'); Returns a reference to the `EventEmitter`, so that calls can be chained. ### `emitter.setMaxListeners(n)` + @@ -683,12 +700,13 @@ modified for this specific `EventEmitter` instance. The value can be set to Returns a reference to the `EventEmitter`, so that calls can be chained. ### `emitter.rawListeners(eventName)` + * `eventName` {string|symbol} -* Returns: {Function[]} +* Returns: {Function\[]} Returns a copy of the array of listeners for the event named `eventName`, including any wrappers (such as those created by `.once()`). @@ -718,6 +736,7 @@ emitter.emit('log'); ``` ### `emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])` + @@ -763,12 +783,12 @@ added: v0.11.2 By default, a maximum of `10` listeners can be registered for any single event. This limit can be changed for individual `EventEmitter` instances using the [`emitter.setMaxListeners(n)`][] method. To change the default -for *all* `EventEmitter` instances, the `events.defaultMaxListeners` +for _all_ `EventEmitter` instances, the `events.defaultMaxListeners` property can be used. If this value is not a positive number, a `RangeError` is thrown. Take caution when setting the `events.defaultMaxListeners` because the -change affects *all* `EventEmitter` instances, including those created before +change affects _all_ `EventEmitter` instances, including those created before the change is made. However, calling [`emitter.setMaxListeners(n)`][] still has precedence over `events.defaultMaxListeners`. @@ -796,6 +816,7 @@ listeners, respectively. Its `name` property is set to `'MaxListenersExceededWarning'`. ## `events.errorMonitor` + + * `emitterOrTarget` {EventEmitter|EventTarget} * `eventName` {string|symbol} -* Returns: {Function[]} +* Returns: {Function\[]} Returns a copy of the array of listeners for the event named `eventName`. @@ -845,6 +868,7 @@ const { getEventListeners, EventEmitter } = require('events'); ``` ## `events.once(emitter, name[, options])` + * `n` {number} A non-negative number. The maximum number of listeners per `EventTarget` event. -* `...eventsTargets` {EventTarget[]|EventEmitter[]} Zero or more {EventTarget} +* `...eventsTargets` {EventTarget\[]|EventEmitter\[]} Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} objects. @@ -1137,7 +1166,9 @@ setMaxListeners(5, target, emitter); ``` + ## `EventTarget` and `Event` API + @@ -1292,6 +1325,7 @@ added: v14.5.0 This is not used in Node.js and is provided purely for completeness. #### `event.cancelBubble()` + @@ -1300,6 +1334,7 @@ Alias for `event.stopPropagation()`. This is not used in Node.js and is provided purely for completeness. #### `event.cancelable` + @@ -1307,6 +1342,7 @@ added: v14.5.0 * Type: {boolean} True if the event was created with the `cancelable` option. #### `event.composed` + @@ -1316,6 +1352,7 @@ added: v14.5.0 This is not used in Node.js and is provided purely for completeness. #### `event.composedPath()` + @@ -1325,6 +1362,7 @@ empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. #### `event.currentTarget` + @@ -1334,6 +1372,7 @@ added: v14.5.0 Alias for `event.target`. #### `event.defaultPrevented` + @@ -1344,6 +1383,7 @@ Is `true` if `cancelable` is `true` and `event.preventDefault()` has been called. #### `event.eventPhase` + @@ -1354,6 +1394,7 @@ added: v14.5.0 This is not used in Node.js and is provided purely for completeness. #### `event.isTrusted` + @@ -1364,6 +1405,7 @@ The {AbortSignal} `"abort"` event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. #### `event.preventDefault()` + @@ -1371,6 +1413,7 @@ added: v14.5.0 Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. #### `event.returnValue` + @@ -1380,6 +1423,7 @@ added: v14.5.0 This is not used in Node.js and is provided purely for completeness. #### `event.srcElement` + @@ -1389,6 +1433,7 @@ added: v14.5.0 Alias for `event.target`. #### `event.stopImmediatePropagation()` + @@ -1396,6 +1441,7 @@ added: v14.5.0 Stops the invocation of event listeners after the current one completes. #### `event.stopPropagation()` + @@ -1403,6 +1449,7 @@ added: v14.5.0 This is not used in Node.js and is provided purely for completeness. #### `event.target` + @@ -1410,6 +1457,7 @@ added: v14.5.0 * Type: {EventTarget} The `EventTarget` dispatching the event. #### `event.timeStamp` + @@ -1419,6 +1467,7 @@ added: v14.5.0 The millisecond timestamp when the `Event` object was created. #### `event.type` + @@ -1428,6 +1477,7 @@ added: v14.5.0 The event type identifier. ### Class: `EventTarget` + #### `eventTarget.addEventListener(type, listener[, options])` + @@ -1480,6 +1531,7 @@ target.removeEventListener('foo', handler, { capture: true }); ``` #### `eventTarget.dispatchEvent(event)` + @@ -1494,6 +1546,7 @@ The registered event listeners is synchronously invoked in the order they were registered. #### `eventTarget.removeEventListener(type, listener)` + @@ -1506,6 +1559,7 @@ added: v14.5.0 Removes the `listener` from the list of handlers for event `type`. ### Class: `NodeEventTarget` + @@ -1516,12 +1570,15 @@ The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` that emulates a subset of the `EventEmitter` API. #### `nodeEventTarget.addListener(type, listener[, options])` + * `type` {string} + * `listener` {Function|EventListener} + * `options` {Object} * `once` {boolean} @@ -1533,16 +1590,18 @@ equivalent `EventEmitter` API. The only difference between `addListener()` and `EventTarget`. #### `nodeEventTarget.eventNames()` + -* Returns: {string[]} +* Returns: {string\[]} Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. #### `nodeEventTarget.listenerCount(type)` + @@ -1555,11 +1614,13 @@ Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. #### `nodeEventTarget.off(type, listener)` + * `type` {string} + * `listener` {Function|EventListener} * Returns: {EventTarget} this @@ -1567,12 +1628,15 @@ added: v14.5.0 Node.js-specific alias for `eventTarget.removeListener()`. #### `nodeEventTarget.on(type, listener[, options])` + * `type` {string} + * `listener` {Function|EventListener} + * `options` {Object} * `once` {boolean} @@ -1581,12 +1645,15 @@ added: v14.5.0 Node.js-specific alias for `eventTarget.addListener()`. #### `nodeEventTarget.once(type, listener[, options])` + * `type` {string} + * `listener` {Function|EventListener} + * `options` {Object} * Returns: {EventTarget} this @@ -1596,6 +1663,7 @@ listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. #### `nodeEventTarget.removeAllListeners([type])` + @@ -1609,11 +1677,13 @@ removes all registered listeners for `type`, otherwise removes all registered listeners. #### `nodeEventTarget.removeListener(type, listener)` + * `type` {string} + * `listener` {Function|EventListener} * Returns: {EventTarget} this diff --git a/doc/api/fs.md b/doc/api/fs.md index f09063a575d5f2..c277c7874f9f88 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -122,6 +122,7 @@ try { ``` ## Promises API + @@ -165,6 +167,7 @@ it can be unreliable and the file may not be closed. Instead, always explicitly close {FileHandle}s. Node.js may change this behavior in the future. #### Event: `'close'` + @@ -173,6 +176,7 @@ The `'close'` event is emitted when the {FileHandle} has been closed and can no longer be used. #### `filehandle.appendFile(data[, options])` + @@ -189,6 +193,7 @@ to with [`fsPromises.open()`][]. Therefore, this is equivalent to [`filehandle.writeFile()`][]. #### `filehandle.chmod(mode)` + @@ -199,6 +204,7 @@ added: v10.0.0 Modifies the permissions on the file. See chmod(2). #### `filehandle.chown(uid, gid)` + @@ -210,6 +216,7 @@ added: v10.0.0 Changes the ownership of the file. A wrapper for chown(2). #### `filehandle.close()` + @@ -231,6 +238,7 @@ try { ``` #### `filehandle.createReadStream([options])` + @@ -250,7 +258,7 @@ returned by this method has a default `highWaterMark` of 64 kb. `options` can include `start` and `end` values to read a range of bytes from the file instead of the entire file. Both `start` and `end` are inclusive and start counting at 0, allowed values are in the -[0, [`Number.MAX_SAFE_INTEGER`][]] range. If `start` is +\[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}. @@ -297,6 +305,7 @@ fd.createReadStream({ start: 90, end: 99 }); ``` #### `filehandle.createWriteStream([options])` + @@ -310,9 +319,9 @@ added: v16.11.0 `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}. +\[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}. If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, @@ -324,6 +333,7 @@ By default, the stream will emit a `'close'` event after it has been destroyed. Set the `emitClose` option to `false` to change this behavior. #### `filehandle.datasync()` + @@ -337,6 +347,7 @@ fdatasync(2) documentation for details. Unlike `filehandle.sync` this method does not flush modified metadata. #### `filehandle.fd` + @@ -344,6 +355,7 @@ added: v10.0.0 * {number} The numeric file descriptor managed by the {FileHandle} object. #### `filehandle.read(buffer, offset, length, position)` + @@ -367,11 +379,13 @@ If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. #### `filehandle.read([options])` + + * `options` {Object} * `buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the file data read. **Default:** `Buffer.alloc(16384)` @@ -394,6 +408,7 @@ If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero. #### `filehandle.readFile(options)` + @@ -417,24 +432,26 @@ position till the end of the file. It doesn't always read from the beginning of the file. #### `filehandle.readv(buffers[, position])` + -* `buffers` {Buffer[]|TypedArray[]|DataView[]} +* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} * `position` {integer} The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. * Returns: {Promise} Fulfills upon success an object containing two properties: * `bytesRead` {integer} the number of bytes read - * `buffers` {Buffer[]|TypedArray[]|DataView[]} property containing + * `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} property containing a reference to the `buffers` input. Read from a file and write to an array of {ArrayBufferView}s #### `filehandle.stat([options])` + @@ -461,6 +479,7 @@ device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. #### `filehandle.truncate(len)` + @@ -493,6 +512,7 @@ extended part is filled with null bytes (`'\0'`): If `len` is negative then `0` will be used. #### `filehandle.utimes(atime, mtime)` + @@ -505,6 +525,7 @@ Change the file system timestamps of the object referenced by the {FileHandle} then resolves the promise with no arguments upon success. #### `filehandle.write(buffer[, offset[, length[, position]]])` + -* `buffers` {Buffer[]|TypedArray[]|DataView[]} +* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} * `position` {integer} The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current position. @@ -643,7 +667,7 @@ Write an array of {ArrayBufferView}s to the file. The promise is resolved with an object containing a two properties: * `bytesWritten` {integer} the number of bytes written -* `buffers` {Buffer[]|TypedArray[]|DataView[]} a reference to the `buffers` +* `buffers` {Buffer\[]|TypedArray\[]|DataView\[]} a reference to the `buffers` input. It is unsafe to call `writev()` multiple times on the same file without waiting @@ -654,6 +678,7 @@ The kernel ignores the position argument and always appends the data to the end of the file. ### `fsPromises.access(path[, mode])` + @@ -692,6 +717,7 @@ calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible. ### `fsPromises.appendFile(path, data[, options])` + @@ -716,6 +742,7 @@ The `path` may be specified as a {FileHandle} that has been opened for appending (using `fsPromises.open()`). ### `fsPromises.chmod(path, mode)` + @@ -727,6 +754,7 @@ added: v10.0.0 Changes the permissions of a file. ### `fsPromises.chown(path, uid, gid)` + @@ -739,6 +767,7 @@ added: v10.0.0 Changes the ownership of a file. ### `fsPromises.copyFile(src, dest[, mode])` + @@ -808,7 +838,7 @@ added: v16.7.0 * `filter` {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`. - * `force` {boolean} overwrite existing file or directory. _The copy + * `force` {boolean} 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. **Default:** `true`. @@ -824,6 +854,7 @@ When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. ### `fsPromises.lchmod(path, mode)` + @@ -837,6 +868,7 @@ Changes the permissions on a symbolic link. This method is only implemented on macOS. ### `fsPromises.lchown(path, uid, gid)` + @@ -882,6 +916,7 @@ Creates a new link from the `existingPath` to the `newPath`. See the POSIX link(2) documentation for more detail. ### `fsPromises.lstat(path[, options])` + @@ -923,6 +959,7 @@ property indicating whether parent directories should be created. Calling rejection only when `recursive` is false. ### `fsPromises.mkdtemp(prefix[, options])` + + * `path` {string|Buffer|URL} * `options` {string|Object} * `encoding` {string} **Default:** `'utf8'` @@ -1146,6 +1189,7 @@ the link path returned. If the `encoding` is set to `'buffer'`, the link path returned will be passed as a {Buffer} object. ### `fsPromises.realpath(path[, options])` + @@ -1170,6 +1214,7 @@ be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. ### `fsPromises.rename(oldPath, newPath)` + @@ -1181,6 +1226,7 @@ added: v10.0.0 Renames `oldPath` to `newPath`. ### `fsPromises.rmdir(path[, options])` + @@ -1264,6 +1311,7 @@ added: v14.14.0 Removes files and directories (modeled on the standard POSIX `rm` utility). ### `fsPromises.stat(path[, options])` + @@ -1298,6 +1347,7 @@ to be absolute. When using `'junction'`, the `target` argument will automatically be normalized to absolute path. ### `fsPromises.truncate(path[, len])` + @@ -1310,6 +1360,7 @@ Truncates (shortens or extends the length) of the content at `path` to `len` bytes. ### `fsPromises.unlink(path)` + @@ -1323,6 +1374,7 @@ path that is not a symbolic link, the file is deleted. See the POSIX unlink(2) documentation for more detail. ### `fsPromises.utimes(path, atime, mtime)` + @@ -1342,6 +1394,7 @@ The `atime` and `mtime` arguments follow these rules: `-Infinity`, an `Error` will be thrown. ### `fsPromises.watch(filename[, options])` + @@ -1355,7 +1408,7 @@ added: v15.9.0 specified, and only on supported platforms (See [caveats][]). **Default:** `false`. * `encoding` {string} Specifies the character encoding to be used for the - filename passed to the listener. **Default:** `'utf8'`. + filename passed to the listener. **Default:** `'utf8'`. * `signal` {AbortSignal} An {AbortSignal} used to signal when the watcher should stop. * Returns: {AsyncIterator} of objects with the properties: @@ -1391,6 +1444,7 @@ disappears in the directory. All the [caveats][] for `fs.watch()` also apply to `fsPromises.watch()`. ### `fsPromises.writeFile(file, data[, options])` + @@ -1959,7 +2020,7 @@ added: v16.7.0 * `filter` {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`. - * `force` {boolean} overwrite existing file or directory. _The copy + * `force` {boolean} 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. **Default:** `true`. @@ -1975,6 +2036,7 @@ When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. ### `fs.createReadStream(path[, options])` + + * `fd` {integer} * `options` {Object} * `buffer` {Buffer|TypedArray|DataView} **Default:** `Buffer.alloc(16384)` @@ -2976,6 +3059,7 @@ Similar to the [`fs.read()`][] function, this version takes an optional above values. ### `fs.readdir(path[, options], callback)` + * `fd` {integer} -* `buffers` {ArrayBufferView[]} +* `buffers` {ArrayBufferView\[]} * `position` {integer} * `callback` {Function} * `err` {Error} * `bytesRead` {integer} - * `buffers` {ArrayBufferView[]} + * `buffers` {ArrayBufferView\[]} Read from a file specified by `fd` and write to an array of `ArrayBufferView`s using `readv()`. @@ -3223,6 +3310,7 @@ If this method is invoked as its [`util.promisify()`][]ed version, it returns a promise for an `Object` with `bytesRead` and `buffers` properties. ### `fs.realpath(path[, options], callback)` + @@ -3311,6 +3400,7 @@ be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. ### `fs.rename(oldPath, newPath, callback)` + @@ -3451,6 +3543,7 @@ utility). No arguments other than a possible exception are given to the completion callback. ### `fs.stat(path[, options], callback)` + @@ -3713,7 +3810,7 @@ added: v0.1.31 `fs.watchFile()` Stop watching for changes on `filename`. If `listener` is specified, only that -particular listener is removed. Otherwise, *all* listeners are removed, +particular listener is removed. Otherwise, _all_ listeners are removed, effectively stopping watching of `filename`. Calling `fs.unwatchFile()` with a filename that is not being watched is a @@ -3724,6 +3821,7 @@ Using [`fs.watch()`][] is more efficient than `fs.watchFile()` and and `fs.unwatchFile()` when possible. ### `fs.utimes(path, atime, mtime, callback)` + * `fd` {integer} -* `buffers` {ArrayBufferView[]} +* `buffers` {ArrayBufferView\[]} * `position` {integer} * `callback` {Function} * `err` {Error} * `bytesWritten` {integer} - * `buffers` {ArrayBufferView[]} + * `buffers` {ArrayBufferView\[]} Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. @@ -4270,6 +4374,7 @@ The synchronous APIs perform all operations synchronously, blocking the event loop until the operation completes or fails. ### `fs.accessSync(path[, mode])` + @@ -4419,6 +4528,7 @@ through any other `fs` operation may lead to undefined behavior. See the POSIX close(2) documentation for more detail. ### `fs.copyFileSync(src, dest[, mode])` + @@ -4477,7 +4588,7 @@ added: v16.7.0 exists, throw an error. **Default:** `false`. * `filter` {Function} Function to filter copied files/directories. Return `true` to copy the item, `false` to ignore it. **Default:** `undefined` - * `force` {boolean} overwrite existing file or directory. _The copy + * `force` {boolean} 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. **Default:** `true`. @@ -4492,6 +4603,7 @@ When copying a directory to another directory, globs are not supported and behavior is similar to `cp dir1/ dir2/`. ### `fs.existsSync(path)` + @@ -4533,6 +4646,7 @@ Sets the permissions on the file. Returns `undefined`. See the POSIX fchmod(2) documentation for more detail. ### `fs.fchownSync(fd, uid, gid)` + @@ -4546,6 +4660,7 @@ Sets the owner of the file. Returns `undefined`. See the POSIX fchown(2) documentation for more detail. ### `fs.fdatasyncSync(fd)` + @@ -4557,6 +4672,7 @@ operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. Returns `undefined`. ### `fs.fstatSync(fd[, options])` + @@ -4588,6 +4705,7 @@ device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. Returns `undefined`. ### `fs.ftruncateSync(fd[, len])` + @@ -4601,6 +4719,7 @@ For detailed information, see the documentation of the asynchronous version of this API: [`fs.ftruncate()`][]. ### `fs.futimesSync(fd, atime, mtime)` + @@ -4631,6 +4751,7 @@ This method is only implemented on macOS. See the POSIX lchmod(2) documentation for more detail. ### `fs.lchownSync(path, uid, gid)` + * `fd` {integer} -* `buffers` {ArrayBufferView[]} +* `buffers` {ArrayBufferView\[]} * `position` {integer} * Returns: {number} The number of bytes read. @@ -4987,6 +5121,7 @@ For detailed information, see the documentation of the asynchronous version of this API: [`fs.readv()`][]. ### `fs.realpathSync(path[, options])` + @@ -5040,6 +5176,7 @@ be mounted on `/proc` in order for this function to work. Glibc does not have this restriction. ### `fs.renameSync(oldPath, newPath)` + @@ -5143,6 +5282,7 @@ Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. ### `fs.statSync(path[, options])` + @@ -5212,6 +5354,7 @@ Passing a file descriptor is deprecated and may result in an error being thrown in the future. ### `fs.unlinkSync(path)` + * `fd` {integer} -* `buffers` {ArrayBufferView[]} +* `buffers` {ArrayBufferView\[]} * `position` {integer} * Returns: {number} The number of bytes written. @@ -5379,6 +5527,7 @@ The common objects are shared by all of the file system API variants (promise, callback, and synchronous). ### Class: `fs.Dir` + @@ -5404,6 +5553,7 @@ When using the async iterator, the {fs.Dir} object will be automatically closed after the iterator exits. #### `dir.close()` + @@ -5417,6 +5567,7 @@ A promise is returned that will be resolved after the resource has been closed. #### `dir.close(callback)` + @@ -5430,6 +5581,7 @@ Subsequent reads will result in errors. The `callback` will be called after the resource handle has been closed. #### `dir.closeSync()` + @@ -5438,6 +5590,7 @@ Synchronously close the directory's underlying resource handle. Subsequent reads will result in errors. #### `dir.path` + @@ -5448,6 +5601,7 @@ The read-only path of this directory as was provided to [`fs.opendir()`][], [`fs.opendirSync()`][], or [`fsPromises.opendir()`][]. #### `dir.read()` + @@ -5466,6 +5620,7 @@ Entries added or removed while iterating over the directory might not be included in the iteration results. #### `dir.read(callback)` + @@ -5486,6 +5641,7 @@ Entries added or removed while iterating over the directory might not be included in the iteration results. #### `dir.readSync()` + @@ -5503,6 +5659,7 @@ Entries added or removed while iterating over the directory might not be included in the iteration results. #### `dir[Symbol.asyncIterator]()` + @@ -5523,6 +5680,7 @@ Entries added or removed while iterating over the directory might not be included in the iteration results. ### Class: `fs.Dirent` + @@ -5536,6 +5694,7 @@ the `withFileTypes` option set to `true`, the resulting array is filled with {fs.Dirent} objects, rather than strings or {Buffer}s. #### `dirent.isBlockDevice()` + @@ -5545,6 +5704,7 @@ added: v10.10.0 Returns `true` if the {fs.Dirent} object describes a block device. #### `dirent.isCharacterDevice()` + @@ -5554,6 +5714,7 @@ added: v10.10.0 Returns `true` if the {fs.Dirent} object describes a character device. #### `dirent.isDirectory()` + @@ -5564,6 +5725,7 @@ Returns `true` if the {fs.Dirent} object describes a file system directory. #### `dirent.isFIFO()` + @@ -5574,6 +5736,7 @@ Returns `true` if the {fs.Dirent} object describes a first-in-first-out (FIFO) pipe. #### `dirent.isFile()` + @@ -5583,6 +5746,7 @@ added: v10.10.0 Returns `true` if the {fs.Dirent} object describes a regular file. #### `dirent.isSocket()` + @@ -5592,6 +5756,7 @@ added: v10.10.0 Returns `true` if the {fs.Dirent} object describes a socket. #### `dirent.isSymbolicLink()` + @@ -5601,6 +5766,7 @@ added: v10.10.0 Returns `true` if the {fs.Dirent} object describes a symbolic link. #### `dirent.name` + @@ -5612,6 +5778,7 @@ value is determined by the `options.encoding` passed to [`fs.readdir()`][] or [`fs.readdirSync()`][]. ### Class: `fs.FSWatcher` + @@ -5625,6 +5792,7 @@ All {fs.FSWatcher} objects emit a `'change'` event whenever a specific watched file is modified. #### Event: `'change'` + @@ -5652,6 +5820,7 @@ watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => { ``` #### Event: `'close'` + @@ -5660,6 +5829,7 @@ Emitted when the watcher stops watching for changes. The closed {fs.FSWatcher} object is no longer usable in the event handler. #### Event: `'error'` + @@ -5670,6 +5840,7 @@ Emitted when an error occurs while watching the file. The errored {fs.FSWatcher} object is no longer usable in the event handler. #### `watcher.close()` + @@ -5678,6 +5849,7 @@ Stop watching for changes on the given {fs.FSWatcher}. Once stopped, the {fs.FSWatcher} object is no longer usable. #### `watcher.ref()` + @@ -5764,6 +5941,7 @@ Instances of {fs.ReadStream} are created and returned using the [`fs.createReadStream()`][] function. #### Event: `'close'` + @@ -5771,6 +5949,7 @@ added: v0.1.93 Emitted when the {fs.ReadStream}'s underlying file descriptor has been closed. #### Event: `'open'` + @@ -5780,6 +5959,7 @@ added: v0.1.93 Emitted when the {fs.ReadStream}'s file descriptor has been opened. #### Event: `'ready'` + @@ -5789,6 +5969,7 @@ Emitted when the {fs.ReadStream} is ready to be used. Fires immediately after `'open'`. #### `readStream.bytesRead` + @@ -5798,6 +5979,7 @@ added: v6.4.0 The number of bytes that have been read so far. #### `readStream.path` + @@ -5811,6 +5993,7 @@ argument to `fs.createReadStream()`. If `path` is passed as a string, then `readStream.path` will be `undefined`. #### `readStream.pending` + @@ -5899,6 +6084,7 @@ added: v0.1.10 Returns `true` if the {fs.Stats} object describes a block device. #### `stats.isCharacterDevice()` + @@ -5908,6 +6094,7 @@ added: v0.1.10 Returns `true` if the {fs.Stats} object describes a character device. #### `stats.isDirectory()` + @@ -5921,6 +6108,7 @@ always return `false`. This is because [`fs.lstat()`][] returns information about a symbolic link itself and not the path it resolves to. #### `stats.isFIFO()` + @@ -5931,6 +6119,7 @@ Returns `true` if the {fs.Stats} object describes a first-in-first-out (FIFO) pipe. #### `stats.isFile()` + @@ -5940,6 +6129,7 @@ added: v0.1.10 Returns `true` if the {fs.Stats} object describes a regular file. #### `stats.isSocket()` + @@ -5949,6 +6139,7 @@ added: v0.1.10 Returns `true` if the {fs.Stats} object describes a socket. #### `stats.isSymbolicLink()` + @@ -6020,6 +6211,7 @@ The file system block size for i/o operations. The number of blocks allocated for this file. #### `stats.atimeMs` + @@ -6030,6 +6222,7 @@ The timestamp indicating the last time this file was accessed expressed in milliseconds since the POSIX Epoch. #### `stats.mtimeMs` + @@ -6040,6 +6233,7 @@ The timestamp indicating the last time this file was modified expressed in milliseconds since the POSIX Epoch. #### `stats.ctimeMs` + @@ -6050,6 +6244,7 @@ The timestamp indicating the last time the file status was changed expressed in milliseconds since the POSIX Epoch. #### `stats.birthtimeMs` + @@ -6060,6 +6255,7 @@ The timestamp indicating the creation time of this file expressed in milliseconds since the POSIX Epoch. #### `stats.atimeNs` + @@ -6072,6 +6268,7 @@ The timestamp indicating the last time this file was accessed expressed in nanoseconds since the POSIX Epoch. #### `stats.mtimeNs` + @@ -6084,6 +6281,7 @@ The timestamp indicating the last time this file was modified expressed in nanoseconds since the POSIX Epoch. #### `stats.ctimeNs` + @@ -6096,6 +6294,7 @@ The timestamp indicating the last time the file status was changed expressed in nanoseconds since the POSIX Epoch. #### `stats.birthtimeNs` + @@ -6108,6 +6307,7 @@ The timestamp indicating the creation time of this file expressed in nanoseconds since the POSIX Epoch. #### `stats.atime` + @@ -6117,6 +6317,7 @@ added: v0.11.13 The timestamp indicating the last time this file was accessed. #### `stats.mtime` + @@ -6126,6 +6327,7 @@ added: v0.11.13 The timestamp indicating the last time this file was modified. #### `stats.ctime` + @@ -6135,6 +6337,7 @@ added: v0.11.13 The timestamp indicating the last time the file status was changed. #### `stats.birthtime` + @@ -6184,6 +6387,7 @@ 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. ### Class: `fs.WriteStream` + @@ -6194,6 +6398,7 @@ Instances of {fs.WriteStream} are created and returned using the [`fs.createWriteStream()`][] function. #### Event: `'close'` + @@ -6201,6 +6406,7 @@ added: v0.1.93 Emitted when the {fs.WriteStream}'s underlying file descriptor has been closed. #### Event: `'open'` + @@ -6210,6 +6416,7 @@ added: v0.1.93 Emitted when the {fs.WriteStream}'s file is opened. #### Event: `'ready'` + @@ -6219,6 +6426,7 @@ Emitted when the {fs.WriteStream} is ready to be used. Fires immediately after `'open'`. #### `writeStream.bytesWritten` + @@ -6227,6 +6435,7 @@ The number of bytes written so far. Does not include data that is still queued for writing. #### `writeStream.close([callback])` + @@ -6239,6 +6448,7 @@ callback that will be executed once the `writeStream` is closed. #### `writeStream.path` + @@ -6249,6 +6459,7 @@ argument to [`fs.createWriteStream()`][]. If `path` is passed as a string, then `writeStream.path` will be a {Buffer}. #### `writeStream.pending` + @@ -6668,9 +6879,11 @@ try { ``` #### File URL paths + + For most `fs` module functions, the `path` or `filename` argument may be passed as a {URL} object using the `file:` protocol. @@ -6792,7 +7005,7 @@ example `fs.readdirSync('C:\\')` can potentially return a different result than On POSIX systems, for every process, the kernel maintains a table of currently open files and resources. Each open file is assigned a simple numeric -identifier called a *file descriptor*. At the system-level, all file system +identifier called a _file descriptor_. At the system-level, all file system operations use these file descriptors to identify and track each specific file. Windows systems use a different but conceptually similar mechanism for tracking resources. To simplify things for users, Node.js abstracts away the diff --git a/doc/api/globals.md b/doc/api/globals.md index db071e2cb95dfb..c7e539ca41aade 100644 --- a/doc/api/globals.md +++ b/doc/api/globals.md @@ -19,6 +19,7 @@ that are part of the JavaScript language itself, which are also globally accessible. ## Class: `AbortController` + @@ -52,6 +54,7 @@ Triggers the abort signal, causing the `abortController.signal` to emit the `'abort'` event. ### `abortController.signal` + @@ -59,6 +62,7 @@ added: v15.0.0 * Type: {AbortSignal} ### Class: `AbortSignal` + @@ -69,6 +73,7 @@ The `AbortSignal` is used to notify observers when the `abortController.abort()` method is called. #### Static method: `AbortSignal.abort()` + @@ -78,6 +83,7 @@ added: v15.12.0 Returns a new already aborted `AbortSignal`. #### Event: `'abort'` + @@ -112,6 +118,7 @@ removed as soon as the `'abort'` event is handled. Failure to do so may result in memory leaks. #### `abortSignal.aborted` + @@ -119,6 +126,7 @@ added: v15.0.0 * Type: {boolean} True after the `AbortController` has been aborted. #### `abortSignal.onabort` + @@ -129,6 +137,7 @@ An optional callback function that may be set by user code to be notified when the `abortController.abort()` function has been called. ## Class: `Buffer` + @@ -148,6 +157,7 @@ This variable may appear to be global but is not. See [`__dirname`][]. This variable may appear to be global but is not. See [`__filename`][]. ## `atob(data)` + @@ -157,6 +167,7 @@ added: v16.0.0 Global alias for [`buffer.atob()`][]. ## `btoa(data)` + @@ -166,6 +177,7 @@ added: v16.0.0 Global alias for [`buffer.btoa()`][]. ## `clearImmediate(immediateObject)` + @@ -175,6 +187,7 @@ added: v0.9.1 [`clearImmediate`][] is described in the [timers][] section. ## `clearInterval(intervalObject)` + @@ -184,6 +197,7 @@ added: v0.0.1 [`clearInterval`][] is described in the [timers][] section. ## `clearTimeout(timeoutObject)` + @@ -193,6 +207,7 @@ added: v0.0.1 [`clearTimeout`][] is described in the [timers][] section. ## `console` + @@ -204,6 +219,7 @@ added: v0.1.100 Used to print to stdout and stderr. See the [`console`][] section. ## `Event` + @@ -250,6 +268,7 @@ Node.js this is different. The top-level scope is not the global scope; `var something` inside a Node.js module will be local to that module. ## `MessageChannel` + @@ -259,6 +278,7 @@ added: v15.0.0 The `MessageChannel` class. See [`MessageChannel`][] for more details. ## `MessageEvent` + @@ -268,6 +288,7 @@ added: v15.0.0 The `MessageEvent` class. See [`MessageEvent`][] for more details. ## `MessagePort` + @@ -285,6 +306,7 @@ This variable may appear to be global but is not. See [`module`][]. The [`perf_hooks.performance`][] object. ## `process` + @@ -296,6 +318,7 @@ added: v0.1.7 The process object. See the [`process` object][] section. ## `queueMicrotask(callback)` + @@ -339,6 +362,7 @@ DataHandler.prototype.load = async function load(key) { This variable may appear to be global but is not. See [`require()`][]. ## `setImmediate(callback[, ...args])` + @@ -348,6 +372,7 @@ added: v0.9.1 [`setImmediate`][] is described in the [timers][] section. ## `setInterval(callback, delay[, ...args])` + @@ -357,6 +382,7 @@ added: v0.0.1 [`setInterval`][] is described in the [timers][] section. ## `setTimeout(callback, delay[, ...args])` + @@ -366,6 +392,7 @@ added: v0.0.1 [`setTimeout`][] is described in the [timers][] section. ## `TextDecoder` + @@ -375,6 +402,7 @@ added: v11.0.0 The WHATWG `TextDecoder` class. See the [`TextDecoder`][] section. ## `TextEncoder` + @@ -384,6 +412,7 @@ added: v11.0.0 The WHATWG `TextEncoder` class. See the [`TextEncoder`][] section. ## `URL` + @@ -393,6 +422,7 @@ added: v10.0.0 The WHATWG `URL` class. See the [`URL`][] section. ## `URLSearchParams` + @@ -402,6 +432,7 @@ added: v10.0.0 The WHATWG `URLSearchParams` class. See the [`URLSearchParams`][] section. ## `WebAssembly` + diff --git a/doc/api/http.md b/doc/api/http.md index 74b0f9975fd5bb..70133e1e509598 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -17,6 +17,7 @@ user is able to stream data. HTTP message headers are represented by an object like this: + ```js { 'content-length': '123', 'content-type': 'text/plain', @@ -40,6 +41,7 @@ example, the previous message header object might have a `rawHeaders` list like the following: + ```js [ 'ConTent-Length', '123456', 'content-LENGTH', '123', @@ -50,6 +52,7 @@ list like the following: ``` ## Class: `http.Agent` + @@ -110,6 +113,7 @@ http.get({ ``` ### `new Agent([options])` + @@ -213,6 +218,7 @@ type other than {net.Socket}. `callback` has a signature of `(err, stream)`. ### `agent.keepSocketAlive(socket)` + @@ -236,6 +242,7 @@ The `socket` argument can be an instance of {net.Socket}, a subclass of {stream.Duplex}. ### `agent.reuseSocket(socket, request)` + @@ -256,6 +263,7 @@ The `socket` argument can be an instance of {net.Socket}, a subclass of {stream.Duplex}. ### `agent.destroy()` + @@ -269,6 +277,7 @@ sockets might stay open for quite a long time before the server terminates them. ### `agent.freeSockets` + @@ -306,6 +316,7 @@ the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability. ### `agent.maxFreeSockets` + @@ -317,6 +328,7 @@ sets the maximum number of sockets that will be left open in the free state. ### `agent.maxSockets` + @@ -327,6 +339,7 @@ By default set to `Infinity`. Determines how many concurrent sockets the agent can have open per origin. Origin is the returned value of [`agent.getName()`][]. ### `agent.maxTotalSockets` + @@ -376,7 +392,7 @@ added: v0.1.17 This object is created internally and returned from [`http.request()`][]. It represents an _in-progress_ request whose header has already been queued. The header is still mutable using the [`setHeader(name, value)`][], - [`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will +[`getHeader(name)`][], [`removeHeader(name)`][] API. The actual header will be sent along with the first data chunk or when calling [`request.end()`][]. To get the response, add a listener for [`'response'`][] to the request object. @@ -403,6 +419,7 @@ Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not. ### Event: `'abort'` + @@ -488,6 +506,7 @@ proxy.listen(1337, '127.0.0.1', () => { ``` ### Event: `'continue'` + @@ -497,6 +516,7 @@ the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body. ### Event: `'information'` + @@ -508,7 +528,7 @@ added: v10.0.0 * `statusCode` {integer} * `statusMessage` {string} * `headers` {Object} - * `rawHeaders` {string[]} + * `rawHeaders` {string\[]} Emitted when the server sends a 1xx intermediate response (excluding 101 Upgrade). The listeners of this event will receive an object containing the @@ -539,6 +559,7 @@ upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the [`'upgrade'`][] event instead. ### Event: `'response'` + @@ -549,6 +570,7 @@ Emitted when a response is received to this request. This event is emitted only once. ### Event: `'socket'` + @@ -560,6 +582,7 @@ a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. ### Event: `'timeout'` + @@ -570,6 +593,7 @@ that the socket has been idle. The request must be destroyed manually. See also: [`request.setTimeout()`][]. ### Event: `'upgrade'` + @@ -631,6 +655,7 @@ server.listen(1337, '127.0.0.1', () => { ``` ### `request.abort()` + @@ -760,6 +792,7 @@ data is not sent until possibly much later. `request.flushHeaders()` bypasses the optimization and kickstarts the request. ### `request.getHeader(name)` + @@ -784,11 +817,12 @@ const cookie = request.getHeader('Cookie'); ``` ### `request.getRawHeaderNames()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing being set. @@ -808,6 +842,7 @@ const headerNames = request.getRawHeaderNames(); Limits maximum response headers count. If set to 0, no limit will be applied. ### `request.path` + @@ -815,6 +850,7 @@ added: v0.4.0 * {string} The request path. ### `request.method` + @@ -822,6 +858,7 @@ added: v0.1.97 * {string} The request method. ### `request.host` + @@ -853,6 +892,7 @@ request.removeHeader('Content-Type'); ``` ### `request.reusedSocket` + @@ -935,6 +976,7 @@ request.setHeader('Cookie', ['type=ninja', 'language=javascript']); ``` ### `request.setNoDelay([noDelay])` + @@ -945,6 +987,7 @@ Once a socket is assigned to this request and is connected [`socket.setNoDelay()`][] will be called. ### `request.setSocketKeepAlive([enable][, initialDelay])` + @@ -956,6 +999,7 @@ Once a socket is assigned to this request and is connected [`socket.setKeepAlive()`][] will be called. ### `request.setTimeout(timeout[, callback])` + @@ -1003,6 +1048,7 @@ a subclass of {stream.Duplex}, unless the user specified a socket type other than {net.Socket}. ### `request.writableEnded` + @@ -1014,6 +1060,7 @@ does not indicate whether the data has been flushed, for this use [`request.writableFinished`][] instead. ### `request.writableFinished` + @@ -1024,6 +1071,7 @@ Is `true` if all data has been flushed to the underlying system, immediately before the [`'finish'`][] event is emitted. ### `request.write(chunk[, encoding][, callback])` + @@ -1053,6 +1101,7 @@ When `write` function is called with empty string or buffer, it does nothing and waits for more input. ## Class: `http.Server` + @@ -1060,6 +1109,7 @@ added: v0.1.17 * Extends: {net.Server} ### Event: `'checkContinue'` + @@ -1080,6 +1130,7 @@ When this event is emitted and handled, the [`'request'`][] event will not be emitted. ### Event: `'checkExpectation'` + @@ -1095,6 +1146,7 @@ When this event is emitted and handled, the [`'request'`][] event will not be emitted. ### Event: `'clientError'` + @@ -1179,6 +1232,7 @@ added: v0.1.4 Emitted when the server closes. ### Event: `'connect'` + @@ -1201,6 +1255,7 @@ event listener, meaning it will need to be bound in order to handle data sent to the server on that socket. ### Event: `'connection'` + @@ -1225,6 +1280,7 @@ a subclass of {stream.Duplex}, unless the user specifies a socket type other than {net.Socket}. ### Event: `'request'` + @@ -1236,6 +1292,7 @@ Emitted each time there is a request. There may be multiple requests per connection (in the case of HTTP Keep-Alive connections). ### Event: `'upgrade'` + @@ -1271,6 +1329,7 @@ added: v0.1.90 Stops the server from accepting new connections. See [`net.Server.close()`][]. ### `server.headersTimeout` + @@ -1305,6 +1365,7 @@ added: v5.7.0 * {boolean} Indicates whether or not the server is listening for connections. ### `server.maxHeadersCount` + @@ -1314,6 +1375,7 @@ added: v0.7.0 Limits maximum incoming headers count. If set to 0, no limit will be applied. ### `server.requestTimeout` + @@ -1331,6 +1393,7 @@ potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front. ### `server.setTimeout([msecs][, callback])` + @@ -1371,6 +1435,7 @@ but will not actually close the connection, subsequent requests sent after the limit is reached will get `503 Service Unavailable` as a response. ### `server.timeout` + @@ -1411,6 +1477,7 @@ The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections. ## Class: `http.ServerResponse` + @@ -1421,6 +1488,7 @@ This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the [`'request'`][] event. ### Event: `'close'` + @@ -1429,6 +1497,7 @@ Indicates that the response is completed, or its underlying connection was terminated prematurely (before the response completion). ### Event: `'finish'` + @@ -1439,6 +1508,7 @@ handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet. ### `response.addTrailers(headers)` + @@ -1467,6 +1537,7 @@ Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. ### `response.connection` + @@ -1534,6 +1609,7 @@ added: v1.6.0 Flushes the response headers. See also: [`request.flushHeaders()`][]. ### `response.getHeader(name)` + @@ -1558,11 +1634,12 @@ const setCookie = response.getHeader('set-cookie'); ``` ### `response.getHeaderNames()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array containing the unique names of the current outgoing headers. All header names are lowercase. @@ -1576,6 +1653,7 @@ const headerNames = response.getHeaderNames(); ``` ### `response.getHeaders()` + @@ -1591,7 +1669,7 @@ are lowercase. The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others -are not defined and *will not work*. +are not defined and _will not work_. ```js response.setHeader('Foo', 'bar'); @@ -1602,6 +1680,7 @@ const headers = response.getHeaders(); ``` ### `response.hasHeader(name)` + @@ -1617,6 +1696,7 @@ const hasContentType = response.hasHeader('content-type'); ``` ### `response.headersSent` + @@ -1626,6 +1706,7 @@ added: v0.9.3 Boolean (read-only). True if headers were sent, false otherwise. ### `response.removeHeader(name)` + @@ -1639,6 +1720,7 @@ response.removeHeader('Content-Encoding'); ``` ### `response.req` + @@ -1648,6 +1730,7 @@ added: v15.7.0 A reference to the original HTTP `request` object. ### `response.sendDate` + @@ -1661,6 +1744,7 @@ This should only be disabled for testing; HTTP requires the Date header in responses. ### `response.setHeader(name, value)` + @@ -1714,6 +1798,7 @@ is desired with potential future retrieval and modification, use [`response.setHeader()`][] instead of [`response.writeHead()`][]. ### `response.setTimeout(msecs[, callback])` + @@ -1732,6 +1817,7 @@ assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. ### `response.socket` + @@ -1757,6 +1843,7 @@ a subclass of {stream.Duplex}, unless the user specified a socket type other than {net.Socket}. ### `response.statusCode` + @@ -1775,6 +1862,7 @@ After response header was sent to the client, this property indicates the status code which was sent out. ### `response.statusMessage` + @@ -1794,6 +1882,7 @@ After response header was sent to the client, this property indicates the status message which was sent out. ### `response.uncork()` + @@ -1814,6 +1904,7 @@ does not indicate whether the data has been flushed, for this use [`response.writableFinished`][] instead. ### `response.writableFinished` + @@ -1824,6 +1915,7 @@ Is `true` if all data has been flushed to the underlying system, immediately before the [`'finish'`][] event is emitted. ### `response.write(chunk[, encoding][, callback])` + @@ -1861,6 +1953,7 @@ buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is free again. ### `response.writeContinue()` + @@ -1870,6 +1963,7 @@ the request body should be sent. See the [`'checkContinue'`][] event on `Server`. ### `response.writeHead(statusCode[, statusMessage][, headers])` + @@ -1961,6 +2056,7 @@ Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent. ## Class: `http.IncomingMessage` + @@ -2005,6 +2103,7 @@ added: v0.4.2 Indicates that the underlying connection was closed. ### `message.aborted` + @@ -2046,6 +2146,7 @@ const req = http.request({ ``` ### `message.connection` + @@ -2126,6 +2230,7 @@ Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. ### `message.method` + @@ -2137,15 +2242,16 @@ added: v0.1.1 The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. ### `message.rawHeaders` + -* {string[]} +* {string\[]} The raw request/response headers list exactly as they were received. -The keys and values are in the same list. It is *not* a +The keys and values are in the same list. It is _not_ a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. @@ -2166,16 +2272,18 @@ console.log(request.rawHeaders); ``` ### `message.rawTrailers` + -* {string[]} +* {string\[]} The raw request/response trailer keys and values exactly as they were received. Only populated at the `'end'` event. ### `message.setTimeout(msecs[, callback])` + @@ -2187,6 +2295,7 @@ added: v0.5.9 Calls `message.socket.setTimeout(msecs, callback)`. ### `message.socket` + @@ -2203,6 +2312,7 @@ a subclass of {stream.Duplex}, unless the user specified a socket type other than {net.Socket}. ### `message.statusCode` + @@ -2214,6 +2324,7 @@ added: v0.1.1 The 3-digit HTTP response status code. E.G. `404`. ### `message.statusMessage` + @@ -2226,6 +2337,7 @@ The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. ### `message.trailers` + @@ -2235,6 +2347,7 @@ added: v0.3.0 The request/response trailers object. Only populated at the `'end'` event. ### `message.url` + @@ -2280,6 +2393,7 @@ URL { ``` ## Class: `http.OutgoingMessage` + @@ -2291,6 +2405,7 @@ and [`http.ServerResponse`][]. It is an abstract of outgoing message from the perspective of the participants of HTTP transaction. ### Event: `drain` + @@ -2298,6 +2413,7 @@ added: v0.3.6 Emitted when the buffer of the message is free again. ### Event: `finish` + @@ -2305,6 +2421,7 @@ added: v0.1.17 Emitted when the transmission is finished successfully. ### Event: `prefinish` + @@ -2314,6 +2431,7 @@ When the event is emitted, all data has been processed but not necessarily completely flushed. ### `outgoingMessage.addTrailers(headers)` + @@ -2340,6 +2458,7 @@ Attempting to set a header field name or value that contains invalid characters will result in a `TypeError` being thrown. ### `outgoingMessage.connection` + @@ -2356,6 +2477,7 @@ added: v14.0.0 See [`writable.cork()`][]. ### `outgoingMessage.destroy([error])` + @@ -2367,6 +2489,7 @@ Destroys the message. Once a socket is associated with the message and is connected, that socket will be destroyed as well. ### `outgoingMessage.end(chunk[, encoding][, callback])` + @@ -2407,6 +2531,7 @@ data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the request. ### `outgoingMessage.getHeader(name)` + @@ -2418,16 +2543,18 @@ Gets the value of HTTP header with the given name. If such a name doesn't exist in message, it will be `undefined`. ### `outgoingMessage.getHeaderNames()` + -* Returns {string[]} +* Returns {string\[]} Returns an array of names of headers of the outgoing outgoingMessage. All names are lowercase. ### `outgoingMessage.getHeaders()` + @@ -2454,6 +2581,7 @@ const headers = outgoingMessage.getHeaders(); ``` ### `outgoingMessage.hasHeader(name)` + @@ -2469,6 +2597,7 @@ const hasContentType = outgoingMessage.hasHeader('content-type'); ``` ### `outgoingMessage.headersSent` + @@ -2478,6 +2607,7 @@ added: v0.9.3 Read-only. `true` if the headers were sent, otherwise `false`. ### `outgoingMessage.pipe()` + @@ -2492,6 +2622,7 @@ it inherits from `Stream`. The User should not call this function directly. ### `outgoingMessage.removeHeader()` + @@ -2503,6 +2634,7 @@ outgoingMessage.removeHeader('Content-Encoding'); ``` ### `outgoingMessage.setHeader(name, value)` + @@ -2514,6 +2646,7 @@ added: v0.4.0 Sets a single header value for the header object. ### `outgoingMessage.setTimeout(msesc[, callback])` + @@ -2527,6 +2660,7 @@ Once a socket is associated with the message and is connected, [`socket.setTimeout()`][] will be called with `msecs` as the first parameter. ### `outgoingMessage.socket` + @@ -2539,6 +2673,7 @@ this property. After calling `outgoingMessage.end()`, this property will be nulled. ### `outgoingMessage.uncork()` + @@ -2546,6 +2681,7 @@ added: v14.0.0 See [`writable.uncork()`][] ### `outgoingMessage.writableCorked` + @@ -2556,6 +2692,7 @@ This `outgoingMessage.writableCorked` will return the time how many `outgoingMessage.cork()` have been called. ### `outgoingMessage.writableEnded` + @@ -2567,6 +2704,7 @@ this property does not reflect whether the data has been flush. For that purpose, use `message.writableFinished` instead. ### `outgoingMessage.writableFinished` + @@ -2576,6 +2714,7 @@ added: v13.0.0 Readonly. `true` if all data has been flushed to the underlying system. ### `outgoingMessage.writableHighWaterMark` + @@ -2590,6 +2729,7 @@ underlying socket if socket exists. Else, it would be the default buffered by the socket. ### `outgoingMessage.writableLength` + @@ -2600,6 +2740,7 @@ Readonly, This `outgoingMessage.writableLength` contains the number of bytes (or objects) in the buffer ready to send. ### `outgoingMessage.writableObjectMode` + @@ -2609,6 +2750,7 @@ added: v13.0.0 Readonly, always returns `false`. ### `outgoingMessage.write(chunk[, encoding][, callback])` + -* {string[]} +* {string\[]} A list of the HTTP methods that are supported by the parser. ## `http.STATUS_CODES` + @@ -2672,6 +2816,7 @@ short description of each. For example, `http.STATUS_CODES[404] === 'Not Found'`. ## `http.createServer([options][, requestListener])` + @@ -2837,6 +2986,7 @@ Global instance of `Agent` which is used as the default for all HTTP client requests. ## `http.maxHeaderSize` + @@ -3154,6 +3307,7 @@ or response. The HTTP module will automatically validate such headers. Examples: Example: + ```js const { validateHeaderName } = require('http'); @@ -3167,6 +3321,7 @@ try { ``` ## `http.validateHeaderValue(name, value)` + @@ -3178,6 +3333,7 @@ Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. Passing illegal value as `value` will result in a [`TypeError`][] being thrown. + * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. diff --git a/doc/api/http2.md b/doc/api/http2.md index bc03c14ef50ddd..51efb6c9dc886c 100644 --- a/doc/api/http2.md +++ b/doc/api/http2.md @@ -1,4 +1,5 @@ # HTTP/2 + + > Stability: 2 - Stable @@ -29,7 +31,7 @@ const http2 = require('http2'); ## Core API The Core API provides a low-level interface designed specifically around -support for HTTP/2 protocol features. It is specifically *not* designed for +support for HTTP/2 protocol features. It is specifically _not_ designed for compatibility with the existing [HTTP/1][] module API. However, the [Compatibility API][] is. @@ -105,6 +107,7 @@ req.end(); ``` ### Class: `Http2Session` + @@ -112,7 +115,7 @@ added: v8.4.0 * Extends: {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* +session between an HTTP/2 client and server. Instances of this class are _not_ intended to be constructed directly by user code. Each `Http2Session` instance will exhibit slightly different behaviors @@ -144,6 +147,7 @@ Once a `Socket` has been bound to an `Http2Session`, user code should rely solely on the API of the `Http2Session`. #### Event: `'close'` + @@ -152,6 +156,7 @@ The `'close'` event is emitted once the `Http2Session` has been destroyed. Its listener does not expect any arguments. #### Event: `'connect'` + @@ -165,6 +170,7 @@ connected to the remote peer and communication may begin. User code will typically not listen for this event directly. #### Event: `'error'` + @@ -175,6 +181,7 @@ The `'error'` event is emitted when an error occurs during the processing of an `Http2Session`. #### Event: `'frameError'` + @@ -195,6 +202,7 @@ event is not associated with a stream, the `Http2Session` will be shut down immediately following the `'frameError'` event. #### Event: `'goaway'` + @@ -211,6 +219,7 @@ The `Http2Session` instance will be shut down automatically when the `'goaway'` event is emitted. #### Event: `'localSettings'` + @@ -232,6 +241,7 @@ session.on('localSettings', (settings) => { ``` #### Event: `'ping'` + @@ -242,6 +252,7 @@ The `'ping'` event is emitted whenever a `PING` frame is received from the connected peer. #### Event: `'remoteSettings'` + @@ -258,6 +269,7 @@ session.on('remoteSettings', (settings) => { ``` #### Event: `'stream'` + @@ -313,6 +325,7 @@ a network error will destroy each individual stream and must be handled on the stream level, as shown above. #### Event: `'timeout'` + @@ -328,6 +341,7 @@ session.on('timeout', () => { /* .. */ }); ``` #### `http2session.alpnProtocol` + @@ -340,6 +354,7 @@ will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. #### `http2session.close([callback])` + @@ -348,13 +363,14 @@ added: v9.4.0 Gracefully closes the `Http2Session`, allowing any existing streams to complete on their own and preventing new `Http2Stream` instances from being -created. Once closed, `http2session.destroy()` *might* be called if there +created. Once closed, `http2session.destroy()` _might_ be called if there are no open `Http2Stream` instances. If specified, the `callback` function is registered as a handler for the `'close'` event. #### `http2session.closed` + @@ -365,6 +381,7 @@ Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. #### `http2session.connecting` + @@ -376,6 +393,7 @@ to `false` before emitting `connect` event and/or calling the `http2.connect` callback. #### `http2session.destroy([error][, code])` + @@ -397,6 +415,7 @@ If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. #### `http2session.destroyed` + @@ -407,6 +426,7 @@ Will be `true` if this `Http2Session` instance has been destroyed and must no longer be used, otherwise `false`. #### `http2session.encrypted` + @@ -419,6 +439,7 @@ and `false` if the `Http2Session` is connected to any other kind of socket or stream. #### `http2session.goaway([code[, lastStreamID[, opaqueData]]])` + @@ -428,10 +449,11 @@ added: v9.4.0 * `opaqueData` {Buffer|TypedArray|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 +Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the `Http2Session`. #### `http2session.localSettings` + @@ -439,14 +461,15 @@ added: v8.4.0 * {HTTP/2 Settings Object} A prototype-less object describing the current local settings of this -`Http2Session`. The local settings are local to *this* `Http2Session` instance. +`Http2Session`. The local settings are local to _this_ `Http2Session` instance. #### `http2session.originSet` + -* {string[]|undefined} +* {string\[]|undefined} If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property will return an `Array` of origins for which the `Http2Session` may be @@ -455,6 +478,7 @@ considered authoritative. The `originSet` property is only available when using a secure TLS connection. #### `http2session.pendingSettingsAck` + @@ -467,6 +491,7 @@ a sent `SETTINGS` frame. Will be `true` after calling the frames have been acknowledged. #### `http2session.ping([payload, ]callback)` + @@ -505,6 +530,7 @@ If the `payload` argument is not specified, the default payload will be the 64-bit timestamp (little endian) marking the start of the `PING` duration. #### `http2session.ref()` + @@ -513,6 +539,7 @@ Calls [`ref()`][`net.Socket.prototype.ref()`] on this `Http2Session` instance's underlying [`net.Socket`][]. #### `http2session.remoteSettings` + @@ -520,9 +547,10 @@ added: v8.4.0 * {HTTP/2 Settings Object} A prototype-less object describing the current remote settings of this -`Http2Session`. The remote settings are set by the *connected* HTTP/2 peer. +`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. #### `http2session.setLocalWindowSize(windowSize)` + @@ -546,6 +574,7 @@ server.on('connect', (session) => { ``` #### `http2session.setTimeout(msecs, callback)` + @@ -558,6 +587,7 @@ the `Http2Session` after `msecs` milliseconds. The given `callback` is registered as a listener on the `'timeout'` event. #### `http2session.socket` + @@ -576,6 +606,7 @@ an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See All other interactions will be routed directly to the socket. #### `http2session.state` + @@ -606,6 +637,7 @@ Provides miscellaneous information about the current state of the An object describing the current status of this `Http2Session`. #### `http2session.settings([settings][, callback])` + @@ -629,6 +661,7 @@ is received and the `'localSettings'` event is emitted. It is possible to send multiple `SETTINGS` frames while acknowledgment is still pending. #### `http2session.type` + @@ -641,6 +674,7 @@ server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a client. #### `http2session.unref()` + @@ -649,6 +683,7 @@ Calls [`unref()`][`net.Socket.prototype.unref()`] on this `Http2Session` instance's underlying [`net.Socket`][]. ### Class: `ServerHttp2Session` + @@ -656,6 +691,7 @@ added: v8.4.0 * Extends: {Http2Session} #### `serverhttp2session.altsvc(alt, originOrStream)` + @@ -687,7 +723,7 @@ server.on('stream', (stream) => { Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate service is associated with the origin of the given `Http2Stream`. -The `alt` and origin string *must* contain only ASCII bytes and are +The `alt` and origin string _must_ contain only ASCII bytes and are strictly interpreted as a sequence of ASCII bytes. The special value `'clear'` may be passed to clear any previously set alternative service for a given domain. @@ -700,7 +736,7 @@ cannot be parsed as a URL or if a valid origin cannot be derived. A `URL` object, or any object with an `origin` property, may be passed as `originOrStream`, in which case the value of the `origin` property will be -used. The value of the `origin` property *must* be a properly serialized +used. The value of the `origin` property _must_ be a properly serialized ASCII origin. #### Specifying alternative services @@ -711,7 +747,7 @@ associated with a specific host and port. For example, the value `'h2="example.org:81"'` indicates that the HTTP/2 protocol is available on the host `'example.org'` on TCP/IP port 81. The -host and port *must* be contained within the quote (`"`) characters. +host and port _must_ be contained within the quote (`"`) characters. Multiple alternatives may be specified, for instance: `'h2="example.org:81", h2=":82"'`. @@ -723,6 +759,7 @@ The syntax of these values is not validated by the Node.js implementation and are passed through as provided by the user or received from the peer. #### `serverhttp2session.origin(...origins)` + @@ -755,7 +792,7 @@ cannot be parsed as a URL or if a valid origin cannot be derived. A `URL` object, or any object with an `origin` property, may be passed as an `origin`, in which case the value of the `origin` property will be -used. The value of the `origin` property *must* be a properly serialized +used. The value of the `origin` property _must_ be a properly serialized ASCII origin. Alternatively, the `origins` option may be used when creating a new HTTP/2 @@ -773,6 +810,7 @@ server.on('stream', (stream) => { ``` ### Class: `ClientHttp2Session` + @@ -780,6 +818,7 @@ added: v8.4.0 * Extends: {Http2Session} #### Event: `'altsvc'` + @@ -805,11 +844,12 @@ client.on('altsvc', (alt, origin, streamId) => { ``` #### Event: `'origin'` + -* `origins` {string[]} +* `origins` {string\[]} The `'origin'` event is emitted whenever an `ORIGIN` frame is received by the client. The event is emitted with an array of `origin` strings. The @@ -829,13 +869,15 @@ client.on('origin', (origins) => { The `'origin'` event is only emitted when using a secure TLS connection. #### `clienthttp2session.request(headers[, options])` + * `headers` {HTTP/2 Headers Object} + * `options` {Object} - * `endStream` {boolean} `true` if the `Http2Stream` *writable* side should + * `endStream` {boolean} `true` if the `Http2Stream` _writable_ side should be closed initially, such as when sending a `GET` request that should not expect a payload body. * `exclusive` {boolean} When `true` and `parent` identifies a parent Stream, @@ -898,6 +940,7 @@ they respectively default to: * `:path` = `/` ### Class: `Http2Stream` + @@ -983,6 +1026,7 @@ property will be `true` and the `http2stream.rstCode` property will specify the destroyed. #### Event: `'aborted'` + @@ -995,6 +1039,7 @@ The `'aborted'` event will only be emitted if the `Http2Stream` writable side has not been ended. #### Event: `'close'` + @@ -1007,6 +1052,7 @@ the `http2stream.rstCode` property. If the code is any value other than `NGHTTP2_NO_ERROR` (`0`), an `'error'` event will have also been emitted. #### Event: `'error'` + @@ -1017,6 +1063,7 @@ The `'error'` event is emitted when an error occurs during the processing of an `Http2Stream`. #### Event: `'frameError'` + @@ -1033,6 +1080,7 @@ error code. The `Http2Stream` instance will be destroyed immediately after the `'frameError'` event is emitted. #### Event: `'ready'` + @@ -1042,6 +1090,7 @@ been assigned an `id`, and can be used. The listener does not expect any arguments. #### Event: `'timeout'` + @@ -1052,6 +1101,7 @@ The `'timeout'` event is emitted after no activity is received for this Its listener does not expect any arguments. #### Event: `'trailers'` + @@ -1074,6 +1124,7 @@ stream.on('trailers', (headers, flags) => { ``` #### Event: `'wantTrailers'` + @@ -1084,6 +1135,7 @@ trailing headers. When initiating a request or response, the `waitForTrailers` option must be set for this event to be emitted. #### `http2stream.aborted` + @@ -1094,6 +1146,7 @@ Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, the `'aborted'` event will have been emitted. #### `http2stream.bufferSize` + @@ -1119,6 +1173,7 @@ Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the connected HTTP/2 peer. #### `http2stream.closed` + @@ -1128,6 +1183,7 @@ added: v9.4.0 Set to `true` if the `Http2Stream` instance has been closed. #### `http2stream.destroyed` + @@ -1138,6 +1194,7 @@ Set to `true` if the `Http2Stream` instance has been destroyed and is no longer usable. #### `http2stream.endAfterHeaders` + @@ -1149,6 +1206,7 @@ HEADERS frame received, indicating that no additional data should be received and the readable side of the `Http2Stream` will be closed. #### `http2stream.id` + @@ -1159,6 +1217,7 @@ The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. #### `http2stream.pending` + @@ -1169,6 +1228,7 @@ Set to `true` if the `Http2Stream` instance has not yet been assigned a numeric stream identifier. #### `http2stream.priority(options)` + @@ -1189,6 +1249,7 @@ added: v8.4.0 Updates the priority for this `Http2Stream` instance. #### `http2stream.rstCode` + @@ -1201,6 +1262,7 @@ calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. #### `http2stream.sentHeaders` + @@ -1210,16 +1272,18 @@ added: v9.5.0 An object containing the outbound headers sent for this `Http2Stream`. #### `http2stream.sentInfoHeaders` + -* {HTTP/2 Headers Object[]} +* {HTTP/2 Headers Object\[]} An array of objects containing the outbound informational (additional) headers sent for this `Http2Stream`. #### `http2stream.sentTrailers` + @@ -1229,6 +1293,7 @@ added: v9.5.0 An object containing the outbound trailers sent for this `HttpStream`. #### `http2stream.session` + @@ -1239,6 +1304,7 @@ 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)` + @@ -1257,9 +1323,11 @@ req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); ``` #### `http2stream.state` + + Provides miscellaneous information about the current state of the `Http2Stream`. @@ -1279,6 +1347,7 @@ Provides miscellaneous information about the current state of the A current state of this `Http2Stream`. #### `http2stream.sendTrailers(headers)` + @@ -1308,6 +1377,7 @@ The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header fields (e.g. `':method'`, `':path'`, etc). ### Class: `ClientHttp2Stream` + @@ -1320,6 +1390,7 @@ provide events such as `'response'` and `'push'` that are only relevant on the client. #### Event: `'continue'` + @@ -1329,6 +1400,7 @@ the request contained `Expect: 100-continue`. This is an instruction that the client should send the request body. #### Event: `'headers'` + @@ -1345,6 +1417,7 @@ stream.on('headers', (headers, flags) => { ``` #### Event: `'push'` + @@ -1360,6 +1433,7 @@ stream.on('push', (headers, flags) => { ``` #### Event: `'response'` + @@ -1379,6 +1453,7 @@ req.on('response', (headers, flags) => { ``` ### Class: `ServerHttp2Stream` + @@ -1391,6 +1466,7 @@ provide additional methods such as `http2stream.pushStream()` and `http2stream.respond()` that are only relevant on the server. #### `http2stream.additionalHeaders(headers)` + @@ -1400,6 +1476,7 @@ added: v8.4.0 Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. #### `http2stream.headersSent` + @@ -1409,6 +1486,7 @@ added: v8.4.0 True if headers were sent, false otherwise (read-only). #### `http2stream.pushAllowed` + @@ -1421,6 +1499,7 @@ accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. #### `http2stream.pushStream(headers[, options], callback)` + @@ -1466,6 +1545,7 @@ Calling `http2stream.pushStream()` from within a pushed stream is not permitted and will throw an error. #### `http2stream.respond([headers[, options]])` + @@ -1755,6 +1838,7 @@ function. The `Http2Server` class is not exported directly by the `http2` module. #### Event: `'checkContinue'` + @@ -1777,6 +1861,7 @@ When this event is emitted and handled, the [`'request'`][] event will not be emitted. #### Event: `'connection'` + @@ -1791,6 +1876,7 @@ This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case, any [`Duplex`][] stream can be passed. #### Event: `'request'` + @@ -1802,6 +1888,7 @@ Emitted each time there is a request. There may be multiple requests per session. See the [Compatibility API][]. #### Event: `'session'` + @@ -1810,6 +1897,7 @@ The `'session'` event is emitted when a new `Http2Session` is created by the `Http2Server`. #### Event: `'sessionError'` + @@ -1818,6 +1906,7 @@ The `'sessionError'` event is emitted when an `'error'` event is emitted by an `Http2Session` object associated with the `Http2Server`. #### Event: `'stream'` + @@ -1857,6 +1946,7 @@ server.on('stream', (stream, headers, flags) => { ``` #### Event: `'timeout'` + @@ -1886,6 +1977,7 @@ closed, although the server has already stopped allowing new sessions. See [`net.Server.close()`][] for more details. #### `server.setTimeout([msecs][, callback])` + @@ -1940,6 +2034,7 @@ Throws `ERR_HTTP2_INVALID_SETTING_VALUE` for invalid `settings` values. Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. ### Class: `Http2SecureServer` + @@ -1951,6 +2046,7 @@ Instances of `Http2SecureServer` are created using the exported directly by the `http2` module. #### Event: `'checkContinue'` + @@ -1973,6 +2069,7 @@ When this event is emitted and handled, the [`'request'`][] event will not be emitted. #### Event: `'connection'` + @@ -1987,6 +2084,7 @@ This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case, any [`Duplex`][] stream can be passed. #### Event: `'request'` + @@ -1998,6 +2096,7 @@ Emitted each time there is a request. There may be multiple requests per session. See the [Compatibility API][]. #### Event: `'session'` + @@ -2006,6 +2105,7 @@ The `'session'` event is emitted when a new `Http2Session` is created by the `Http2SecureServer`. #### Event: `'sessionError'` + @@ -2014,6 +2114,7 @@ The `'sessionError'` event is emitted when an `'error'` event is emitted by an `Http2Session` object associated with the `Http2SecureServer`. #### Event: `'stream'` + @@ -2055,6 +2156,7 @@ server.on('stream', (stream, headers, flags) => { ``` #### Event: `'timeout'` + @@ -2064,6 +2166,7 @@ a given number of milliseconds set using `http2secureServer.setTimeout()`. **Default:** 2 minutes. #### Event: `'unknownProtocol'` + @@ -2076,6 +2179,7 @@ the connection is terminated. A timeout may be specified using the See the [Compatibility API][]. #### `server.close([callback])` + @@ -2092,6 +2196,7 @@ closed, although the server has already stopped allowing new sessions. See [`tls.Server.close()`][] for more details. #### `server.setTimeout([msecs][, callback])` + @@ -2110,6 +2215,7 @@ In case if `callback` is not a function, a new `ERR_INVALID_CALLBACK` error will be thrown. #### `server.timeout` + @@ -2142,6 +2249,7 @@ Throws `ERR_HTTP2_INVALID_SETTING_VALUE` for invalid `settings` values. Throws `ERR_INVALID_ARG_TYPE` for invalid `settings` argument. ### `http2.createServer(options[, onRequestHandler])` + @@ -2555,7 +2666,7 @@ added: v8.4.0 #### Error codes for `RST_STREAM` and `GOAWAY` | Value | Name | Constant | -|--------|---------------------|-----------------------------------------------| +| ------ | ------------------- | --------------------------------------------- | | `0x00` | No Error | `http2.constants.NGHTTP2_NO_ERROR` | | `0x01` | Protocol Error | `http2.constants.NGHTTP2_PROTOCOL_ERROR` | | `0x02` | Internal Error | `http2.constants.NGHTTP2_INTERNAL_ERROR` | @@ -2575,6 +2686,7 @@ The `'timeout'` event is emitted when there is no activity on the Server for a given number of milliseconds set using `http2server.setTimeout()`. ### `http2.getDefaultSettings()` + @@ -2586,6 +2698,7 @@ instance. This method returns a new object instance every time it is called so instances returned may be safely modified for use. ### `http2.getPackedSettings([settings])` + @@ -2607,6 +2720,7 @@ console.log(packed.toString('base64')); ``` ### `http2.getUnpackedSettings(buf)` + @@ -2618,6 +2732,7 @@ Returns a [HTTP/2 Settings Object][] containing the deserialized settings from the given `Buffer` as generated by `http2.getPackedSettings()`. ### `http2.sensitiveHeaders` + @@ -2703,6 +2818,7 @@ This property is also set for received headers. It will contain the names of all headers marked as sensitive, including ones marked that way automatically. ### Settings object + + The `http2.getDefaultSettings()`, `http2.getPackedSettings()`, `http2.createServer()`, `http2.createSecureServer()`, `http2session.settings()`, `http2session.localSettings`, and @@ -2726,7 +2843,7 @@ properties. is 232-1. **Default:** `4096`. * `enablePush` {boolean} Specifies `true` if HTTP/2 Push Streams are to be permitted on the `Http2Session` instances. **Default:** `true`. -* `initialWindowSize` {number} Specifies the *sender's* initial window size in +* `initialWindowSize` {number} Specifies the _sender's_ initial window size in bytes for stream-level flow control. The minimum allowed value is 0. The maximum allowed value is 232-1. **Default:** `65535`. * `maxFrameSize` {number} Specifies the size in bytes of the largest frame @@ -2777,20 +2894,20 @@ on where and when the error occurs. The HTTP/2 implementation applies stricter handling of invalid characters in HTTP header names and values than the HTTP/1 implementation. -Header field names are *case-insensitive* and are transmitted over the wire +Header field names are _case-insensitive_ and are transmitted over the wire strictly as lower-case strings. The API provided by Node.js allows header names to be set as mixed-case strings (e.g. `Content-Type`) but will convert those to lower-case (e.g. `content-type`) upon transmission. -Header field-names *must only* contain one or more of the following ASCII +Header field-names _must only_ contain one or more of the following ASCII characters: `a`-`z`, `A`-`Z`, `0`-`9`, `!`, `#`, `$`, `%`, `&`, `'`, `*`, `+`, `-`, `.`, `^`, `_`, `` ` `` (backtick), `|`, and `~`. Using invalid characters within an HTTP header field name will cause the stream to be closed with a protocol error being reported. -Header field values are handled with more leniency but *should* not contain -new-line or carriage return characters and *should* be limited to US-ASCII +Header field values are handled with more leniency but _should_ not contain +new-line or carriage return characters and _should_ be limited to US-ASCII characters, per the requirements of the HTTP specification. ### Push streams on the client @@ -2989,6 +3106,7 @@ The `'request'` event works identically on both [HTTPS][] and HTTP/2. ### Class: `http2.Http2ServerRequest` + @@ -3001,6 +3119,7 @@ A `Http2ServerRequest` object is created by [`http2.Server`][] or data. #### Event: `'aborted'` + @@ -3012,6 +3131,7 @@ The `'aborted'` event will only be emitted if the `Http2ServerRequest` writable side has not been ended. #### Event: `'close'` + @@ -3020,6 +3140,7 @@ Indicates that the underlying [`Http2Stream`][] was closed. Just like `'end'`, this event occurs only once per response. #### `request.aborted` + @@ -3030,6 +3151,7 @@ The `request.aborted` property will be `true` if the request has been aborted. #### `request.authority` + @@ -3042,6 +3164,7 @@ to set either `:authority` or `host`, this value is derived from `req.headers['host']`. #### `request.complete` + @@ -3052,6 +3175,7 @@ The `request.complete` property will be `true` if the request has been completed, aborted, or destroyed. #### `request.connection` + @@ -3077,6 +3202,7 @@ is emitted and `error` is passed as an argument to any listeners on the event. It does nothing if the stream was already destroyed. #### `request.headers` + @@ -3110,6 +3236,7 @@ assert(request.url); // Fails because the :path header has been removed ``` #### `request.httpVersion` + @@ -3124,6 +3251,7 @@ Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. #### `request.method` + @@ -3133,15 +3261,16 @@ added: v8.4.0 The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. #### `request.rawHeaders` + -* {string[]} +* {string\[]} The raw request/response headers list exactly as they were received. -The keys and values are in the same list. It is *not* a +The keys and values are in the same list. It is _not_ a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values. @@ -3162,16 +3291,18 @@ console.log(request.rawHeaders); ``` #### `request.rawTrailers` + -* {string[]} +* {string\[]} The raw request/response trailer keys and values exactly as they were received. Only populated at the `'end'` event. #### `request.scheme` + @@ -3182,6 +3313,7 @@ The request scheme pseudo header field indicating the scheme portion of the target URL. #### `request.setTimeout(msecs, callback)` + @@ -3200,6 +3332,7 @@ handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. #### `request.socket` + @@ -3226,6 +3359,7 @@ use [`request.socket.getPeerCertificate()`][] to obtain the client's authentication details. #### `request.stream` + @@ -3235,6 +3369,7 @@ added: v8.4.0 The [`Http2Stream`][] object backing the request. #### `request.trailers` + @@ -3244,6 +3379,7 @@ added: v8.4.0 The request/response trailers object. Only populated at the `'end'` event. #### `request.url` + @@ -3261,6 +3397,7 @@ Accept: text/plain Then `request.url` will be: + ```js '/status?name=ryan' ``` @@ -3287,6 +3424,7 @@ URL { ``` ### Class: `http2.Http2ServerResponse` + @@ -3297,6 +3435,7 @@ This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the [`'request'`][] event. #### Event: `'close'` + @@ -3305,6 +3444,7 @@ Indicates that the underlying [`Http2Stream`][] was terminated before [`response.end()`][] was called or able to flush. #### Event: `'finish'` + @@ -3317,6 +3457,7 @@ does not imply that the client has received anything yet. After this event, no more events will be emitted on the response object. #### `response.addTrailers(headers)` + @@ -3330,6 +3471,7 @@ Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. #### `response.connection` + @@ -3361,6 +3504,7 @@ parameter if successful. When `Http2ServerRequest` is closed, the callback is called with an error `ERR_HTTP2_INVALID_STREAM`. #### `response.end([data[, encoding]][, callback])` + @@ -3415,11 +3561,12 @@ const contentType = response.getHeader('content-type'); ``` #### `response.getHeaderNames()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array containing the unique names of the current outgoing headers. All header names are lowercase. @@ -3433,6 +3580,7 @@ const headerNames = response.getHeaderNames(); ``` #### `response.getHeaders()` + @@ -3448,7 +3596,7 @@ are lowercase. The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others -are not defined and *will not work*. +are not defined and _will not work_. ```js response.setHeader('Foo', 'bar'); @@ -3459,6 +3607,7 @@ const headers = response.getHeaders(); ``` #### `response.hasHeader(name)` + @@ -3474,6 +3623,7 @@ const hasContentType = response.hasHeader('content-type'); ``` #### `response.headersSent` + @@ -3483,6 +3633,7 @@ added: v8.4.0 True if headers were sent, false otherwise (read-only). #### `response.removeHeader(name)` + @@ -3496,6 +3647,7 @@ response.removeHeader('Content-Encoding'); ``` ### `response.req` + @@ -3505,6 +3657,7 @@ added: v15.7.0 A reference to the original HTTP2 `request` object. #### `response.sendDate` + @@ -3518,12 +3671,13 @@ This should only be disabled for testing; HTTP requires the Date header in responses. #### `response.setHeader(name, value)` + * `name` {string} -* `value` {string|string[]} +* `value` {string|string\[]} Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings @@ -3557,6 +3711,7 @@ const server = http2.createServer((req, res) => { ``` #### `response.setTimeout(msecs[, callback])` + @@ -3575,6 +3730,7 @@ handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. #### `response.socket` + @@ -3608,6 +3764,7 @@ const server = http2.createServer((req, res) => { ``` #### `response.statusCode` + @@ -3626,6 +3783,7 @@ After response header was sent to the client, this property indicates the status code which was sent out. #### `response.statusMessage` + @@ -3636,6 +3794,7 @@ Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns an empty string. #### `response.stream` + @@ -3645,6 +3804,7 @@ added: v8.4.0 The [`Http2Stream`][] object backing the response. #### `response.writableEnded` + @@ -3656,6 +3816,7 @@ does not indicate whether the data has been flushed, for this use [`writable.writableFinished`][] instead. #### `response.write(chunk[, encoding][, callback])` + @@ -3694,6 +3855,7 @@ buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is free again. #### `response.writeContinue()` + @@ -3703,6 +3865,7 @@ should be sent. See the [`'checkContinue'`][] event on `Http2Server` and `Http2SecureServer`. #### `response.writeHead(statusCode[, statusMessage][, headers])` + @@ -84,6 +88,7 @@ added: v0.3.4 See [`http.Server`][] for more information. ### `server.close([callback])` + @@ -94,6 +99,7 @@ added: v0.1.90 See [`server.close()`][`http.close()`] from the HTTP module for details. ### `server.headersTimeout` + @@ -114,6 +120,7 @@ This method is identical to [`server.listen()`][] from [`net.Server`][]. See [`http.Server#maxHeadersCount`][]. ### `server.requestTimeout` + @@ -123,6 +130,7 @@ added: v14.11.0 See [`http.Server#requestTimeout`][]. ### `server.setTimeout([msecs][, callback])` + @@ -134,6 +142,7 @@ added: v0.11.2 See [`http.Server#setTimeout()`][]. ### `server.timeout` + @@ -156,6 +166,7 @@ added: v8.0.0 See [`http.Server#keepAliveTimeout`][]. ## `https.createServer([options][, requestListener])` + @@ -199,7 +210,9 @@ https.createServer(options, (req, res) => { ``` ## `https.get(options[, callback])` + ## `https.get(url[, options][, callback])` + @@ -247,7 +261,9 @@ added: v0.5.9 Global instance of [`https.Agent`][] for all HTTPS client requests. ## `https.request(options[, callback])` + ## `https.request(url[, options][, callback])` + @@ -87,6 +88,7 @@ The `inspector.Session` is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. ### `new inspector.Session()` + @@ -96,6 +98,7 @@ needs to be connected through [`session.connect()`][] before the messages can be dispatched to the inspector backend. ### Event: `'inspectorNotification'` + @@ -113,6 +116,7 @@ session.on('inspectorNotification', (message) => console.log(message.method)); It is also possible to subscribe only to notifications with specific method: ### Event: ``; + @@ -134,6 +138,7 @@ session.on('Debugger.paused', ({ params }) => { ``` ### `session.connect()` + @@ -141,6 +146,7 @@ added: v8.0.0 Connects a session to the inspector back-end. ### `session.connectToMainThread()` + @@ -149,6 +155,7 @@ 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()` + @@ -159,6 +166,7 @@ messages again. Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. ### `session.post(method[, params][, callback])` + diff --git a/doc/api/intl.md b/doc/api/intl.md index 716047a7c39c9a..cf4a852035d4e1 100644 --- a/doc/api/intl.md +++ b/doc/api/intl.md @@ -45,7 +45,7 @@ An overview of available Node.js and JavaScript features for each `configure` option: | Feature | `none` | `system-icu` | `small-icu` | `full-icu` | -|-----------------------------------------|-----------------------------------|------------------------------|------------------------|------------| +| --------------------------------------- | --------------------------------- | ---------------------------- | ---------------------- | ---------- | | [`String.prototype.normalize()`][] | none (function is no-op) | full | full | full | | `String.prototype.to*Case()` | full | full | full | full | | [`Intl`][] | none (object does not exist) | partial/full (depends on OS) | partial (English-only) | full | @@ -80,7 +80,7 @@ OS. Functionalities that only require the ICU library itself, such as [`String.prototype.normalize()`][] and the [WHATWG URL parser][], are fully supported under `system-icu`. Features that require ICU locale data in -addition, such as [`Intl.DateTimeFormat`][] *may* be fully or partially +addition, such as [`Intl.DateTimeFormat`][] _may_ be fully or partially supported, depending on the completeness of the ICU data installed on the system. diff --git a/doc/api/module.md b/doc/api/module.md index 519240841a644f..749bd350ba9c42 100644 --- a/doc/api/module.md +++ b/doc/api/module.md @@ -15,6 +15,7 @@ Provides general utility methods when interacting with instances of via `import 'module'` or `require('module')`. ### `module.builtinModules` + -* {string[]} +* {string\[]} A list of the names of all modules provided by Node.js. Can be used to verify if a module is maintained by a third party or not. @@ -43,6 +44,7 @@ const builtin = require('module').builtinModules; ``` ### `module.createRequire(filename)` + @@ -61,6 +63,7 @@ const siblingModule = require('./sibling-module'); ``` ### `module.syncBuiltinESMExports()` + @@ -99,6 +102,7 @@ import('fs').then((esmFS) => { ``` ## Source map v3 support + + + ### `module.findSourceMap(path)` @@ -547,6 +548,7 @@ console.log(path.dirname(__filename)); ``` ### `__filename` + @@ -585,6 +587,7 @@ References to `__filename` within `b.js` will return `a.js` will return `/Users/mjr/app/a.js`. ### `exports` + @@ -598,6 +601,7 @@ See the section about the [exports shortcut][] for details on when to use `exports` and when to use `module.exports`. ### `module` + @@ -611,6 +615,7 @@ A reference to the current module, see the section about the a module exports and makes available through `require()`. ### `require(id)` + @@ -641,6 +646,7 @@ const crypto = require('crypto'); ``` #### `require.cache` + @@ -658,6 +664,7 @@ only `node:`-prefixed require calls are going to receive the native module. Use with care! + ```js const assert = require('assert'); const realFs = require('fs'); @@ -670,6 +677,7 @@ assert.strictEqual(require('node:fs'), realFs); ``` #### `require.extensions` + @@ -717,6 +726,7 @@ node entry.js ``` + ```js Module { id: '.', @@ -733,6 +743,7 @@ Module { ``` #### `require.resolve(request[, options])` + * `request` {string} The module path whose lookup paths are being retrieved. -* Returns: {string[]|null} +* Returns: {string\[]|null} Returns an array containing the paths searched during resolution of `request` or `null` if the `request` string references a core module, for example `http` or `fs`. ## The `module` object + @@ -785,15 +798,17 @@ also accessible via the `exports` module-global. `module` is not actually a global but rather local to each module. ### `module.children` + -* {module[]} +* {module\[]} The module objects required for the first time by this one. ### `module.exports` + @@ -848,6 +863,7 @@ console.log(x.a); ``` #### `exports` shortcut + @@ -868,6 +884,7 @@ When the `module.exports` property is being completely replaced by a new object, it is common to also reassign `exports`: + ```js module.exports = exports = function Constructor() { // ... etc. @@ -895,6 +912,7 @@ function require(/* ... */) { ``` ### `module.filename` + @@ -904,6 +922,7 @@ added: v0.1.16 The fully resolved filename of the module. ### `module.id` + @@ -914,6 +933,7 @@ The identifier for the module. Typically this is the fully resolved filename. ### `module.isPreloading` + @@ -922,6 +942,7 @@ added: v15.4.0 phase. ### `module.loaded` + @@ -932,6 +953,7 @@ Whether or not the module is done loading, or is in the process of loading. ### `module.parent` + @@ -959,15 +982,17 @@ The directory name of the module. This is usually the same as the [`path.dirname()`][] of the [`module.id`][]. ### `module.paths` + -* {string[]} +* {string\[]} The search paths for the module. ### `module.require(id)` + @@ -980,7 +1005,7 @@ The `module.require()` method provides a way to load a module as if In order to do this, it is necessary to get a reference to the `module` object. Since `require()` returns the `module.exports`, and the `module` is typically -*only* available within a specific module's code, it must be explicitly exported +_only_ available within a specific module's code, it must be explicitly exported in order to be used. ## The `Module` object @@ -989,6 +1014,7 @@ This section was moved to [Modules: `module` core module](module.md#the-module-object). + * `module.builtinModules` * `module.createRequire(filename)` * `module.syncBuiltinESMExports()` @@ -999,6 +1025,7 @@ This section was moved to [Modules: `module` core module](module.md#source-map-v3-support). + * `module.findSourceMap(path)` * Class: `module.SourceMap` * `new SourceMap(payload)` diff --git a/doc/api/n-api.md b/doc/api/n-api.md index f4025ffdbf37f7..fac452651e0fa5 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -91,24 +91,24 @@ versions: * the Node.js C++ APIs available via any of - ```cpp - #include - #include - #include - #include - ``` + ```cpp + #include + #include + #include + #include + ``` * the libuv APIs which are also included with Node.js and available via - ```cpp - #include - ``` + ```cpp + #include + ``` * the V8 API available via - ```cpp - #include - ``` + ```cpp + #include + ``` Thus, for an addon to remain ABI-compatible across Node.js major versions, it must use Node-API exclusively by restricting itself to using @@ -126,7 +126,7 @@ Unlike modules written in JavaScript, developing and deploying Node.js native addons using Node-API requires an additional set of tools. Besides the basic tools required to develop for Node.js, the native addon developer requires a toolchain that can compile C and C++ code into a binary. In -addition, depending upon how the native addon is deployed, the *user* of +addition, depending upon how the native addon is deployed, the _user_ of the native addon will also need to have a C/C++ toolchain installed. For Linux developers, the necessary C/C++ toolchain packages are readily @@ -155,7 +155,7 @@ and deploying Node.js native addons. ### Build tools -Both the tools listed here require that *users* of the native +Both the tools listed here require that _users_ of the native addon have a C/C++ toolchain installed in order to successfully install the native addon. @@ -482,7 +482,8 @@ the addon. To this end, Node-API provides a way to allocate data such that its life cycle is tied to the life cycle of the Agent. -### napi_set_instance_data +### `napi_set_instance_data` + + Integral status code indicating the success or failure of a Node-API call. Currently, the following status codes are supported. @@ -580,7 +584,8 @@ typedef enum { If additional information is required upon an API returning a failed status, it can be obtained by calling `napi_get_last_error_info`. -### napi_extended_error_info +### `napi_extended_error_info` + + 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 +#### `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 minimum lifetimes explicitly. For more details, review the [Object lifetime management][]. -#### napi_type_tag +#### `napi_type_tag` + + 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 invoked. -#### napi_callback +#### `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 following signature: @@ -769,11 +788,13 @@ typedef napi_value (*napi_callback)(napi_env, napi_callback_info); Unless for reasons discussed in [Object Lifetime Management][], creating a handle and/or callback scope inside a `napi_callback` is not necessary. -#### napi_finalize +#### `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 object with which it was associated with, has been garbage-collected. The user @@ -790,11 +811,13 @@ typedef void (*napi_finalize)(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_async_execute_callback +#### `napi_async_execute_callback` + + Function pointer used with functions that support asynchronous operations. Callback functions must satisfy the following signature: @@ -807,11 +830,13 @@ JavaScript or interact with JavaScript objects. Node-API calls should be in the `napi_async_complete_callback` instead. Do not use the `napi_env` parameter as it will likely result in execution of JavaScript. -#### napi_async_complete_callback +#### `napi_async_complete_callback` + + Function pointer used with functions that support asynchronous operations. Callback functions must satisfy the following signature: @@ -824,7 +849,8 @@ typedef void (*napi_async_complete_callback)(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_threadsafe_function_call_js +#### `napi_threadsafe_function_call_js` + @@ -66,6 +67,7 @@ disabling inbound or outbound access to specific IP addresses, IP ranges, or IP subnets. ### `blockList.addAddress(address[, type])` + @@ -76,6 +78,7 @@ added: v15.0.0 Adds a rule to block the given IP address. ### `blockList.addRange(start, end[, type])` + @@ -89,6 +92,7 @@ Adds a rule to block a range of IP addresses from `start` (inclusive) to `end` (inclusive). ### `blockList.addSubnet(net, prefix[, type])` + @@ -102,6 +106,7 @@ added: v15.0.0 Adds a rule to block a range of IP addresses specified as a subnet mask. ### `blockList.check(address[, type])` + @@ -129,19 +134,23 @@ console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true ``` ### `blockList.rules` + -* Type: {string[]} +* Type: {string\[]} The list of rules added to the blocklist. ## Class: `net.SocketAddress` + + ### `new net.SocketAddress([options])` + @@ -150,11 +159,13 @@ added: v15.14.0 * `address` {string} The network address as either an IPv4 or IPv6 string. **Default**: `'127.0.0.1'` if `family` is `'ipv4'`; `'::'` if `family` is `'ipv6'`. - * `family` {string} One of either `'ipv4'` or 'ipv6'`. **Default**: `'ipv4'`. + * `family` {string} One of either `'ipv4'` or `'ipv6'`. + **Default**: `'ipv4'`. * `flowlabel` {number} An IPv6 flow-label used only if `family` is `'ipv6'`. * `port` {number} An IP port. ### `socketaddress.address` + @@ -162,6 +173,7 @@ added: v15.14.0 * Type {string} ### `socketaddress.family` + @@ -169,6 +181,7 @@ added: v15.14.0 * Type {string} Either `'ipv4'` or `'ipv6'`. ### `socketaddress.flowlabel` + @@ -176,6 +189,7 @@ added: v15.14.0 * Type {number} ### `socketaddress.port` + @@ -183,6 +197,7 @@ added: v15.14.0 * Type {number} ## Class: `net.Server` + @@ -202,6 +217,7 @@ This class is used to create a TCP or [IPC][] server. `net.Server` is an [`EventEmitter`][] with the following events: ### Event: `'close'` + @@ -210,6 +226,7 @@ Emitted when the server closes. If connections exist, this event is not emitted until all connections are ended. ### Event: `'connection'` + @@ -220,6 +237,7 @@ Emitted when a new connection is made. `socket` is an instance of `net.Socket`. ### Event: `'error'` + @@ -232,6 +250,7 @@ event will **not** be emitted directly following this event unless [`server.listen()`][]. ### Event: `'listening'` + @@ -239,6 +258,7 @@ added: v0.1.90 Emitted when the server has been bound after calling [`server.listen()`][]. ### `server.address()` + @@ -271,6 +291,7 @@ server.listen(() => { emitted or after calling `server.close()`. ### `server.close([callback])` + @@ -286,6 +307,7 @@ that event, it will be called with an `Error` as its only argument if the server was not open when it was closed. ### `server.getConnections(callback)` + @@ -305,15 +327,12 @@ an [IPC][] server depending on what it listens to. Possible signatures: - * [`server.listen(handle[, backlog][, callback])`][`server.listen(handle)`] * [`server.listen(options[, callback])`][`server.listen(options)`] * [`server.listen(path[, backlog][, callback])`][`server.listen(path)`] for [IPC][] servers -* - server.listen([port[, host[, backlog]]][, callback]) +* [`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port)`] for TCP servers - This function is asynchronous. When the server starts listening, the [`'listening'`][] event will be emitted. The last parameter `callback` @@ -349,6 +368,7 @@ server.on('error', (e) => { ``` #### `server.listen(handle[, backlog][, callback])` + @@ -368,6 +388,7 @@ valid file descriptor. Listening on a file descriptor is not supported on Windows. #### `server.listen(options[, callback])` + If `port` is specified, it behaves the same as - -server.listen([port[, host[, backlog]]][, callback]). +[`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port)`]. Otherwise, if `path` is specified, it behaves the same as [`server.listen(path[, backlog][, callback])`][`server.listen(path)`]. If none of them is specified, an error will be thrown. - If `exclusive` is `false` (default), then cluster workers will use the same underlying handle, allowing connection handling duties to be shared. When @@ -441,6 +459,7 @@ controller.abort(); ``` #### `server.listen(path[, backlog][, callback])` + @@ -454,6 +473,7 @@ added: v0.1.90 Start an [IPC][] server listening for connections on the given `path`. #### `server.listen([port[, host[, backlog]]][, callback])` + @@ -479,6 +499,7 @@ may cause the `net.Server` to also listen on the [unspecified IPv4 address][] (`0.0.0.0`). ### `server.listening` + @@ -486,6 +507,7 @@ added: v5.7.0 * {boolean} Indicates whether or not the server is listening for connections. ### `server.maxConnections` + @@ -499,6 +521,7 @@ It is not recommended to use this option once a socket has been sent to a child with [`child_process.fork()`][]. ### `server.ref()` + @@ -506,10 +529,11 @@ added: v0.9.1 * Returns: {net.Server} 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). +_not_ let the program exit if it's the only server left (the default behavior). If the server is `ref`ed calling `ref()` again will have no effect. ### `server.unref()` + @@ -521,6 +545,7 @@ active server in the event system. If the server is already `unref`ed calling `unref()` again will have no effect. ## Class: `net.Socket` + @@ -541,6 +566,7 @@ is received. For example, it is passed to the listeners of a it to interact with the client. ### `new net.Socket([options])` + @@ -580,6 +607,7 @@ Emitted once the socket is fully closed. The argument `hadError` is a boolean which says if the socket was closed due to a transmission error. ### Event: `'connect'` + @@ -588,6 +616,7 @@ Emitted when a socket connection is successfully established. See [`net.createConnection()`][]. ### Event: `'data'` + @@ -601,6 +630,7 @@ The data will be lost if there is no listener when a `Socket` emits a `'data'` event. ### Event: `'drain'` + @@ -610,6 +640,7 @@ Emitted when the write buffer becomes empty. Can be used to throttle uploads. See also: the return values of `socket.write()`. ### Event: `'end'` + @@ -626,6 +657,7 @@ allowing the user to write arbitrary amounts of data. The user must call FIN packet back). ### Event: `'error'` + @@ -636,6 +668,7 @@ Emitted when an error occurs. The `'close'` event will be called directly following this event. ### Event: `'lookup'` + @@ -662,6 +696,7 @@ Emitted when a socket is ready to be used. Triggered immediately after `'connect'`. ### Event: `'timeout'` + @@ -672,6 +707,7 @@ the socket has been idle. The user must manually close the connection. See also: [`socket.setTimeout()`][]. ### `socket.address()` + @@ -683,6 +719,7 @@ socket as reported by the operating system: `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` ### `socket.bufferSize` + @@ -718,6 +756,7 @@ added: v0.5.3 The amount of received bytes. ### `socket.bytesWritten` + @@ -751,6 +790,7 @@ This function should only be used for reconnecting a socket after behavior. #### `socket.connect(options[, connectListener])` + @@ -858,6 +899,7 @@ Alias to called with `{port: port, host: host}` as `options`. ### `socket.connecting` + @@ -873,6 +915,7 @@ that the callback is a listener for the `'connect'` event. ### `socket.destroy([error])` + @@ -893,6 +936,7 @@ See [`writable.destroy()`][] for further details. See [`writable.destroyed`][] for further details. ### `socket.end([data[, encoding]][, callback])` + @@ -908,6 +952,7 @@ server will still send some data. See [`writable.end()`][] for further details. ### `socket.localAddress` + @@ -920,6 +965,7 @@ connects on `'192.168.1.1'`, the value of `socket.localAddress` would be `'192.168.1.1'`. ### `socket.localPort` + @@ -936,6 +982,7 @@ Pauses the reading of data. That is, [`'data'`][] events will not be emitted. Useful to throttle back an upload. ### `socket.pending` + @@ -956,10 +1004,11 @@ added: v0.9.1 * Returns: {net.Socket} 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). +_not_ let the program exit if it's the only socket left (the default behavior). If the socket is `ref`ed calling `ref` again will have no effect. ### `socket.remoteAddress` + @@ -971,6 +1020,7 @@ The string representation of the remote IP address. For example, the socket is destroyed (for example, if the client disconnected). ### `socket.remoteFamily` + @@ -980,6 +1030,7 @@ added: v0.11.14 The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. ### `socket.remotePort` + @@ -995,6 +1046,7 @@ The numeric representation of the remote port. For example, `80` or `21`. Resumes reading after a call to [`socket.pause()`][]. ### `socket.setEncoding([encoding])` + @@ -1006,6 +1058,7 @@ Set the encoding for the socket as a [Readable Stream][]. See [`readable.setEncoding()`][] for more information. ### `socket.setKeepAlive([enable][, initialDelay])` + @@ -1054,6 +1109,7 @@ algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's algorithm. ### `socket.setTimeout(timeout[, callback])` + @@ -1083,6 +1139,7 @@ The optional `callback` parameter will be added as a one-time listener for the [`'timeout'`][] event. ### `socket.timeout` + @@ -1093,6 +1150,7 @@ The socket timeout in milliseconds as set by [`socket.setTimeout()`][]. It is `undefined` if a timeout has not been set. ### `socket.unref()` + @@ -1104,6 +1162,7 @@ active socket in the event system. If the socket is already `unref`ed calling `unref()` again will have no effect. ### `socket.write(data[, encoding][, callback])` + @@ -1127,6 +1186,7 @@ See `Writable` stream [`write()`][stream_writable_write] method for more information. ### `socket.readyState` + @@ -1154,6 +1214,7 @@ Possible signatures: for TCP connections. ### `net.connect(options[, connectListener])` + @@ -1166,6 +1227,7 @@ Alias to [`net.createConnection(options[, connectListener])`][`net.createConnection(options)`]. ### `net.connect(path[, connectListener])` + @@ -1178,6 +1240,7 @@ Alias to [`net.createConnection(path[, connectListener])`][`net.createConnection(path)`]. ### `net.connect(port[, host][, connectListener])` + @@ -1211,6 +1274,7 @@ Possible signatures: The [`net.connect()`][] function is an alias to this function. ### `net.createConnection(options[, connectListener])` + @@ -1260,6 +1324,7 @@ const client = net.createConnection({ path: '/tmp/echo.sock' }); ``` ### `net.createConnection(path[, connectListener])` + @@ -1281,6 +1346,7 @@ immediately initiates connection with then returns the `net.Socket` that starts the connection. ### `net.createConnection(port[, host][, connectListener])` + @@ -1289,7 +1355,7 @@ added: v0.1.90 [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. * `host` {string} Host the socket should connect to. Will be passed to [`socket.connect(port[, host][, connectListener])`][`socket.connect(port)`]. - **Default:** `'localhost'`. + **Default:** `'localhost'`. * `connectListener` {Function} Common parameter of the [`net.createConnection()`][] functions, an "once" listener for the `'connect'` event on the initiating socket. Will be passed to @@ -1304,6 +1370,7 @@ immediately initiates connection with then returns the `net.Socket` that starts the connection. ## `net.createServer([options][, connectionListener])` + @@ -1380,6 +1447,7 @@ $ nc -U /tmp/echo.sock ``` ## `net.isIP(input)` + @@ -1392,6 +1460,7 @@ returns `4` for IP version 4 addresses, and returns `6` for IP version 6 addresses. ## `net.isIPv4(input)` + @@ -1402,6 +1471,7 @@ added: v0.3.0 Returns `true` if input is a version 4 IP address, otherwise returns `false`. ## `net.isIPv6(input)` + @@ -1445,6 +1515,7 @@ Returns `true` if input is a version 6 IP address, otherwise returns `false`. [`server.listen(handle)`]: #serverlistenhandle-backlog-callback [`server.listen(options)`]: #serverlistenoptions-callback [`server.listen(path)`]: #serverlistenpath-backlog-callback +[`server.listen(port)`]: #serverlistenport-host-backlog-callback [`socket(7)`]: https://man7.org/linux/man-pages/man7/socket.7.html [`socket.connect()`]: #socketconnect [`socket.connect(options)`]: #socketconnectoptions-connectlistener diff --git a/doc/api/os.md b/doc/api/os.md index 85469a56293cc6..c8d4380bec40ea 100644 --- a/doc/api/os.md +++ b/doc/api/os.md @@ -14,6 +14,7 @@ const os = require('os'); ``` ## `os.EOL` + @@ -26,6 +27,7 @@ The operating system-specific end-of-line marker. * `\r\n` on Windows ## `os.arch()` + @@ -39,6 +41,7 @@ compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`, The return value is equivalent to [`process.arch`][]. ## `os.constants` + @@ -50,11 +53,12 @@ process signals, and so on. The specific constants defined are described in [OS constants](#os-constants). ## `os.cpus()` + -* Returns: {Object[]} +* Returns: {Object\[]} Returns an array of objects containing information about each logical CPU core. @@ -70,6 +74,7 @@ The properties included on each object include: * `irq` {number} The number of milliseconds the CPU has spent in irq mode. + ```js [ { @@ -123,6 +128,7 @@ The properties included on each object include: are always 0. ## `os.devNull` + @@ -135,6 +141,7 @@ The platform-specific file path of the null device. * `/dev/null` on POSIX ## `os.endianness()` + @@ -147,6 +154,7 @@ binary was compiled. Possible values are `'BE'` for big endian and `'LE'` for little endian. ## `os.freemem()` + @@ -156,6 +164,7 @@ added: v0.3.3 Returns the amount of free system memory in bytes as an integer. ## `os.getPriority([pid])` + @@ -168,6 +177,7 @@ Returns the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the priority of the current process is returned. ## `os.homedir()` + @@ -183,6 +193,7 @@ On Windows, it uses the `USERPROFILE` environment variable if defined. Otherwise it uses the path to the profile directory of the current user. ## `os.hostname()` + @@ -192,11 +203,12 @@ added: v0.3.3 Returns the host name of the operating system as a string. ## `os.loadavg()` + -* Returns: {number[]} +* Returns: {number\[]} Returns an array containing the 1, 5, and 15 minute load averages. @@ -207,6 +219,7 @@ The load average is a Unix-specific concept. On Windows, the return value is always `[0, 0, 0]`. ## `os.networkInterfaces()` + @@ -234,6 +247,7 @@ The properties available on the assigned network address object include: to `null`. + ```js { lo: [ @@ -278,6 +292,7 @@ The properties available on the assigned network address object include: ``` ## `os.platform()` + @@ -294,6 +309,7 @@ The value `'android'` may also be returned if Node.js is built on the Android operating system. [Android support is experimental][Android building]. ## `os.release()` + @@ -307,6 +323,7 @@ On POSIX systems, the operating system release is determined by calling for more information. ## `os.setPriority([pid, ]priority)` + @@ -330,6 +347,7 @@ privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. ## `os.tmpdir()` + @@ -354,6 +373,7 @@ added: v0.3.3 Returns the total amount of system memory in bytes as an integer. ## `os.type()` + @@ -367,6 +387,7 @@ See for additional information about the output of running [`uname(3)`][] on various operating systems. ## `os.uptime()` + @@ -404,6 +426,7 @@ operating system response. Throws a [`SystemError`][] if a user has no `username` or `homedir`. ## `os.version()` + diff --git a/doc/api/packages.md b/doc/api/packages.md index 3c14b9897c5856..4d38ee61881afe 100644 --- a/doc/api/packages.md +++ b/doc/api/packages.md @@ -140,6 +140,7 @@ package: `"commonjs"` package). ### `--input-type` flag + @@ -275,6 +276,7 @@ absolute subpath of the package such as `require('/path/to/node_modules/pkg/subpath.js')` will still load `subpath.js`. ### Subpath exports + @@ -308,6 +310,7 @@ import submodule from 'es-module-package/private-module.js'; ``` ### Subpath imports + @@ -494,6 +500,7 @@ can be written: ``` ### Conditional exports + @@ -1096,6 +1109,7 @@ When a package has an [`"exports"`][] field, this will take precedence over the `"main"` field when importing the package by name. ### `"packageManager"` + @@ -1120,6 +1134,7 @@ This field is currently experimental and needs to be opted-in; check the [Corepack][] page for details about the procedure. ### `"type"` + -* Type: {Object} | {string} | {string[]} +* Type: {Object} | {string} | {string\[]} ```json { @@ -1219,6 +1235,7 @@ All paths defined in the `"exports"` must be relative file URLs starting with `./`. ### `"imports"` + @@ -136,6 +138,7 @@ process.env.PATH.split(path.delimiter); ``` ## `path.dirname(path)` + @@ -263,6 +268,7 @@ path.format({ ``` ## `path.isAbsolute(path)` + @@ -298,6 +304,7 @@ path.isAbsolute('.'); // false A [`TypeError`][] is thrown if `path` is not a string. ## `path.join([...paths])` + @@ -323,6 +330,7 @@ path.join('foo', {}, 'bar'); A [`TypeError`][] is thrown if any of the path segments is not a string. ## `path.normalize(path)` + @@ -366,6 +374,7 @@ path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar'); A [`TypeError`][] is thrown if `path` is not a string. ## `path.parse(path)` + @@ -432,6 +441,7 @@ path.parse('C:\\path\\dir\\file.txt'); A [`TypeError`][] is thrown if `path` is not a string. ## `path.posix` + @@ -527,6 +539,7 @@ path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); A [`TypeError`][] is thrown if any of the arguments is not a string. ## `path.sep` + @@ -557,6 +570,7 @@ as path segment separators; however, the `path` methods only add backward slashes (`\`). ## `path.toNamespacedPath(path)` + @@ -572,6 +586,7 @@ This method is meaningful only on Windows systems. On POSIX systems, the method is non-operational and always returns `path` without modifications. ## `path.win32` + @@ -44,6 +45,7 @@ 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])` + @@ -54,6 +56,7 @@ If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. If `name` is provided, removes only the named mark. ### `performance.eventLoopUtilization([utilization1[, utilization2]])` + * `utilization1` {Object} The result of a previous call to - `eventLoopUtilization()`. + `eventLoopUtilization()`. * `utilization2` {Object} The result of a previous call to - `eventLoopUtilization()` prior to `utilization1`. + `eventLoopUtilization()` prior to `utilization1`. * Returns {Object} * `idle` {number} * `active` {number} @@ -116,6 +119,7 @@ Passing in a user-defined object instead of the result of a previous call to are not guaranteed to reflect any correct state of the event loop. ### `performance.mark([name[, options]])` + @@ -191,6 +197,7 @@ An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. ### `performance.now()` + @@ -201,6 +208,7 @@ Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. ### `performance.timeOrigin` + @@ -211,6 +219,7 @@ The [`timeOrigin`][] specifies the high resolution millisecond timestamp at which the current `node` process began, measured in Unix time. ### `performance.timerify(fn[, options])` + @@ -270,11 +280,13 @@ An object which is JSON representation of the `performance` object. It is similar to [`window.performance.toJSON`][] in browsers. ## Class: `PerformanceEntry` + ### `performanceEntry.detail` + @@ -284,6 +296,7 @@ added: v16.0.0 Additional detail specific to the `entryType`. ### `performanceEntry.duration` + @@ -294,6 +307,7 @@ The total number of milliseconds elapsed for this entry. This value will not be meaningful for all Performance Entry types. ### `performanceEntry.entryType` + @@ -311,6 +325,7 @@ The type of the performance entry. It may be one of: * `'http'` (Node.js only) ### `performanceEntry.flags` + @@ -348,6 +364,7 @@ added: v8.5.0 The name of the performance entry. ### `performanceEntry.kind` + @@ -447,6 +465,7 @@ When `performanceEntry.type` is equal to `'function'`, the the input arguments to the timed function. ## Class: `PerformanceNodeTiming` + @@ -459,6 +478,7 @@ Provides timing details for Node.js itself. The constructor of this class is not exposed to users. ### `performanceNodeTiming.bootstrapComplete` + @@ -470,6 +490,7 @@ completed bootstrapping. If bootstrapping has not yet finished, the property has the value of -1. ### `performanceNodeTiming.environment` + @@ -480,6 +501,7 @@ The high resolution millisecond timestamp at which the Node.js environment was initialized. ### `performanceNodeTiming.idleTime` + @@ -506,6 +529,7 @@ exited. If the event loop has not yet exited, the property has the value of -1. It can only have a value of not -1 in a handler of the [`'exit'`][] event. ### `performanceNodeTiming.loopStart` + @@ -517,6 +541,7 @@ started. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1. ### `performanceNodeTiming.nodeStart` + @@ -527,6 +552,7 @@ The high resolution millisecond timestamp at which the Node.js process was initialized. ### `performanceNodeTiming.v8Start` + @@ -539,6 +565,7 @@ initialized. ## Class: `perf_hooks.PerformanceObserver` ### `new PerformanceObserver(callback)` + @@ -576,12 +603,15 @@ notified about new `PerformanceEntry` instances. The callback receives a `PerformanceObserver`. ### `performanceObserver.disconnect()` + + Disconnects the `PerformanceObserver` instance from all notifications. ### `performanceObserver.observe(options)` + @@ -635,11 +666,12 @@ The `PerformanceObserverEntryList` class is used to provide access to the The constructor of this class is not exposed to users. ### `performanceObserverEntryList.getEntries()` + -* Returns: {PerformanceEntry[]} +* Returns: {PerformanceEntry\[]} Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. @@ -677,13 +709,14 @@ performance.mark('meow'); ``` ### `performanceObserverEntryList.getEntriesByName(name[, type])` + * `name` {string} * `type` {string} -* Returns: {PerformanceEntry[]} +* Returns: {PerformanceEntry\[]} Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` whose `performanceEntry.name` is @@ -731,12 +764,13 @@ performance.mark('meow'); ``` ### `performanceObserverEntryList.getEntriesByType(type)` + * `type` {string} -* Returns: {PerformanceEntry[]} +* Returns: {PerformanceEntry\[]} Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` @@ -775,6 +809,7 @@ performance.mark('meow'); ``` ## `perf_hooks.createHistogram([options])` + @@ -791,6 +826,7 @@ added: v15.9.0 Returns a {RecordableHistogram}. ## `perf_hooks.monitorEventLoopDelay([options])` + @@ -827,11 +863,13 @@ console.log(h.percentile(99)); ``` ## Class: `Histogram` + ### `histogram.exceeds` + @@ -842,6 +880,7 @@ The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. ### `histogram.max` + @@ -851,6 +890,7 @@ added: v11.10.0 The maximum recorded event loop delay. ### `histogram.mean` + @@ -860,6 +900,7 @@ added: v11.10.0 The mean of the recorded event loop delays. ### `histogram.min` + @@ -869,6 +910,7 @@ added: v11.10.0 The minimum recorded event loop delay. ### `histogram.percentile(percentile)` + @@ -879,6 +921,7 @@ added: v11.10.0 Returns the value at the given percentile. ### `histogram.percentiles` + @@ -888,6 +931,7 @@ added: v11.10.0 Returns a `Map` object detailing the accumulated percentile distribution. ### `histogram.reset()` + @@ -895,6 +939,7 @@ added: v11.10.0 Resets the collected histogram data. ### `histogram.stddev` + @@ -908,6 +953,7 @@ The standard deviation of the recorded event loop delays. A `Histogram` that is periodically updated on a given interval. ### `histogram.disable()` + @@ -918,6 +964,7 @@ Disables the update interval timer. Returns `true` if the timer was stopped, `false` if it was already stopped. ### `histogram.enable()` + @@ -934,11 +981,13 @@ end, the histogram is cloned as a plain {Histogram} object that does not implement the `enable()` and `disable()` methods. ## Class: `RecordableHistogram extends Histogram` + ### `histogram.record(val)` + @@ -946,6 +995,7 @@ added: v15.9.0 * `val` {number|bigint} The amount to record in the histogram. ### `histogram.recordDelta()` + @@ -1005,6 +1055,7 @@ The following example measures the duration of `require()` operations to load dependencies: + ```js 'use strict'; const { diff --git a/doc/api/process.md b/doc/api/process.md index db6f48eb25fe44..269efb72223ef3 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -23,6 +23,7 @@ const process = require('process'); The `process` object is an instance of [`EventEmitter`][]. ### Event: `'beforeExit'` + @@ -36,10 +37,10 @@ continue. The listener callback function is invoked with the value of [`process.exitCode`][] passed as the only argument. -The `'beforeExit'` event is *not* emitted for conditions causing explicit +The `'beforeExit'` event is _not_ emitted for conditions causing explicit termination, such as calling [`process.exit()`][] or uncaught exceptions. -The `'beforeExit'` should *not* be used as an alternative to the `'exit'` event +The `'beforeExit'` should _not_ be used as an alternative to the `'exit'` event unless the intention is to schedule additional work. ```mjs @@ -81,6 +82,7 @@ console.log('This message is displayed first.'); ``` ### Event: `'disconnect'` + @@ -90,6 +92,7 @@ and [Cluster][] documentation), the `'disconnect'` event will be emitted when the IPC channel is closed. ### Event: `'exit'` + @@ -151,6 +154,7 @@ process.on('exit', (code) => { ``` ### Event: `'message'` + @@ -174,6 +178,7 @@ to represent. See [Advanced serialization for `child_process`][] for more details. ### Event: `'multipleResolves'` + @@ -254,6 +259,7 @@ main().then(console.log); ``` ### Event: `'rejectionHandled'` + @@ -315,6 +321,7 @@ likely best for long-running application) or upon process exit (which is likely most convenient for scripts). ### Event: `'uncaughtException'` + @@ -627,6 +637,7 @@ The `*-deprecation` command-line flags only affect warnings that use the name `'DeprecationWarning'`. ### Event: `'worker'` + @@ -676,7 +687,7 @@ refer to signal(7) for a listing of standard POSIX signal names such as Signals are not available on [`Worker`][] threads. The signal handler will receive the signal's name (`'SIGINT'`, - `'SIGTERM'`, etc.) as the first argument. +`'SIGTERM'`, etc.) as the first argument. The name of each event will be the uppercase common name for the signal (e.g. `'SIGINT'` for `SIGINT` signals). @@ -735,8 +746,8 @@ process.on('SIGTERM', handle); * `'SIGTERM'` is not supported on Windows, it can be listened on. * `'SIGINT'` from the terminal is supported on all platforms, and can usually be generated with Ctrl+C (though this may be configurable). - It is not generated when [terminal raw mode][] is enabled and - Ctrl+C is used. + It is not generated when [terminal raw mode][] is enabled + and Ctrl+C is used. * `'SIGBREAK'` is delivered on Windows when Ctrl+Break is pressed. On non-Windows platforms, it can be listened on, but there is no way to send or generate it. @@ -747,15 +758,16 @@ process.on('SIGTERM', handle); terminate Node.js on all platforms. * `'SIGSTOP'` cannot have a listener installed. * `'SIGBUS'`, `'SIGFPE'`, `'SIGSEGV'` and `'SIGILL'`, when not raised - artificially using kill(2), inherently leave the process in a state from - which it is not safe to call JS listeners. Doing so might cause the process - to stop responding. + artificially using kill(2), inherently leave the process in a state from + which it is not safe to call JS listeners. Doing so might cause the process + to stop responding. * `0` can be sent to test for the existence of a process, it has no effect if - the process exists, but will throw an error if the process does not exist. + the process exists, but will throw an error if the process does not exist. Windows does not support signals so has no equivalent to termination by signal, but Node.js offers some emulation with [`process.kill()`][], and [`subprocess.kill()`][]: + * Sending `SIGINT`, `SIGTERM`, and `SIGKILL` will cause the unconditional termination of the target process, and afterwards, subprocess will report that the process was terminated by signal. @@ -763,6 +775,7 @@ but Node.js offers some emulation with [`process.kill()`][], and existence of a process. ## `process.abort()` + @@ -773,6 +786,7 @@ generate a core file. This feature is not available in [`Worker`][] threads. ## `process.allowedNodeEnvironmentFlags` + @@ -791,16 +805,16 @@ return `true` in the following cases: * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. * Flags passed through to V8 (as listed in `--v8-options`) may replace - one or more *non-leading* dashes for an underscore, or vice-versa; + one or more _non-leading_ dashes for an underscore, or vice-versa; e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, etc. * Flags may contain one or more equals (`=`) characters; all characters after and including the first equals will be ignored; e.g., `--stack-trace-limit=100`. -* Flags *must* be allowable within [`NODE_OPTIONS`][]. +* Flags _must_ be allowable within [`NODE_OPTIONS`][]. When iterating over `process.allowedNodeEnvironmentFlags`, flags will -appear only *once*; each will begin with one or more dashes. Flags +appear only _once_; each will begin with one or more dashes. Flags passed through to V8 will contain underscores instead of non-leading dashes: @@ -830,11 +844,12 @@ The methods `add()`, `clear()`, and `delete()` of `process.allowedNodeEnvironmentFlags` do nothing, and will fail silently. -If Node.js was compiled *without* [`NODE_OPTIONS`][] support (shown in +If Node.js was compiled _without_ [`NODE_OPTIONS`][] support (shown in [`process.config`][]), `process.allowedNodeEnvironmentFlags` will -contain what *would have* been allowable. +contain what _would have_ been allowable. ## `process.arch` + @@ -858,11 +873,12 @@ console.log(`This processor architecture is ${process.arch}`); ``` ## `process.argv` + -* {string[]} +* {string\[]} The `process.argv` property returns an array containing the command-line arguments passed when the Node.js process was launched. The first element will @@ -908,6 +924,7 @@ Would generate the output: ``` ## `process.argv0` + @@ -926,6 +943,7 @@ $ bash -c 'exec -a customArgv0 ./node' ``` ## `process.channel` + @@ -954,6 +973,7 @@ listeners on the `process` object. However, this method can be used to explicitly request a specific behavior. ### `process.channel.unref()` + @@ -966,6 +986,7 @@ listeners on the `process` object. However, this method can be used to explicitly request a specific behavior. ## `process.chdir(directory)` + @@ -1003,6 +1024,7 @@ try { This feature is not available in [`Worker`][] threads. ## `process.config` + + ```js { target_defaults: @@ -1058,6 +1081,7 @@ Modifying the `process.config` property, or any child-property of the read-only in a future release. ## `process.connected` + @@ -1073,6 +1097,7 @@ Once `process.connected` is `false`, it is no longer possible to send messages over the IPC channel using `process.send()`. ## `process.cpuUsage([previousValue])` + @@ -1121,6 +1146,7 @@ console.log(cpuUsage(startUsage)); ``` ## `process.cwd()` + @@ -1143,6 +1169,7 @@ console.log(`Current directory: ${cwd()}`); ``` ## `process.debugPort` + @@ -1164,6 +1191,7 @@ process.debugPort = 5858; ``` ## `process.disconnect()` + @@ -1180,6 +1208,7 @@ If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. ## `process.dlopen(module, filename[, flags])` + @@ -1239,7 +1269,7 @@ added: v8.0.0 * `warning` {string|Error} The warning to emit. * `options` {Object} * `type` {string} When `warning` is a `String`, `type` is the name to use - for the *type* of warning being emitted. **Default:** `'Warning'`. + for the _type_ of warning being emitted. **Default:** `'Warning'`. * `code` {string} A unique identifier for the warning instance being emitted. * `ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** @@ -1307,13 +1337,14 @@ process.on('warning', (warning) => { If `warning` is passed as an `Error` object, the `options` argument is ignored. ## `process.emitWarning(warning[, type[, code]][, ctor])` + * `warning` {string|Error} The warning to emit. * `type` {string} When `warning` is a `String`, `type` is the name to use - for the *type* of warning being emitted. **Default:** `'Warning'`. + for the _type_ of warning being emitted. **Default:** `'Warning'`. * `code` {string} A unique identifier for the warning instance being emitted. * `ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** @@ -1478,6 +1509,7 @@ emitMyWarning(); ``` ## `process.env` + + ```js { TERM: 'xterm-256color', @@ -1611,11 +1644,12 @@ across [`Worker`][] threads, and only the main thread can make changes that are visible to the operating system or to native add-ons. ## `process.execArgv` + -* {string[]} +* {string\[]} The `process.execArgv` property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not @@ -1631,6 +1665,7 @@ $ node --harmony script.js --version Results in `process.execArgv`: + ```js ['--harmony'] ``` @@ -1638,6 +1673,7 @@ Results in `process.execArgv`: And `process.argv`: + ```js ['/usr/local/bin/node', 'script.js', '--version'] ``` @@ -1646,6 +1682,7 @@ Refer to [`Worker` constructor][] for the detailed behavior of worker threads with this property. ## `process.execPath` + @@ -1656,11 +1693,13 @@ The `process.execPath` property returns the absolute pathname of the executable that started the Node.js process. Symbolic links, if any, are resolved. + ```js '/usr/local/bin/node' ``` ## `process.exit([code])` + @@ -1695,11 +1734,11 @@ completed fully, including I/O operations to `process.stdout` and `process.stderr`. In most situations, it is not actually necessary to call `process.exit()` -explicitly. The Node.js process will exit on its own *if there is no additional -work pending* in the event loop. The `process.exitCode` property can be set to +explicitly. The Node.js process will exit on its own _if there is no additional +work pending_ in the event loop. The `process.exitCode` property can be set to tell the process which exit code to use when the process exits gracefully. -For instance, the following example illustrates a *misuse* of the +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: @@ -1724,11 +1763,11 @@ if (someConditionNotMet()) { ``` The reason this is problematic is because writes to `process.stdout` in Node.js -are sometimes *asynchronous* and may occur over multiple ticks of the Node.js +are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js event loop. Calling `process.exit()`, however, forces the process to exit -*before* those additional writes to `stdout` can be performed. +_before_ those additional writes to `stdout` can be performed. -Rather than calling `process.exit()` directly, the code *should* set the +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: @@ -1755,13 +1794,14 @@ if (someConditionNotMet()) { ``` If it is necessary to terminate the Node.js process due to an error condition, -throwing an *uncaught* error and allowing the process to terminate accordingly +throwing an _uncaught_ error and allowing the process to terminate accordingly is safer than calling `process.exit()`. In [`Worker`][] threads, this function stops the current thread rather than the current process. ## `process.exitCode` + @@ -1776,6 +1816,7 @@ Specifying a code to [`process.exit(code)`][`process.exit()`] will override any previous setting of `process.exitCode`. ## `process.getegid()` + @@ -1803,6 +1844,7 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). ## `process.geteuid()` + @@ -1832,6 +1874,7 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). ## `process.getgid()` + @@ -1861,11 +1904,12 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). ## `process.getgroups()` + -* Returns: {integer[]} +* Returns: {integer\[]} The `process.getgroups()` method returns an array with the supplementary group IDs. POSIX leaves it unspecified if the effective group ID is included but @@ -1891,6 +1935,7 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). ## `process.getuid()` + @@ -1920,6 +1965,7 @@ This function is only available on POSIX platforms (i.e. not Windows or Android). ## `process.hasUncaughtExceptionCaptureCallback()` + @@ -1930,14 +1976,15 @@ Indicates whether a callback has been set using [`process.setUncaughtExceptionCaptureCallback()`][]. ## `process.hrtime([time])` + > Stability: 3 - Legacy. Use [`process.hrtime.bigint()`][] instead. -* `time` {integer[]} The result of a previous call to `process.hrtime()` -* Returns: {integer[]} +* `time` {integer\[]} The result of a previous call to `process.hrtime()` +* Returns: {integer\[]} This is the legacy version of [`process.hrtime.bigint()`][] before `bigint` was introduced in JavaScript. @@ -1989,6 +2036,7 @@ setTimeout(() => { ``` ## `process.hrtime.bigint()` + @@ -2033,6 +2081,7 @@ setTimeout(() => { ``` ## `process.initgroups(user, extraGroup)` + @@ -2072,6 +2121,7 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.kill(pid[, signal])` + @@ -2129,6 +2179,7 @@ When `SIGUSR1` is received by a Node.js process, Node.js will start the debugger. See [Signal Events][]. ## `process.mainModule` + @@ -2250,6 +2303,7 @@ console.log(memoryUsage.rss()); ``` ## `process.nextTick(callback[, ...args])` + @@ -2482,6 +2537,7 @@ the [`'warning'` event][process_warning] and the flag's behavior. ## `process.pid` + @@ -2503,6 +2559,7 @@ console.log(`This process is pid ${pid}`); ``` ## `process.platform` + @@ -2539,6 +2596,7 @@ Android operating system. However, Android support in Node.js [is experimental][Android building]. ## `process.ppid` + + ```js { name: 'node', @@ -2616,6 +2676,7 @@ In custom builds from non-release versions of the source tree, only the relied upon to exist. ## `process.report` + @@ -3007,6 +3079,7 @@ console.log(resourceUsage()); ``` ## `process.send(message[, sendHandle[, options]][, callback])` + @@ -3032,6 +3105,7 @@ The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent. ## `process.setegid(id)` + @@ -3076,6 +3150,7 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.seteuid(id)` + @@ -3120,6 +3195,7 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.setgid(id)` + @@ -3164,11 +3240,12 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.setgroups(groups)` + -* `groups` {integer[]} +* `groups` {integer\[]} The `process.setgroups()` method sets the supplementary group IDs for the Node.js process. This is a privileged operation that requires the Node.js @@ -3207,6 +3284,7 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.setuid(id)` + @@ -3251,6 +3329,7 @@ Android). This feature is not available in [`Worker`][] threads. ## `process.setSourceMapsEnabled(val)` + @@ -3269,6 +3348,7 @@ Only source maps in JavaScript files that are loaded after source maps has been enabled will be parsed and loaded. ## `process.setUncaughtExceptionCaptureCallback(fn)` + @@ -3383,9 +3463,9 @@ important ways: respectively. 2. Writes may be synchronous depending on what the stream is connected to and whether the system is Windows or POSIX: - * Files: *synchronous* on Windows and POSIX - * TTYs (Terminals): *asynchronous* on Windows, *synchronous* on POSIX - * Pipes (and sockets): *synchronous* on Windows, *asynchronous* on POSIX + * Files: _synchronous_ on Windows and POSIX + * TTYs (Terminals): _asynchronous_ on Windows, _synchronous_ on POSIX + * Pipes (and sockets): _synchronous_ on Windows, _asynchronous_ on POSIX These behaviors are partly for historical reasons, as changing them would create backward incompatibility, but they are also expected by some users. @@ -3395,7 +3475,7 @@ Synchronous writes avoid problems such as output written with `console.log()` or `process.exit()` is called before an asynchronous write completes. See [`process.exit()`][] for more information. -***Warning***: Synchronous writes block the event loop until the write has +_**Warning**_: Synchronous writes block the event loop until the write has completed. This can be near instantaneous in the case of output to a file, but under high system load, pipes that are not being read at the receiving end, or with slow terminals or file systems, its possible for the event loop to be @@ -3423,6 +3503,7 @@ false See the [TTY][] documentation for more information. ## `process.throwDeprecation` + @@ -3453,6 +3534,7 @@ Thrown: ``` ## `process.title` + @@ -3477,6 +3559,7 @@ within process manager applications such as macOS Activity Monitor or Windows Services Manager. ## `process.traceDeprecation` + @@ -3490,6 +3573,7 @@ documentation for the [`'warning'` event][process_warning] and the flag's behavior. ## `process.umask()` + @@ -3542,6 +3627,7 @@ console.log( In [`Worker`][] threads, `process.umask(mask)` will throw an exception. ## `process.uptime()` + @@ -3555,6 +3641,7 @@ The return value includes fractions of a second. Use `Math.floor()` to get whole seconds. ## `process.version` + @@ -3581,6 +3668,7 @@ To get the version string without the prepended _v_, use `process.versions.node`. ## `process.versions` + @@ -39,6 +40,7 @@ made available to developers as a convenience. Fixes or other modifications to the module must be directed to the [Punycode.js][] project. ## `punycode.decode(string)` + @@ -54,6 +56,7 @@ punycode.decode('--dqo34k'); // '☃-⌘' ``` ## `punycode.encode(string)` + @@ -69,6 +72,7 @@ punycode.encode('☃-⌘'); // '--dqo34k' ``` ## `punycode.toASCII(domain)` + @@ -88,6 +92,7 @@ punycode.toASCII('example.com'); // 'example.com' ``` ## `punycode.toUnicode(domain)` + @@ -106,11 +111,13 @@ punycode.toUnicode('example.com'); // 'example.com' ``` ## `punycode.ucs2` + ### `punycode.ucs2.decode(string)` + @@ -127,11 +134,12 @@ punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306] ``` ### `punycode.ucs2.encode(codePoints)` + -* `codePoints` {integer[]} +* `codePoints` {integer\[]} The `punycode.ucs2.encode()` method returns a string based on an array of numeric code point values. @@ -142,6 +150,7 @@ punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06' ``` ## `punycode.version` + diff --git a/doc/api/querystring.md b/doc/api/querystring.md index 4b7db7afc3b948..32e9904553d568 100644 --- a/doc/api/querystring.md +++ b/doc/api/querystring.md @@ -19,6 +19,7 @@ The `querystring` API is considered Legacy. While it is still maintained, new code should use the {URLSearchParams} API instead. ## `querystring.decode()` + @@ -26,6 +27,7 @@ added: v0.1.99 The `querystring.decode()` function is an alias for `querystring.parse()`. ## `querystring.encode()` + @@ -33,6 +35,7 @@ added: v0.1.99 The `querystring.encode()` function is an alias for `querystring.stringify()`. ## `querystring.escape(str)` + @@ -49,6 +52,7 @@ application code to provide a replacement percent-encoding implementation if necessary by assigning `querystring.escape` to an alternative function. ## `querystring.parse(str[, sep[, eq[, options]]])` + + ```js { foo: 'bar', @@ -93,7 +98,7 @@ For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others -are not defined and *will not work*. +are not defined and _will not work_. By default, percent-encoded characters within the query string will be assumed to use UTF-8 encoding. If an alternative character encoding is used, then an @@ -107,6 +112,7 @@ querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, ``` ## `querystring.stringify(obj[, sep[, eq[, options]]])` + @@ -125,7 +131,7 @@ The `querystring.stringify()` method produces a URL query string from a given `obj` by iterating through the object's "own properties". It serializes the following types of values passed in `obj`: -{string|number|bigint|boolean|string[]|number[]|bigint[]|boolean[]} +{string|number|bigint|boolean|string\[]|number\[]|bigint\[]|boolean\[]} The numeric values must be finite. Any other input values will be coerced to empty strings. @@ -149,6 +155,7 @@ querystring.stringify({ w: '中文', foo: 'bar' }, null, null, ``` ## `querystring.unescape(str)` + diff --git a/doc/api/readline.md b/doc/api/readline.md index e2b2214ccd98a2..7111e92b4a7016 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -37,6 +37,7 @@ Once this code is invoked, the Node.js application will not terminate until the received on the `input` stream. ## Class: `Interface` + @@ -50,6 +51,7 @@ The `output` stream is used to print prompts for user input that arrives on, and is read from, the `input` stream. ### Event: `'close'` + @@ -71,6 +73,7 @@ The `readline.Interface` instance is finished once the `'close'` event is emitted. ### Event: `'line'` + @@ -89,6 +92,7 @@ rl.on('line', (input) => { ``` ### Event: `'history'` + @@ -111,6 +115,7 @@ rl.on('history', (history) => { ``` ### Event: `'pause'` + @@ -130,6 +135,7 @@ rl.on('pause', () => { ``` ### Event: `'resume'` + @@ -145,6 +151,7 @@ rl.on('resume', () => { ``` ### Event: `'SIGCONT'` + @@ -153,7 +160,7 @@ The `'SIGCONT'` event is emitted when a Node.js process previously moved into the background using Ctrl+Z (i.e. `SIGTSTP`) is then brought back to the foreground using fg(1p). -If the `input` stream was paused *before* the `SIGTSTP` request, this event will +If the `input` stream was paused _before_ the `SIGTSTP` request, this event will not be emitted. The listener function is invoked without passing any arguments. @@ -168,14 +175,15 @@ rl.on('SIGCONT', () => { The `'SIGCONT'` event is _not_ supported on Windows. ### Event: `'SIGINT'` + -The `'SIGINT'` event is emitted whenever the `input` stream receives a -Ctrl+C input, known typically as `SIGINT`. If there are no `'SIGINT'` -event listeners registered when the `input` stream receives a `SIGINT`, the -`'pause'` event will be emitted. +The `'SIGINT'` event is emitted whenever the `input` stream receives +a Ctrl+C input, known typically as `SIGINT`. If there are no +`'SIGINT'` event listeners registered when the `input` stream receives a +`SIGINT`, the `'pause'` event will be emitted. The listener function is invoked without passing any arguments. @@ -188,12 +196,13 @@ rl.on('SIGINT', () => { ``` ### Event: `'SIGTSTP'` + -The `'SIGTSTP'` event is emitted when the `input` stream receives a -Ctrl+Z input, typically known as `SIGTSTP`. If there are +The `'SIGTSTP'` event is emitted when the `input` stream receives +a Ctrl+Z input, typically known as `SIGTSTP`. If there are no `'SIGTSTP'` event listeners registered when the `input` stream receives a `SIGTSTP`, the Node.js process will be sent to the background. @@ -216,6 +225,7 @@ rl.on('SIGTSTP', () => { The `'SIGTSTP'` event is _not_ supported on Windows. ### `rl.close()` + @@ -228,6 +238,7 @@ Calling `rl.close()` does not immediately stop other events (including `'line'`) from being emitted by the `readline.Interface` instance. ### `rl.pause()` + @@ -239,6 +250,7 @@ Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `readline.Interface` instance. ### `rl.prompt([preserveCursor])` + @@ -257,6 +269,7 @@ If the `readline.Interface` was created with `output` set to `null` or `undefined` the prompt is not written. ### `rl.question(query[, options], callback)` + @@ -328,6 +341,7 @@ questionExample(); ``` ### `rl.resume()` + @@ -335,6 +349,7 @@ added: v0.3.4 The `rl.resume()` method resumes the `input` stream if it has been paused. ### `rl.setPrompt(prompt)` + @@ -345,6 +360,7 @@ The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. ### `rl.getPrompt()` + @@ -354,6 +370,7 @@ added: v15.3.0 The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. ### `rl.write(data[, key])` + @@ -385,9 +402,10 @@ rl.write(null, { ctrl: true, name: 'u' }); ``` The `rl.write()` method will write the data to the `readline` `Interface`'s -`input` *as if it were provided by the user*. +`input` _as if it were provided by the user_. ### `rl[Symbol.asyncIterator]()` + @@ -486,6 +506,7 @@ portion of the input string that will be modified as input is processed, as well as the column where the terminal caret will be rendered. ### `rl.getCursorPos()` + @@ -719,6 +745,7 @@ if (process.stdin.isTTY) ``` ## `readline.moveCursor(stream, dx, dy[, callback])` + The REPL supports bi-directional reverse-i-search similar to [ZSH][]. It is -triggered with Ctrl+R to search backward and -Ctrl+S to search -forwards. +triggered with Ctrl+R to search backward +and Ctrl+S to search forwards. Duplicated history entries will be skipped. Entries are accepted as soon as any key is pressed that doesn't correspond -with the reverse search. Cancelling is possible by pressing Esc or -Ctrl+C. +with the reverse search. Cancelling is possible by pressing Esc +or Ctrl+C. Changing the direction immediately searches for the next entry in the expected direction from the current position on. @@ -367,6 +369,7 @@ function myWriter(output) { ``` ## Class: `REPLServer` + @@ -387,6 +390,7 @@ const secondInstance = new repl.REPLServer(options); ``` ### Event: `'exit'` + @@ -406,12 +410,13 @@ replServer.on('exit', () => { ``` ### Event: `'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 +whenever the `.clear` command is received as input _unless_ the REPL is using the default evaluator and the `repl.REPLServer` instance was created with the `useGlobal` option set to `true`. The listener callback will be called with a reference to the `context` object as the only argument. @@ -451,11 +456,12 @@ Clearing context... ``` ### `replServer.defineCommand(keyword, cmd)` + -* `keyword` {string} The command keyword (*without* a leading `.` character). +* `keyword` {string} The command keyword (_without_ a leading `.` character). * `cmd` {Object|Function} The function to invoke when the command is processed. The `replServer.defineCommand()` method is used to add new `.`-prefixed commands @@ -497,6 +503,7 @@ Goodbye! ``` ### `replServer.displayPrompt([preserveCursor])` + @@ -517,6 +524,7 @@ within the action function for commands registered using the `replServer.defineCommand()` method. ### `replServer.clearBufferedCommand()` + @@ -527,6 +535,7 @@ called from within the action function for commands registered using the `replServer.defineCommand()` method. ### `replServer.parseREPLKeyword(keyword[, rest])` + @@ -558,15 +568,17 @@ programmatically. Use this method to initialize a history log file when working with REPL instances programmatically. ## `repl.builtinModules` + -* {string[]} +* {string\[]} A list of the names of all Node.js modules, e.g., `'http'`. ## `repl.start([options])` + @@ -110,12 +111,12 @@ enforce a strict memory limitation in general. Specific stream implementations may choose to enforce stricter limits but doing so is optional. Because [`Duplex`][] and [`Transform`][] streams are both `Readable` and -`Writable`, each maintains *two* separate internal buffers used for reading and +`Writable`, each maintains _two_ separate internal buffers used for reading and writing, allowing each side to operate independently of the other while maintaining an appropriate and efficient flow of data. For example, [`net.Socket`][] instances are [`Duplex`][] streams whose `Readable` side allows -consumption of data received *from* the socket and whose `Writable` side allows -writing data *to* the socket. Because data may be written to the socket at a +consumption of data received _from_ the socket and whose `Writable` side allows +writing data _to_ the socket. Because data may be written to the socket at a faster or slower rate than data is received, each side should operate (and buffer) independently of the other. @@ -196,7 +197,7 @@ section [API for stream implementers][]. ### Writable streams -Writable streams are an abstraction for a *destination* to which data is +Writable streams are an abstraction for a _destination_ to which data is written. Examples of [`Writable`][] streams include: @@ -228,6 +229,7 @@ myStream.end('done writing data'); ``` #### Class: `stream.Writable` + @@ -235,6 +237,7 @@ added: v0.9.4 ##### Event: `'close'` + @@ -289,6 +293,7 @@ function writeOneMillionTimes(writer, data, encoding, callback) { ``` ##### Event: `'error'` + @@ -302,10 +307,11 @@ The stream is closed when the `'error'` event is emitted unless the [`autoDestroy`][writable-new] option was set to `false` when creating the stream. -After `'error'`, no further events other than `'close'` *should* be emitted +After `'error'`, no further events other than `'close'` _should_ be emitted (including `'error'` events). ##### Event: `'finish'` + @@ -325,6 +331,7 @@ writer.end('This is the end\n'); ``` ##### Event: `'pipe'` + @@ -345,6 +352,7 @@ reader.pipe(writer); ``` ##### Event: `'unpipe'` + @@ -371,6 +379,7 @@ reader.unpipe(writer); ``` ##### `writable.cork()` + @@ -391,6 +400,7 @@ to be processed. However, use of `writable.cork()` without implementing See also: [`writable.uncork()`][], [`writable._writev()`][stream-_writev]. ##### `writable.destroy([error])` + @@ -466,6 +477,7 @@ console.log(myStream.destroyed); // true ``` ##### `writable.end([chunk[, encoding]][, callback])` + @@ -562,6 +576,7 @@ process.nextTick(() => { See also: [`writable.cork()`][]. ##### `writable.writable` + @@ -572,6 +587,7 @@ Is `true` if it is safe to call [`writable.write()`][stream-write], which means the stream has not been destroyed, errored or ended. ##### `writable.writableEnded` + @@ -583,6 +599,7 @@ does not indicate whether the data has been flushed, for this use [`writable.writableFinished`][] instead. ##### `writable.writableCorked` + @@ -604,6 +622,7 @@ added: v12.6.0 Is set to `true` immediately before the [`'finish'`][] event is emitted. ##### `writable.writableHighWaterMark` + @@ -613,6 +632,7 @@ added: v9.3.0 Return the value of `highWaterMark` passed when creating this `Writable`. ##### `writable.writableLength` + @@ -624,6 +644,7 @@ ready to be written. The value provides introspection data regarding the status of the `highWaterMark`. ##### `writable.writableNeedDrain` + @@ -633,6 +654,7 @@ added: v15.2.0 Is `true` if the stream's buffer has been full and stream will emit `'drain'`. ##### `writable.writableObjectMode` + @@ -642,6 +664,7 @@ added: v12.3.0 Getter for the property `objectMode` of a given `Writable` stream. ##### `writable.write(chunk[, encoding][, callback])` + @@ -852,6 +876,7 @@ added: v0.9.4 ##### Event: `'close'` + @@ -902,6 +928,7 @@ readable.on('data', (chunk) => { ``` ##### Event: `'end'` + @@ -925,6 +952,7 @@ readable.on('end', () => { ``` ##### Event: `'error'` + @@ -939,6 +967,7 @@ to push an invalid chunk of data. The listener callback will be passed a single `Error` object. ##### Event: `'pause'` + @@ -947,6 +976,7 @@ The `'pause'` event is emitted when [`stream.pause()`][stream-pause] is called and `readableFlowing` is not `false`. ##### Event: `'readable'` + @@ -1024,6 +1055,7 @@ The `'resume'` event is emitted when [`stream.resume()`][stream-resume] is called and `readableFlowing` is not `true`. ##### `readable.destroy([error])` + @@ -1056,6 +1089,7 @@ added: v8.0.0 Is `true` after [`readable.destroy()`][readable-destroy] has been called. ##### `readable.isPaused()` + @@ -1078,6 +1112,7 @@ readable.isPaused(); // === false ``` ##### `readable.pause()` + @@ -1105,6 +1140,7 @@ The `readable.pause()` method has no effect if there is a `'readable'` event listener. ##### `readable.pipe(destination[, options])` + @@ -1112,7 +1148,7 @@ added: v0.9.4 * `destination` {stream.Writable} The destination for writing data * `options` {Object} Pipe options * `end` {boolean} End the writer when the reader ends. **Default:** `true`. -* Returns: {stream.Writable} The *destination*, allowing for a chain of pipes if +* Returns: {stream.Writable} 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`, @@ -1135,7 +1171,7 @@ readable.pipe(writable); It is possible to attach multiple `Writable` streams to a single `Readable` stream. -The `readable.pipe()` method returns a reference to the *destination* stream +The `readable.pipe()` method returns a reference to the _destination_ stream making it possible to set up chains of piped streams: ```js @@ -1159,14 +1195,15 @@ reader.on('end', () => { ``` One important caveat is that if the `Readable` stream emits an error during -processing, the `Writable` destination *is not closed* automatically. If an -error occurs, it will be necessary to *manually* close each stream in order +processing, the `Writable` destination _is not closed_ automatically. If an +error occurs, it will be necessary to _manually_ close each stream in order to prevent memory leaks. The [`process.stderr`][] and [`process.stdout`][] `Writable` streams are never closed until the Node.js process exits, regardless of the specified options. ##### `readable.read([size])` + @@ -1181,7 +1218,7 @@ specified using the `readable.setEncoding()` method or the stream is operating in object mode. The optional `size` argument specifies a specific number of bytes to read. If -`size` bytes are not available to be read, `null` will be returned *unless* +`size` bytes are not available to be read, `null` will be returned _unless_ the stream has ended, in which case all of the data remaining in the internal buffer will be returned. @@ -1250,6 +1287,7 @@ Calling [`stream.read([size])`][stream-read] after the [`'end'`][] event has been emitted will return `null`. No runtime error will be raised. ##### `readable.readable` + @@ -1260,6 +1298,7 @@ Is `true` if it is safe to call [`readable.read()`][stream-read], which means the stream has not been destroyed or emitted `'error'` or `'end'`. ##### `readable.readableAborted` + @@ -1271,6 +1310,7 @@ added: v16.8.0 Returns whether the stream was destroyed or errored before emitting `'end'`. ##### `readable.readableDidRead` + @@ -1282,6 +1322,7 @@ added: v16.7.0 Returns whether `'data'` has been emitted. ##### `readable.readableEncoding` + @@ -1292,6 +1333,7 @@ Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the [`readable.setEncoding()`][] method. ##### `readable.readableEnded` + @@ -1301,6 +1343,7 @@ added: v12.9.0 Becomes `true` when [`'end'`][] event is emitted. ##### `readable.readableFlowing` + @@ -1311,6 +1354,7 @@ This property reflects the current state of a `Readable` stream as described in the [Three states][] section. ##### `readable.readableHighWaterMark` + @@ -1320,6 +1364,7 @@ added: v9.3.0 Returns the value of `highWaterMark` passed when creating this `Readable`. ##### `readable.readableLength` + @@ -1331,6 +1376,7 @@ ready to be read. The value provides introspection data regarding the status of the `highWaterMark`. ##### `readable.readableObjectMode` + @@ -1340,6 +1386,7 @@ added: v12.3.0 Getter for the property `objectMode` of a given `Readable` stream. ##### `readable.resume()` + @@ -1401,6 +1449,7 @@ readable.on('data', (chunk) => { ``` ##### `readable.unpipe([destination])` + @@ -1411,7 +1460,7 @@ added: v0.9.4 The `readable.unpipe()` method detaches a `Writable` stream previously attached using the [`stream.pipe()`][] method. -If the `destination` is not specified, then *all* pipes are detached. +If the `destination` is not specified, then _all_ pipes are detached. If the `destination` is specified, but no pipe is set up for it, then the method does nothing. @@ -1432,6 +1481,7 @@ setTimeout(() => { ``` ##### `readable.unshift(chunk[, encoding])` + @@ -1541,6 +1592,7 @@ myReader.on('readable', () => { ``` ##### `readable[Symbol.asyncIterator]()` + @@ -1632,6 +1685,7 @@ showBoth(); ### Duplex and transform streams #### Class: `stream.Duplex` + @@ -1668,6 +1723,7 @@ This can be changed manually to change the half-open behavior of an existing emitted. #### Class: `stream.Transform` + @@ -1684,6 +1740,7 @@ Examples of `Transform` streams include: * [crypto streams][crypto] ##### `transform.destroy([error])` + -* `streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]} +* `streams` {Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]} * `source` {Stream|Iterable|AsyncIterable|Function} * Returns: {Iterable|AsyncIterable} * `...transforms` {Stream|Function} @@ -1946,6 +2006,7 @@ run().catch(console.error); ``` `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * `Readable` streams which have emitted `'end'` or `'close'`. * `Writable` streams which have emitted `'finish'` or `'close'`. @@ -1954,13 +2015,14 @@ after the `callback` has been invoked. In the case of reuse of streams after failure, this can cause event listener leaks and swallowed errors. ### `stream.compose(...streams)` + > Stability: 1 - `stream.compose` is experimental. -* `streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]} +* `streams` {Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]} * Returns: {stream.Duplex} Combines two or more streams into a `Duplex` stream that writes to the @@ -2043,6 +2105,7 @@ console.log(res); // prints 'HELLOWORLD' ``` ### `stream.Readable.from(iterable[, options])` + @@ -2094,6 +2158,7 @@ added: v16.11.0 * Returns: {stream.Readable} ### `stream.Readable.isDisturbed(stream)` + @@ -2106,6 +2171,7 @@ added: v16.8.0 Returns whether the stream has been read from or cancelled. ### `stream.Duplex.from(src)` + @@ -2134,9 +2200,11 @@ A utility method for creating duplex streams. * Returns: {stream.Duplex} ### `stream.addAbortSignal(signal, stream)` + + * `signal` {AbortSignal} A signal representing possible cancellation * `stream` {Stream} a stream to attach a signal to @@ -2182,6 +2250,7 @@ const stream = addAbortSignal( } })(); ``` + ## API for stream implementers @@ -2195,6 +2264,7 @@ of the four basic stream classes (`stream.Writable`, `stream.Readable`, parent class constructor: + ```js const { Writable } = require('stream'); @@ -2216,14 +2286,14 @@ options are forwarded instead of implicitly forwarding all options. The new stream class must then implement one or more specific methods, depending on the type of stream being created, as detailed in the chart below: -| Use-case | Class | Method(s) to implement | -| -------- | ----- | ---------------------- | -| Reading only | [`Readable`][] | [`_read()`][stream-_read] | -| Writing only | [`Writable`][] | [`_write()`][stream-_write], [`_writev()`][stream-_writev], [`_final()`][stream-_final] | -| Reading and writing | [`Duplex`][] | [`_read()`][stream-_read], [`_write()`][stream-_write], [`_writev()`][stream-_writev], [`_final()`][stream-_final] | -| Operate on written data, then read the result | [`Transform`][] | [`_transform()`][stream-_transform], [`_flush()`][stream-_flush], [`_final()`][stream-_final] | +| Use-case | Class | Method(s) to implement | +| --------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------ | +| Reading only | [`Readable`][] | [`_read()`][stream-_read] | +| Writing only | [`Writable`][] | [`_write()`][stream-_write], [`_writev()`][stream-_writev], [`_final()`][stream-_final] | +| Reading and writing | [`Duplex`][] | [`_read()`][stream-_read], [`_write()`][stream-_write], [`_writev()`][stream-_writev], [`_final()`][stream-_final] | +| Operate on written data, then read the result | [`Transform`][] | [`_transform()`][stream-_transform], [`_flush()`][stream-_flush], [`_final()`][stream-_final] | -The implementation code for a stream should *never* call the "public" methods +The implementation code for a stream should _never_ call the "public" methods of a stream that are intended for use by consumers (as described in the [API for stream consumers][] section). Doing so may lead to adverse side effects in application code consuming the stream. @@ -2236,6 +2306,7 @@ and/or compatibility issues with other streams, stream utilities, and user expectations. ### Simplified construction + @@ -2265,11 +2336,12 @@ const myWritable = new Writable({ The `stream.Writable` class is extended to implement a [`Writable`][] stream. -Custom `Writable` streams *must* call the `new stream.Writable([options])` +Custom `Writable` streams _must_ call the `new stream.Writable([options])` constructor and implement the `writable._write()` and/or `writable._writev()` method. #### `new stream.Writable([options])` + + ```js const { Writable } = require('stream'); @@ -2386,7 +2459,9 @@ const myWritable = new Writable({ // Later, abort the operation closing the stream controller.abort(); ``` + #### `writable._construct(callback)` + @@ -2436,6 +2511,7 @@ class WriteStream extends Writable { ``` #### `writable._write(chunk, encoding, callback)` + @@ -2528,6 +2605,7 @@ The `_destroy()` method is called by [`writable.destroy()`][writable-destroy]. It can be overridden by child classes but it **must not** be called directly. #### `writable._final(callback)` + @@ -2633,10 +2711,11 @@ console.log(w.data); // currency: € The `stream.Readable` class is extended to implement a [`Readable`][] stream. -Custom `Readable` streams *must* call the `new stream.Readable([options])` +Custom `Readable` streams _must_ call the `new stream.Readable([options])` constructor and implement the [`readable._read()`][] method. #### `new stream.Readable([options])` + + ```js const { Readable } = require('stream'); @@ -2731,6 +2811,7 @@ controller.abort(); ``` #### `readable._construct(callback)` + @@ -2788,6 +2869,7 @@ class ReadStream extends Readable { ``` #### `readable._read(size)` + @@ -2826,6 +2908,7 @@ internal to the class that defines it, and should never be called directly by user programs. #### `readable._destroy(err, callback)` + @@ -2838,6 +2921,7 @@ The `_destroy()` method is called by [`readable.destroy()`][readable-destroy]. It can be overridden by child classes but it **must not** be called directly. #### `readable.push(chunk[, encoding])` + + ```js const { Duplex } = require('stream'); @@ -3185,8 +3271,8 @@ The `stream.Transform` class is extended to implement a [`Transform`][] stream. The `stream.Transform` class prototypically inherits from `stream.Duplex` and implements its own versions of the `writable._write()` and -[`readable._read()`][] methods. Custom `Transform` implementations *must* -implement the [`transform._transform()`][stream-_transform] method and *may* +[`readable._read()`][] methods. Custom `Transform` implementations _must_ +implement the [`transform._transform()`][stream-_transform] method and _may_ also implement the [`transform._flush()`][stream-_flush] method. Care must be taken when using `Transform` streams in that data written to the @@ -3203,6 +3289,7 @@ output on the `Readable` side is not consumed. method. + ```js const { Transform } = require('stream'); @@ -3269,7 +3356,7 @@ store an amount of internal state used to optimally compress the output. When the stream ends, however, that additional data needs to be flushed so that the compressed data will be complete. -Custom [`Transform`][] implementations *may* implement the `transform._flush()` +Custom [`Transform`][] implementations _may_ implement the `transform._flush()` method. This will be called when there is no more written data to be consumed, but before the [`'end'`][] event is emitted signaling the end of the [`Readable`][] stream. @@ -3452,7 +3539,7 @@ less powerful and less useful. were required to store read data into buffers so the data would not be lost. * The [`stream.pause()`][stream-pause] method was advisory, rather than guaranteed. This meant that it was still necessary to be prepared to receive - [`'data'`][] events *even when the stream was in a paused state*. + [`'data'`][] events _even when the stream was in a paused state_. In Node.js 0.10, the [`Readable`][] class was added. For backward compatibility with older Node.js programs, `Readable` streams switch into @@ -3526,7 +3613,7 @@ situations within Node.js where this is done, particularly in the Use of `readable.push('')` is not recommended. Pushing a zero-byte string, `Buffer` or `Uint8Array` to a stream that is not in -object mode has an interesting side effect. Because it *is* a call to +object mode has an interesting side effect. Because it _is_ a call to [`readable.push()`][stream-push], the call will end the reading process. However, because the argument is an empty string, no data is added to the readable buffer so there is nothing for a user to consume. diff --git a/doc/api/string_decoder.md b/doc/api/string_decoder.md index 42a288c7c832ed..a628a5a8a14cf4 100644 --- a/doc/api/string_decoder.md +++ b/doc/api/string_decoder.md @@ -47,6 +47,7 @@ console.log(decoder.end(Buffer.from([0xAC]))); ## Class: `StringDecoder` ### `new StringDecoder([encoding])` + @@ -57,6 +58,7 @@ added: v0.1.99 Creates a new `StringDecoder` instance. ### `stringDecoder.end([buffer])` + @@ -74,6 +76,7 @@ is performed before returning the remaining input. After `end()` is called, the `stringDecoder` object can be reused for new input. ### `stringDecoder.write(buffer)` + @@ -35,13 +36,14 @@ added: v11.0.0 If true, the `Immediate` object will keep the Node.js event loop active. ### `immediate.ref()` + * Returns: {Immediate} a reference to `immediate` -When called, requests that the Node.js event loop *not* exit so long as the +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 effect. @@ -49,6 +51,7 @@ By default, all `Immediate` objects are "ref'ed", making it normally unnecessary to call `immediate.ref()` unless `immediate.unref()` had been called previously. ### `immediate.unref()` + @@ -73,6 +76,7 @@ export both `timeout.ref()` and `timeout.unref()` functions that can be used to control this default behavior. ### `timeout.close()` + @@ -84,6 +88,7 @@ added: v0.9.1 Cancels the timeout. ### `timeout.hasRef()` + @@ -93,19 +98,21 @@ added: v11.0.0 If true, the `Timeout` object will keep the Node.js event loop active. ### `timeout.ref()` + * Returns: {Timeout} a reference to `timeout` -When called, requests that the Node.js event loop *not* exit so long as the +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. By default, all `Timeout` objects are "ref'ed", making it normally unnecessary to call `timeout.ref()` unless `timeout.unref()` had been called previously. ### `timeout.refresh()` + @@ -121,6 +128,7 @@ Using this on a timer that has already called its callback will reactivate the timer. ### `timeout.unref()` + @@ -137,6 +145,7 @@ event loop. Creating too many of these can adversely impact performance of the Node.js application. ### `timeout[Symbol.toPrimitive]()` + @@ -184,6 +194,7 @@ This method has a custom variant for promises that is available using [`timersPromises.setImmediate()`][]. ### `setInterval(callback[, delay[, ...args]])` + @@ -205,6 +216,7 @@ This method has a custom variant for promises that is available using [`timersPromises.setInterval()`][]. ### `setTimeout(callback[, delay[, ...args]])` + @@ -277,6 +289,7 @@ ac.abort(); ``` ### `clearImmediate(immediate)` + @@ -287,6 +300,7 @@ added: v0.9.1 Cancels an `Immediate` object created by [`setImmediate()`][]. ### `clearInterval(timeout)` + @@ -297,6 +311,7 @@ added: v0.0.1 Cancels a `Timeout` object created by [`setInterval()`][]. ### `clearTimeout(timeout)` + @@ -307,6 +322,7 @@ added: v0.0.1 Cancels a `Timeout` object created by [`setTimeout()`][]. ## Timers Promises API + @@ -371,6 +388,7 @@ setTimeout(100, 'result').then((res) => { ``` ### `timersPromises.setImmediate([value[, options]])` + @@ -404,6 +422,7 @@ setImmediate('result').then((res) => { ``` ### `timersPromises.setInterval([delay[, value[, options]]])` + @@ -411,7 +430,7 @@ added: v15.9.0 Returns an async iterator that generates values in an interval of `delay` ms. * `delay` {number} The number of milliseconds to wait between iterations. - **Default:** `1`. + **Default:** `1`. * `value` {any} A value with which the iterator returns. * `options` {Object} * `ref` {boolean} Set to `false` to indicate that the scheduled `Timeout` diff --git a/doc/api/tls.md b/doc/api/tls.md index 6926b7cda0c66b..ac582be4dd761d 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -17,7 +17,7 @@ const tls = require('tls'); ## TLS/SSL concepts The TLS/SSL is a public/private key infrastructure (PKI). For most common -cases, each client and server must have a *private key*. +cases, each client and server must have a _private key_. Private keys can be generated in multiple ways. The example below illustrates use of the OpenSSL command-line interface to generate a 2048-bit RSA private @@ -27,11 +27,11 @@ key: openssl genrsa -out ryans-key.pem 2048 ``` -With TLS/SSL, all servers (and some clients) must have a *certificate*. -Certificates are *public keys* that correspond to a private key, and that are +With TLS/SSL, all servers (and some clients) must have a _certificate_. +Certificates are _public keys_ that correspond to a private key, and that are digitally signed either by a Certificate Authority or by the owner of the private key (such certificates are referred to as "self-signed"). The first -step to obtaining a certificate is to create a *Certificate Signing Request* +step to obtaining a certificate is to create a _Certificate Signing Request_ (CSR) file. The OpenSSL command-line interface can be used to generate a CSR for a private @@ -64,7 +64,7 @@ Where: * `in`: is the signed certificate * `inkey`: is the associated private key * `certfile`: is a concatenation of all Certificate Authority (CA) certs into - a single file, e.g. `cat ca1-cert.pem ca2-cert.pem > ca-cert.pem` + a single file, e.g. `cat ca1-cert.pem ca2-cert.pem > ca-cert.pem` ### Perfect forward secrecy @@ -190,7 +190,7 @@ send it to the client. Clients and servers save the session state. When reconnecting, clients send the ID of their saved session state and if the server also has the state for that ID, it can agree to use it. Otherwise, the server will create a new session. See [RFC 2246][] for more information, page 23 and -30. +30\. Resumption using session identifiers is supported by most web browsers when making HTTPS requests. @@ -237,8 +237,8 @@ securely generate 48 bytes of secure random data and set them with the regenerated and server's keys can be reset with [`server.setTicketKeys()`][]. -Session ticket keys are cryptographic keys, and they ***must be stored -securely***. With TLS 1.2 and below, if they are compromised all sessions that +Session ticket keys are cryptographic keys, and they _**must be stored +securely**_. With TLS 1.2 and below, if they are compromised all sessions that used tickets encrypted with them can be decrypted. They should not be stored on disk, and they should be regenerated regularly. @@ -280,6 +280,7 @@ default cipher list can be configured when building Node.js to allow distributions to provide their own default list. The following command can be used to show the default cipher suite: + ```console node -p crypto.constants.defaultCoreCipherList | tr ':' '\n' TLS_AES_256_GCM_SHA384 @@ -329,7 +330,7 @@ The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones that start with `'TLS_'`, and specifications for TLSv1.2 and below cipher suites. The TLSv1.2 ciphers support a legacy specification format, consult the OpenSSL [cipher list format][] documentation for details, but those -specifications do *not* apply to TLSv1.3 ciphers. The TLSv1.3 suites can only +specifications do _not_ apply to TLSv1.3 ciphers. The TLSv1.3 suites can only be enabled by including their full name in the cipher list. They cannot, for example, be enabled or disabled by using the legacy TLSv1.2 `'EECDH'` or `'!EECDH'` specification. @@ -347,7 +348,7 @@ used only if absolutely necessary. The default cipher suite prefers GCM ciphers for [Chrome's 'modern cryptography' setting][] and also prefers ECDHE and DHE ciphers for perfect -forward secrecy, while offering *some* backward compatibility. +forward secrecy, while offering _some_ backward compatibility. 128 bit AES is preferred over 192 and 256 bit AES in light of [specific attacks affecting larger AES key sizes][]. @@ -380,6 +381,7 @@ has the property `code` which can take one of the following values: values are taken from src/crypto/crypto_common.cc description are taken from deps/openssl/openssl/crypto/x509/x509_txt.c --> + * `'UNABLE_TO_GET_ISSUER_CERT'`: Unable to get issuer certificate. * `'UNABLE_TO_GET_CRL'`: Unable to get certificate CRL. * `'UNABLE_TO_DECRYPT_CERT_SIGNATURE'`: Unable to decrypt certificate's @@ -413,6 +415,7 @@ description are taken from deps/openssl/openssl/crypto/x509/x509_txt.c * `'HOSTNAME_MISMATCH'`: Hostname mismatch. ## Class: `tls.CryptoStream` + The `cryptoStream.bytesWritten` property returns the total number of bytes -written to the underlying socket *including* the bytes required for the +written to the underlying socket _including_ the bytes required for the implementation of the TLS protocol. ## Class: `tls.SecurePair` + @@ -467,6 +474,7 @@ added: v0.3.2 Accepts encrypted connections using TLS or SSL. ### Event: `'connection'` + @@ -481,6 +489,7 @@ This event can also be explicitly emitted by users to inject connections into the TLS server. In that case, any [`Duplex`][] stream can be passed. ### Event: `'keylog'` + @@ -581,6 +592,7 @@ after the addition of the event listener. An npm module like [asn1.js][] may be used to parse the certificates. ### Event: `'resumeSession'` + @@ -620,6 +632,7 @@ server.on('resumeSession', (id, cb) => { ``` ### Event: `'secureConnection'` + @@ -644,6 +657,7 @@ The `tlsSocket.servername` property is a string containing the server name requested via SNI. ### Event: `'tlsClientError'` + @@ -657,6 +671,7 @@ called: error originated. ### `server.addContext(hostname, context)` + @@ -673,6 +688,7 @@ When there are multiple matching contexts, the most recently added one is used. ### `server.address()` + @@ -684,6 +700,7 @@ server as reported by the operating system. See [`net.Server.address()`][] for more information. ### `server.close([callback])` + @@ -698,6 +715,7 @@ This function operates asynchronously. The `'close'` event will be emitted when the server has no more open connections. ### `server.getTicketKeys()` + @@ -714,6 +732,7 @@ Starts the server listening for encrypted connections. This method is identical to [`server.listen()`][] from [`net.Server`][]. ### `server.setSecureContext(options)` + @@ -726,6 +745,7 @@ The `server.setSecureContext()` method replaces the secure context of an existing server. Existing connections to the server are not interrupted. ### `server.setTicketKeys(keys)` + @@ -741,6 +761,7 @@ Existing or currently pending server connections will use the previous keys. See [Session Resumption][] for more information. ## Class: `tls.TLSSocket` + @@ -757,6 +778,7 @@ Methods that return TLS connection metadata (e.g. connection is open. ### `new tls.TLSSocket(socket[, options])` + @@ -836,6 +860,7 @@ Typically, the `response` is a digitally signed object from the server's CA that contains information about server's certificate revocation status. ### Event: `'secureConnect'` + @@ -854,6 +879,7 @@ The `'secureConnect'` event is not emitted when a {tls.TLSSocket} is created using the `new tls.TLSSocket()` constructor. ### Event: `'session'` + @@ -893,6 +919,7 @@ tlsSocket.once('session', (session) => { ``` ### `tlsSocket.address()` + @@ -904,6 +931,7 @@ underlying socket as reported by the operating system: `{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. ### `tlsSocket.authorizationError` + @@ -912,6 +940,7 @@ Returns the reason why the peer's certificate was not been verified. This property is set only when `tlsSocket.authorized === false`. ### `tlsSocket.authorized` + @@ -922,6 +951,7 @@ Returns `true` if the peer certificate was signed by one of the CAs specified when creating the `tls.TLSSocket` instance, otherwise `false`. ### `tlsSocket.disableRenegotiation()` + @@ -930,6 +960,7 @@ Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts to renegotiate will trigger an `'error'` event on the `TLSSocket`. ### `tlsSocket.enableTrace()` + @@ -937,12 +968,13 @@ added: v12.2.0 When enabled, TLS packet trace information is written to `stderr`. This can be used to debug TLS connection problems. -Note: The format of the output is identical to the output of `openssl s_client --trace` or `openssl s_server -trace`. While it is produced by OpenSSL's -`SSL_trace()` function, the format is undocumented, can change without notice, -and should not be relied on. +The format of the output is identical to the output of +`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by +OpenSSL's `SSL_trace()` function, the format is undocumented, can change +without notice, and should not be relied on. ### `tlsSocket.encrypted` + @@ -951,6 +983,7 @@ Always returns `true`. This may be used to distinguish TLS sockets from regular `net.Socket` instances. ### `tlsSocket.exportKeyingMaterial(length, label[, context])` + * `length` {number} number of bytes to retrieve from keying material + * `label` {string} an application specific label, typically this will be a value from the [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * `context` {Buffer} Optionally provide a context. * Returns: {Buffer} requested bytes of the keying material @@ -982,10 +1017,12 @@ const keyingMaterial = tlsSocket.exportKeyingMaterial( 74 ef 2c ... 78 more bytes> */ ``` + See the OpenSSL [`SSL_export_keying_material`][] documentation for more information. ### `tlsSocket.getCertificate()` + @@ -1002,6 +1039,7 @@ If there is no local certificate, an empty object will be returned. If the socket has been destroyed, `null` will be returned. ### `tlsSocket.getCipher()` + @@ -1054,6 +1094,7 @@ if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. ### `tlsSocket.getFinished()` + @@ -1071,6 +1112,7 @@ Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used to implement the `tls-unique` channel binding from [RFC 5929][]. ### `tlsSocket.getPeerCertificate([detailed])` + @@ -1088,6 +1130,7 @@ If the full certificate chain was requested, each certificate will include an certificate. #### Certificate object + + ```js { subject: { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ], @@ -1178,6 +1222,7 @@ Example certificate: ``` ### `tlsSocket.getPeerFinished()` + @@ -1195,6 +1240,7 @@ Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used to implement the `tls-unique` channel binding from [RFC 5929][]. ### `tlsSocket.getPeerX509Certificate()` + @@ -1207,6 +1253,7 @@ If there is no peer certificate, or the socket has been destroyed, `undefined` will be returned. ### `tlsSocket.getProtocol()` + @@ -1229,6 +1276,7 @@ Protocol versions are: See the OpenSSL [`SSL_get_version`][] documentation for more information. ### `tlsSocket.getSession()` + @@ -1246,6 +1294,7 @@ Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications must use the [`'session'`][] event (it also works for TLSv1.2 and below). ### `tlsSocket.getSharedSigalgs()` + @@ -1254,10 +1303,11 @@ added: v12.11.0 the client in the order of decreasing preference. See -[SSL_get_shared_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) +[SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL\_get\_shared\_sigalgs.html) for more information. ### `tlsSocket.getTLSTicket()` + @@ -1272,6 +1322,7 @@ It may be useful for debugging. See [Session Resumption][] for more information. ### `tlsSocket.getX509Certificate()` + @@ -1284,6 +1335,7 @@ If there is no local certificate, or the socket has been destroyed, `undefined` will be returned. ### `tlsSocket.isSessionReused()` + @@ -1293,6 +1345,7 @@ added: v0.5.6 See [Session Resumption][] for more information. ### `tlsSocket.localAddress` + @@ -1302,6 +1355,7 @@ added: v0.11.4 Returns the string representation of the local IP address. ### `tlsSocket.localPort` + @@ -1311,6 +1365,7 @@ added: v0.11.4 Returns the numeric representation of the local port. ### `tlsSocket.remoteAddress` + @@ -1321,6 +1376,7 @@ Returns the string representation of the remote IP address. For example, `'74.125.127.100'` or `'2001:4860:a005::68'`. ### `tlsSocket.remoteFamily` + @@ -1330,6 +1386,7 @@ added: v0.11.4 Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`. ### `tlsSocket.remotePort` + @@ -1339,6 +1396,7 @@ added: v0.11.4 Returns the numeric representation of the remote port. For example, `443`. ### `tlsSocket.renegotiate(options, callback)` + @@ -1349,11 +1407,12 @@ added: v0.11.8 verification fails; `err.code` contains the OpenSSL error code. **Default:** `true`. * `requestCert` + * `callback` {Function} If `renegotiate()` returned `true`, callback is - attached once to the `'secure'` event. If `renegotiate()` returned `false`, - `callback` will be called in the next tick with an error, unless the - `tlsSocket` has been destroyed, in which case `callback` will not be called - at all. + attached once to the `'secure'` event. If `renegotiate()` returned `false`, + `callback` will be called in the next tick with an error, unless the + `tlsSocket` has been destroyed, in which case `callback` will not be called + at all. * Returns: {boolean} `true` if renegotiation was initiated, `false` otherwise. @@ -1371,6 +1430,7 @@ For TLSv1.3, renegotiation cannot be initiated, it is not supported by the protocol. ### `tlsSocket.setMaxSendFragment(size)` + @@ -1390,6 +1450,7 @@ smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput. ## `tls.checkServerIdentity(hostname, cert)` + @@ -1413,6 +1474,7 @@ This function is only called if the certificate passed all other checks, such as being issued by trusted CA (`options.ca`). ## `tls.connect(options[, callback])` + @@ -1605,6 +1669,7 @@ as an argument instead of an option. A path option, if specified, will take precedence over the path argument. ## `tls.connect(port[, host][, options][, callback])` + @@ -1622,6 +1687,7 @@ A port or host option, if specified, will take precedence over any port or host argument. ## `tls.createSecureContext([options])` + * `options` {Object} - * `ca` {string|string[]|Buffer|Buffer[]} Optionally override the trusted CA + * `ca` {string|string\[]|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 @@ -1686,20 +1752,20 @@ changes: For PEM encoded certificates, supported types are "TRUSTED CERTIFICATE", "X509 CERTIFICATE", and "CERTIFICATE". See also [`tls.rootCertificates`][]. - * `cert` {string|string[]|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, and not - including the root CA (the root CA must be pre-known to the peer, see `ca`). - When providing multiple cert chains, they do not have to be in the same - order as their private keys in `key`. If the intermediate certificates are - not provided, the peer will not be able to validate the certificate, and the - handshake will fail. + * `cert` {string|string\[]|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, + and not including the root CA (the root CA must be pre-known to the peer, + see `ca`). When providing multiple cert chains, they do not have to be in + the same order as their private keys in `key`. If the intermediate + certificates are not provided, the peer will not be able to validate the + certificate, and the handshake will fail. * `sigalgs` {string} Colon-separated list of supported signature algorithms. The list can contain digest algorithms (`SHA256`, `MD5` etc.), public key algorithms (`RSA-PSS`, `ECDSA` etc.), combination of both (e.g 'RSA+SHA384') or TLS v1.3 scheme names (e.g. `rsa_pss_pss_sha512`). - See [OpenSSL man pages](https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set1_sigalgs_list.html) + See [OpenSSL man pages](https://www.openssl.org/docs/man1.1.1/man3/SSL\_CTX\_set1\_sigalgs\_list.html) for more info. * `ciphers` {string} Cipher suite specification, replacing the default. For more information, see [modifying the default cipher suite][]. Permitted @@ -1707,7 +1773,7 @@ changes: uppercased in order for OpenSSL to accept them. * `clientCertEngine` {string} Name of an OpenSSL engine which can provide the client certificate. - * `crl` {string|string[]|Buffer|Buffer[]} PEM formatted CRLs (Certificate + * `crl` {string|string\[]|Buffer|Buffer\[]} PEM formatted CRLs (Certificate Revocation Lists). * `dhparam` {string|Buffer} Diffie-Hellman parameters, required for [perfect forward secrecy][]. Use `openssl dhparam` to create the parameters. @@ -1726,11 +1792,11 @@ changes: 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|string[]|Buffer|Buffer[]|Object[]} 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 strings or - buffers, or an array of objects in the form + * `key` {string|string\[]|Buffer|Buffer\[]|Object\[]} 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 + strings or buffers, or an array of objects in the form `{pem: [, passphrase: ]}`. The object form can only occur in an array. `object.passphrase` is optional. Encrypted keys will be decrypted with `object.passphrase` if provided, or `options.passphrase` if @@ -1753,7 +1819,7 @@ changes: **Default:** [`tls.DEFAULT_MIN_VERSION`][]. * `passphrase` {string} Shared passphrase used for a single private key and/or a PFX. - * `pfx` {string|string[]|Buffer|Buffer[]|Object[]} PFX or PKCS12 encoded + * `pfx` {string|string\[]|Buffer|Buffer\[]|Object\[]} 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 @@ -1770,9 +1836,9 @@ changes: version to use, it does not support independent control of the minimum and maximum version, and does not support limiting the protocol to TLSv1.3. Use `minVersion` and `maxVersion` instead. The possible values are listed as - [SSL_METHODS][], use the function names as strings. For example, use - `'TLSv1_1_method'` to force TLS version 1.1, or `'TLS_method'` to allow any - TLS protocol version up to TLSv1.3. It is not recommended to use TLS + [SSL\_METHODS][SSL_METHODS], use the function names as strings. For example, + use `'TLSv1_1_method'` to force TLS version 1.1, or `'TLS_method'` to allow + any TLS protocol version up to TLSv1.3. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability. **Default:** none, see `minVersion`. * `sessionIdContext` {string} Opaque identifier used by servers to ensure @@ -1794,13 +1860,14 @@ 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. -A key is *required* for ciphers that use certificates. Either `key` or +A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of CAs][]. ## `tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])` + * `options` {Object} - * `ALPNProtocols`: {string[]|Buffer[]|TypedArray[]|DataView[]|Buffer| + * `ALPNProtocols`: {string\[]|Buffer\[]|TypedArray\[]|DataView\[]|Buffer| TypedArray|DataView} An array of strings, `Buffer`s or `TypedArray`s or `DataView`s, or a single `Buffer` or `TypedArray` or `DataView` containing the supported ALPN @@ -1923,6 +1991,7 @@ changes: * `ticketKeys`: {Buffer} 48-bytes of cryptographically strong pseudorandom data. See [Session Resumption][] for more information. * `pskCallback` {Function} + * socket: {tls.TLSSocket} the server [`tls.TLSSocket`][] instance for this connection. * identity: {string} identity parameter sent from the client. @@ -1933,10 +2002,10 @@ changes: When negotiating TLS-PSK (pre-shared keys), this function is called with the identity provided by the client. If the return value is `null` the negotiation process will stop and an - "unknown_psk_identity" alert message will be sent to the other party. + "unknown\_psk\_identity" alert message will be sent to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data as `psk` to make the connection - fail with "decrypt_error" before negotiation is finished. + fail with "decrypt\_error" before negotiation is finished. PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with the `ciphers` option. More information can be found in the [RFC 4279][]. @@ -1990,11 +2059,12 @@ The server can be tested by connecting to it using the example client from [`tls.connect()`][]. ## `tls.getCiphers()` + -* Returns: {string[]} +* Returns: {string\[]} Returns an array with the names of the supported TLS ciphers. The names are lower-case for historical reasons, but must be uppercased to be used in @@ -2008,11 +2078,12 @@ console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] ``` ## `tls.rootCertificates` + -* {string[]} +* {string\[]} An immutable array of strings representing the root certificates (in PEM format) from the bundled Mozilla CA store as supplied by current Node.js version. @@ -2021,6 +2092,7 @@ The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store that is fixed at release time. It is identical on all supported platforms. ## `tls.DEFAULT_ECDH_CURVE` + @@ -2047,6 +2120,7 @@ added: v11.4.0 highest maximum is used. ## `tls.DEFAULT_MIN_VERSION` + diff --git a/doc/api/tracing.md b/doc/api/tracing.md index 4b7a9bd8ff1913..d0b5ac4250e978 100644 --- a/doc/api/tracing.md +++ b/doc/api/tracing.md @@ -44,7 +44,7 @@ node --trace-event-categories v8,node,node.async_hooks server.js Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the -`--trace-events-enabled` flag *may* still be used and will enable the +`--trace-events-enabled` flag _may_ still be used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. ```bash @@ -88,11 +88,13 @@ unlike `process.hrtime()` which returns nanoseconds. The features from this module are not available in [`Worker`][] threads. ## The `trace_events` module + ### `Tracing` object + @@ -107,6 +109,7 @@ categories. Calling `tracing.disable()` will remove the categories from the set of enabled trace event categories. #### `tracing.categories` + @@ -117,14 +120,15 @@ A comma-separated list of the trace event categories covered by this `Tracing` object. #### `tracing.disable()` + Disables this `Tracing` object. -Only trace event categories *not* covered by other enabled `Tracing` objects -and *not* specified by the `--trace-event-categories` flag will be disabled. +Only trace event categories _not_ covered by other enabled `Tracing` objects +and _not_ specified by the `--trace-event-categories` flag will be disabled. ```js const trace_events = require('trace_events'); @@ -143,6 +147,7 @@ console.log(trace_events.getEnabledCategories()); ``` #### `tracing.enable()` + @@ -151,6 +156,7 @@ Enables this `Tracing` object for the set of categories covered by the `Tracing` object. #### `tracing.enabled` + @@ -158,12 +164,13 @@ added: v10.0.0 * {boolean} `true` only if the `Tracing` object has been enabled. ### `trace_events.createTracing(options)` + * `options` {Object} - * `categories` {string[]} An array of trace category names. Values included + * `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}. @@ -180,6 +187,7 @@ tracing.disable(); ``` ### `trace_events.getEnabledCategories()` + @@ -188,7 +196,7 @@ added: v10.0.0 Returns a comma-separated list of all currently-enabled trace event categories. The current set of enabled trace event categories is determined -by the *union* of all currently-enabled `Tracing` objects and any categories +by the _union_ of all currently-enabled `Tracing` objects and any categories enabled using the `--trace-event-categories` flag. Given the file `test.js` below, the command diff --git a/doc/api/tty.md b/doc/api/tty.md index 10eb874e561f8b..ea0640274f7e41 100644 --- a/doc/api/tty.md +++ b/doc/api/tty.md @@ -33,6 +33,7 @@ manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. ## Class: `tty.ReadStream` + @@ -44,6 +45,7 @@ Represents the readable side of a TTY. In normal circumstances process and there should be no reason to create additional instances. ### `readStream.isRaw` + @@ -52,6 +54,7 @@ A `boolean` that is `true` if the TTY is currently configured to operate as a raw device. Defaults to `false`. ### `readStream.isTTY` + @@ -59,6 +62,7 @@ added: v0.5.8 A `boolean` that is always `true` for `tty.ReadStream` instances. ### `readStream.setRawMode(mode)` + @@ -73,10 +77,12 @@ Allows configuration of `tty.ReadStream` so that it operates as a raw device. When in raw mode, input is always available character-by-character, not including modifiers. Additionally, all special processing of characters by the -terminal is disabled, including echoing input characters. -Ctrl+C will no longer cause a `SIGINT` when in this mode. +terminal is disabled, including echoing input +characters. Ctrl+C will no longer cause a `SIGINT` when +in this mode. ## Class: `tty.WriteStream` + @@ -89,6 +95,7 @@ Represents the writable side of a TTY. In normal circumstances, should be no reason to create additional instances. ### Event: `'resize'` + @@ -105,6 +112,7 @@ process.stdout.on('resize', () => { ``` ### `writeStream.clearLine(dir[, callback])` + @@ -151,6 +161,7 @@ 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])` + @@ -204,11 +216,12 @@ Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. ### `writeStream.getWindowSize()` + -* Returns: {number[]} +* Returns: {number\[]} `writeStream.getWindowSize()` returns the size of the TTY corresponding to this `WriteStream`. The array is of the type @@ -216,6 +229,7 @@ corresponding to this `WriteStream`. The array is of the type of columns and rows in the corresponding TTY. ### `writeStream.hasColors([count][, env])` + @@ -254,6 +269,7 @@ added: v0.5.8 A `boolean` that is always `true`. ### `writeStream.moveCursor(dx, dy[, callback])` + @@ -281,6 +298,7 @@ A `number` specifying the number of rows the TTY currently has. This property is updated whenever the `'resize'` event is emitted. ## `tty.isatty(fd)` + diff --git a/doc/api/url.md b/doc/api/url.md index e42ccdd5f5ea1a..a7f68bfb564fd8 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -105,6 +105,7 @@ console.log(myURL.href); ## The WHATWG URL API ### Class: `URL` + @@ -644,6 +649,7 @@ Threads, `Blob` objects registered within one Worker will not be available to other workers or the main thread. #### `URL.revokeObjectURL(id)` + @@ -656,6 +662,7 @@ added: v16.7.0 Removes the stored {Blob} identified by the given ID. ### Class: `URLSearchParams` + @@ -1099,6 +1112,7 @@ fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) ``` ### `url.format(URL[, options])` + @@ -1153,6 +1167,7 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); ``` ### `url.pathToFileURL(path)` + @@ -1188,6 +1203,7 @@ pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSI ``` ### `url.urlToHttpOptions(url)` + @@ -1251,6 +1267,7 @@ console.log(urlToHttpOptions(myUrl)); ``` ## Legacy URL API + @@ -71,6 +72,7 @@ callbackFunction((err, ret) => { ``` ## `util.debuglog(section[, callback])` + @@ -137,6 +139,7 @@ let debuglog = util.debuglog('internals', (debug) => { ``` ### `debuglog().enabled` + @@ -165,6 +168,7 @@ hello from foo [123] ``` ## `util.debug(section)` + @@ -173,6 +177,7 @@ 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])` + @@ -358,6 +365,7 @@ util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); ``` ## `util.getSystemErrorName(err)` + @@ -377,6 +385,7 @@ fs.access('file/that/does/not/exist', (err) => { ``` ## `util.getSystemErrorMap()` + @@ -396,6 +405,7 @@ fs.access('file/that/does/not/exist', (err) => { ``` ## `util.inherits(constructor, superConstructor)` + @@ -951,6 +965,7 @@ console.log(arr); // logs the full array ``` ## `util.isDeepStrictEqual(val1, val2)` + @@ -966,6 +981,7 @@ See [`assert.deepStrictEqual()`][] for more information about deep strict equality. ## `util.promisify(original)` + @@ -1079,6 +1095,7 @@ If `promisify.custom` is defined but is not a function, `promisify()` will throw an error. ### `util.promisify.custom` + @@ -1125,6 +1143,7 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); ``` ## Class: `util.TextDecoder` + @@ -1152,47 +1171,47 @@ Different Node.js build configurations support different sets of encodings. #### Encodings supported by default (with full ICU data) -| Encoding | Aliases | -| ----------------- | -------------------------------- | -| `'ibm866'` | `'866'`, `'cp866'`, `'csibm866'` | -| `'iso-8859-2'` | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'` | -| `'iso-8859-3'` | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'` | -| `'iso-8859-4'` | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'` | -| `'iso-8859-5'` | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'` | -| `'iso-8859-6'` | `'arabic'`, `'asmo-708'`, `'csiso88596e'`, `'csiso88596i'`, `'csisolatinarabic'`, `'ecma-114'`, `'iso-8859-6-e'`, `'iso-8859-6-i'`, `'iso-ir-127'`, `'iso8859-6'`, `'iso88596'`, `'iso_8859-6'`, `'iso_8859-6:1987'` | -| `'iso-8859-7'` | `'csisolatingreek'`, `'ecma-118'`, `'elot_928'`, `'greek'`, `'greek8'`, `'iso-ir-126'`, `'iso8859-7'`, `'iso88597'`, `'iso_8859-7'`, `'iso_8859-7:1987'`, `'sun_eu_greek'` | -| `'iso-8859-8'` | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'` | -| `'iso-8859-8-i'` | `'csiso88598i'`, `'logical'` | -| `'iso-8859-10'` | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'` | -| `'iso-8859-13'` | `'iso8859-13'`, `'iso885913'` | -| `'iso-8859-14'` | `'iso8859-14'`, `'iso885914'` | -| `'iso-8859-15'` | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'` | -| `'koi8-r'` | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'` | -| `'koi8-u'` | `'koi8-ru'` | -| `'macintosh'` | `'csmacintosh'`, `'mac'`, `'x-mac-roman'` | -| `'windows-874'` | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'` | -| `'windows-1250'` | `'cp1250'`, `'x-cp1250'` | -| `'windows-1251'` | `'cp1251'`, `'x-cp1251'` | +| Encoding | Aliases | +| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `'ibm866'` | `'866'`, `'cp866'`, `'csibm866'` | +| `'iso-8859-2'` | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'` | +| `'iso-8859-3'` | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'` | +| `'iso-8859-4'` | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'` | +| `'iso-8859-5'` | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'` | +| `'iso-8859-6'` | `'arabic'`, `'asmo-708'`, `'csiso88596e'`, `'csiso88596i'`, `'csisolatinarabic'`, `'ecma-114'`, `'iso-8859-6-e'`, `'iso-8859-6-i'`, `'iso-ir-127'`, `'iso8859-6'`, `'iso88596'`, `'iso_8859-6'`, `'iso_8859-6:1987'` | +| `'iso-8859-7'` | `'csisolatingreek'`, `'ecma-118'`, `'elot_928'`, `'greek'`, `'greek8'`, `'iso-ir-126'`, `'iso8859-7'`, `'iso88597'`, `'iso_8859-7'`, `'iso_8859-7:1987'`, `'sun_eu_greek'` | +| `'iso-8859-8'` | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'` | +| `'iso-8859-8-i'` | `'csiso88598i'`, `'logical'` | +| `'iso-8859-10'` | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'` | +| `'iso-8859-13'` | `'iso8859-13'`, `'iso885913'` | +| `'iso-8859-14'` | `'iso8859-14'`, `'iso885914'` | +| `'iso-8859-15'` | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'` | +| `'koi8-r'` | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'` | +| `'koi8-u'` | `'koi8-ru'` | +| `'macintosh'` | `'csmacintosh'`, `'mac'`, `'x-mac-roman'` | +| `'windows-874'` | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'` | +| `'windows-1250'` | `'cp1250'`, `'x-cp1250'` | +| `'windows-1251'` | `'cp1251'`, `'x-cp1251'` | | `'windows-1252'` | `'ansi_x3.4-1968'`, `'ascii'`, `'cp1252'`, `'cp819'`, `'csisolatin1'`, `'ibm819'`, `'iso-8859-1'`, `'iso-ir-100'`, `'iso8859-1'`, `'iso88591'`, `'iso_8859-1'`, `'iso_8859-1:1987'`, `'l1'`, `'latin1'`, `'us-ascii'`, `'x-cp1252'` | -| `'windows-1253'` | `'cp1253'`, `'x-cp1253'` | -| `'windows-1254'` | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'` | -| `'windows-1255'` | `'cp1255'`, `'x-cp1255'` | -| `'windows-1256'` | `'cp1256'`, `'x-cp1256'` | -| `'windows-1257'` | `'cp1257'`, `'x-cp1257'` | -| `'windows-1258'` | `'cp1258'`, `'x-cp1258'` | -| `'x-mac-cyrillic'` | `'x-mac-ukrainian'` | -| `'gbk'` | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'` | -| `'gb18030'` | | -| `'big5'` | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'` | -| `'euc-jp'` | `'cseucpkdfmtjapanese'`, `'x-euc-jp'` | -| `'iso-2022-jp'` | `'csiso2022jp'` | -| `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` | -| `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` | +| `'windows-1253'` | `'cp1253'`, `'x-cp1253'` | +| `'windows-1254'` | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'` | +| `'windows-1255'` | `'cp1255'`, `'x-cp1255'` | +| `'windows-1256'` | `'cp1256'`, `'x-cp1256'` | +| `'windows-1257'` | `'cp1257'`, `'x-cp1257'` | +| `'windows-1258'` | `'cp1258'`, `'x-cp1258'` | +| `'x-mac-cyrillic'` | `'x-mac-ukrainian'` | +| `'gbk'` | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'` | +| `'gb18030'` | | +| `'big5'` | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'` | +| `'euc-jp'` | `'cseucpkdfmtjapanese'`, `'x-euc-jp'` | +| `'iso-2022-jp'` | `'csiso2022jp'` | +| `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` | +| `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` | #### Encodings supported when Node.js is built with the `small-icu` option | Encoding | Aliases | -| ----------- | ------------------------------- | +| ------------ | ------------------------------- | | `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | | `'utf-16le'` | `'utf-16'` | | `'utf-16be'` | | @@ -1200,7 +1219,7 @@ Different Node.js build configurations support different sets of encodings. #### Encodings supported when ICU is disabled | Encoding | Aliases | -| ----------- | ------------------------------- | +| ------------ | ------------------------------- | | `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | | `'utf-16le'` | `'utf-16'` | @@ -1208,6 +1227,7 @@ The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] is not supported. ### `new TextDecoder([encoding[, options]])` + @@ -1331,6 +1353,7 @@ Returns the `string` after replacing any surrogate code points Unicode "replacement character" U+FFFD. ## `util.types` + @@ -1370,6 +1394,7 @@ util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true ``` ### `util.types.isArrayBufferView(value)` + @@ -1389,6 +1414,7 @@ util.types.isArrayBufferView(new ArrayBuffer()); // false ``` ### `util.types.isArgumentsObject(value)` + @@ -1399,6 +1425,7 @@ added: v10.0.0 Returns `true` if the value is an `arguments` object. + ```js function foo() { util.types.isArgumentsObject(arguments); // Returns true @@ -1406,6 +1433,7 @@ function foo() { ``` ### `util.types.isArrayBuffer(value)` + @@ -1414,7 +1442,7 @@ added: v10.0.0 * Returns: {boolean} Returns `true` if the value is a built-in [`ArrayBuffer`][] instance. -This does *not* include [`SharedArrayBuffer`][] instances. Usually, it is +This does _not_ include [`SharedArrayBuffer`][] instances. Usually, it is desirable to test for both; See [`util.types.isAnyArrayBuffer()`][] for that. ```js @@ -1423,6 +1451,7 @@ util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false ``` ### `util.types.isAsyncFunction(value)` + @@ -1441,6 +1470,7 @@ util.types.isAsyncFunction(async function foo() {}); // Returns true ``` ### `util.types.isBigInt64Array(value)` + @@ -1456,6 +1486,7 @@ util.types.isBigInt64Array(new BigUint64Array()); // Returns false ``` ### `util.types.isBigUint64Array(value)` + @@ -1471,6 +1502,7 @@ util.types.isBigUint64Array(new BigUint64Array()); // Returns true ``` ### `util.types.isBooleanObject(value)` + @@ -1491,6 +1523,7 @@ util.types.isBooleanObject(Boolean(true)); // Returns false ``` ### `util.types.isBoxedPrimitive(value)` + @@ -1512,6 +1545,7 @@ util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true ``` ### `util.types.isCryptoKey(value)` + @@ -1522,6 +1556,7 @@ added: v16.2.0 Returns `true` if `value` is a {CryptoKey}, `false` otherwise. ### `util.types.isDataView(value)` + @@ -1540,6 +1575,7 @@ util.types.isDataView(new Float64Array()); // Returns false See also [`ArrayBuffer.isView()`][]. ### `util.types.isDate(value)` + @@ -1554,6 +1590,7 @@ util.types.isDate(new Date()); // Returns true ``` ### `util.types.isExternal(value)` + @@ -1599,6 +1636,7 @@ For further information on `napi_create_external`, refer to [`napi_create_external()`][]. ### `util.types.isFloat32Array(value)` + @@ -1615,6 +1653,7 @@ util.types.isFloat32Array(new Float64Array()); // Returns false ``` ### `util.types.isFloat64Array(value)` + @@ -1631,6 +1670,7 @@ util.types.isFloat64Array(new Float64Array()); // Returns true ``` ### `util.types.isGeneratorFunction(value)` + @@ -1649,6 +1689,7 @@ util.types.isGeneratorFunction(function* foo() {}); // Returns true ``` ### `util.types.isGeneratorObject(value)` + @@ -1669,6 +1710,7 @@ util.types.isGeneratorObject(generator); // Returns true ``` ### `util.types.isInt8Array(value)` + @@ -1685,6 +1727,7 @@ util.types.isInt8Array(new Float64Array()); // Returns false ``` ### `util.types.isInt16Array(value)` + @@ -1701,6 +1744,7 @@ util.types.isInt16Array(new Float64Array()); // Returns false ``` ### `util.types.isInt32Array(value)` + @@ -1717,6 +1761,7 @@ util.types.isInt32Array(new Float64Array()); // Returns false ``` ### `util.types.isKeyObject(value)` + @@ -1727,6 +1772,7 @@ added: v16.2.0 Returns `true` if `value` is a {KeyObject}, `false` otherwise. ### `util.types.isMap(value)` + @@ -1741,6 +1787,7 @@ util.types.isMap(new Map()); // Returns true ``` ### `util.types.isMapIterator(value)` + @@ -1760,6 +1807,7 @@ util.types.isMapIterator(map[Symbol.iterator]()); // Returns true ``` ### `util.types.isModuleNamespaceObject(value)` + @@ -1770,6 +1818,7 @@ added: v10.0.0 Returns `true` if the value is an instance of a [Module Namespace Object][]. + ```js import * as ns from './a.js'; @@ -1777,6 +1826,7 @@ util.types.isModuleNamespaceObject(ns); // Returns true ``` ### `util.types.isNativeError(value)` + @@ -1793,6 +1843,7 @@ util.types.isNativeError(new RangeError()); // Returns true ``` ### `util.types.isNumberObject(value)` + @@ -1809,6 +1860,7 @@ util.types.isNumberObject(new Number(0)); // Returns true ``` ### `util.types.isPromise(value)` + @@ -1823,6 +1875,7 @@ util.types.isPromise(Promise.resolve(42)); // Returns true ``` ### `util.types.isProxy(value)` + @@ -1840,6 +1893,7 @@ util.types.isProxy(proxy); // Returns true ``` ### `util.types.isRegExp(value)` + @@ -1855,6 +1909,7 @@ util.types.isRegExp(new RegExp('abc')); // Returns true ``` ### `util.types.isSet(value)` + @@ -1869,6 +1924,7 @@ util.types.isSet(new Set()); // Returns true ``` ### `util.types.isSetIterator(value)` + @@ -1888,6 +1944,7 @@ util.types.isSetIterator(set[Symbol.iterator]()); // Returns true ``` ### `util.types.isSharedArrayBuffer(value)` + @@ -1896,7 +1953,7 @@ added: v10.0.0 * Returns: {boolean} Returns `true` if the value is a built-in [`SharedArrayBuffer`][] instance. -This does *not* include [`ArrayBuffer`][] instances. Usually, it is +This does _not_ include [`ArrayBuffer`][] instances. Usually, it is desirable to test for both; See [`util.types.isAnyArrayBuffer()`][] for that. ```js @@ -1905,6 +1962,7 @@ util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true ``` ### `util.types.isStringObject(value)` + @@ -1921,6 +1979,7 @@ util.types.isStringObject(new String('foo')); // Returns true ``` ### `util.types.isSymbolObject(value)` + @@ -1938,6 +1997,7 @@ util.types.isSymbolObject(Object(symbol)); // Returns true ``` ### `util.types.isTypedArray(value)` + @@ -1956,6 +2016,7 @@ util.types.isTypedArray(new Float64Array()); // Returns true See also [`ArrayBuffer.isView()`][]. ### `util.types.isUint8Array(value)` + @@ -1972,6 +2033,7 @@ util.types.isUint8Array(new Float64Array()); // Returns false ``` ### `util.types.isUint8ClampedArray(value)` + @@ -1988,6 +2050,7 @@ util.types.isUint8ClampedArray(new Float64Array()); // Returns false ``` ### `util.types.isUint16Array(value)` + @@ -2004,6 +2067,7 @@ util.types.isUint16Array(new Float64Array()); // Returns false ``` ### `util.types.isUint32Array(value)` + @@ -2020,6 +2084,7 @@ util.types.isUint32Array(new Float64Array()); // Returns false ``` ### `util.types.isWeakMap(value)` + @@ -2034,6 +2099,7 @@ util.types.isWeakMap(new WeakMap()); // Returns true ``` ### `util.types.isWeakSet(value)` + @@ -2048,6 +2114,7 @@ util.types.isWeakSet(new WeakSet()); // Returns true ``` ### `util.types.isWebAssemblyCompiledModule(value)` + @@ -33,6 +34,7 @@ console.log(v8.cachedDataVersionTag()); // 183726201 ``` ## `v8.getHeapCodeStatistics()` + @@ -46,6 +48,7 @@ Returns an object with the following properties: * `external_script_source_size` {number} + ```js { code_and_metadata_size: 212208, @@ -55,6 +58,7 @@ Returns an object with the following properties: ``` ## `v8.getHeapSnapshot()` + @@ -75,6 +79,7 @@ stream.pipe(process.stdout); ``` ## `v8.getHeapSpaceStatistics()` + -* Returns: {Object[]} +* Returns: {Object\[]} Returns statistics about the V8 heap spaces, i.e. the segments which make up the V8 heap. Neither the ordering of heap spaces, nor the availability of a @@ -140,6 +145,7 @@ The value returned is an array of objects containing the following properties: ``` ## `v8.getHeapStatistics()` + + ```js { total_heap_size: 7326976, @@ -200,6 +207,7 @@ being non-zero indicates a potential memory leak. ``` ## `v8.setFlagsFromString(flags)` + @@ -254,6 +262,7 @@ When the process is about to exit, one last coverage will still be written to disk unless [`v8.stopCoverage()`][] is invoked before the process exits. ## `v8.writeHeapSnapshot([filename])` + @@ -314,6 +323,7 @@ The format is backward-compatible (i.e. safe to store to disk). Equal JavaScript values may result in different serialized output. ### `v8.serialize(value)` + @@ -324,6 +334,7 @@ added: v8.0.0 Uses a [`DefaultSerializer`][] to serialize `value` into a buffer. ### `v8.deserialize(buffer)` + @@ -334,11 +345,13 @@ Uses a [`DefaultDeserializer`][] with default options to read a JS value from a buffer. ### Class: `v8.Serializer` + #### `new Serializer()` + Creates a new `Serializer` object. #### `serializer.writeHeader()` @@ -445,6 +458,7 @@ Indicate whether to treat `TypedArray` and `DataView` objects as host objects, i.e. pass them to [`serializer._writeHostObject()`][]. ### Class: `v8.Deserializer` + @@ -493,7 +507,7 @@ For use inside of a custom [`deserializer._readHostObject()`][]. #### `deserializer.readUint64()` -* Returns: {integer[]} +* Returns: {integer\[]} Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. @@ -526,6 +540,7 @@ This method is not present on the `Deserializer` class itself but can be provided by subclasses. ### Class: `v8.DefaultSerializer` + @@ -535,6 +550,7 @@ A subclass of [`Serializer`][] that serializes `TypedArray` stores the part of their underlying `ArrayBuffer`s that they are referring to. ### Class: `v8.DefaultDeserializer` + diff --git a/doc/api/vm.md b/doc/api/vm.md index a1451cdc059343..19ff922bcaf23d 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -43,6 +43,7 @@ console.log(x); // 1; y is not defined. ``` ## Class: `vm.Script` + @@ -51,6 +52,7 @@ Instances of the `vm.Script` class contain precompiled scripts that can be executed in specific contexts. ### `new vm.Script(code[, options])` + @@ -136,6 +139,7 @@ const cacheWithX = script.createCachedData(); ``` ### `script.runInContext(contextifiedObject[, options])` + @@ -560,6 +568,7 @@ The identifier of the current module, as set in the constructor. unsupported assertion is present. * `referencingModule` {vm.Module} The `Module` object `link()` is called on. + * Returns: {vm.Module|Promise} * Returns: {Promise} @@ -634,6 +643,7 @@ Other than `'errored'`, this status string corresponds to the specification's value that is not `undefined`. ## Class: `vm.SourceTextModule` + @@ -649,6 +659,7 @@ The `vm.SourceTextModule` class provides the [Source Text Module Record][] as defined in the ECMAScript specification. ### `new vm.SourceTextModule(code[, options])` + -* `exportNames` {string[]} Array of names that will be exported from the module. +* `exportNames` {string\[]} Array of names that will be exported from the + module. * `evaluateCallback` {Function} Called when the module is evaluated. * `options` * `identifier` {string} String used in stack traces. @@ -827,6 +842,7 @@ the module to access information outside the specified `context`. Use `vm.runInContext()` to create objects in a specific context. ### `syntheticModule.setExport(name, value)` + * `code` {string} The body of the function to compile. -* `params` {string[]} An array of strings containing all parameters for the +* `params` {string\[]} An array of strings containing all parameters for the function. * `options` {Object} * `filename` {string} Specifies the filename used in stack traces produced @@ -899,12 +916,12 @@ changes: is displayed in stack traces produced by this script. **Default:** `0`. * `cachedData` {Buffer|TypedArray|DataView} Provides an optional `Buffer` or `TypedArray`, or `DataView` with V8's code cache data for the supplied - source. + source. * `produceCachedData` {boolean} Specifies whether to produce new cache data. **Default:** `false`. * `parsingContext` {Object} The [contextified][] object in which the said function should be compiled in. - * `contextExtensions` {Object[]} An array containing a collection of context + * `contextExtensions` {Object\[]} An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling. **Default:** `[]`. * `importModuleDynamically` {Function} Called during evaluation of this module @@ -927,6 +944,7 @@ supplied, the current context is used), and returns it wrapped inside a function with the given `params`. ## `vm.createContext([contextObject[, options]])` + @@ -1089,6 +1108,7 @@ vm.measureMemory({ mode: 'detailed', execution: 'eager' }) ``` ## `vm.runInContext(code, contextifiedObject[, options])` + + ```js const vm = require('vm'); let localVar = 'initial value'; @@ -1364,7 +1387,7 @@ console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`); ``` Because `vm.runInThisContext()` does not have access to the local scope, -`localVar` is unchanged. In contrast, [`eval()`][] *does* have access to the +`localVar` is unchanged. In contrast, [`eval()`][] _does_ have access to the local scope, so the value `localVar` is changed. In this way `vm.runInThisContext()` is much like an [indirect `eval()` call][], e.g. `(0,eval)('code')`. diff --git a/doc/api/wasi.md b/doc/api/wasi.md index e0cd77a5a42c78..644daa217e900e 100644 --- a/doc/api/wasi.md +++ b/doc/api/wasi.md @@ -107,6 +107,7 @@ The `--experimental-wasi-unstable-preview1` CLI argument is needed for this example to run. ## Class: `WASI` + @@ -340,6 +341,7 @@ Calling `require('crypto').webcrypto` returns an instance of the `Crypto` class. `Crypto` is a singleton that provides access to the remainder of the crypto API. ### `crypto.subtle` + @@ -349,6 +351,7 @@ added: v15.0.0 Provides access to the `SubtleCrypto` API. ### `crypto.getRandomValues(typedArray)` + @@ -362,6 +365,7 @@ filled with random values, and a reference to `typedArray` is returned. An error will be thrown if the given `typedArray` is larger than 65,536 bytes. ### `crypto.randomUUID()` + @@ -372,17 +376,21 @@ Generates a random [RFC 4122][] version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator. ## Class: `CryptoKey` + ### `cryptoKey.algorithm` + + * Type: {AesKeyGenParams|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams} + An object detailing the algorithm for which the key can be used along with @@ -391,6 +399,7 @@ additional algorithm-specific parameters. Read-only. ### `cryptoKey.extractable` + @@ -403,6 +412,7 @@ When `true`, the {CryptoKey} can be extracted using either Read-only. ### `cryptoKey.type` + @@ -413,11 +423,12 @@ A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. ### `cryptoKey.usages` + -* Type: {string[]} +* Type: {string\[]} An array of strings identifying the operations for which the key may be used. @@ -436,29 +447,30 @@ The possible usages are: Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). -| Key Type | `'encrypt'` | `'decrypt'` | `'sign'` | `'verify'` | `'deriveKey'` | `'deriveBits'` | `'wrapKey'` | `'unwrapKey'` | -| -------------------- | ----------- | ----------- | -------- | ---------- | ------------- | --------------- | ----------- | ------------- | -| `'AES-CBC'` | ✔ | ✔ | | | | | ✔ | ✔ | -| `'AES-CTR'` | ✔ | ✔ | | | | | ✔ | ✔ | -| `'AES-GCM'` | ✔ | ✔ | | | | | ✔ | ✔ | -| `'AES-KW'` | | | | | | | ✔ | ✔ | -| `'ECDH'` | | | | | ✔ | ✔ | | | -| `'ECDSA'` | | | ✔ | ✔ | | | | | -| `'HDKF'` | | | | | ✔ | ✔ | | | -| `'HMAC'` | | | ✔ | ✔ | | | | | -| `'PBKDF2'` | | | | | ✔ | ✔ | | | -| `'RSA-OAEP'` | ✔ | ✔ | | | | | ✔ | ✔ | -| `'RSA-PSS'` | | | ✔ | ✔ | | | | | -| `'RSASSA-PKCS1-v1_5'` | | | ✔ | ✔ | | | | | -| `'NODE-DSA'` 1 | | | ✔ | ✔ | | | | | -| `'NODE-DH'` 1 | | | | | ✔ | ✔ | | | -| `'NODE-SCRYPT'` 1 | | | | | ✔ | ✔ | | | -| `'NODE-ED25519'` 1 | | | ✔ | ✔ | | | | | -| `'NODE-ED448'` 1 | | | ✔ | ✔ | | | | | +| Key Type | `'encrypt'` | `'decrypt'` | `'sign'` | `'verify'` | `'deriveKey'` | `'deriveBits'` | `'wrapKey'` | `'unwrapKey'` | +| ----------------------------- | ----------- | ----------- | -------- | ---------- | ------------- | -------------- | ----------- | ------------- | +| `'AES-CBC'` | ✔ | ✔ | | | | | ✔ | ✔ | +| `'AES-CTR'` | ✔ | ✔ | | | | | ✔ | ✔ | +| `'AES-GCM'` | ✔ | ✔ | | | | | ✔ | ✔ | +| `'AES-KW'` | | | | | | | ✔ | ✔ | +| `'ECDH'` | | | | | ✔ | ✔ | | | +| `'ECDSA'` | | | ✔ | ✔ | | | | | +| `'HDKF'` | | | | | ✔ | ✔ | | | +| `'HMAC'` | | | ✔ | ✔ | | | | | +| `'PBKDF2'` | | | | | ✔ | ✔ | | | +| `'RSA-OAEP'` | ✔ | ✔ | | | | | ✔ | ✔ | +| `'RSA-PSS'` | | | ✔ | ✔ | | | | | +| `'RSASSA-PKCS1-v1_5'` | | | ✔ | ✔ | | | | | +| `'NODE-DSA'` 1 | | | ✔ | ✔ | | | | | +| `'NODE-DH'` 1 | | | | | ✔ | ✔ | | | +| `'NODE-SCRYPT'` 1 | | | | | ✔ | ✔ | | | +| `'NODE-ED25519'` 1 | | | ✔ | ✔ | | | | | +| `'NODE-ED448'` 1 | | | ✔ | ✔ | | | | | 1 Node.js-specific extension. ## Class: `CryptoKeyPair` + @@ -467,6 +479,7 @@ The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. ### `cryptoKeyPair.privateKey` + @@ -474,6 +487,7 @@ added: v15.0.0 * Type: {CryptoKey} A {CryptoKey} whose `type` will be `'private'`. ### `cryptoKeyPair.publicKey` + @@ -481,11 +495,13 @@ added: v15.0.0 * Type: {CryptoKey} A {CryptoKey} whose `type` will be `'public'`. ## Class: `SubtleCrypto` + ### `subtle.decrypt(algorithm, key, data)` + @@ -508,15 +524,18 @@ The algorithms currently supported include: * `'AES-GCM`' ### `subtle.deriveBits(algorithm, baseKey, length)` + + * `algorithm`: {EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params|NodeDhDeriveBitsParams|NodeScryptParams} * `baseKey`: {CryptoKey} * `length`: {number} * Returns: {Promise} containing {ArrayBuffer} + Using the method and parameters specified in `algorithm` and the keying @@ -536,17 +555,20 @@ The algorithms currently supported include: 1 Node.js-specific extension ### `subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)` + + * `algorithm`: {EcdhKeyDeriveParams|HkdfParams|Pbkdf2Params|NodeDhDeriveBitsParams|NodeScryptParams} * `baseKey`: {CryptoKey} * `derivedKeyAlgorithm`: {HmacKeyGenParams|AesKeyGenParams} * `extractable`: {boolean} -* `keyUsages`: {string[]} See [Key usages][]. +* `keyUsages`: {string\[]} See [Key usages][]. * Returns: {Promise} containing {CryptoKey} + Using the method and parameters specified in `algorithm`, and the keying @@ -569,6 +591,7 @@ The algorithms currently supported include: 1 Node.js-specific extension ### `subtle.digest(algorithm, data)` + @@ -592,6 +615,7 @@ If `algorithm` is provided as an {Object}, it must have a `name` property whose value is one of the above. ### `subtle.encrypt(algorithm, key, data)` + @@ -613,6 +637,7 @@ The algorithms currently supported include: * `'AES-GCM`' ### `subtle.exportKey(format, key)` + + * `algorithm`: {RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|AesKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams|NodeEdKeyGenParams} + + * `extractable`: {boolean} -* `keyUsages`: {string[]} See [Key usages][]. +* `keyUsages`: {string\[]} See [Key usages][]. * Returns: {Promise} containing {CryptoKey|CryptoKeyPair} Using the method and parameters provided in `algorithm`, `subtle.generateKey()` @@ -704,6 +733,7 @@ The {CryptoKey} (secret key) generating algorithms supported include: 1 Non-standard Node.js extension ### `subtle.importKey(format, keyData, algorithm, extractable, keyUsages)` + + * `algorithm`: {RsaHashedImportParams|EcKeyImportParams|HmacImportParams|AesImportParams|Pbkdf2ImportParams|NodeDsaImportParams|NodeDhImportParams|NodeScryptImportParams|NodeEdKeyImportParams} + + * `extractable`: {boolean} -* `keyUsages`: {string[]} See [Key usages][]. +* `keyUsages`: {string\[]} See [Key usages][]. * Returns: {Promise} containing {CryptoKey} The `subtle.importKey()` method attempts to interpret the provided `keyData` @@ -734,38 +768,41 @@ If importing a `'PBKDF2'` key, `extractable` must be `false`. The algorithms currently supported include: -| Key Type | `'spki'` | `'pkcs8'` | `'jwk'` | `'raw'` | -| --------------------- | -------- | --------- | ------- | ------- | -| `'AES-CBC'` | | | ✔ | ✔ | -| `'AES-CTR'` | | | ✔ | ✔ | -| `'AES-GCM'` | | | ✔ | ✔ | -| `'AES-KW'` | | | ✔ | ✔ | -| `'ECDH'` | ✔ | ✔ | ✔ | ✔ | -| `'ECDSA'` | ✔ | ✔ | ✔ | ✔ | -| `'HDKF'` | | | | ✔ | -| `'HMAC'` | | | ✔ | ✔ | -| `'PBKDF2'` | | | | ✔ | -| `'RSA-OAEP'` | ✔ | ✔ | ✔ | | -| `'RSA-PSS'` | ✔ | ✔ | ✔ | | -| `'RSASSA-PKCS1-v1_5'` | ✔ | ✔ | ✔ | | -| `'NODE-DSA'` 1 | ✔ | ✔ | | | -| `'NODE-DH'` 1 | ✔ | ✔ | | | -| `'NODE-SCRYPT'` 1 | | | | ✔ | -| `'NODE-ED25519'` 1 | ✔ | ✔ | ✔ | ✔ | -| `'NODE-ED448'` 1 | ✔ | ✔ | ✔ | ✔ | +| Key Type | `'spki'` | `'pkcs8'` | `'jwk'` | `'raw'` | +| ----------------------------- | -------- | --------- | ------- | ------- | +| `'AES-CBC'` | | | ✔ | ✔ | +| `'AES-CTR'` | | | ✔ | ✔ | +| `'AES-GCM'` | | | ✔ | ✔ | +| `'AES-KW'` | | | ✔ | ✔ | +| `'ECDH'` | ✔ | ✔ | ✔ | ✔ | +| `'ECDSA'` | ✔ | ✔ | ✔ | ✔ | +| `'HDKF'` | | | | ✔ | +| `'HMAC'` | | | ✔ | ✔ | +| `'PBKDF2'` | | | | ✔ | +| `'RSA-OAEP'` | ✔ | ✔ | ✔ | | +| `'RSA-PSS'` | ✔ | ✔ | ✔ | | +| `'RSASSA-PKCS1-v1_5'` | ✔ | ✔ | ✔ | | +| `'NODE-DSA'` 1 | ✔ | ✔ | | | +| `'NODE-DH'` 1 | ✔ | ✔ | | | +| `'NODE-SCRYPT'` 1 | | | | ✔ | +| `'NODE-ED25519'` 1 | ✔ | ✔ | ✔ | ✔ | +| `'NODE-ED448'` 1 | ✔ | ✔ | ✔ | ✔ | 1 Node.js-specific extension ### `subtle.sign(algorithm, key, data)` + + * `algorithm`: {RsaSignParams|RsaPssParams|EcdsaParams|HmacParams|NodeDsaSignParams} * `key`: {CryptoKey} * `data`: {ArrayBuffer|TypedArray|DataView|Buffer} * Returns: {Promise} containing {ArrayBuffer} + Using the method and parameters given by `algorithm` and the keying material @@ -786,6 +823,7 @@ The algorithms currently supported include: 1 Non-standard Node.js extension ### `subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)` + @@ -793,12 +831,16 @@ added: v15.0.0 * `format`: {string} Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. * `wrappedKey`: {ArrayBuffer|TypedArray|DataView|Buffer} * `unwrappingKey`: {CryptoKey} + + * `unwrapAlgo`: {RsaOaepParams|AesCtrParams|AesCbcParams|AesGcmParams|AesKwParams} * `unwrappedKeyAlgo`: {RsaHashedImportParams|EcKeyImportParams|HmacImportParams|AesImportParams} + + * `extractable`: {boolean} -* `keyUsages`: {string[]} See [Key usages][]. +* `keyUsages`: {string\[]} See [Key usages][]. * Returns: {Promise} containing {CryptoKey} In cryptography, "wrapping a key" refers to exporting and then encrypting the @@ -836,16 +878,19 @@ The unwrapped key algorithms supported include: 1 Non-standard Node.js extension ### `subtle.verify(algorithm, key, signature, data)` + + * `algorithm`: {RsaSignParams|RsaPssParams|EcdsaParams|HmacParams|NodeDsaSignParams} * `key`: {CryptoKey} * `signature`: {ArrayBuffer|TypedArray|DataView|Buffer} * `data`: {ArrayBuffer|TypedArray|DataView|Buffer} * Returns: {Promise} containing {boolean} + Using the method and parameters given in `algorithm` and the keying material @@ -866,6 +911,7 @@ The algorithms currently supported include: 1 Non-standard Node.js extension ### `subtle.wrapKey(format, key, wrappingKey, wrapAlgo)` + @@ -901,11 +947,13 @@ the various {SubtleCrypto} methods. While described here as "classes", they are simple JavaScript dictionary objects. ### Class: `AesCbcParams` + #### `aesCbcParams.iv` + @@ -916,6 +964,7 @@ Provides the initialization vector. It must be exactly 16-bytes in length and should be unpredictable and cryptographically random. #### `aesCbcParams.name` + @@ -923,11 +972,13 @@ added: v15.0.0 * Type: {string} Must be `'AES-CBC'`. ### Class: `AesCtrParams` + #### `aesCtrParams.counter` + @@ -940,6 +991,7 @@ The `AES-CTR` method uses the rightmost `length` bits of the block as the counter and the remaining bits as the nonce. #### `aesCtrParams.length` + @@ -948,6 +1000,7 @@ added: v15.0.0 to be used as the counter. #### `aesCtrParams.name` + @@ -955,11 +1008,13 @@ added: v15.0.0 * Type: {string} Must be `'AES-CTR'`. ### Class: `AesGcmParams` + #### `aesGcmParams.additionalData` + @@ -971,6 +1026,7 @@ encrypted but is included in the authentication of the data. The use of `additionalData` is optional. #### `aesGcmParams.iv` + @@ -982,6 +1038,7 @@ using a given key. It is recommended by the AES-GCM specification that this contain at least 12 random bytes. #### `aesGcmParams.name` + @@ -989,6 +1046,7 @@ added: v15.0.0 * Type: {string} Must be `'AES-GCM'`. #### `aesGcmParams.tagLength` + @@ -998,11 +1056,13 @@ added: v15.0.0 `128`. **Default:** `128`. ### Class: `AesImportParams` + #### `aesImportParams.name` + @@ -1011,11 +1071,13 @@ added: v15.0.0 `'AES-KW'`. ### Class: `AesKeyGenParams` + #### `aesKeyGenParams.length` + @@ -1026,6 +1088,7 @@ The length of the AES key to be generated. This must be either `128`, `192`, or `256`. #### `aesKeyGenParams.name` + @@ -1034,11 +1097,13 @@ added: v15.0.0 `'AES-KW'` ### Class: `AesKwParams` + #### `aesKwParams.name` + @@ -1046,11 +1111,13 @@ added: v15.0.0 * Type: {string} Must be `'AES-KW'`. ### Class: `EcdhKeyDeriveParams` + #### `ecdhKeyDeriveParams.name` + @@ -1058,6 +1125,7 @@ added: v15.0.0 * Type: {string} Must be `'ECDH'`. #### `ecdhKeyDeriveParams.public` + @@ -1070,11 +1138,13 @@ The `ecdhKeyDeriveParams.public` property is set to the other parties public key. ### Class: `EcdsaParams` + #### `ecdsaParams.hash` + @@ -1092,6 +1162,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `ecdsaParams.name` + @@ -1099,11 +1170,13 @@ added: v15.0.0 * Type: {string} Must be `'ECDSA'`. ### Class: `EcKeyGenParams` + #### `ecKeyGenParams.name` + @@ -1111,6 +1184,7 @@ added: v15.0.0 * Type: {string} Must be one of `'ECDSA'` or `'ECDH'`. #### `ecKeyGenParams.namedCurve` + @@ -1119,11 +1193,13 @@ added: v15.0.0 `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`. ### Class: `EcKeyImportParams` + #### `ecKeyImportParams.name` + @@ -1131,6 +1207,7 @@ added: v15.0.0 * Type: {string} Must be one of `'ECDSA'` or `'ECDH'`. #### `ecKeyImportParams.namedCurve` + @@ -1139,11 +1216,13 @@ added: v15.0.0 `'NODE-ED25519'`, `'NODE-ED448'`, `'NODE-X25519'`, or `'NODE-X448'`. ### Class: `HkdfParams` + #### `hkdfParams.hash` + @@ -1161,6 +1240,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `hkdfParams.info` + @@ -1171,6 +1251,7 @@ Provides application-specific contextual input to the HKDF algorithm. This can be zero-length but must be provided. #### `hkdfParams.name` + @@ -1178,6 +1259,7 @@ added: v15.0.0 * Type: {string} Must be `'HKDF'`. #### `hkdfParams.salt` + @@ -1190,11 +1272,13 @@ output of the digest function (for instance, if using `'SHA-256'` as the digest, the salt should be 256-bits of random data). ### Class: `HmacImportParams` + #### `hmacImportParams.hash` + @@ -1212,6 +1296,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `hmacImportParams.length` + @@ -1222,6 +1307,7 @@ The optional number of bits in the HMAC key. This is optional and should be omitted for most cases. #### `hmacImportParams.name` + @@ -1229,11 +1315,13 @@ added: v15.0.0 * Type: {string} Must be `'HMAC'`. ### Class: `HmacKeyGenParams` + #### `hmacKeyGenParams.hash` + @@ -1251,6 +1339,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `hmacKeyGenParams.length` + @@ -1262,6 +1351,7 @@ the length will be determined by the hash algorithm used. This is optional and should be omitted for most cases. #### `hmacKeyGenParams.name` + @@ -1269,11 +1359,13 @@ added: v15.0.0 * Type: {string} Must be `'HMAC'`. ### Class: `HmacParams` + #### `hmacParams.name` + @@ -1281,11 +1373,13 @@ added: v15.0.0 * Type: {string} Must be `'HMAC'`. ### Class: `Pbkdf2ImportParams` + #### `pbkdf2ImportParams.name` + @@ -1293,11 +1387,13 @@ added: v15.0.0 * Type: {string} Must be `'PBKDF2'` ### Class: `Pbkdf2Params` + #### `pbkdb2Params.hash` + @@ -1315,6 +1411,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `pbkdf2Params.iterations` + @@ -1324,6 +1421,7 @@ added: v15.0.0 The number of iterations the PBKDF2 algorithm should make when deriving bits. #### `pbkdf2Params.name` + @@ -1331,6 +1429,7 @@ added: v15.0.0 * Type: {string} Must be `'PBKDF2'`. #### `pbkdf2Params.salt` + @@ -1340,11 +1439,13 @@ added: v15.0.0 Should be at least 16 random or pseudorandom bytes. ### Class: `RsaHashedImportParams` + #### `rsaHashedImportParams.hash` + @@ -1362,6 +1463,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `rsaHashedImportParams.name` + @@ -1370,11 +1472,13 @@ added: v15.0.0 `'RSA-OAEP'`. ### Class: `RsaHashedKeyGenParams` + #### `rsaHashedKeyGenParams.hash` + @@ -1392,6 +1496,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. #### `rsaHashedKeyGenParams.modulusLength` + @@ -1402,6 +1507,7 @@ The length in bits of the RSA modulus. As a best practice, this should be at least `2048`. #### `rsaHashedKeyGenParams.name` + @@ -1410,6 +1516,7 @@ added: v15.0.0 `'RSA-OAEP'`. #### `rsaHashedKeyGenParams.publicExponent` + @@ -1423,11 +1530,13 @@ there is reason to use a different value, use `new Uint8Array([1, 0, 1])` (65537) as the public exponent. ### Class: `RsaOaepParams` + #### rsaOaepParams.label + @@ -1440,6 +1549,7 @@ to the generated ciphertext. The `rsaOaepParams.label` parameter is optional. #### rsaOaepParams.name + @@ -1447,11 +1557,13 @@ added: v15.0.0 * Type: {string} must be `'RSA-OAEP'`. ### Class: `RsaPssParams` + #### `rsaPssParams.name` + @@ -1459,6 +1571,7 @@ added: v15.0.0 * Type: {string} Must be `'RSA-PSS'`. #### `rsaPssParams.saltLength` + @@ -1468,11 +1581,13 @@ added: v15.0.0 The length (in bytes) of the random salt to use. ### Class: `RsaSignParams` + #### `rsaSignParams.name` + @@ -1492,6 +1607,7 @@ not supported by other WebCrypto implementations and reduce the portability of code to other environments. ### `NODE-DH` Algorithm + @@ -1500,11 +1616,13 @@ The `NODE-DH` algorithm is the common implementation of Diffie-Hellman key agreement. #### Class: `NodeDhImportParams` + ##### `nodeDhImportParams.name` + @@ -1512,11 +1630,13 @@ added: v15.0.0 * Type: {string} Must be `'NODE-DH'`. #### Class: `NodeDhKeyGenParams` + ##### `nodeDhKeyGenParams.generator` + @@ -1524,6 +1644,7 @@ added: v15.0.0 * Type: {number} A custom generator. ##### `nodeDhKeyGenParams.group` + @@ -1531,6 +1652,7 @@ added: v15.0.0 * Type: {string} The Diffie-Hellman group name. ##### `nodeDhKeyGenParams.prime` + @@ -1538,6 +1660,7 @@ added: v15.0.0 * Type: {Buffer} The prime parameter. ##### `nodeDhKeyGenParams.primeLength` + @@ -1545,11 +1668,13 @@ added: v15.0.0 * Type: {number} The length in bits of the prime. #### Class: NodeDhDeriveBitsParams + ##### `nodeDhDeriveBitsParams.public` + @@ -1557,6 +1682,7 @@ added: v15.0.0 * Type: {CryptoKey} The other parties public key. ### `NODE-DSA` Algorithm + @@ -1565,11 +1691,13 @@ The `NODE-DSA` algorithm is the common implementation of the DSA digital signature algorithm. #### Class: `NodeDsaImportParams` + ##### `nodeDsaImportParams.hash` + @@ -1587,6 +1715,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. ##### `nodeDsaImportParams.name` + @@ -1594,11 +1723,13 @@ added: v15.0.0 * Type: {string} Must be `'NODE-DSA'`. #### Class: `NodeDsaKeyGenParams` + ##### `nodeDsaKeyGenParams.divisorLength` + @@ -1608,6 +1739,7 @@ added: v15.0.0 The optional length in bits of the DSA divisor. ##### `nodeDsaKeyGenParams.hash` + @@ -1625,6 +1757,7 @@ If represented as an {Object}, the object must have a `name` property whose value is one of the above listed values. ##### `nodeDsaKeyGenParams.modulusLength` + @@ -1635,6 +1768,7 @@ The length in bits of the DSA modulus. As a best practice, this should be at least `2048`. ##### `nodeDsaKeyGenParams.name` + @@ -1642,11 +1776,13 @@ added: v15.0.0 * Type: {string} Must be `'NODE-DSA'`. #### Class: `NodeDsaSignParams` + ##### `nodeDsaSignParams.name` + @@ -1654,16 +1790,19 @@ added: v15.0.0 * Type: {string} Must be `'NODE-DSA'` ### `NODE-ED25519` and `NODE-ED448` Algorithms + #### Class: `NodeEdKeyGenParams` + ##### `nodeEdKeyGenParams.name` + @@ -1671,6 +1810,7 @@ added: v15.8.0 * Type: {string} Must be one of `'NODE-ED25519'`, `'NODE-ED448'` or `'ECDH'`. ##### `nodeEdKeyGenParams.namedCurve` + @@ -1679,11 +1819,13 @@ added: v15.8.0 `'NODE-X25519'`, or `'NODE-X448'`. #### Class: `NodeEdKeyImportParams` + ##### `nodeEdKeyImportParams.name` + @@ -1693,6 +1835,7 @@ added: v15.8.0 an `X25519` or `X448` key. ##### `nodeEdKeyImportParams.namedCurve` + @@ -1701,6 +1844,7 @@ added: v15.8.0 `'NODE-X25519'`, or `'NODE-X448'`. ##### `nodeEdKeyImportParams.public` + @@ -1711,6 +1855,7 @@ The `public` parameter is used to specify that the `'raw'` format key is to be interpreted as a public key. **Default:** `false`. ### `NODE-SCRYPT` Algorithm + @@ -1719,11 +1864,13 @@ The `NODE-SCRYPT` algorithm is the common implementation of the scrypt key derivation algorithm. #### Class: `NodeScryptImportParams` + ##### `nodeScryptImportParams.name` + @@ -1731,11 +1878,13 @@ added: v15.0.0 * Type: {string} Must be `'NODE-SCRYPT'`. #### Class: `NodeScryptParams` + ##### `nodeScryptParams.encoding` + @@ -1743,6 +1892,7 @@ added: v15.0.0 * Type: {string} The string encoding when `salt` is a string. ##### `nodeScryptParams.maxmem` + @@ -1751,6 +1901,7 @@ added: v15.0.0 `127 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`. ##### `nodeScryptParams.N` + @@ -1759,6 +1910,7 @@ added: v15.0.0 greater than 1. **Default:** `16384`. ##### `nodeScryptParams.p` + @@ -1766,6 +1918,7 @@ added: v15.0.0 * Type: {number} Parallelization parameter. **Default:** `1`. ##### `nodeScryptParams.r` + @@ -1773,6 +1926,7 @@ added: v15.0.0 * Type: {number} Block size parameter. **Default:** `8`. ##### `nodeScryptParams.salt` + diff --git a/doc/api/webstreams.md b/doc/api/webstreams.md index fa10dcf4e2213b..14909704f384f1 100644 --- a/doc/api/webstreams.md +++ b/doc/api/webstreams.md @@ -98,16 +98,19 @@ const stream = new ReadableStream({ ## API ### Class: `ReadableStream` + #### `new ReadableStream([underlyingSource [, strategy]])` + + * `underlyingSource` {Object} * `start` {Function} A user-defined function that is invoked immediately when the `ReadableStream` is created. @@ -133,9 +136,11 @@ added: v16.5.0 chunk of data. * `chunk` {any} * Returns: {number} + #### `readableStream.locked` + @@ -148,6 +153,7 @@ switch to `true` while there is an active reader consuming the stream's data. #### `readableStream.cancel([reason])` + @@ -157,6 +163,7 @@ added: v16.5.0 been completed. #### `readableStream.getReader([options])` + @@ -188,6 +195,7 @@ reader.read().then(console.log); Causes the `readableStream.locked` to be `true`. #### `readableStream.pipeThrough(transform[, options])` + @@ -270,6 +278,7 @@ const transformedStream = stream.pipeThrough(transform); ``` #### `readableStream.pipeTo(destination, options)` + @@ -292,11 +301,12 @@ Causes the `readableStream.locked` to be `true` while the pipe operation is active. #### `readableStream.tee()` + -* Returns: {ReadableStream[]} +* Returns: {ReadableStream\[]} Returns a pair of new {ReadableStream} instances to which this `ReadableStream`'s data will be forwarded. Each will receive the @@ -305,6 +315,7 @@ same data. Causes the `readableStream.locked` to be `true`. #### `readableStream.values([options])` + @@ -373,6 +384,7 @@ port2.postMessage(stream, [stream]); ``` ### Class: `ReadableStreamDefaultReader` + @@ -384,6 +396,7 @@ values, which allows the {ReadableStream} to work with generally any JavaScript value. #### `new ReadableStreamDefaultReader(stream)` + @@ -394,6 +407,7 @@ Creates a new {ReadableStreamDefaultReader} that is locked to the given {ReadableStream}. #### `readableStreamDefaultReader.cancel([reason])` + @@ -405,6 +419,7 @@ Cancels the {ReadableStream} and returns a promise that is fulfilled when the underlying stream has been canceled. #### `readableStreamDefaultReader.closed` + @@ -413,6 +428,7 @@ added: v16.5.0 {ReadableStream} is closed or this reader's lock is released. #### `readableStreamDefaultReader.read()` + @@ -426,6 +442,7 @@ and returns a promise that is fulfilled with the data once it is available. #### `readableStreamDefaultReader.releaseLock()` + @@ -433,13 +450,14 @@ added: v16.5.0 Releases this reader's lock on the underlying {ReadableStream}. ### Class: `ReadableStreamBYOBReader` + The `ReadableStreamBYOBReader` is an alternative consumer for byte-oriented {ReadableStream}'s (those that are created with -`underlyingSource.type` set equal to `'bytes`` when the +`underlyingSource.type` set equal to `'bytes'` when the `ReadableStream` was created). The `BYOB` is short for "bring your own buffer". This is a @@ -505,6 +523,7 @@ console.log(Buffer.from(data).toString()); ``` #### `new ReadableStreamBYOBReader(stream)` + @@ -515,6 +534,7 @@ Creates a new `ReadableStreamBYOBReader` that is locked to the given {ReadableStream}. #### `readableStreamBYOBReader.cancel([reason])` + @@ -526,6 +546,7 @@ Cancels the {ReadableStream} and returns a promise that is fulfilled when the underlying stream has been canceled. #### `readableStreamBYOBReader.closed` + @@ -534,6 +555,7 @@ added: v16.5.0 {ReadableStream} is closed or this reader's lock is released. #### `readableStreamBYOBReader.read(view)` + @@ -554,11 +576,12 @@ callbacks. These types of `Buffer`s use a shared underlying {ArrayBuffer} object that contains all of the data from all of the pooled `Buffer` instances. When a `Buffer`, {TypedArray}, or {DataView} is passed in to `readableStreamBYOBReader.read()`, -the view's underlying `ArrayBuffer` is *detached*, invalidating +the view's underlying `ArrayBuffer` is _detached_, invalidating all existing views that may exist on that `ArrayBuffer`. This can have disastrous consequences for your application. #### `readableStreamBYOBReader.releaseLock()` + @@ -566,6 +589,7 @@ added: v16.5.0 Releases this reader's lock on the underlying {ReadableStream}. ### Class: `ReadableStreamDefaultController` + @@ -576,6 +600,7 @@ the internal state and management of the stream's queue. The implementation for `ReadableStream`s that are not byte-oriented. #### `readableStreamDefaultController.close()` + @@ -583,6 +608,7 @@ added: v16.5.0 Closes the {ReadableStream} to which this controller is associated. #### `readableStreamDefaultController.desiredSize` + @@ -593,6 +619,7 @@ Returns the amount of data remaining to fill the {ReadableStream}'s queue. #### `readableStreamDefaultController.enqueue(chunk)` + @@ -602,6 +629,7 @@ added: v16.5.0 Appends a new chunk of data to the {ReadableStream}'s queue. #### `readableStreamDefaultController.error(error)` + @@ -611,6 +639,7 @@ added: v16.5.0 Signals an error that causes the {ReadableStream} to error and close. ### Class: `ReadableByteStreamController` + @@ -620,6 +649,7 @@ the internal state and management of the stream's queue. The `ReadableByteStreamController` is for byte-oriented `ReadableStream`s. #### `readableByteStreamController.byobRequest` + @@ -627,6 +657,7 @@ added: v16.5.0 * Type: {ReadableStreamBYOBRequest} #### `readableByteStreamController.close()` + @@ -634,6 +665,7 @@ added: v16.5.0 Closes the {ReadableStream} to which this controller is associated. #### `readableByteStreamController.desiredSize` + @@ -644,6 +676,7 @@ Returns the amount of data remaining to fill the {ReadableStream}'s queue. #### `readableByteStreamController.enqueue(chunk)` + @@ -653,6 +686,7 @@ added: v16.5.0 Appends a new chunk of data to the {ReadableStream}'s queue. #### `readableByteStreamController.error(error)` + @@ -662,6 +696,7 @@ added: v16.5.0 Signals an error that causes the {ReadableStream} to error and close. ### Class: `ReadableStreamBYOBRequest` + @@ -677,6 +712,7 @@ and provides methods for signaling that the data has been provided. #### `readableStreamBYOBRequest.respond(bytesWritten)` + @@ -687,6 +723,7 @@ Signals that a `bytesWritten` number of bytes have been written to `readableStreamBYOBRequest.view`. #### `readableStreamBYOBRequest.respondWithNewView(view)` + @@ -697,6 +734,7 @@ Signals that the request has been fulfilled with bytes written to a new `Buffer`, `TypedArray`, or `DataView`. #### `readableStreamBYOBRequest.view` + @@ -704,6 +742,7 @@ added: v16.5.0 * Type: {Buffer|TypedArray|DataView} ### Class: `WritableStream` + @@ -725,6 +764,7 @@ await stream.getWriter().write('Hello World'); ``` #### `new WritableStream([underlyingSink[, strategy]])` + @@ -746,7 +786,7 @@ added: v16.5.0 the `WritableStream`. * `reason` {any} * Returns: A promise fulfilled with `undefined`. - * `type` {any} The `type` option is reserved for future use and *must* be + * `type` {any} The `type` option is reserved for future use and _must_ be undefined. * `strategy` {Object} * `highWaterMark` {number} The maximum internal queue size before backpressure @@ -757,6 +797,7 @@ added: v16.5.0 * Returns: {number} #### `writableStream.abort([reason])` + @@ -768,6 +809,7 @@ Abruptly terminates the `WritableStream`. All queued writes will be canceled with their associated promises rejected. #### `writableStream.close()` + @@ -777,6 +819,7 @@ added: v16.5.0 Closes the `WritableStream` when no additional writes are expected. #### `writableStream.getWriter()` + @@ -787,6 +830,7 @@ Creates and creates a new writer instance that can be used to write data into the `WritableStream`. #### `writableStream.locked` + @@ -814,11 +858,13 @@ port2.postMessage(stream, [stream]); ``` ### Class: `WritableStreamDefaultWriter` + #### `new WritableStreamDefaultWriter(stream)` + @@ -829,6 +875,7 @@ Creates a new `WritableStreamDefaultWriter` that is locked to the given `WritableStream`. #### `writableStreamDefaultWriter.abort([reason])` + @@ -840,6 +887,7 @@ Abruptly terminates the `WritableStream`. All queued writes will be canceled with their associated promises rejected. #### `writableStreamDefaultWriter.close()` + @@ -849,6 +897,7 @@ added: v16.5.0 Closes the `WritableStream` when no additional writes are expected. #### `writableStreamDefaultWriter.closed` + @@ -858,6 +907,7 @@ added: v16.5.0 released. #### `writableStreamDefaultWriter.desiredSize` + @@ -867,6 +917,7 @@ added: v16.5.0 The amount of data required to fill the {WritableStream}'s queue. #### `writableStreamDefaultWriter.ready` + @@ -875,6 +926,7 @@ added: v16.5.0 writer is ready to be used. #### `writableStreamDefaultWriter.releaseLock()` + @@ -882,6 +934,7 @@ added: v16.5.0 Releases this writer's lock on the underlying {ReadableStream}. #### `writableStreamDefaultWriter.write([chunk])` + @@ -892,6 +945,7 @@ added: v16.5.0 Appends a new chunk of data to the {WritableStream}'s queue. ### Class: `WritableStreamDefaultController` + @@ -904,6 +958,7 @@ internal state. * Type: {any} The `reason` value passed to `writableStream.abort()`. #### `writableStreamDefaultController.error(error)` + @@ -920,6 +975,7 @@ with currently pending writes canceled. write or close operations when a {WritableStream} is aborted. ### Class: `TransformStream` + @@ -947,6 +1003,7 @@ await Promise.all([ ``` #### `new TransformStream([transformer[, writableStrategy[, readableStrategy]]])` + @@ -968,9 +1025,9 @@ added: v16.5.0 * `controller` {TransformStreamDefaultController} * Returns: A promise fulfilled with `undefined`. * `readableType` {any} the `readableType` option is reserved for future use - and *must* be `undefined. + and _must_ be `undefined`. * `writableType` {any} the `writableType` option is reserved for future use - and *must* be `undefined. + and _must_ be `undefined`. * `writableStrategy` {Object} * `highWaterMark` {number} The maximum internal queue size before backpressure is applied. @@ -987,6 +1044,7 @@ added: v16.5.0 * Returns: {number} #### `transformStream.readable` + @@ -994,6 +1052,7 @@ added: v16.5.0 * Type: {ReadableStream} #### `transformStream.writable` + @@ -1018,6 +1077,7 @@ port2.postMessage(stream, [stream]); ``` ### Class: `TransformStreamDefaultController` + @@ -1026,6 +1086,7 @@ The `TransformStreamDefaultController` manages the internal state of the `TransformStream`. #### `transformStreamDefaultController.desiredSize` + @@ -1035,6 +1096,7 @@ added: v16.5.0 The amount of data required to fill the readable side's queue. #### `transformStreamDefaultController.enqueue([chunk])` + @@ -1044,6 +1106,7 @@ added: v16.5.0 Appends a chunk of data to the readable side's queue. #### `transformStreamDefaultController.error([reason])` + @@ -1055,6 +1118,7 @@ while processing the transform data, causing both sides to be abruptly closed. #### `transformStreamDefaultController.terminate()` + @@ -1063,11 +1127,13 @@ Closes the readable side of the transport and causes the writable side to be abruptly closed with an error. ### Class: `ByteLengthQueuingStrategy` + #### `new ByteLengthQueuingStrategy(options)` + @@ -1076,6 +1142,7 @@ added: v16.5.0 * `highWaterMark` {number} #### `byteLengthQueuingStrategy.highWaterMark` + @@ -1083,6 +1150,7 @@ added: v16.5.0 * Type: {number} #### `byteLengthQueuingStrategy.size` + @@ -1092,11 +1160,13 @@ added: v16.5.0 * Returns: {number} ### Class: `CountQueuingStrategy` + #### `new CountQueuingStrategy(options)` + @@ -1105,6 +1175,7 @@ added: v16.5.0 * `highWaterMark` {number} #### `countQueuingStrategy.highWaterMark` + @@ -1112,6 +1183,7 @@ added: v16.5.0 * Type: {number} #### `countQueuingStrategy.size` + @@ -1121,11 +1193,13 @@ added: v16.5.0 * Returns: {number} ### Class: `TextEncoderStream` + #### `new TextEncoderStream()` + @@ -1133,6 +1207,7 @@ added: v16.6.0 Creates a new `TextEncoderStream` instance. #### `textEncoderStream.encoding` + @@ -1142,6 +1217,7 @@ added: v16.6.0 The encoding supported by the `TextEncoderStream` instance. #### `textEncoderStream.readable` + @@ -1149,6 +1225,7 @@ added: v16.6.0 * Type: {ReadableStream} #### `textEncoderStream.writable` + @@ -1156,11 +1233,13 @@ added: v16.6.0 * Type: {WritableStream} ### Class: `TextDecoderStream` + #### `new TextDecoderStream([encoding[, options]])` + @@ -1177,6 +1256,7 @@ added: v16.6.0 Creates a new `TextDecoderStream` instance. #### `textDecoderStream.encoding` + @@ -1186,6 +1266,7 @@ added: v16.6.0 The encoding supported by the `TextDecoderStream` instance. #### `textDecoderStream.fatal` + @@ -1196,6 +1277,7 @@ The value will be `true` if decoding errors result in a `TypeError` being thrown. #### `textDecoderStream.ignoreBOM` + @@ -1206,6 +1288,7 @@ The value will be `true` if the decoding result will include the byte order mark. #### `textDecoderStream.readable` + @@ -1213,6 +1296,7 @@ added: v16.6.0 * Type: {ReadableStream} #### `textDecoderStream.writable` + @@ -1220,6 +1304,7 @@ added: v16.6.0 * Type: {WritableStream} ### Utility Consumers + @@ -1248,6 +1333,7 @@ const { ``` #### `streamConsumers.arrayBuffer(stream)` + @@ -1257,6 +1343,7 @@ added: v16.7.0 contents of the stream. #### `streamConsumers.blob(stream)` + @@ -1266,6 +1353,7 @@ added: v16.7.0 of the stream. #### `streamConsumers.buffer(stream)` + @@ -1275,6 +1363,7 @@ added: v16.7.0 contents of the stream. #### `streamConsumers.json(stream)` + @@ -1284,6 +1373,7 @@ added: v16.7.0 UTF-8 encoded string that is then passed through `JSON.parse()`. #### `streamConsumers.text(stream)` + diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index bfd8248b8482e5..73cd29538da91f 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -62,6 +62,7 @@ Worker threads inherit non-process-specific options by default. Refer to specifically `argv` and `execArgv` options. ## `worker.getEnvironmentData(key)` + @@ -94,6 +95,7 @@ if (isMainThread) { ``` ## `worker.isMainThread` + @@ -115,6 +117,7 @@ if (isMainThread) { ``` ## `worker.markAsUntransferable(object)` + * `port` {MessagePort} The message port to transfer. + * `contextifiedSandbox` {Object} A [contextified][] object as returned by the `vm.createContext()` method. @@ -178,6 +183,7 @@ However, the created `MessagePort` no longer inherits from events using it. ## `worker.parentPort` + @@ -209,6 +215,7 @@ if (isMainThread) { ``` ## `worker.receiveMessageOnPort(port)` + @@ -279,6 +288,7 @@ new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV }) ``` ## `worker.setEnvironmentData(key[, value])` + @@ -296,6 +306,7 @@ The `worker.setEnvironmentData()` API sets the content of instances spawned from the current context. ## `worker.threadId` + @@ -307,6 +318,7 @@ An integer identifier for the current thread. On the corresponding worker object This value is unique for each [`Worker`][] instance inside a single process. ## `worker.workerData` + @@ -328,6 +340,7 @@ if (isMainThread) { ``` ## Class: `BroadcastChannel extends EventTarget` + @@ -363,14 +376,16 @@ if (isMainThread) { ``` ### `new BroadcastChannel(name)` + * `name` {any} The name of the channel to connect to. Any JavaScript value - that can be converted to a string using ``${name}`` is permitted. + that can be converted to a string using `` `${name}` `` is permitted. ### `broadcastChannel.close()` + @@ -378,6 +393,7 @@ added: v15.4.0 Closes the `BroadcastChannel` connection. ### `broadcastChannel.onmessage` + @@ -386,6 +402,7 @@ added: v15.4.0 when a message is received. ### `broadcastChannel.onmessageerror` + @@ -394,6 +411,7 @@ added: v15.4.0 deserialized. ### `broadcastChannel.postMessage(message)` + @@ -401,16 +419,18 @@ added: v15.4.0 * `message` {any} 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 +BroadcastChannel does _not_ let the program exit if it's the only active handle left (the default behavior). If the port is `ref()`ed, calling `ref()` again has no effect. ### `broadcastChannel.unref()` + @@ -420,6 +440,7 @@ is the only active handle in the event system. If the BroadcastChannel is already `unref()`ed calling `unref()` again has no effect. ## Class: `MessageChannel` + @@ -440,6 +461,7 @@ port2.postMessage({ foo: 'bar' }); ``` ## Class: `MessagePort` + @@ -482,6 +505,7 @@ port1.close(); ``` ### Event: `'message'` + @@ -495,6 +519,7 @@ Listeners on this event receive a clone of the `value` parameter as passed to `postMessage()` and no further arguments. ### Event: `'messageerror'` + @@ -524,6 +550,7 @@ The [`'close'` event][] is emitted on both `MessagePort` instances that are part of the channel. ### `port.postMessage(value[, transferList])` + * `value` {any} -* `transferList` {Object[]} +* `transferList` {Object\[]} Sends a JavaScript value to the receiving side of this channel. `value` is transferred in a way which is compatible with @@ -564,7 +591,7 @@ In particular, the significant differences to `JSON` are: * `value` may contain instances of builtin JS types such as `RegExp`s, `BigInt`s, `Map`s, `Set`s, etc. * `value` may contain typed arrays, both using `ArrayBuffer`s - and `SharedArrayBuffer`s. + and `SharedArrayBuffer`s. * `value` may contain [`WebAssembly.Module`][] instances. * `value` may not contain native (C++-backed) objects other than: * {CryptoKey}s, @@ -723,12 +750,13 @@ port2.postMessage(new URL('https://example.org')); ``` ### `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 +_not_ let the program exit if it's the only active handle left (the default behavior). If the port is `ref()`ed, calling `ref()` again has no effect. If listeners are attached or removed using `.on('message')`, the port @@ -736,6 +764,7 @@ is `ref()`ed and `unref()`ed automatically depending on whether listeners for the event exist. ### `port.start()` + @@ -751,6 +780,7 @@ automatically calls `.start()`, but unsetting it lets messages queue up until a new handler is set or the port is discarded. ### `port.unref()` + @@ -764,6 +794,7 @@ If listeners are attached or removed using `.on('message')`, the port is listeners for the event exist. ## Class: `Worker` + @@ -839,6 +870,7 @@ if (isMainThread) { ``` ### `new Worker(filename[, options])` + @@ -949,6 +982,7 @@ The `'error'` event is emitted if the worker thread throws an uncaught exception. In that case, the worker is terminated. ### Event: `'exit'` + @@ -963,6 +997,7 @@ passed exit code. If the worker was terminated, the `exitCode` parameter is This is the final event emitted by any `Worker` instance. ### Event: `'message'` + @@ -977,6 +1012,7 @@ All messages sent from the worker thread are emitted before the [`'exit'` event][] is emitted on the `Worker` object. ### Event: `'messageerror'` + @@ -996,6 +1033,7 @@ The `'online'` event is emitted when the worker thread has started executing JavaScript code. ### `worker.getHeapSnapshot()` + * `utilization1` {Object} The result of a previous call to - `eventLoopUtilization()`. + `eventLoopUtilization()`. * `utilization2` {Object} The result of a previous call to - `eventLoopUtilization()` prior to `utilization1`. + `eventLoopUtilization()` prior to `utilization1`. * Returns {Object} * `idle` {number} * `active` {number} @@ -1076,28 +1116,31 @@ event][] emitted, and if called before this, or after the [`'exit'` event][], then all properties have the value of `0`. ### `worker.postMessage(value[, transferList])` + * `value` {any} -* `transferList` {Object[]} +* `transferList` {Object\[]} Send a message to the worker that is received via [`require('worker_threads').parentPort.on('message')`][]. 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 +_not_ let the program exit if it's the only active handle left (the default behavior). If the worker is `ref()`ed, calling `ref()` again has no effect. ### `worker.resourceLimits` + @@ -1129,6 +1173,7 @@ inside the worker thread. If `stderr: true` was not passed to the [`process.stderr`][] stream. ### `worker.stdin` + @@ -1140,6 +1185,7 @@ writable stream. The data written to this stream will be made available in the worker thread as [`process.stdin`][]. ### `worker.stdout` + @@ -1152,6 +1198,7 @@ inside the worker thread. If `stdout: true` was not passed to the [`process.stdout`][] stream. ### `worker.terminate()` + @@ -1181,6 +1229,7 @@ it is available as [`require('worker_threads').threadId`][]. This value is unique for each `Worker` instance inside a single process. ### `worker.unref()` + diff --git a/doc/api/zlib.md b/doc/api/zlib.md index a2ce8fe682f976..85a0e02efb44e9 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -265,6 +265,7 @@ From `zlib/zconf.h`, modified for Node.js usage: The memory requirements for deflate are (in bytes): + ```js (1 << (windowBits + 2)) + (1 << (memLevel + 9)) ``` @@ -354,6 +355,7 @@ http.createServer((request, response) => { ``` ## Constants + @@ -412,6 +414,7 @@ Compression strategy. * `zlib.constants.Z_DEFAULT_STRATEGY` ### Brotli constants + @@ -588,6 +596,7 @@ added: v0.5.8 Compress data using deflate. ## Class: `zlib.DeflateRaw` + @@ -595,6 +604,7 @@ added: v0.5.8 Compress data using deflate, and do not append a `zlib` header. ## Class: `zlib.Gunzip` + @@ -620,6 +631,7 @@ added: v0.5.8 Compress data using gzip. ## Class: `zlib.Inflate` + @@ -653,6 +667,7 @@ Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header. ## Class: `zlib.ZlibBase` + @@ -696,6 +713,7 @@ the engine, before the bytes are processed (compressed or decompressed, as appropriate for the derived class). ### `zlib.close([callback])` + @@ -705,6 +723,7 @@ added: v0.9.4 Close the underlying handle. ### `zlib.flush([kind, ]callback)` + @@ -722,6 +741,7 @@ normal call to `.write()`, i.e. it will be queued up behind other pending writes and will only produce output when data is being read from the stream. ### `zlib.params(level, strategy, callback)` + @@ -736,6 +756,7 @@ Dynamically update the compression level and compression strategy. Only applicable to deflate algorithm. ### `zlib.reset()` + @@ -744,6 +765,7 @@ Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms. ## `zlib.constants` + @@ -751,6 +773,7 @@ added: v7.0.0 Provides an object enumerating Zlib-related constants. ## `zlib.createBrotliCompress([options])` + @@ -782,6 +807,7 @@ added: v0.5.8 Creates and returns a new [`Deflate`][] object. ## `zlib.createDeflateRaw([options])` + @@ -798,6 +824,7 @@ since passing `windowBits = 9` to zlib actually results in a compressed stream that effectively uses an 8-bit window only. ## `zlib.createGunzip([options])` + @@ -807,6 +834,7 @@ added: v0.5.8 Creates and returns a new [`Gunzip`][] object. ## `zlib.createGzip([options])` + @@ -817,6 +845,7 @@ Creates and returns a new [`Gzip`][] object. See [example][zlib.createGzip example]. ## `zlib.createInflate([options])` + @@ -826,6 +855,7 @@ added: v0.5.8 Creates and returns a new [`Inflate`][] object. ## `zlib.createInflateRaw([options])` + @@ -835,6 +865,7 @@ added: v0.5.8 Creates and returns a new [`InflateRaw`][] object. ## `zlib.createUnzip([options])` + @@ -856,6 +887,7 @@ Every method has a `*Sync` counterpart, which accept the same arguments, but without a callback. ### `zlib.brotliCompress(buffer[, options], callback)` +