doc: format doc/api/*.md with markdown formatter

PR-URL: https://github.com/nodejs/node/pull/40403
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Zijian Liu <lxxyxzj@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Rich Trott 2021-10-10 21:55:04 -07:00 committed by Antoine du Hamel
parent a7c17e08de
commit d0b58c0287
58 changed files with 4248 additions and 1133 deletions

View File

@ -235,6 +235,7 @@ NODE_MODULE_INIT(/* exports, module, context */) {
```
#### Worker support
<!-- YAML
changes:
- version:

View File

@ -10,6 +10,7 @@ The `assert` module provides a set of assertion functions for verifying
invariants.
## Strict assertion mode
<!-- YAML
added: v9.9.0
changes:
@ -138,6 +139,7 @@ Indicates the failure of an assertion. All errors thrown by the `assert` module
will be instances of the `AssertionError` class.
### `new assert.AssertionError(options)`
<!-- YAML
added: v0.1.21
-->
@ -216,6 +218,7 @@ try {
```
## Class: `assert.CallTracker`
<!-- YAML
added:
- v14.2.0
@ -227,6 +230,7 @@ added:
This feature is currently experimental and behavior might still change.
### `new assert.CallTracker()`
<!-- YAML
added:
- v14.2.0
@ -278,6 +282,7 @@ process.on('exit', () => {
```
### `tracker.calls([fn][, exact])`
<!-- YAML
added:
- v14.2.0
@ -320,6 +325,7 @@ const callsfunc = tracker.calls(func);
```
### `tracker.report()`
<!-- YAML
added:
- v14.2.0
@ -396,6 +402,7 @@ tracker.report();
```
### `tracker.verify()`
<!-- YAML
added:
- v14.2.0
@ -443,6 +450,7 @@ tracker.verify();
```
## `assert(value[, message])`
<!-- YAML
added: v0.5.9
-->
@ -453,6 +461,7 @@ added: v0.5.9
An alias of [`assert.ok()`][].
## `assert.deepEqual(actual, expected[, message])`
<!-- YAML
added: v0.1.21
changes:
@ -629,6 +638,7 @@ parameter is an instance of an [`Error`][] then it will be thrown instead of the
[`AssertionError`][].
## `assert.deepStrictEqual(actual, expected[, message])`
<!-- YAML
added: v1.2.0
changes:
@ -879,6 +889,7 @@ parameter is an instance of an [`Error`][] then it will be thrown instead of the
`AssertionError`.
## `assert.doesNotMatch(string, regexp[, message])`
<!-- YAML
added:
- v13.6.0
@ -929,6 +940,7 @@ instance of an [`Error`][] then it will be thrown instead of the
[`AssertionError`][].
## `assert.doesNotReject(asyncFn[, error][, message])`
<!-- YAML
added: v10.0.0
-->
@ -1001,6 +1013,7 @@ assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
```
## `assert.doesNotThrow(fn[, error][, message])`
<!-- YAML
added: v0.1.21
changes:
@ -1117,6 +1130,7 @@ assert.doesNotThrow(
```
## `assert.equal(actual, expected[, message])`
<!-- YAML
added: v0.1.21
changes:
@ -1187,6 +1201,7 @@ parameter is an instance of an [`Error`][] then it will be thrown instead of the
`AssertionError`.
## `assert.fail([message])`
<!-- YAML
added: v0.1.21
-->
@ -1227,6 +1242,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]]])`
<!-- YAML
added: v0.1.21
changes:
@ -1324,6 +1340,7 @@ suppressFrame();
```
## `assert.ifError(value)`
<!-- YAML
added: v0.1.97
changes:
@ -1397,6 +1414,7 @@ let err;
```
## `assert.match(string, regexp[, message])`
<!-- YAML
added:
- v13.6.0
@ -1447,6 +1465,7 @@ instance of an [`Error`][] then it will be thrown instead of the
[`AssertionError`][].
## `assert.notDeepEqual(actual, expected[, message])`
<!-- YAML
added: v0.1.21
changes:
@ -1570,6 +1589,7 @@ If the values are deeply equal, an [`AssertionError`][] is thrown with a
instead of the `AssertionError`.
## `assert.notDeepStrictEqual(actual, expected[, message])`
<!-- YAML
added: v1.2.0
changes:
@ -1629,6 +1649,7 @@ the `message` parameter is an instance of an [`Error`][] then it will be thrown
instead of the [`AssertionError`][].
## `assert.notEqual(actual, expected[, message])`
<!-- YAML
added: v0.1.21
changes:
@ -1693,6 +1714,7 @@ parameter is an instance of an [`Error`][] then it will be thrown instead of the
`AssertionError`.
## `assert.notStrictEqual(actual, expected[, message])`
<!-- YAML
added: v0.1.21
changes:
@ -1745,6 +1767,7 @@ If the values are strictly equal, an [`AssertionError`][] is thrown with a
instead of the `AssertionError`.
## `assert.ok(value[, message])`
<!-- YAML
added: v0.1.21
changes:
@ -1862,6 +1885,7 @@ assert(0);
```
## `assert.rejects(asyncFn[, error][, message])`
<!-- YAML
added: v10.0.0
-->
@ -1982,6 +2006,7 @@ example in [`assert.throws()`][] carefully if using a string as the second
argument gets considered.
## `assert.strictEqual(actual, expected[, message])`
<!-- YAML
added: v0.1.21
changes:
@ -2060,6 +2085,7 @@ If the values are not strictly equal, an [`AssertionError`][] is thrown with a
instead of the [`AssertionError`][].
## `assert.throws(fn[, error][, message])`
<!-- YAML
added: v0.1.21
changes:

View File

@ -7,6 +7,7 @@
<!-- source_link=lib/async_hooks.js -->
## 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`
<!-- YAML
added:
- v13.10.0
@ -115,6 +117,7 @@ Multiple instances can safely exist simultaneously without risk of interfering
with each other data.
### `new AsyncLocalStorage()`
<!-- YAML
added:
- v13.10.0
@ -125,6 +128,7 @@ Creates a new instance of `AsyncLocalStorage`. Store is only provided within a
`run()` call or after an `enterWith()` call.
### `asyncLocalStorage.disable()`
<!-- YAML
added:
- v13.10.0
@ -149,6 +153,7 @@ Use this method when the `asyncLocalStorage` is not in use anymore
in the current process.
### `asyncLocalStorage.getStore()`
<!-- YAML
added:
- v13.10.0
@ -163,6 +168,7 @@ calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it
returns `undefined`.
### `asyncLocalStorage.enterWith(store)`
<!-- YAML
added:
- v13.11.0
@ -212,6 +218,7 @@ asyncLocalStorage.getStore(); // Returns the same object
```
### `asyncLocalStorage.run(store, callback[, ...args])`
<!-- YAML
added:
- v13.10.0
@ -251,6 +258,7 @@ try {
```
### `asyncLocalStorage.exit(callback[, ...args])`
<!-- YAML
added:
- v13.10.0
@ -326,6 +334,7 @@ the loss. When the code logs `undefined`, the last callback called is probably
responsible for the context loss.
## Class: `AsyncResource`
<!-- YAML
changes:
- version: v16.4.0
@ -434,6 +443,7 @@ class DBQuery extends AsyncResource {
```
### Static method: `AsyncResource.bind(fn[, type, [thisArg]])`
<!-- YAML
added:
- v14.8.0
@ -455,6 +465,7 @@ The returned function will have an `asyncResource` property referencing
the `AsyncResource` to which the function is bound.
### `asyncResource.bind(fn[, thisArg])`
<!-- YAML
added:
- v14.8.0
@ -474,6 +485,7 @@ The returned function will have an `asyncResource` property referencing
the `AsyncResource` to which the function is bound.
### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])`
<!-- YAML
added: v9.6.0
-->
@ -507,6 +519,7 @@ never be called.
`AsyncResource` constructor.
<a id="async-resource-worker-pool"></a>
### Using `AsyncResource` for a `Worker` thread pool
The following example shows how to use the `AsyncResource` class to properly

View File

@ -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)`

View File

@ -83,6 +83,7 @@ const buf7 = Buffer.from('tést', 'latin1');
```
## Buffers and character encodings
<!-- YAML
changes:
- version:
@ -233,6 +234,7 @@ the WHATWG specification it is possible that the server actually returned
the characters.
## Buffers and TypedArrays
<!-- YAML
changes:
- version: v3.0.0
@ -449,6 +451,7 @@ Additionally, the [`buf.values()`][], [`buf.keys()`][], and
[`buf.entries()`][] methods can be used to create iterators.
## Class: `Blob`
<!-- YAML
added:
- v15.7.0
@ -461,6 +464,7 @@ A [`Blob`][] encapsulates immutable, raw data that can be safely shared across
multiple worker threads.
### `new buffer.Blob([sources[, options]])`
<!-- YAML
added:
- v15.7.0
@ -472,9 +476,9 @@ changes:
and removed the non-standard `encoding` option.
-->
* `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
@ -493,6 +497,7 @@ Unmatched surrogate pairs within each string part will be replaced by Unicode
U+FFFD replacement characters.
### `blob.arrayBuffer()`
<!-- YAML
added:
- v15.7.0
@ -505,6 +510,7 @@ Returns a promise that fulfills with an {ArrayBuffer} containing a copy of
the `Blob` data.
### `blob.size`
<!-- YAML
added:
- v15.7.0
@ -514,6 +520,7 @@ added:
The total size of the `Blob` in bytes.
### `blob.slice([start, [end, [type]]])`
<!-- YAML
added:
- v15.7.0
@ -528,6 +535,7 @@ Creates and returns a new `Blob` containing a subset of this `Blob` objects
data. The original `Blob` is not altered.
### `blob.stream()`
<!-- YAML
added: v16.7.0
-->
@ -537,6 +545,7 @@ added: v16.7.0
Returns a new `ReadableStream` that allows the content of the `Blob` to be read.
### `blob.text()`
<!-- YAML
added:
- v15.7.0
@ -549,6 +558,7 @@ Returns a promise that fulfills with the contents of the `Blob` decoded as a
UTF-8 string.
### `blob.type`
<!-- YAML
added:
- v15.7.0
@ -626,6 +636,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]])`
<!-- YAML
added: v5.10.0
changes:
@ -728,6 +739,7 @@ data that might not have been allocated for `Buffer`s.
A `TypeError` will be thrown if `size` is not a number.
### Static method: `Buffer.allocUnsafe(size)`
<!-- YAML
added: v5.10.0
changes:
@ -746,9 +758,9 @@ Allocates a new `Buffer` of `size` bytes. If `size` is larger than
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_ARG_VALUE`][]
is thrown.
The underlying memory for `Buffer` instances created in this way is *not
initialized*. The contents of the newly created `Buffer` are unknown and
*may contain sensitive data*. Use [`Buffer.alloc()`][] instead to initialize
The underlying memory for `Buffer` instances created in this way is _not
initialized_. The contents of the newly created `Buffer` are unknown and
_may contain sensitive data_. Use [`Buffer.alloc()`][] instead to initialize
`Buffer` instances with zeroes.
```mjs
@ -790,13 +802,14 @@ to `Buffer.poolSize >> 1` (floor of [`Buffer.poolSize`][] divided by two).
Use of this pre-allocated internal memory pool is a key difference between
calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
Specifically, `Buffer.alloc(size, fill)` will *never* use the internal `Buffer`
pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal
Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`
pool, while `Buffer.allocUnsafe(size).fill(fill)` _will_ use the internal
`Buffer` pool if `size` is less than or equal to half [`Buffer.poolSize`][]. The
difference is subtle but can be important when an application requires the
additional performance that [`Buffer.allocUnsafe()`][] provides.
### Static method: `Buffer.allocUnsafeSlow(size)`
<!-- YAML
added: v5.12.0
changes:
@ -812,9 +825,9 @@ Allocates a new `Buffer` of `size` bytes. If `size` is larger than
[`buffer.constants.MAX_LENGTH`][] or smaller than 0, [`ERR_INVALID_ARG_VALUE`][]
is thrown. A zero-length `Buffer` is created if `size` is 0.
The underlying memory for `Buffer` instances created in this way is *not
initialized*. The contents of the newly created `Buffer` are unknown and
*may contain sensitive data*. Use [`buf.fill(0)`][`buf.fill()`] to initialize
The underlying memory for `Buffer` instances created in this way is _not
initialized_. The contents of the newly created `Buffer` are unknown and
_may contain sensitive data_. Use [`buf.fill(0)`][`buf.fill()`] to initialize
such `Buffer` instances with zeroes.
When using [`Buffer.allocUnsafe()`][] to allocate new `Buffer` instances,
@ -872,6 +885,7 @@ socket.on('readable', () => {
A `TypeError` will be thrown if `size` is not a number.
### Static method: `Buffer.byteLength(string[, encoding])`
<!-- YAML
added: v0.1.90
changes:
@ -924,6 +938,7 @@ When `string` is a `Buffer`/[`DataView`][]/[`TypedArray`][]/[`ArrayBuffer`][]/
is returned.
### Static method: `Buffer.compare(buf1, buf2)`
<!-- YAML
added: v0.11.13
changes:
@ -966,6 +981,7 @@ console.log(arr.sort(Buffer.compare));
```
### Static method: `Buffer.concat(list[, totalLength])`
<!-- YAML
added: v0.7.11
changes:
@ -974,7 +990,7 @@ changes:
description: The elements of `list` can now be `Uint8Array`s.
-->
* `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.
@ -1039,11 +1055,12 @@ console.log(bufA.length);
[`Buffer.allocUnsafe()`][] does.
### Static method: `Buffer.from(array)`
<!-- YAML
added: v5.10.0
-->
* `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.
@ -1069,6 +1086,7 @@ appropriate for `Buffer.from()` variants.
`Buffer` pool like [`Buffer.allocUnsafe()`][] does.
### Static method: `Buffer.from(arrayBuffer[, byteOffset[, length]])`
<!-- YAML
added: v5.10.0
-->
@ -1184,6 +1202,7 @@ console.log(buf);
```
### Static method: `Buffer.from(buffer)`
<!-- YAML
added: v5.10.0
-->
@ -1225,6 +1244,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]])`
<!-- YAML
added: v8.2.0
-->
@ -1283,6 +1303,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])`
<!-- YAML
added: v5.10.0
-->
@ -1325,6 +1346,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)`
<!-- YAML
added: v0.1.101
-->
@ -1355,6 +1377,7 @@ Buffer.isBuffer(new Uint8Array(1024)); // false
```
### Static method: `Buffer.isEncoding(encoding)`
<!-- YAML
added: v0.9.1
-->
@ -1398,6 +1421,7 @@ console.log(Buffer.isEncoding(''));
```
### Class property: `Buffer.poolSize`
<!-- YAML
added: v0.11.3
-->
@ -1525,6 +1549,7 @@ new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
```
### `buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])`
<!-- YAML
added: v0.11.13
changes:
@ -1553,8 +1578,8 @@ comes before, after, or is the same as `target` in sort order.
Comparison is based on the actual sequence of bytes in each `Buffer`.
* `0` is returned if `target` is the same as `buf`
* `1` is returned if `target` should come *before* `buf` when sorted.
* `-1` is returned if `target` should come *after* `buf` when sorted.
* `1` is returned if `target` should come _before_ `buf` when sorted.
* `-1` is returned if `target` should come _after_ `buf` when sorted.
```mjs
import { Buffer } from 'buffer';
@ -1636,6 +1661,7 @@ console.log(buf1.compare(buf2, 5, 6, 5));
`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`.
### `buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])`
<!-- YAML
added: v0.1.90
-->
@ -1737,6 +1763,7 @@ console.log(buf.toString());
```
### `buf.entries()`
<!-- YAML
added: v1.1.0
-->
@ -1785,6 +1812,7 @@ for (const pair of buf.entries()) {
```
### `buf.equals(otherBuffer)`
<!-- YAML
added: v0.11.13
changes:
@ -1828,6 +1856,7 @@ console.log(buf1.equals(buf3));
```
### `buf.fill(value[, offset[, end]][, encoding])`
<!-- YAML
added: v0.5.0
changes:
@ -1939,6 +1968,7 @@ console.log(buf.fill('zz', 'hex'));
```
### `buf.includes(value[, byteOffset][, encoding])`
<!-- YAML
added: v5.3.0
-->
@ -1995,6 +2025,7 @@ console.log(buf.includes('this', 4));
```
### `buf.indexOf(value[, byteOffset][, encoding])`
<!-- YAML
added: v1.5.0
changes:
@ -2128,6 +2159,7 @@ than `buf.length`, `byteOffset` will be returned. If `value` is empty and
`byteOffset` is at least `buf.length`, `buf.length` will be returned.
### `buf.keys()`
<!-- YAML
added: v1.1.0
-->
@ -2171,6 +2203,7 @@ for (const key of buf.keys()) {
```
### `buf.lastIndexOf(value[, byteOffset][, encoding])`
<!-- YAML
added: v6.0.0
changes:
@ -2301,6 +2334,7 @@ console.log(b.lastIndexOf('b', []));
If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned.
### `buf.length`
<!-- YAML
added: v0.1.90
-->
@ -2342,6 +2376,7 @@ console.log(buf.length);
```
### `buf.parent`
<!-- YAML
deprecated: v8.0.0
-->
@ -2351,6 +2386,7 @@ deprecated: v8.0.0
The `buf.parent` property is a deprecated alias for `buf.buffer`.
### `buf.readBigInt64BE([offset])`
<!-- YAML
added:
- v12.0.0
@ -2367,6 +2403,7 @@ Integers read from a `Buffer` are interpreted as two's complement signed
values.
### `buf.readBigInt64LE([offset])`
<!-- YAML
added:
- v12.0.0
@ -2384,6 +2421,7 @@ Integers read from a `Buffer` are interpreted as two's complement signed
values.
### `buf.readBigUInt64BE([offset])`
<!-- YAML
added:
- v12.0.0
@ -2424,6 +2462,7 @@ console.log(buf.readBigUInt64BE(0));
```
### `buf.readBigUInt64LE([offset])`
<!-- YAML
added:
- v12.0.0
@ -2464,6 +2503,7 @@ console.log(buf.readBigUInt64LE(0));
```
### `buf.readDoubleBE([offset])`
<!-- YAML
added: v0.11.15
changes:
@ -2498,6 +2538,7 @@ console.log(buf.readDoubleBE(0));
```
### `buf.readDoubleLE([offset])`
<!-- YAML
added: v0.11.15
changes:
@ -2536,6 +2577,7 @@ console.log(buf.readDoubleLE(1));
```
### `buf.readFloatBE([offset])`
<!-- YAML
added: v0.11.15
changes:
@ -2570,6 +2612,7 @@ console.log(buf.readFloatBE(0));
```
### `buf.readFloatLE([offset])`
<!-- YAML
added: v0.11.15
changes:
@ -2608,6 +2651,7 @@ console.log(buf.readFloatLE(1));
```
### `buf.readInt8([offset])`
<!-- YAML
added: v0.5.0
changes:
@ -2652,6 +2696,7 @@ console.log(buf.readInt8(2));
```
### `buf.readInt16BE([offset])`
<!-- YAML
added: v0.5.5
changes:
@ -2688,6 +2733,7 @@ console.log(buf.readInt16BE(0));
```
### `buf.readInt16LE([offset])`
<!-- YAML
added: v0.5.5
changes:
@ -2729,6 +2775,7 @@ console.log(buf.readInt16LE(1));
```
### `buf.readInt32BE([offset])`
<!-- YAML
added: v0.5.5
changes:
@ -2765,6 +2812,7 @@ console.log(buf.readInt32BE(0));
```
### `buf.readInt32LE([offset])`
<!-- YAML
added: v0.5.5
changes:
@ -2806,6 +2854,7 @@ console.log(buf.readInt32LE(1));
```
### `buf.readIntBE(offset, byteLength)`
<!-- YAML
added: v0.11.15
changes:
@ -2852,6 +2901,7 @@ console.log(buf.readIntBE(1, 0).toString(16));
```
### `buf.readIntLE(offset, byteLength)`
<!-- YAML
added: v0.11.15
changes:
@ -2890,6 +2940,7 @@ console.log(buf.readIntLE(0, 6).toString(16));
```
### `buf.readUInt8([offset])`
<!-- YAML
added: v0.5.0
changes:
@ -2939,6 +2990,7 @@ console.log(buf.readUInt8(2));
```
### `buf.readUInt16BE([offset])`
<!-- YAML
added: v0.5.5
changes:
@ -2985,6 +3037,7 @@ console.log(buf.readUInt16BE(1).toString(16));
```
### `buf.readUInt16LE([offset])`
<!-- YAML
added: v0.5.5
changes:
@ -3035,6 +3088,7 @@ console.log(buf.readUInt16LE(2).toString(16));
```
### `buf.readUInt32BE([offset])`
<!-- YAML
added: v0.5.5
changes:
@ -3077,6 +3131,7 @@ console.log(buf.readUInt32BE(0).toString(16));
```
### `buf.readUInt32LE([offset])`
<!-- YAML
added: v0.5.5
changes:
@ -3123,6 +3178,7 @@ console.log(buf.readUInt32LE(1).toString(16));
```
### `buf.readUIntBE(offset, byteLength)`
<!-- YAML
added: v0.11.15
changes:
@ -3172,6 +3228,7 @@ console.log(buf.readUIntBE(1, 6).toString(16));
```
### `buf.readUIntLE(offset, byteLength)`
<!-- YAML
added: v0.11.15
changes:
@ -3217,6 +3274,7 @@ console.log(buf.readUIntLE(0, 6).toString(16));
```
### `buf.subarray([start[, end]])`
<!-- YAML
added: v3.0.0
-->
@ -3325,6 +3383,7 @@ console.log(buf.subarray(-5, -2).toString());
```
### `buf.slice([start[, end]])`
<!-- YAML
added: v0.3.0
changes:
@ -3383,6 +3442,7 @@ console.log(buf.toString());
```
### `buf.swap16()`
<!-- YAML
added: v5.10.0
-->
@ -3390,7 +3450,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
@ -3449,6 +3509,7 @@ buf.swap16(); // Convert to big-endian UTF-16 text.
```
### `buf.swap32()`
<!-- YAML
added: v5.10.0
-->
@ -3456,7 +3517,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
@ -3498,13 +3559,14 @@ buf2.swap32();
```
### `buf.swap64()`
<!-- YAML
added: v6.3.0
-->
* 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
@ -3546,6 +3608,7 @@ buf2.swap64();
```
### `buf.toJSON()`
<!-- YAML
added: v0.9.2
-->
@ -3597,6 +3660,7 @@ console.log(copy);
```
### `buf.toString([encoding[, start[, end]]])`
<!-- YAML
added: v0.1.90
-->
@ -3667,6 +3731,7 @@ console.log(buf2.toString(undefined, 0, 3));
```
### `buf.values()`
<!-- YAML
added: v1.1.0
-->
@ -3733,6 +3798,7 @@ for (const value of buf) {
```
### `buf.write(string[, offset[, length]][, encoding])`
<!-- YAML
added: v0.1.90
-->
@ -3787,6 +3853,7 @@ console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
```
### `buf.writeBigInt64BE(value[, offset])`
<!-- YAML
added:
- v12.0.0
@ -3825,6 +3892,7 @@ console.log(buf);
```
### `buf.writeBigInt64LE(value[, offset])`
<!-- YAML
added:
- v12.0.0
@ -3863,6 +3931,7 @@ console.log(buf);
```
### `buf.writeBigUInt64BE(value[, offset])`
<!-- YAML
added:
- v12.0.0
@ -3907,6 +3976,7 @@ console.log(buf);
```
### `buf.writeBigUInt64LE(value[, offset])`
<!-- YAML
added:
- v12.0.0
@ -3951,6 +4021,7 @@ console.log(buf);
This function is also available under the `writeBigUint64LE` alias.
### `buf.writeDoubleBE(value[, offset])`
<!-- YAML
added: v0.11.15
changes:
@ -3992,6 +4063,7 @@ console.log(buf);
```
### `buf.writeDoubleLE(value[, offset])`
<!-- YAML
added: v0.11.15
changes:
@ -4033,6 +4105,7 @@ console.log(buf);
```
### `buf.writeFloatBE(value[, offset])`
<!-- YAML
added: v0.11.15
changes:
@ -4073,6 +4146,7 @@ console.log(buf);
```
### `buf.writeFloatLE(value[, offset])`
<!-- YAML
added: v0.11.15
changes:
@ -4113,6 +4187,7 @@ console.log(buf);
```
### `buf.writeInt8(value[, offset])`
<!-- YAML
added: v0.5.0
changes:
@ -4158,6 +4233,7 @@ console.log(buf);
```
### `buf.writeInt16BE(value[, offset])`
<!-- YAML
added: v0.5.5
changes:
@ -4201,6 +4277,7 @@ console.log(buf);
```
### `buf.writeInt16LE(value[, offset])`
<!-- YAML
added: v0.5.5
changes:
@ -4244,6 +4321,7 @@ console.log(buf);
```
### `buf.writeInt32BE(value[, offset])`
<!-- YAML
added: v0.5.5
changes:
@ -4287,6 +4365,7 @@ console.log(buf);
```
### `buf.writeInt32LE(value[, offset])`
<!-- YAML
added: v0.5.5
changes:
@ -4330,6 +4409,7 @@ console.log(buf);
```
### `buf.writeIntBE(value, offset, byteLength)`
<!-- YAML
added: v0.11.15
changes:
@ -4373,6 +4453,7 @@ console.log(buf);
```
### `buf.writeIntLE(value, offset, byteLength)`
<!-- YAML
added: v0.11.15
changes:
@ -4416,6 +4497,7 @@ console.log(buf);
```
### `buf.writeUInt8(value[, offset])`
<!-- YAML
added: v0.5.0
changes:
@ -4470,6 +4552,7 @@ console.log(buf);
```
### `buf.writeUInt16BE(value[, offset])`
<!-- YAML
added: v0.5.5
changes:
@ -4520,6 +4603,7 @@ console.log(buf);
```
### `buf.writeUInt16LE(value[, offset])`
<!-- YAML
added: v0.5.5
changes:
@ -4570,6 +4654,7 @@ console.log(buf);
```
### `buf.writeUInt32BE(value[, offset])`
<!-- YAML
added: v0.5.5
changes:
@ -4618,6 +4703,7 @@ console.log(buf);
```
### `buf.writeUInt32LE(value[, offset])`
<!-- YAML
added: v0.5.5
changes:
@ -4666,6 +4752,7 @@ console.log(buf);
```
### `buf.writeUIntBE(value, offset, byteLength)`
<!-- YAML
added: v0.5.5
changes:
@ -4716,6 +4803,7 @@ console.log(buf);
```
### `buf.writeUIntLE(value, offset, byteLength)`
<!-- YAML
added: v0.5.5
changes:
@ -4766,6 +4854,7 @@ console.log(buf);
```
### `new Buffer(array)`
<!-- YAML
deprecated: v6.0.0
changes:
@ -4783,11 +4872,12 @@ changes:
> Stability: 0 - Deprecated: Use [`Buffer.from(array)`][] instead.
* `array` {integer[]} An array of bytes to copy from.
* `array` {integer\[]} An array of bytes to copy from.
See [`Buffer.from(array)`][].
### `new Buffer(arrayBuffer[, byteOffset[, length]])`
<!-- YAML
added: v3.0.0
deprecated: v6.0.0
@ -4821,6 +4911,7 @@ See
[`Buffer.from(arrayBuffer[, byteOffset[, length]])`][`Buffer.from(arrayBuf)`].
### `new Buffer(buffer)`
<!-- YAML
deprecated: v6.0.0
changes:
@ -4844,6 +4935,7 @@ changes:
See [`Buffer.from(buffer)`][].
### `new Buffer(size)`
<!-- YAML
deprecated: v6.0.0
changes:
@ -4872,6 +4964,7 @@ See [`Buffer.alloc()`][] and [`Buffer.allocUnsafe()`][]. This variant of the
constructor is equivalent to [`Buffer.alloc()`][].
### `new Buffer(string[, encoding])`
<!-- YAML
deprecated: v6.0.0
changes:
@ -4902,6 +4995,7 @@ While, the `Buffer` object is available as a global, there are additional
accessed using `require('buffer')`.
### `buffer.atob(data)`
<!-- YAML
added:
- v15.13.0
@ -4925,6 +5019,7 @@ and binary data should be performed using `Buffer.from(str, 'base64')` and
`buf.toString('base64')`.**
### `buffer.btoa(data)`
<!-- YAML
added:
- v15.13.0
@ -4948,6 +5043,7 @@ and binary data should be performed using `Buffer.from(str, 'base64')` and
`buf.toString('base64')`.**
### `buffer.INSPECT_MAX_BYTES`
<!-- YAML
added: v0.5.4
-->
@ -4959,6 +5055,7 @@ Returns the maximum number of bytes that will be returned when
[`util.inspect()`][] for more details on `buf.inspect()` behavior.
### `buffer.kMaxLength`
<!-- YAML
added: v3.0.0
-->
@ -4968,6 +5065,7 @@ added: v3.0.0
An alias for [`buffer.constants.MAX_LENGTH`][].
### `buffer.kStringMaxLength`
<!-- YAML
added: v3.0.0
-->
@ -4977,6 +5075,7 @@ added: v3.0.0
An alias for [`buffer.constants.MAX_STRING_LENGTH`][].
### `buffer.resolveObjectURL(id)`
<!-- YAML
added: v16.7.0
-->
@ -4991,6 +5090,7 @@ Resolves a `'blob:nodedata:...'` an associated {Blob} object registered using
a prior call to `URL.createObjectURL()`.
### `buffer.transcode(source, fromEnc, toEnc)`
<!-- YAML
added: v7.1.0
changes:
@ -5036,6 +5136,7 @@ Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced
with `?` in the transcoded `Buffer`.
### Class: `SlowBuffer`
<!-- YAML
deprecated: v6.0.0
-->
@ -5047,6 +5148,7 @@ the constructor always returned a `Buffer` instance, rather than a `SlowBuffer`
instance.
#### `new SlowBuffer(size)`
<!-- YAML
deprecated: v6.0.0
-->
@ -5058,11 +5160,13 @@ deprecated: v6.0.0
See [`Buffer.allocUnsafeSlow()`][].
### Buffer constants
<!-- YAML
added: v8.2.0
-->
#### `buffer.constants.MAX_LENGTH`
<!-- YAML
added: v8.2.0
changes:
@ -5088,6 +5192,7 @@ It reflects [`v8::TypedArray::kMaxLength`][] under the hood.
This value is also available as [`buffer.kMaxLength`][].
#### `buffer.constants.MAX_STRING_LENGTH`
<!-- YAML
added: v8.2.0
-->
@ -5107,11 +5212,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
@ -5145,18 +5250,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
@ -5169,12 +5274,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
<!-- YAML
added: v5.10.0
-->
@ -5196,14 +5302,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

View File

@ -143,6 +143,7 @@ exec('"my script.cmd" a b', (err, stdout, stderr) => {
```
### `child_process.exec(command[, options][, callback])`
<!-- YAML
added: v0.1.90
changes:
@ -190,7 +191,7 @@ changes:
Spawns a shell then executes the `command` within that shell, buffering any
generated output. The `command` string passed to the exec function is processed
directly by the shell and special characters (vary based on
[shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters))
[shell](https://en.wikipedia.org/wiki/List\_of\_command-line\_interpreters))
need to be dealt with accordingly:
```js
@ -274,6 +275,7 @@ controller.abort();
```
### `child_process.execFile(file[, args][, options][, callback])`
<!-- YAML
added: v0.1.91
changes:
@ -294,7 +296,7 @@ changes:
-->
* `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`.
@ -385,6 +387,7 @@ controller.abort();
```
### `child_process.fork(modulePath[, args][, options])`
<!-- YAML
added: v0.5.0
changes:
@ -423,7 +426,7 @@ changes:
-->
* `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
@ -431,7 +434,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
@ -506,6 +509,7 @@ if (process.argv[2] === 'child') {
```
### `child_process.spawn(command[, args][, options])`
<!-- YAML
added: v0.1.90
changes:
@ -547,7 +551,7 @@ changes:
-->
* `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`.
@ -578,7 +582,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
@ -701,6 +704,7 @@ controller.abort(); // Stops the child process
```
#### `options.detached`
<!-- YAML
added: v0.7.10
-->
@ -759,6 +763,7 @@ subprocess.unref();
```
#### `options.stdio`
<!-- YAML
added: v0.7.10
changes:
@ -796,13 +801,13 @@ pipes between the parent and child. The value is one of the following:
`child_process` object as [`subprocess.stdio[fd]`][`subprocess.stdio`]. Pipes
created for fds 0, 1, and 2 are also available as [`subprocess.stdin`][],
[`subprocess.stdout`][] and [`subprocess.stderr`][], respectively.
1. `'overlapped'`: Same as `'pipe'` except that the `FILE_FLAG_OVERLAPPED` flag
2. `'overlapped'`: Same as `'pipe'` except that the `FILE_FLAG_OVERLAPPED` flag
is set on the handle. This is necessary for overlapped I/O on the child
process's stdio handles. See the
[docs](https://docs.microsoft.com/en-us/windows/win32/fileio/synchronous-and-asynchronous-i-o)
for more details. This is exactly the same as `'pipe'` on non-Windows
systems.
1. `'ipc'`: Create an IPC channel for passing messages/file descriptors
3. `'ipc'`: Create an IPC channel for passing messages/file descriptors
between parent and child. A [`ChildProcess`][] may have at most one IPC
stdio file descriptor. Setting this option enables the
[`subprocess.send()`][] method. If the child is a Node.js process, the
@ -813,25 +818,25 @@ pipes between the parent and child. The value is one of the following:
Accessing the IPC channel fd in any way other than [`process.send()`][]
or using the IPC channel with a child process that is not a Node.js instance
is not supported.
1. `'ignore'`: Instructs Node.js to ignore the fd in the child. While Node.js
4. `'ignore'`: Instructs Node.js to ignore the fd in the child. While Node.js
will always open fds 0, 1, and 2 for the processes it spawns, setting the fd
to `'ignore'` will cause Node.js to open `/dev/null` and attach it to the
child's fd.
1. `'inherit'`: Pass through the corresponding stdio stream to/from the
5. `'inherit'`: Pass through the corresponding stdio stream to/from the
parent process. In the first three positions, this is equivalent to
`process.stdin`, `process.stdout`, and `process.stderr`, respectively. In
any other position, equivalent to `'ignore'`.
1. {Stream} object: Share a readable or writable stream that refers to a tty,
6. {Stream} object: Share a readable or writable stream that refers to a tty,
file, socket, or a pipe with the child process. The stream's underlying
file descriptor is duplicated in the child process to the fd that
corresponds to the index in the `stdio` array. The stream must have an
underlying descriptor (file streams do not until the `'open'` event has
occurred).
1. Positive integer: The integer value is interpreted as a file descriptor
7. Positive integer: The integer value is interpreted as a file descriptor
that is currently open in the parent process. It is shared with the child
process, similar to how {Stream} objects can be shared. Passing sockets
is not supported on Windows.
1. `null`, `undefined`: Use default value. For stdio fds 0, 1, and 2 (in other
8. `null`, `undefined`: Use default value. For stdio fds 0, 1, and 2 (in other
words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
default is `'ignore'`.
@ -849,12 +854,12 @@ spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
```
*It is worth noting that when an IPC channel is established between the
_It is worth noting that when an IPC channel is established between the
parent and child processes, and the child is a Node.js process, the child
is launched with the IPC channel unreferenced (using `unref()`) until the
child registers an event handler for the [`'disconnect'`][] event
or the [`'message'`][] event. This allows the child to exit
normally without the process being held open by the open IPC channel.*
normally without the process being held open by the open IPC channel._
On Unix-like operating systems, the [`child_process.spawn()`][] method
performs memory operations synchronously before decoupling the event loop
@ -876,6 +881,7 @@ scripting tasks and for simplifying the loading/processing of application
configuration at startup.
### `child_process.execFileSync(file[, args][, options])`
<!-- YAML
added: v0.11.12
changes:
@ -903,7 +909,7 @@ changes:
-->
* `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
@ -951,6 +957,7 @@ function. Any input containing shell metacharacters may be used to trigger
arbitrary command execution.**
### `child_process.execSync(command[, options])`
<!-- YAML
added: v0.11.12
changes:
@ -1017,6 +1024,7 @@ The [`Error`][] object will contain the entire result from
metacharacters may be used to trigger arbitrary command execution.**
### `child_process.spawnSync(command[, args][, options])`
<!-- YAML
added: v0.11.12
changes:
@ -1047,7 +1055,7 @@ changes:
-->
* `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
@ -1102,6 +1110,7 @@ function. Any input containing shell metacharacters may be used to trigger
arbitrary command execution.**
## Class: `ChildProcess`
<!-- YAML
added: v2.2.0
-->
@ -1116,6 +1125,7 @@ use the [`child_process.spawn()`][], [`child_process.exec()`][],
instances of `ChildProcess`.
### Event: `'close'`
<!-- YAML
added: v0.7.7
-->
@ -1147,6 +1157,7 @@ ls.on('exit', (code) => {
```
### Event: `'disconnect'`
<!-- YAML
added: v0.7.2
-->
@ -1174,6 +1185,7 @@ against accidentally invoking handler functions multiple times.
See also [`subprocess.kill()`][] and [`subprocess.send()`][].
### Event: `'exit'`
<!-- YAML
added: v0.1.90
-->
@ -1197,6 +1209,7 @@ re-raise the handled signal.
See waitpid(2).
### Event: `'message'`
<!-- YAML
added: v0.5.9
-->
@ -1217,6 +1230,7 @@ to represent.
See [Advanced serialization][] for more details.
### Event: `'spawn'`
<!-- YAML
added:
- v15.1.0
@ -1236,6 +1250,7 @@ the `'spawn'` event will fire, though `bash` may fail to spawn `some-command`.
This caveat also applies when using `{ shell: true }`.
### `subprocess.channel`
<!-- YAML
added: v7.1.0
changes:
@ -1250,6 +1265,7 @@ The `subprocess.channel` property is a reference to the child's IPC channel. If
no IPC channel currently exists, this property is `undefined`.
#### `subprocess.channel.ref()`
<!-- YAML
added: v7.1.0
-->
@ -1258,6 +1274,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()`
<!-- YAML
added: v7.1.0
-->
@ -1266,6 +1283,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`
<!-- YAML
added: v0.7.2
-->
@ -1277,6 +1295,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()`
<!-- YAML
added: v0.7.2
-->
@ -1303,6 +1322,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])`
<!-- YAML
added: v0.1.90
-->
@ -1370,6 +1390,7 @@ setTimeout(() => {
```
### `subprocess.killed`
<!-- YAML
added: v0.5.10
-->
@ -1382,6 +1403,7 @@ successfully received a signal from `subprocess.kill()`. The `killed` property
does not indicate that the child process has been terminated.
### `subprocess.pid`
<!-- YAML
added: v0.1.90
-->
@ -1401,6 +1423,7 @@ grep.stdin.end();
```
### `subprocess.ref()`
<!-- YAML
added: v0.7.10
-->
@ -1422,6 +1445,7 @@ subprocess.ref();
```
### `subprocess.send(message[, sendHandle[, options]][, callback])`
<!-- YAML
added: v0.5.9
changes:
@ -1629,6 +1653,7 @@ For [`child_process.exec()`][], its value will be the name of the shell
in which the child process is launched.
### `subprocess.stderr`
<!-- YAML
added: v0.1.90
-->
@ -1647,6 +1672,7 @@ The `subprocess.stderr` property can be `null` if the child process could
not be successfully spawned.
### `subprocess.stdin`
<!-- YAML
added: v0.1.90
-->
@ -1668,6 +1694,7 @@ The `subprocess.stdin` property can be `undefined` if the child process could
not be successfully spawned.
### `subprocess.stdio`
<!-- YAML
added: v0.7.10
-->
@ -1711,6 +1738,7 @@ The `subprocess.stdio` property can be `undefined` if the child process could
not be successfully spawned.
### `subprocess.stdout`
<!-- YAML
added: v0.1.90
-->
@ -1739,6 +1767,7 @@ The `subprocess.stdout` property can be `null` if the child process could
not be successfully spawned.
### `subprocess.unref()`
<!-- YAML
added: v0.7.10
-->
@ -1784,6 +1813,7 @@ spawned, `'cmd.exe'` is used as a fallback if `process.env.ComSpec` is
unavailable.
## Advanced serialization
<!-- YAML
added:
- v13.2.0

View File

@ -22,6 +22,7 @@ Execute without arguments to start the [REPL][].
For more info about `node inspect`, see the [debugger][] documentation.
## Options
<!-- YAML
changes:
- version: v10.12.0
@ -40,6 +41,7 @@ command line take precedence over options passed through the [`NODE_OPTIONS`][]
environment variable.
### `-`
<!-- YAML
added: v8.0.0
-->
@ -49,6 +51,7 @@ meaning that the script is read from stdin, and the rest of the options
are passed to that script.
### `--`
<!-- YAML
added: v6.11.0
-->
@ -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`
<!-- YAML
added: v0.10.8
-->
@ -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`
<!-- YAML
added: v10.12.0
-->
@ -82,6 +87,7 @@ $ source node_bash_completion
```
### `-C=condition`, `--conditions=condition`
<!-- YAML
added:
- v14.9.0
@ -105,6 +111,7 @@ $ node -C=development app.js
```
### `--cpu-prof`
<!-- YAML
added: v12.0.0
-->
@ -127,6 +134,7 @@ CPU.20190409.202950.15293.0.0.cpuprofile
```
### `--cpu-prof-dir`
<!-- YAML
added: v12.0.0
-->
@ -140,6 +148,7 @@ The default value is controlled by the
[`--diagnostic-dir`][] command-line option.
### `--cpu-prof-interval`
<!-- YAML
added: v12.2.0
-->
@ -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`
<!-- YAML
added: v12.0.0
-->
@ -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`
<!-- YAML
added:
- v13.12.0
@ -180,6 +192,7 @@ property is removed entirely. If `mode` is `throw`, accesses to the
property throw an exception with the code `ERR_PROTO_ACCESS`.
### `--disallow-code-generation-from-strings`
<!-- YAML
added: v9.8.0
-->
@ -189,6 +202,7 @@ code from strings throw an exception instead. This does not affect the Node.js
`vm` module.
### `--dns-result-order=order`
<!-- YAML
added:
- v16.4.0
@ -197,6 +211,7 @@ added:
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`.
@ -204,6 +219,7 @@ The default is `ipv4first` and [`dns.setDefaultResultOrder()`][] have higher
priority than `--dns-result-order`.
### `--enable-fips`
<!-- YAML
added: v6.0.0
-->
@ -212,6 +228,7 @@ Enable FIPS-compliant crypto at startup. (Requires Node.js to be built
against FIPS-compatible OpenSSL.)
### `--enable-source-maps`
<!-- YAML
added: v12.12.0
changes:
@ -233,6 +250,7 @@ Overriding `Error.prepareStackTrace` prevents `--enable-source-maps` from
modifying the stack trace.
### `--experimental-abortcontroller`
<!-- YAML
added:
- v15.0.0
@ -247,6 +265,7 @@ changes:
Use of this command-line flag is no longer required.
### `--experimental-import-meta-resolve`
<!-- YAML
added:
- v13.9.0
@ -256,6 +275,7 @@ added:
Enable experimental `import.meta.resolve()` support.
### `--experimental-json-modules`
<!-- YAML
added: v12.9.0
-->
@ -263,6 +283,7 @@ added: v12.9.0
Enable experimental JSON support for the ES Module loader.
### `--experimental-loader=module`
<!-- YAML
added: v9.0.0
-->
@ -271,6 +292,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`
<!-- YAML
added: v8.5.0
-->
@ -278,6 +300,7 @@ added: v8.5.0
Enable latest experimental modules features (deprecated).
### `--experimental-policy`
<!-- YAML
added: v11.8.0
-->
@ -285,12 +308,15 @@ added: v11.8.0
Use the specified file as a security policy.
### `--no-experimental-repl-await`
<!-- YAML
added: v16.6.0
-->
Use this flag to disable top-level await in REPL.
Use this flag to disable top-level await in REPL.
### `--experimental-specifier-resolution=mode`
<!-- YAML
added:
- v13.4.0
@ -307,6 +333,7 @@ the ability to import a directory that has an index file.
See [customizing ESM specifier resolution][] for example usage.
### `--experimental-vm-modules`
<!-- YAML
added: v9.6.0
-->
@ -314,6 +341,7 @@ added: v9.6.0
Enable experimental ES Module support in the `vm` module.
### `--experimental-wasi-unstable-preview1`
<!-- YAML
added:
- v13.3.0
@ -328,6 +356,7 @@ changes:
Enable experimental WebAssembly System Interface (WASI) support.
### `--experimental-wasm-modules`
<!-- YAML
added: v12.3.0
-->
@ -335,6 +364,7 @@ added: v12.3.0
Enable experimental WebAssembly module support.
### `--force-context-aware`
<!-- YAML
added: v12.12.0
-->
@ -342,6 +372,7 @@ added: v12.12.0
Disable loading native addons that are not [context-aware][].
### `--force-fips`
<!-- YAML
added: v6.0.0
-->
@ -350,6 +381,7 @@ Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.)
(Same requirements as `--enable-fips`.)
### `--frozen-intrinsics`
<!-- YAML
added: v11.12.0
-->
@ -366,6 +398,7 @@ reference. Code may break under this flag.
be added.
### `--heapsnapshot-near-heap-limit=max_count`
<!-- YAML
added:
- v15.1.0
@ -414,6 +447,7 @@ FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaS
```
### `--heapsnapshot-signal=signal`
<!-- YAML
added: v12.0.0
-->
@ -433,6 +467,7 @@ Heap.20190718.133405.15554.0.001.heapsnapshot
```
### `--heap-prof`
<!-- YAML
added: v12.4.0
-->
@ -455,6 +490,7 @@ Heap.20190409.202950.15293.0.001.heapprofile
```
### `--heap-prof-dir`
<!-- YAML
added: v12.4.0
-->
@ -468,6 +504,7 @@ The default value is controlled by the
[`--diagnostic-dir`][] command-line option.
### `--heap-prof-interval`
<!-- YAML
added: v12.4.0
-->
@ -475,9 +512,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`
<!-- YAML
added: v12.4.0
-->
@ -487,6 +525,7 @@ added: v12.4.0
Specify the file name of the heap profile generated by `--heap-prof`.
### `--icu-data-dir=file`
<!-- YAML
added: v0.11.15
-->
@ -494,6 +533,7 @@ added: v0.11.15
Specify ICU data load path. (Overrides `NODE_ICU_DATA`.)
### `--input-type=type`
<!-- YAML
added: v12.0.0
-->
@ -504,6 +544,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]`
<!-- YAML
added: v7.6.0
-->
@ -512,6 +553,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`
<!-- YAML
added: v7.6.0
-->
@ -525,6 +567,7 @@ See the [security warning][] below regarding the `host`
parameter usage.
### `--inspect[=[host:]port]`
<!-- YAML
added: v6.3.0
-->
@ -536,7 +579,9 @@ and profile Node.js instances. The tools attach to Node.js instances via a
tcp port and communicate using the [Chrome DevTools Protocol][].
<!-- Anchor to make sure old links find a target -->
<a id="inspector_security"></a>
#### 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
@ -561,6 +606,7 @@ By default inspector websocket url is available in stderr and under `/json/list`
endpoint on `http://host:port/json/list`.
### `--insecure-http-parser`
<!-- YAML
added:
- v13.4.0
@ -574,6 +620,7 @@ request smuggling and other HTTP attacks that rely on invalid headers being
accepted. Avoid using this option.
### `--jitless`
<!-- YAML
added: v12.0.0
-->
@ -586,6 +633,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`
<!-- YAML
added:
- v11.6.0
@ -599,6 +647,7 @@ changes:
Specify the maximum size, in bytes, of HTTP headers. Defaults to 16 KB.
### `--napi-modules`
<!-- YAML
added: v7.10.0
-->
@ -606,6 +655,7 @@ added: v7.10.0
This option is a no-op. It is kept for compatibility.
### `--no-addons`
<!-- YAML
added: v16.10.0
-->
@ -615,6 +665,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`
<!-- YAML
added: v0.8.0
-->
@ -622,6 +673,7 @@ added: v0.8.0
Silence deprecation warnings.
### `--no-extra-info-on-fatal-exception`
<!-- YAML
added: v17.0.0
-->
@ -629,6 +681,7 @@ added: v17.0.0
Hide extra information on fatal exception that causes exit.
### `--no-force-async-hooks-checks`
<!-- YAML
added: v9.0.0
-->
@ -637,6 +690,7 @@ Disables runtime checks for `async_hooks`. These will still be enabled
dynamically when `async_hooks` is enabled.
### `--no-global-search-paths`
<!-- YAML
added: v16.10.0
-->
@ -645,6 +699,7 @@ Do not search modules from global paths like `$HOME/.node_modules` and
`$NODE_PATH`.
### `--no-warnings`
<!-- YAML
added: v6.0.0
-->
@ -652,6 +707,7 @@ added: v6.0.0
Silence all process warnings (including deprecations).
### `--node-memory-debug`
<!-- YAML
added:
- v15.0.0
@ -662,6 +718,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`
<!-- YAML
added: v6.9.0
-->
@ -671,14 +728,16 @@ used to enable FIPS-compliant crypto if Node.js is built
against FIPS-enabled OpenSSL.
### `--openssl-legacy-provider`
<!-- YAML
added: v17.0.0
-->
Enable OpenSSL 3.0 legacy provider. For more information please see
[OSSL_PROVIDER-legacy][].
[OSSL\_PROVIDER-legacy][OSSL_PROVIDER-legacy].
### `--pending-deprecation`
<!-- YAML
added: v8.0.0
-->
@ -686,13 +745,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`
<!-- YAML
added: v12.7.0
-->
@ -704,6 +764,7 @@ the specified integrity. It expects a [Subresource Integrity][] string as a
parameter.
### `--preserve-symlinks`
<!-- YAML
added: v6.3.0
-->
@ -738,7 +799,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).
@ -748,6 +809,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`
<!-- YAML
added: v10.2.0
-->
@ -767,6 +829,7 @@ resolving relative paths.
See `--preserve-symlinks` for more information.
### `--prof`
<!-- YAML
added: v2.0.0
-->
@ -774,6 +837,7 @@ added: v2.0.0
Generate V8 profiler output.
### `--prof-process`
<!-- YAML
added: v5.2.0
-->
@ -781,6 +845,7 @@ added: v5.2.0
Process V8 profiler output generated using the V8 option `--prof`.
### `--redirect-warnings=file`
<!-- YAML
added: v8.0.0
-->
@ -795,6 +860,7 @@ will be written to is controlled by the
[`--diagnostic-dir`]() command-line option.
### `--report-compact`
<!-- YAML
added:
- v13.12.0
@ -806,6 +872,7 @@ by log processing systems than the default multi-line format designed for
human consumption.
### `--report-dir=directory`, `report-directory=directory`
<!-- YAML
added: v11.8.0
changes:
@ -823,6 +890,7 @@ changes:
Location at which the report will be generated.
### `--report-filename=filename`
<!-- YAML
added: v11.8.0
changes:
@ -840,6 +908,7 @@ changes:
Name of the file to which the report will be written.
### `--report-on-fatalerror`
<!-- YAML
added: v11.8.0
changes:
@ -862,6 +931,7 @@ stack, event loop state, resource consumption etc. to reason about the fatal
error.
### `--report-on-signal`
<!-- YAML
added: v11.8.0
changes:
@ -881,6 +951,7 @@ signal to the running Node.js process. The signal to trigger the report is
specified through `--report-signal`.
### `--report-signal=signal`
<!-- YAML
added: v11.8.0
changes:
@ -899,6 +970,7 @@ Sets or resets the signal for report generation (not supported on Windows).
Default signal is `SIGUSR2`.
### `--report-uncaught-exception`
<!-- YAML
added: v11.8.0
changes:
@ -918,6 +990,7 @@ the JavaScript stack in conjunction with native stack and other runtime
environment data.
### `--secure-heap=n`
<!-- YAML
added: v15.6.0
-->
@ -942,6 +1015,7 @@ The secure heap is not available on Windows.
See [`CRYPTO_secure_malloc_init`][] for more details.
### `--secure-heap-min=n`
<!-- YAML
added: v15.6.0
-->
@ -952,6 +1026,7 @@ The maximum value is the lesser of `--secure-heap` or `2147483647`.
The value given must be a power of two.
### `--throw-deprecation`
<!-- YAML
added: v0.11.14
-->
@ -959,6 +1034,7 @@ added: v0.11.14
Throw errors for deprecations.
### `--title=title`
<!-- YAML
added: v10.7.0
-->
@ -966,6 +1042,7 @@ added: v10.7.0
Set `process.title` on startup.
### `--tls-cipher-list=list`
<!-- YAML
added: v4.0.0
-->
@ -974,6 +1051,7 @@ Specify an alternative default TLS cipher list. Requires Node.js to be built
with crypto support (default).
### `--tls-keylog=file`
<!-- YAML
added:
- v13.2.0
@ -985,6 +1063,7 @@ format and can be used by software (such as Wireshark) to decrypt the TLS
traffic.
### `--tls-max-v1.2`
<!-- YAML
added:
- v12.0.0
@ -995,6 +1074,7 @@ Set [`tls.DEFAULT_MAX_VERSION`][] to 'TLSv1.2'. Use to disable support for
TLSv1.3.
### `--tls-max-v1.3`
<!-- YAML
added: v12.0.0
-->
@ -1003,6 +1083,7 @@ Set default [`tls.DEFAULT_MAX_VERSION`][] to 'TLSv1.3'. Use to enable support
for TLSv1.3.
### `--tls-min-v1.0`
<!-- YAML
added:
- v12.0.0
@ -1013,6 +1094,7 @@ Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1'. Use for compatibility with
old TLS clients or servers.
### `--tls-min-v1.1`
<!-- YAML
added:
- v12.0.0
@ -1023,6 +1105,7 @@ Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.1'. Use for compatibility
with old TLS clients or servers.
### `--tls-min-v1.2`
<!-- YAML
added:
- v12.2.0
@ -1034,6 +1117,7 @@ Set default [`tls.DEFAULT_MIN_VERSION`][] to 'TLSv1.2'. This is the default for
versions.
### `--tls-min-v1.3`
<!-- YAML
added: v12.0.0
-->
@ -1042,6 +1126,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`
<!-- YAML
added: v14.3.0
-->
@ -1069,6 +1154,7 @@ The fields here correspond to:
* The timeout passed to `Atomics.wait`
### `--trace-deprecation`
<!-- YAML
added: v0.8.0
-->
@ -1076,6 +1162,7 @@ added: v0.8.0
Print stack traces for deprecations.
### `--trace-event-categories`
<!-- YAML
added: v7.7.0
-->
@ -1084,6 +1171,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`
<!-- YAML
added: v9.8.0
-->
@ -1092,6 +1180,7 @@ Template string specifying the filepath for the trace event data, it
supports `${rotation}` and `${pid}`.
### `--trace-events-enabled`
<!-- YAML
added: v7.7.0
-->
@ -1099,6 +1188,7 @@ added: v7.7.0
Enables the collection of trace event tracing information.
### `--trace-exit`
<!-- YAML
added:
- v13.5.0
@ -1109,6 +1199,7 @@ Prints a stack trace whenever an environment is exited proactively,
i.e. invoking `process.exit()`.
### `--trace-sigint`
<!-- YAML
added:
- v13.9.0
@ -1118,6 +1209,7 @@ added:
Prints a stack trace on SIGINT.
### `--trace-sync-io`
<!-- YAML
added: v2.1.0
-->
@ -1126,6 +1218,7 @@ Prints a stack trace whenever synchronous I/O is detected after the first turn
of the event loop.
### `--trace-tls`
<!-- YAML
added: v12.2.0
-->
@ -1134,6 +1227,7 @@ Prints TLS packet trace information to `stderr`. This can be used to debug TLS
connection problems.
### `--trace-uncaught`
<!-- YAML
added: v13.1.0
-->
@ -1146,6 +1240,7 @@ to be an `Error` instance).
Enabling this option may affect garbage collection behavior negatively.
### `--trace-warnings`
<!-- YAML
added: v6.0.0
-->
@ -1153,6 +1248,7 @@ added: v6.0.0
Print stack traces for process warnings (including deprecations).
### `--track-heap-objects`
<!-- YAML
added: v2.4.0
-->
@ -1160,6 +1256,7 @@ added: v2.4.0
Track heap object allocations for heap snapshots.
### `--unhandled-rejections=mode`
<!-- YAML
added:
- v12.0.0
@ -1184,6 +1281,7 @@ occurs. One of the following modes can be chosen:
* `none`: Silence all warnings.
### `--use-bundled-ca`, `--use-openssl-ca`
<!-- YAML
added: v6.11.0
-->
@ -1204,6 +1302,7 @@ environment variables.
See `SSL_CERT_DIR` and `SSL_CERT_FILE`.
### `--use-largepages=mode`
<!-- YAML
added:
- v13.6.0
@ -1215,6 +1314,7 @@ the target system, this will cause the Node.js static code to be moved onto 2
MiB pages instead of 4 KiB pages.
The following values are valid for `mode`:
* `off`: No mapping will be attempted. This is the default.
* `on`: If supported by the OS, mapping will be attempted. Failure to map will
be ignored and a message will be printed to standard error.
@ -1222,6 +1322,7 @@ The following values are valid for `mode`:
will be ignored and will not be reported.
### `--v8-options`
<!-- YAML
added: v0.1.3
-->
@ -1229,6 +1330,7 @@ added: v0.1.3
Print V8 command-line options.
### `--v8-pool-size=num`
<!-- YAML
added: v5.10.0
-->
@ -1242,6 +1344,7 @@ If the value provided is larger than V8's maximum, then the largest value
will be chosen.
### `--zero-fill-buffers`
<!-- YAML
added: v6.0.0
-->
@ -1250,6 +1353,7 @@ Automatically zero-fills all newly allocated [`Buffer`][] and [`SlowBuffer`][]
instances.
### `-c`, `--check`
<!-- YAML
added:
- v5.0.0
@ -1263,6 +1367,7 @@ changes:
Syntax check the script without executing.
### `-e`, `--eval "script"`
<!-- YAML
added: v0.5.2
changes:
@ -1279,6 +1384,7 @@ only recognizes double `"` for quoting. In Powershell or Git bash, both `'`
and `"` are usable.
### `-h`, `--help`
<!-- YAML
added: v0.1.3
-->
@ -1287,6 +1393,7 @@ Print node command-line options.
The output of this option is less detailed than this document.
### `-i`, `--interactive`
<!-- YAML
added: v0.7.7
-->
@ -1294,6 +1401,7 @@ added: v0.7.7
Opens the REPL even if stdin does not appear to be a terminal.
### `-p`, `--print "script"`
<!-- YAML
added: v0.6.4
changes:
@ -1305,6 +1413,7 @@ changes:
Identical to `-e` but prints the result.
### `-r`, `--require module`
<!-- YAML
added: v1.6.0
-->
@ -1318,6 +1427,7 @@ Only CommonJS modules are supported. Attempting to preload a
ES6 Module using `--require` will fail with an error.
### `-v`, `--version`
<!-- YAML
added: v0.1.3
-->
@ -1339,7 +1449,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[,…]`
<!-- YAML
added: v0.1.32
-->
@ -1351,6 +1463,7 @@ added: v0.1.32
`','`-separated list of core C++ modules that should print debug information.
### `NODE_DISABLE_COLORS=1`
<!-- YAML
added: v0.3.0
-->
@ -1358,6 +1471,7 @@ added: v0.3.0
When set, colors will not be used in the REPL.
### `NODE_EXTRA_CA_CERTS=file`
<!-- YAML
added: v7.3.0
-->
@ -1379,6 +1493,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`
<!-- YAML
added: v0.11.15
-->
@ -1387,6 +1502,7 @@ Data path for ICU (`Intl` object) data. Will extend linked-in data when compiled
with small-icu support.
### `NODE_NO_WARNINGS=1`
<!-- YAML
added: v6.11.0
-->
@ -1394,6 +1510,7 @@ added: v6.11.0
When set to `1`, process warnings are silenced.
### `NODE_OPTIONS=options...`
<!-- YAML
added: v8.0.0
-->
@ -1429,7 +1546,9 @@ node --require "./a.js" --require "./b.js"
```
Node.js options that are allowed are:
<!-- node-options-node start -->
* `--conditions`, `-C`
* `--diagnostic-dir`
* `--disable-proto`
@ -1516,10 +1635,13 @@ Node.js options that are allowed are:
* `--use-openssl-ca`
* `--v8-pool-size`
* `--zero-fill-buffers`
<!-- node-options-node end -->
V8 options that are allowed are:
<!-- node-options-v8 start -->
* `--abort-on-uncaught-exception`
* `--disallow-code-generation-from-strings`
* `--huge-max-old-generation-size`
@ -1531,12 +1653,14 @@ V8 options that are allowed are:
* `--perf-prof-unwinding-info`
* `--perf-prof`
* `--stack-trace-limit`
<!-- node-options-v8 end -->
`--perf-basic-prof-only-functions`, `--perf-basic-prof`,
`--perf-prof-unwinding-info`, and `--perf-prof` are only available on Linux.
### `NODE_PATH=path[:…]`
<!-- YAML
added: v0.1.32
-->
@ -1546,6 +1670,7 @@ added: v0.1.32
On Windows, this is a `';'`-separated list instead.
### `NODE_PENDING_DEPRECATION=1`
<!-- YAML
added: v8.0.0
-->
@ -1553,7 +1678,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
@ -1565,6 +1690,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`
<!-- YAML
added: v7.1.0
-->
@ -1573,6 +1699,7 @@ When set to `1`, instructs the module loader to preserve symbolic links when
resolving and caching modules.
### `NODE_REDIRECT_WARNINGS=file`
<!-- YAML
added: v8.0.0
-->
@ -1584,6 +1711,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`
<!-- YAML
added: v3.0.0
-->
@ -1593,6 +1721,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`
<!-- YAML
added:
- v13.0.0
@ -1603,6 +1732,7 @@ Path to a Node.js module which will be loaded in place of the built-in REPL.
Overriding this value to an empty string (`''`) will use the built-in REPL.
### `NODE_SKIP_PLATFORM_CHECK=value`
<!-- YAML
added: v14.5.0
-->
@ -1699,18 +1829,20 @@ and the line lengths of the source file (in the key `lineLengths`).
environment variable is arbitrary.
### `OPENSSL_CONF=file`
<!-- YAML
added: v6.11.0
-->
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`
<!-- YAML
added: v7.7.0
-->
@ -1723,6 +1855,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`
<!-- YAML
added: v7.7.0
-->
@ -1735,6 +1868,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`
<!-- YAML
added: v0.0.1
changes:

View File

@ -146,6 +146,7 @@ Although a primary use case for the `cluster` module is networking, it can
also be used for other use cases requiring worker processes.
## Class: `Worker`
<!-- YAML
added: v0.7.0
-->
@ -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'`
<!-- YAML
added: v0.7.7
-->
@ -170,6 +172,7 @@ cluster.fork().on('disconnect', () => {
```
### Event: `'error'`
<!-- YAML
added: v0.7.3
-->
@ -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'`
<!-- YAML
added: v0.11.2
-->
@ -220,6 +224,7 @@ worker.on('exit', (code, signal) => {
```
### Event: `'listening'`
<!-- YAML
added: v0.7.0
-->
@ -247,6 +252,7 @@ cluster.fork().on('listening', (address) => {
It is not emitted in the worker.
### Event: `'message'`
<!-- YAML
added: v0.7.0
-->
@ -351,6 +357,7 @@ if (cluster.isPrimary) {
```
### Event: `'online'`
<!-- YAML
added: v0.7.0
-->
@ -366,6 +373,7 @@ cluster.fork().on('online', () => {
It is not emitted in the worker.
### `worker.disconnect()`
<!-- YAML
added: v0.7.7
changes:
@ -390,7 +398,7 @@ connections will be allowed to close as usual. When no more connections exist,
see [`server.close()`][], the IPC channel to the worker will close allowing it
to die gracefully.
The above applies *only* to server connections, client connections are not
The above applies _only_ to server connections, client connections are not
automatically closed by workers, and disconnect does not wait for them to close
before exiting.
@ -436,6 +444,7 @@ if (cluster.isPrimary) {
```
### `worker.exitedAfterDisconnect`
<!-- YAML
added: v6.0.0
-->
@ -462,6 +471,7 @@ worker.kill();
```
### `worker.id`
<!-- YAML
added: v0.8.0
-->
@ -475,6 +485,7 @@ While a worker is alive, this is the key that indexes it in
`cluster.workers`.
### `worker.isConnected()`
<!-- YAML
added: v0.11.14
-->
@ -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()`
<!-- YAML
added: v0.11.14
-->
@ -556,6 +568,7 @@ if (cluster.isPrimary) {
```
### `worker.kill([signal])`
<!-- YAML
added: v0.9.12
-->
@ -581,6 +594,7 @@ In a worker, `process.kill()` exists, but it is not this function;
it is [`kill()`][].
### `worker.process`
<!-- YAML
added: v0.7.0
-->
@ -598,6 +612,7 @@ on `process` and `.exitedAfterDisconnect` is not `true`. This protects against
accidental disconnection.
### `worker.send(message[, sendHandle[, options]][, callback])`
<!-- YAML
added: v0.7.0
changes:
@ -640,6 +655,7 @@ if (cluster.isPrimary) {
```
## Event: `'disconnect'`
<!-- YAML
added: v0.7.9
-->
@ -661,6 +677,7 @@ cluster.on('disconnect', (worker) => {
```
## Event: `'exit'`
<!-- YAML
added: v0.7.9
-->
@ -685,6 +702,7 @@ cluster.on('exit', (worker, code, signal) => {
See [`child_process` event: `'exit'`][].
## Event: `'fork'`
<!-- YAML
added: v0.7.0
-->
@ -713,6 +731,7 @@ cluster.on('exit', (worker, code, signal) => {
```
## Event: `'listening'`
<!-- YAML
added: v0.7.0
-->
@ -744,6 +763,7 @@ The `addressType` is one of:
* `'udp4'` or `'udp6'` (UDP v4 or v6)
## Event: `'message'`
<!-- YAML
added: v2.5.0
changes:
@ -761,6 +781,7 @@ Emitted when the cluster primary receives a message from any worker.
See [`child_process` event: `'message'`][].
## Event: `'online'`
<!-- YAML
added: v0.7.0
-->
@ -779,6 +800,7 @@ cluster.on('online', (worker) => {
```
## Event: `'setup'`
<!-- YAML
added: v0.7.1
-->
@ -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])`
<!-- YAML
added: v0.7.7
-->
@ -812,6 +835,7 @@ finished.
This can only be called from the primary process.
## `cluster.fork([env])`
<!-- YAML
added: v0.6.0
-->
@ -824,6 +848,7 @@ Spawn a new worker process.
This can only be called from the primary process.
## `cluster.isMaster`
<!-- YAML
added: v0.8.1
deprecated: v16.0.0
@ -833,6 +858,7 @@ Deprecated alias for [`cluster.isPrimary`][].
details.
## `cluster.isPrimary`
<!-- YAML
added: v16.0.0
-->
@ -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`
<!-- YAML
added: v0.6.0
-->
@ -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`
<!-- YAML
added: v0.11.2
-->
@ -871,6 +899,7 @@ distribute IOCP handles without incurring a large performance hit.
values are `'rr'` and `'none'`.
## `cluster.settings`
<!-- YAML
added: v0.7.1
changes:
@ -894,10 +923,10 @@ changes:
-->
* {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])`
<!-- YAML
added: v0.7.1
deprecated: v16.0.0
@ -937,6 +967,7 @@ changes:
Deprecated alias for [`.setupPrimary()`][].
## `cluster.setupPrimary([settings])`
<!-- YAML
added: v16.0.0
-->
@ -990,6 +1021,7 @@ cluster.fork(); // http worker
This can only be called from the primary process.
## `cluster.worker`
<!-- YAML
added: v0.7.0
-->
@ -1023,6 +1055,7 @@ if (cluster.isPrimary) {
```
## `cluster.workers`
<!-- YAML
added: v0.7.0
-->

View File

@ -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`
<!-- YAML
changes:
- version: v8.0.0
@ -88,7 +89,9 @@ const { Console } = console;
```
### `new Console(stdout[, stderr][, ignoreErrors])`
### `new Console(options)`
<!-- YAML
changes:
- version:
@ -148,6 +151,7 @@ new Console({ stdout: process.stdout, stderr: process.stderr });
```
### `console.assert(value[, ...message])`
<!-- YAML
added: v0.1.101
changes:
@ -178,6 +182,7 @@ console.assert();
```
### `console.clear()`
<!-- YAML
added: v8.3.0
-->
@ -192,6 +197,7 @@ will clear only the output in the current terminal viewport for the Node.js
binary.
### `console.count([label])`
<!-- YAML
added: v8.3.0
-->
@ -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`.
<!-- eslint-skip -->
```js
> console.count()
default: 1
@ -225,6 +232,7 @@ undefined
```
### `console.countReset([label])`
<!-- YAML
added: v8.3.0
-->
@ -234,6 +242,7 @@ added: v8.3.0
Resets the internal counter specific to `label`.
<!-- eslint-skip -->
```js
> console.count('abc');
abc: 1
@ -247,6 +256,7 @@ undefined
```
### `console.debug(data[, ...args])`
<!-- YAML
added: v8.0.0
changes:
@ -261,6 +271,7 @@ changes:
The `console.debug()` function is an alias for [`console.log()`][].
### `console.dir(obj[, options])`
<!-- YAML
added: v0.1.101
-->
@ -280,6 +291,7 @@ 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)`
<!-- YAML
added: v8.0.0
changes:
@ -294,6 +306,7 @@ This method calls `console.log()` passing it the arguments received.
This method does not produce any XML formatting.
### `console.error([data][, ...args])`
<!-- YAML
added: v0.1.100
-->
@ -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])`
<!-- YAML
added: v8.5.0
-->
@ -332,6 +346,7 @@ If one or more `label`s are provided, those are printed first without the
additional indentation.
### `console.groupCollapsed()`
<!-- YAML
added: v8.5.0
-->
@ -339,6 +354,7 @@ additional indentation.
An alias for [`console.group()`][].
### `console.groupEnd()`
<!-- YAML
added: v8.5.0
-->
@ -347,6 +363,7 @@ Decreases indentation of subsequent lines by spaces for `groupIndentation`
length.
### `console.info([data][, ...args])`
<!-- YAML
added: v0.1.100
-->
@ -357,6 +374,7 @@ added: v0.1.100
The `console.info()` function is an alias for [`console.log()`][].
### `console.log([data][, ...args])`
<!-- YAML
added: v0.1.100
-->
@ -380,12 +398,13 @@ console.log('count:', count);
See [`util.format()`][] for more information.
### `console.table(tabularData[, properties])`
<!-- YAML
added: v10.0.0
-->
* `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])`
<!-- YAML
added: v0.1.104
-->
@ -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])`
<!-- YAML
added: v0.1.104
changes:
@ -455,6 +476,7 @@ console.timeEnd('100-elements');
```
### `console.timeLog([label][, ...data])`
<!-- YAML
added: v10.7.0
-->
@ -475,6 +497,7 @@ console.timeEnd('process');
```
### `console.trace([message][, ...args])`
<!-- YAML
added: v0.1.104
-->
@ -502,6 +525,7 @@ console.trace('Show me');
```
### `console.warn([data][, ...args])`
<!-- YAML
added: v0.1.100
-->
@ -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])`
<!-- YAML
added: v8.0.0
-->
@ -536,6 +562,7 @@ console.profileEnd('MyLabel');
```
### `console.profileEnd([label])`
<!-- YAML
added: v8.0.0
-->
@ -551,6 +578,7 @@ If this method is called without a label, the most recently started profile is
stopped.
### `console.timeStamp([label])`
<!-- YAML
added: v8.0.0
-->

File diff suppressed because it is too large Load Diff

View File

@ -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:
<!-- eslint-disable no-debugger -->
```js
// myscript.js
global.x = 5;

File diff suppressed because it is too large Load Diff

View File

@ -56,6 +56,7 @@ server.bind(41234);
```
## Class: `dgram.Socket`
<!-- YAML
added: v0.1.99
-->
@ -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'`
<!-- YAML
added: v0.1.99
-->
@ -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'`
<!-- YAML
added: v12.0.0
-->
@ -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'`
<!-- YAML
added: v0.1.99
-->
@ -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'`
<!-- YAML
added: v0.1.99
-->
@ -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'`
<!-- YAML
added: v0.1.99
-->
@ -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])`
<!-- YAML
added: v0.6.9
-->
@ -177,11 +184,13 @@ if (cluster.isPrimary) {
```
### `socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])`
<!-- YAML
added:
- v13.1.0
- v12.16.0
-->
* `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()`
<!-- YAML
added: v0.1.99
-->
@ -210,6 +220,7 @@ properties.
This method throws `EBADF` if called on an unbound socket.
### `socket.bind([port][, address][, callback])`
<!-- YAML
added: v0.1.99
changes:
@ -290,6 +301,7 @@ server.bind(41234);
```
### `socket.bind(options[, callback])`
<!-- YAML
added: v0.11.14
-->
@ -343,6 +355,7 @@ socket.bind({
```
### `socket.close([callback])`
<!-- YAML
added: v0.1.99
-->
@ -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])`
<!-- YAML
added: v12.0.0
-->
@ -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()`
<!-- YAML
added: v12.0.0
-->
@ -382,6 +397,7 @@ disconnected socket will result in an [`ERR_SOCKET_DGRAM_NOT_CONNECTED`][]
exception.
### `socket.dropMembership(multicastAddress[, multicastInterface])`
<!-- YAML
added: v0.6.9
-->
@ -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])`
<!-- YAML
added:
- v13.1.0
@ -418,6 +435,7 @@ If `multicastInterface` is not specified, the operating system will attempt to
drop membership on all valid interfaces.
### `socket.getRecvBufferSize()`
<!-- YAML
added: v8.7.0
-->
@ -427,6 +445,7 @@ added: v8.7.0
This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
### `socket.getSendBufferSize()`
<!-- YAML
added: v8.7.0
-->
@ -436,6 +455,7 @@ added: v8.7.0
This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
### `socket.ref()`
<!-- YAML
added: v0.9.1
-->
@ -454,6 +474,7 @@ The `socket.ref()` method returns a reference to the socket so calls can be
chained.
### `socket.remoteAddress()`
<!-- YAML
added: v12.0.0
-->
@ -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])`
<!-- YAML
added: v0.1.99
changes:
@ -538,7 +560,7 @@ The only way to know for sure that the datagram has been sent is by using a
passed as the first argument to the `callback`. If a `callback` is not given,
the error is emitted as an `'error'` event on the `socket` object.
Offset and length are optional but both *must* be set if either are used.
Offset and length are optional but both _must_ be set if either are used.
They are supported only when the first argument is a `Buffer`, a `TypedArray`,
or a `DataView`.
@ -657,6 +679,7 @@ not work because the packet will get silently dropped without informing the
source that the data did not reach its intended recipient.
### `socket.setBroadcast(flag)`
<!-- YAML
added: v0.6.9
-->
@ -669,16 +692,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)`
<!-- YAML
added: v8.6.0
-->
* `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
@ -719,6 +743,7 @@ socket.bind(1234, () => {
```
#### Example: IPv4 outgoing multicast interface
All systems use an IP of the host on the desired physical interface:
```js
@ -731,10 +756,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
@ -749,6 +774,7 @@ used to return control of the sockets default outgoing interface to the system
for future multicast packets.
### `socket.setMulticastLoopback(flag)`
<!-- YAML
added: v0.3.8
-->
@ -761,6 +787,7 @@ multicast packets will also be received on the local interface.
This method throws `EBADF` if called on an unbound socket.
### `socket.setMulticastTTL(ttl)`
<!-- YAML
added: v0.3.8
-->
@ -778,6 +805,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)`
<!-- YAML
added: v8.7.0
-->
@ -790,6 +818,7 @@ in bytes.
This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
### `socket.setSendBufferSize(size)`
<!-- YAML
added: v8.7.0
-->
@ -802,6 +831,7 @@ in bytes.
This method throws [`ERR_SOCKET_BUFFER_SIZE`][] if called on an unbound socket.
### `socket.setTTL(ttl)`
<!-- YAML
added: v0.1.101
-->
@ -820,6 +850,7 @@ is 64.
This method throws `EBADF` if called on an unbound socket.
### `socket.unref()`
<!-- YAML
added: v0.9.1
-->
@ -840,6 +871,7 @@ chained.
## `dgram` module functions
### `dgram.createSocket(options[, callback])`
<!-- YAML
added: v0.11.13
changes:
@ -897,6 +929,7 @@ controller.abort();
```
### `dgram.createSocket(type[, callback])`
<!-- YAML
added: v0.1.99
-->

View File

@ -52,6 +52,7 @@ dns.resolve4('archive.org', (err, addresses) => {
See the [Implementation considerations section][] for more information.
## Class: `dns.Resolver`
<!-- YAML
added: v8.3.0
-->
@ -94,6 +95,7 @@ The following methods from the `dns` module are available:
* [`resolver.setServers()`][`dns.setServers()`]
### `Resolver([options])`
<!-- YAML
added: v8.3.0
changes:
@ -117,6 +119,7 @@ Create a new resolver.
each name server before giving up. **Default:** `4`
### `resolver.cancel()`
<!-- YAML
added: v8.3.0
-->
@ -125,6 +128,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])`
<!-- YAML
added:
- v15.1.0
@ -148,17 +152,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()`
<!-- YAML
added: v0.11.3
-->
* 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.
<!-- eslint-disable semi-->
```js
[
'4.4.4.4',
@ -169,6 +175,7 @@ section if a custom port is used.
```
## `dns.lookup(hostname[, options], callback)`
<!-- YAML
added: v0.1.90
changes:
@ -250,6 +257,7 @@ is not set to `true`, it returns a `Promise` for an `Object` with `address` and
`family` properties.
### Supported getaddrinfo flags
<!-- YAML
changes:
- version:
@ -271,6 +279,7 @@ The following flags can be passed as hints to [`dns.lookup()`][].
well as IPv4 mapped IPv6 addresses.
## `dns.lookupService(address, port, callback)`
<!-- YAML
added: v0.11.14
-->
@ -303,6 +312,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)`
<!-- YAML
added: v0.1.27
-->
@ -311,7 +321,7 @@ 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
@ -319,7 +329,7 @@ of the resource records. The `callback` function has arguments
records. The type and structure of individual results varies based on `rrtype`:
| `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()`][] |
@ -331,12 +341,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)`
<!-- YAML
added: v0.1.16
changes:
@ -354,7 +365,7 @@ changes:
with the TTL expressed in seconds.
* `callback` {Function}
* `err` {Error}
* `addresses` {string[] | Object[]}
* `addresses` {string\[] | Object\[]}
Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the
`hostname`. The `addresses` argument passed to the `callback` function
@ -362,6 +373,7 @@ will contain an array of IPv4 addresses (e.g.
`['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
## `dns.resolve6(hostname[, options], callback)`
<!-- YAML
added: v0.1.16
changes:
@ -379,7 +391,7 @@ changes:
strings, with the TTL expressed in seconds.
* `callback` {Function}
* `err` {Error}
* `addresses` {string[] | Object[]}
* `addresses` {string\[] | Object\[]}
Uses the DNS protocol to resolve a IPv6 addresses (`AAAA` records) for the
`hostname`. The `addresses` argument passed to the `callback` function
@ -390,7 +402,7 @@ will contain an array of IPv6 addresses.
* `hostname` {string}
* `callback` {Function}
* `err` {Error}
* `ret` {Object[]}
* `ret` {Object\[]}
Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
The `ret` argument passed to the `callback` function will be an array containing
@ -399,7 +411,7 @@ 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` |
@ -414,6 +426,7 @@ will be present on the object:
Here is an example of the `ret` object passed to the callback:
<!-- eslint-disable semi -->
```js
[ { type: 'A', address: '127.0.0.1', ttl: 299 },
{ type: 'CNAME', value: 'example.com' },
@ -435,6 +448,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)`
<!-- YAML
added: v0.3.2
-->
@ -442,7 +456,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
@ -450,6 +464,7 @@ will contain an array of canonical name records available for the `hostname`
(e.g. `['bar.example.com']`).
## `dns.resolveCaa(hostname, callback)`
<!-- YAML
added:
- v15.0.0
@ -459,7 +474,7 @@ added:
* `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
@ -468,6 +483,7 @@ available for the `hostname` (e.g. `[{critical: 0, iodef:
'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`).
## `dns.resolveMx(hostname, callback)`
<!-- YAML
added: v0.1.27
-->
@ -475,7 +491,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
@ -483,6 +499,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)`
<!-- YAML
added: v0.9.12
-->
@ -490,7 +507,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`
@ -504,6 +521,7 @@ function will contain an array of objects with the following properties:
* `preference`
<!-- eslint-skip -->
```js
{
flags: 's',
@ -516,6 +534,7 @@ function will contain an array of objects with the following properties:
```
## `dns.resolveNs(hostname, callback)`
<!-- YAML
added: v0.1.90
-->
@ -523,7 +542,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
@ -531,6 +550,7 @@ contain an array of name server records available for `hostname`
(e.g. `['ns1.example.com', 'ns2.example.com']`).
## `dns.resolvePtr(hostname, callback)`
<!-- YAML
added: v6.0.0
-->
@ -538,13 +558,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)`
<!-- YAML
added: v0.11.10
-->
@ -567,6 +588,7 @@ be an object with the following properties:
* `minttl`
<!-- eslint-skip -->
```js
{
nsname: 'ns.example.com',
@ -580,6 +602,7 @@ be an object with the following properties:
```
## `dns.resolveSrv(hostname, callback)`
<!-- YAML
added: v0.1.27
-->
@ -587,7 +610,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
@ -599,6 +622,7 @@ be an array of objects with the following properties:
* `name`
<!-- eslint-skip -->
```js
{
priority: 10,
@ -609,15 +633,18 @@ be an array of objects with the following properties:
```
## `dns.resolveTxt(hostname, callback)`
<!-- YAML
added: v0.1.27
-->
<!--lint disable no-undefined-references list-item-bullet-indent-->
* `hostname` {string}
* `callback` {Function}
* `err` {Error}
* `records` <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&lt;string[][]&gt;</a>
* `records` <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">\<string\[]\[]></a>
<!--lint enable no-undefined-references list-item-bullet-indent-->
Uses the DNS protocol to resolve text queries (`TXT` records) for the
@ -628,6 +655,7 @@ one record. Depending on the use case, these could be either joined together or
treated separately.
## `dns.reverse(ip, callback)`
<!-- YAML
added: v0.1.16
-->
@ -635,7 +663,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.
@ -644,6 +672,7 @@ On error, `err` is an [`Error`][] object, where `err.code` is
one of the [DNS error codes][].
## `dns.setDefaultResultOrder(order)`
<!-- YAML
added:
- v16.4.0
@ -654,6 +683,7 @@ added:
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`.
@ -663,11 +693,12 @@ priority than [`--dns-result-order`][]. When using [worker threads][],
dns orders in workers.
## `dns.setServers(servers)`
<!-- YAML
added: v0.11.3
-->
* `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
@ -688,17 +719,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
<!-- YAML
added: v10.6.0
changes:
@ -717,6 +749,7 @@ that return `Promise` objects rather than using callbacks. The API is accessible
via `require('dns').promises` or `require('dns/promises')`.
### Class: `dnsPromises.Resolver`
<!-- YAML
added: v10.6.0
-->
@ -764,6 +797,7 @@ The following methods from the `dnsPromises` API are available:
* [`resolver.setServers()`][`dnsPromises.setServers()`]
### `resolver.cancel()`
<!-- YAML
added:
- v15.3.0
@ -774,17 +808,19 @@ Cancel all outstanding DNS queries made by this resolver. The corresponding
promises will be rejected with an error with code `ECANCELLED`.
### `dnsPromises.getServers()`
<!-- YAML
added: v10.6.0
-->
* 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.
<!-- eslint-disable semi-->
```js
[
'4.4.4.4',
@ -795,6 +831,7 @@ section if a custom port is used.
```
### `dnsPromises.lookup(hostname[, options])`
<!-- YAML
added: v10.6.0
-->
@ -861,6 +898,7 @@ dnsPromises.lookup('example.com', options).then((result) => {
```
### `dnsPromises.lookupService(address, port)`
<!-- YAML
added: v10.6.0
-->
@ -887,6 +925,7 @@ dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
```
### `dnsPromises.resolve(hostname[, rrtype])`
<!-- YAML
added: v10.6.0
-->
@ -900,7 +939,7 @@ array of resource records. The type and structure of individual results vary
based on `rrtype`:
| `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()`][] |
@ -912,12 +951,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])`
<!-- YAML
added: v10.6.0
-->
@ -934,6 +974,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])`
<!-- YAML
added: v10.6.0
-->
@ -950,6 +991,7 @@ Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the
addresses.
### `dnsPromises.resolveAny(hostname)`
<!-- YAML
added: v10.6.0
-->
@ -963,7 +1005,7 @@ 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` |
@ -978,6 +1020,7 @@ present on the object:
Here is an example of the result object:
<!-- eslint-disable semi -->
```js
[ { type: 'A', address: '127.0.0.1', ttl: 299 },
{ type: 'CNAME', value: 'example.com' },
@ -995,6 +1038,7 @@ Here is an example of the result object:
```
### `dnsPromises.resolveCaa(hostname)`
<!-- YAML
added:
- v15.0.0
@ -1010,6 +1054,7 @@ certification authority authorization records available for the `hostname`
'pki.example.com'}]`).
### `dnsPromises.resolveCname(hostname)`
<!-- YAML
added: v10.6.0
-->
@ -1021,6 +1066,7 @@ the `Promise` is resolved with an array of canonical name records available for
the `hostname` (e.g. `['bar.example.com']`).
### `dnsPromises.resolveMx(hostname)`
<!-- YAML
added: v10.6.0
-->
@ -1033,6 +1079,7 @@ containing both a `priority` and `exchange` property (e.g.
`[{priority: 10, exchange: 'mx.example.com'}, ...]`).
### `dnsPromises.resolveNaptr(hostname)`
<!-- YAML
added: v10.6.0
-->
@ -1051,6 +1098,7 @@ of objects with the following properties:
* `preference`
<!-- eslint-skip -->
```js
{
flags: 's',
@ -1063,6 +1111,7 @@ of objects with the following properties:
```
### `dnsPromises.resolveNs(hostname)`
<!-- YAML
added: v10.6.0
-->
@ -1075,6 +1124,7 @@ records available for `hostname` (e.g.
`['ns1.example.com', 'ns2.example.com']`).
### `dnsPromises.resolvePtr(hostname)`
<!-- YAML
added: v10.6.0
-->
@ -1086,6 +1136,7 @@ Uses the DNS protocol to resolve pointer records (`PTR` records) for the
containing the reply records.
### `dnsPromises.resolveSoa(hostname)`
<!-- YAML
added: v10.6.0
-->
@ -1105,6 +1156,7 @@ following properties:
* `minttl`
<!-- eslint-skip -->
```js
{
nsname: 'ns.example.com',
@ -1118,6 +1170,7 @@ following properties:
```
### `dnsPromises.resolveSrv(hostname)`
<!-- YAML
added: v10.6.0
-->
@ -1134,6 +1187,7 @@ the following properties:
* `name`
<!-- eslint-skip -->
```js
{
priority: 10,
@ -1144,6 +1198,7 @@ the following properties:
```
### `dnsPromises.resolveTxt(hostname)`
<!-- YAML
added: v10.6.0
-->
@ -1158,6 +1213,7 @@ one record. Depending on the use case, these could be either joined together or
treated separately.
### `dnsPromises.reverse(ip)`
<!-- YAML
added: v10.6.0
-->
@ -1171,6 +1227,7 @@ On error, the `Promise` is rejected with an [`Error`][] object, where `err.code`
is one of the [DNS error codes]().
### `dnsPromises.setDefaultResultOrder(order)`
<!-- YAML
added:
- v16.4.0
@ -1181,6 +1238,7 @@ added:
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`.
@ -1190,11 +1248,12 @@ higher priority than [`--dns-result-order`][]. When using [worker threads][],
default dns orders in workers.
### `dnsPromises.setServers(servers)`
<!-- YAML
added: v10.6.0
-->
* `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
@ -1217,7 +1276,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.

View File

@ -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
<!-- STABILITY_OVERVIEW_SLOT_BEGIN -->
<!-- STABILITY_OVERVIEW_SLOT_END -->
## JSON output
<!-- YAML
added: v0.6.12
-->

View File

@ -1,4 +1,5 @@
# Domain
<!-- YAML
deprecated: v1.4.2
changes:

View File

@ -67,6 +67,7 @@ int main(int argc, char** argv) {
```
### Per-instance state
<!-- YAML
changes:
- version: v15.0.0

File diff suppressed because it is too large Load Diff

View File

@ -83,9 +83,8 @@ provides interoperability between them and its original module format,
[CommonJS][].
<!-- Anchors to make sure old links find a target -->
<i id="esm_package_json_type_field"></i>
<i id="esm_package_scope_and_file_extensions"></i>
<i id="esm_input_type_flag"></i>
<i id="esm_package_json_type_field"></i><i id="esm_package_scope_and_file_extensions"></i><i id="esm_input_type_flag"></i>
## Enabling
@ -99,20 +98,8 @@ via the `.mjs` file extension, the `package.json` [`"type"`][] field, or the
details.
<!-- Anchors to make sure old links find a target -->
<i id="esm_package_entry_points"></i>
<i id="esm_main_entry_point_export"></i>
<i id="esm_subpath_exports"></i>
<i id="esm_package_exports_fallbacks"></i>
<i id="esm_exports_sugar"></i>
<i id="esm_conditional_exports"></i>
<i id="esm_nested_conditions"></i>
<i id="esm_self_referencing_a_package_using_its_name"></i>
<i id="esm_internal_package_imports"></i>
<i id="esm_dual_commonjs_es_module_packages"></i>
<i id="esm_dual_package_hazard"></i>
<i id="esm_writing_dual_packages_while_avoiding_or_minimizing_hazards"></i>
<i id="esm_approach_1_use_an_es_module_wrapper"></i>
<i id="esm_approach_2_isolate_state"></i>
<i id="esm_package_entry_points"></i><i id="esm_main_entry_point_export"></i><i id="esm_subpath_exports"></i><i id="esm_package_exports_fallbacks"></i><i id="esm_exports_sugar"></i><i id="esm_conditional_exports"></i><i id="esm_nested_conditions"></i><i id="esm_self_referencing_a_package_using_its_name"></i><i id="esm_internal_package_imports"></i><i id="esm_dual_commonjs_es_module_packages"></i><i id="esm_dual_package_hazard"></i><i id="esm_writing_dual_packages_while_avoiding_or_minimizing_hazards"></i><i id="esm_approach_1_use_an_es_module_wrapper"></i><i id="esm_approach_2_isolate_state"></i>
## Packages
@ -294,6 +281,7 @@ const buffer = readFileSync(new URL('./data.proto', import.meta.url));
```
### `import.meta.resolve(specifier[, parent])`
<!--
added:
- v13.9.0
@ -320,6 +308,7 @@ Provides a module-relative resolution function scoped to each module, returning
the URL string.
<!-- eslint-skip -->
```js
const dependencyAsset = await import.meta.resolve('component-lib/asset.css');
```
@ -328,6 +317,7 @@ const dependencyAsset = await import.meta.resolve('component-lib/asset.css');
from which to resolve from:
<!-- eslint-skip -->
```js
await import.meta.resolve('./dep', import.meta.url);
```
@ -364,6 +354,7 @@ When importing a CommonJS module, it can be reliably imported using the ES
module default import or its corresponding sugar syntax:
<!-- eslint-disable no-duplicate-imports -->
```js
import { default as cjs } from 'cjs';
@ -386,6 +377,7 @@ This Module Namespace Exotic Object can be directly observed either when using
`import * as m from 'cjs'` or a dynamic import:
<!-- eslint-skip -->
```js
import * as m from 'cjs';
console.log(m);
@ -410,6 +402,7 @@ exports.name = 'exported';
The preceding module supports named imports in ES modules:
<!-- eslint-disable no-duplicate-imports -->
```js
import { name } from './cjs.cjs';
console.log(name);
@ -463,6 +456,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:
<!-- eslint-skip -->
```js
import { readFile } from 'fs/promises';
const json = JSON.parse(await readFile(new URL('./dat.json', import.meta.url)));
@ -523,6 +517,7 @@ same path.
Assuming an `index.mjs` with
<!-- eslint-skip -->
```js
import packageConfig from './package.json';
```
@ -575,6 +570,7 @@ within modules as per the [ECMAScript Top-Level `await` proposal][].
Assuming an `a.mjs` with
<!-- eslint-skip -->
```js
export const five = await Promise.resolve(5);
```
@ -616,7 +612,7 @@ CommonJS modules loaded.
* `specifier` {string}
* `context` {Object}
* `conditions` {string[]}
* `conditions` {string\[]}
* `parentURL` {string|undefined}
* `defaultResolve` {Function} The Node.js default resolver.
* Returns: {Object}
@ -1025,16 +1021,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
@ -1047,6 +1043,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
@ -1062,261 +1059,263 @@ 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
> 1. Set _resolved_ to the result of **PACKAGE_IMPORTS_RESOLVE**(_specifier_,
> 4. Otherwise, if _specifier_ starts with _"#"_, then
> 1. Set _resolved_ to the result of
> **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
> 6. Let _packageSubpath_ be _"."_ concatenated with the substring of
> _packageSpecifier_ from the position at the length of _packageName_.
> 1. If _packageSubpath_ ends in _"/"_, then
> 7. If _packageSubpath_ ends in _"/"_, then
> 1. Throw an _Invalid Module Specifier_ error.
> 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
> 8. Let _selfUrl_ be the result of
> **PACKAGE\_SELF\_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_).
> 9. If _selfUrl_ is not **undefined**, return _selfUrl_.
> 10. 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/"_
> 11. 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
> 2. Set _parentURL_ to the parent folder URL of _parentURL_.
> 3. If the folder at _packageURL_ does not exist, then
> 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
> 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. Return the result of **PACKAGE_EXPORTS_RESOLVE**(_packageURL_,
> 1. Return the result of **PACKAGE\_EXPORTS\_RESOLVE**(_packageURL_,
> _packageSubpath_, _pjson.exports_, _defaultConditions_).
> 1. Otherwise, if _packageSubpath_ is equal to _"."_, then
> 6. Otherwise, if _packageSubpath_ is equal to _"."_, then
> 1. If _pjson.main_ is a string, then
> 1. Return the URL resolution of _main_ in _packageURL_.
> 1. Otherwise,
> 7. Otherwise,
> 1. Return the URL resolution of _packageSubpath_ in _packageURL_.
> 1. Throw a _Module Not Found_ error.
> 12. Throw a _Module Not Found_ error.
**PACKAGE_SELF_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_)
**PACKAGE\_SELF\_RESOLVE**(_packageName_, _packageSubpath_, _parentURL_)
> 1. Let _packageURL_ be the result of **READ_PACKAGE_SCOPE**(_parentURL_).
> 1. If _packageURL_ is **null**, then
> 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
> 1. Return the result of **PACKAGE_EXPORTS_RESOLVE**(_packageURL_,
> 5. If _pjson.name_ is equal to _packageName_, then
> 1. Return the result of **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**, return _resolved_.
> 1. Otherwise, if _exports_ is an Object and all keys of _exports_ start with
> 2. If _resolved_ is not **null** or **undefined**, return _resolved_.
> 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 _resolved_ be the result of **PACKAGE_IMPORTS_EXPORTS_RESOLVE**(
> 2. Let _resolved_ be the result of **PACKAGE\_IMPORTS\_EXPORTS\_RESOLVE**(
> _matchKey_, _exports_, _packageURL_, **false**, _conditions_).
> 1. If _resolved_ is not **null** or **undefined**, return _resolved_.
> 1. Throw a _Package Path Not Exported_ error.
> 3. If _resolved_ is not **null** or **undefined**, return _resolved_.
> 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
> 1. Let _resolved_ be the result of **PACKAGE_IMPORTS_EXPORTS_RESOLVE**(
> 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 _resolved_ be the result of
> **PACKAGE\_IMPORTS\_EXPORTS\_RESOLVE**(
> _specifier_, _pjson.imports_, _packageURL_, **true**, _conditions_).
> 1. If _resolved_ is not **null** or **undefined**, return _resolved_.
> 1. Throw a _Package Import Not Defined_ error.
> 2. If _resolved_ is not **null** or **undefined**, return _resolved_.
> 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 contain _"*"_, then
> 1. Let _target_ be the value of _matchObj_\[_matchKey_\].
> 1. Return the result of **PACKAGE_TARGET_RESOLVE**(_packageURL_, _target_,
> _""_, **false**, _isImports_, _conditions_).
> 1. Let _expansionKeys_ be the list of keys of _matchObj_ 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
> 1. If _matchKey_ is a key of _matchObj_ and does not contain _"\*"_, then
> 1. Let _target_ be the value of _matchObj_\[_matchKey_].
> 2. Return the result of **PACKAGE\_TARGET\_RESOLVE**(_packageURL_,
> _target_, _""_, **false**, _isImports_, _conditions_).
> 2. Let _expansionKeys_ be the list of keys of _matchObj_ 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 the substring of _expansionKey_ up to but excluding
> the first _"*"_ character.
> 1. If _matchKey_ starts with but is not equal to _patternBase_, then
> the first _"\*"_ character.
> 2. If _matchKey_ starts with but is not equal to _patternBase_, then
> 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
> index after the first _"\*"_ character.
> 2. 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. Return the result of **PACKAGE_TARGET_RESOLVE**(_packageURL_,
> 3. Return the result of **PACKAGE\_TARGET\_RESOLVE**(_packageURL_,
> _target_, _subpath_, **true**, _isImports_, _conditions_).
> 1. Return **null**.
> 4. Return **null**.
**PATTERN_KEY_COMPARE**(_keyA_, _keyB_)
**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.
> 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_,
**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
@ -1343,6 +1342,7 @@ success!
```
<!-- Note: The cjs-module-lexer link should be kept in-sync with the deps version -->
[6.1.7 Array Index]: https://tc39.es/ecma262/#integer-index
[CommonJS]: modules.md
[Conditional exports]: packages.md#conditional-exports

View File

@ -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`
<!-- YAML
added: v0.1.26
changes:
@ -252,6 +253,7 @@ It supports the following option:
**Default:** `false`.
### Event: `'newListener'`
<!-- YAML
added: v0.1.26
-->
@ -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'`
<!-- YAML
added: v0.9.3
changes:
@ -307,9 +310,10 @@ changes:
* `eventName` {string|symbol} The event name
* `listener` {Function} The event handler function
The `'removeListener'` event is emitted *after* the `listener` is removed.
The `'removeListener'` event is emitted _after_ the `listener` is removed.
### `emitter.addListener(eventName, listener)`
<!-- YAML
added: v0.1.26
-->
@ -320,6 +324,7 @@ added: v0.1.26
Alias for `emitter.on(eventName, listener)`.
### `emitter.emit(eventName[, ...args])`
<!-- YAML
added: v0.1.26
-->
@ -368,6 +373,7 @@ myEmitter.emit('event', 1, 2, 3, 4, 5);
```
### `emitter.eventNames()`
<!-- YAML
added: v6.0.0
-->
@ -391,6 +397,7 @@ console.log(myEE.eventNames());
```
### `emitter.getMaxListeners()`
<!-- YAML
added: v1.0.0
-->
@ -402,6 +409,7 @@ set by [`emitter.setMaxListeners(n)`][] or defaults to
[`events.defaultMaxListeners`][].
### `emitter.listenerCount(eventName)`
<!-- YAML
added: v3.2.0
-->
@ -412,6 +420,7 @@ added: v3.2.0
Returns the number of listeners listening to the event named `eventName`.
### `emitter.listeners(eventName)`
<!-- YAML
added: v0.1.26
changes:
@ -422,7 +431,7 @@ changes:
-->
* `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)`
<!-- YAML
added: v10.0.0
-->
@ -446,6 +456,7 @@ added: v10.0.0
Alias for [`emitter.removeListener()`][].
### `emitter.on(eventName, listener)`
<!-- YAML
added: v0.1.101
-->
@ -483,6 +494,7 @@ myEE.emit('foo');
```
### `emitter.once(eventName, listener)`
<!-- YAML
added: v0.3.0
-->
@ -517,6 +529,7 @@ myEE.emit('foo');
```
### `emitter.prependListener(eventName, listener)`
<!-- YAML
added: v6.0.0
-->
@ -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)`
<!-- YAML
added: v6.0.0
-->
@ -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])`
<!-- YAML
added: v0.1.26
-->
@ -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)`
<!-- YAML
added: v0.1.26
-->
@ -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)`
<!-- YAML
added: v0.3.5
-->
@ -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)`
<!-- YAML
added: v9.4.0
-->
* `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])`
<!-- YAML
added:
- v13.4.0
@ -756,6 +775,7 @@ class MyClass extends EventEmitter {
```
## `events.defaultMaxListeners`
<!-- YAML
added: v0.11.2
-->
@ -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`
<!-- YAML
added:
- v13.6.0
@ -811,14 +832,16 @@ Installing a listener using this symbol does not change the behavior once an
regular `'error'` listener is installed.
## `events.getEventListeners(emitterOrTarget, eventName)`
<!-- YAML
added:
- v15.2.0
- v14.17.0
-->
* `emitterOrTarget` {EventEmitter|EventTarget}
* `eventName` {string|symbol}
* Returns: {Function[]}
* Returns: {Function\[]}
Returns a copy of the array of listeners for the event named `eventName`.
@ -846,6 +869,7 @@ const { getEventListeners, EventEmitter } = require('events');
```
## `events.once(emitter, name[, options])`
<!-- YAML
added:
- v11.13.0
@ -976,7 +1000,7 @@ process.nextTick(() => {
foo().then(() => console.log('done'));
```
To catch both events, create each of the Promises *before* awaiting either
To catch both events, create each of the Promises _before_ awaiting either
of them, then it becomes possible to use `Promise.all()`, `Promise.race()`,
or `Promise.allSettled()`:
@ -999,6 +1023,7 @@ foo().then(() => console.log('done'));
```
## `events.captureRejections`
<!-- YAML
added:
- v13.4.0
@ -1012,6 +1037,7 @@ Value: {boolean}
Change the default `captureRejections` option on all new `EventEmitter` objects.
## `events.captureRejectionSymbol`
<!-- YAML
added:
- v13.4.0
@ -1025,6 +1051,7 @@ Value: `Symbol.for('nodejs.rejection')`
See how to write a custom [rejection handler][rejection].
## `events.listenerCount(emitter, eventName)`
<!-- YAML
added: v0.9.12
deprecated: v3.2.0
@ -1048,6 +1075,7 @@ console.log(listenerCount(myEmitter, 'event'));
```
## `events.on(emitter, eventName[, options])`
<!-- YAML
added:
- v13.6.0
@ -1115,13 +1143,14 @@ process.nextTick(() => ac.abort());
```
## `events.setMaxListeners(n[, ...eventTargets])`
<!-- YAML
added: v15.4.0
-->
* `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.
@ -1138,7 +1167,9 @@ setMaxListeners(5, target, emitter);
```
<a id="event-target-and-event-api"></a>
## `EventTarget` and `Event` API
<!-- YAML
added: v14.5.0
changes:
@ -1170,7 +1201,7 @@ target.addEventListener('foo', (event) => {
There are two key differences between the Node.js `EventTarget` and the
[`EventTarget` Web API][]:
1. Whereas DOM `EventTarget` instances *may* be hierarchical, there is no
1. Whereas DOM `EventTarget` instances _may_ be hierarchical, there is no
concept of hierarchy and event propagation in Node.js. That is, an event
dispatched to an `EventTarget` does not propagate through a hierarchy of
nested target objects that may each have their own set of handlers for the
@ -1183,8 +1214,8 @@ There are two key differences between the Node.js `EventTarget` and the
### `NodeEventTarget` vs. `EventEmitter`
The `NodeEventTarget` object implements a modified subset of the
`EventEmitter` API that allows it to closely *emulate* an `EventEmitter` in
certain situations. A `NodeEventTarget` is *not* an instance of `EventEmitter`
`EventEmitter` API that allows it to closely _emulate_ an `EventEmitter` in
certain situations. A `NodeEventTarget` is _not_ an instance of `EventEmitter`
and cannot be used in place of an `EventEmitter` in most cases.
1. Unlike `EventEmitter`, any given `listener` can be registered at most once
@ -1197,7 +1228,7 @@ and cannot be used in place of an `EventEmitter` in most cases.
`'removeListener'` events will also not be emitted.
3. The `NodeEventTarget` does not implement any special default behavior
for events with type `'error'`.
3. The `NodeEventTarget` supports `EventListener` objects as well as
4. The `NodeEventTarget` supports `EventListener` objects as well as
functions as handlers for all event types.
### Event listener
@ -1259,7 +1290,7 @@ by default the error is treated as an uncaught exception on
`process.nextTick()`. This means uncaught exceptions in `EventTarget`s will
terminate the Node.js process by default.
Throwing within an event listener will *not* stop the other registered handlers
Throwing within an event listener will _not_ stop the other registered handlers
from being invoked.
The `EventTarget` does not implement any special default handling for `'error'`
@ -1272,6 +1303,7 @@ other Node.js APIs. Any code relying on the `process.on('error')` event should
be aligned with the new behavior.
### Class: `Event`
<!-- YAML
added: v14.5.0
changes:
@ -1284,6 +1316,7 @@ The `Event` object is an adaptation of the [`Event` Web API][]. Instances
are created internally by Node.js.
#### `event.bubbles`
<!-- YAML
added: v14.5.0
-->
@ -1293,6 +1326,7 @@ added: v14.5.0
This is not used in Node.js and is provided purely for completeness.
#### `event.cancelBubble()`
<!-- YAML
added: v14.5.0
-->
@ -1301,6 +1335,7 @@ Alias for `event.stopPropagation()`. This is not used in Node.js and is
provided purely for completeness.
#### `event.cancelable`
<!-- YAML
added: v14.5.0
-->
@ -1308,6 +1343,7 @@ added: v14.5.0
* Type: {boolean} True if the event was created with the `cancelable` option.
#### `event.composed`
<!-- YAML
added: v14.5.0
-->
@ -1317,6 +1353,7 @@ added: v14.5.0
This is not used in Node.js and is provided purely for completeness.
#### `event.composedPath()`
<!-- YAML
added: v14.5.0
-->
@ -1326,6 +1363,7 @@ empty if the event is not being dispatched. This is not used in
Node.js and is provided purely for completeness.
#### `event.currentTarget`
<!-- YAML
added: v14.5.0
-->
@ -1335,6 +1373,7 @@ added: v14.5.0
Alias for `event.target`.
#### `event.defaultPrevented`
<!-- YAML
added: v14.5.0
-->
@ -1345,6 +1384,7 @@ Is `true` if `cancelable` is `true` and `event.preventDefault()` has been
called.
#### `event.eventPhase`
<!-- YAML
added: v14.5.0
-->
@ -1355,6 +1395,7 @@ added: v14.5.0
This is not used in Node.js and is provided purely for completeness.
#### `event.isTrusted`
<!-- YAML
added: v14.5.0
-->
@ -1365,6 +1406,7 @@ The {AbortSignal} `"abort"` event is emitted with `isTrusted` set to `true`. The
value is `false` in all other cases.
#### `event.preventDefault()`
<!-- YAML
added: v14.5.0
-->
@ -1372,6 +1414,7 @@ added: v14.5.0
Sets the `defaultPrevented` property to `true` if `cancelable` is `true`.
#### `event.returnValue`
<!-- YAML
added: v14.5.0
-->
@ -1381,6 +1424,7 @@ added: v14.5.0
This is not used in Node.js and is provided purely for completeness.
#### `event.srcElement`
<!-- YAML
added: v14.5.0
-->
@ -1390,6 +1434,7 @@ added: v14.5.0
Alias for `event.target`.
#### `event.stopImmediatePropagation()`
<!-- YAML
added: v14.5.0
-->
@ -1397,6 +1442,7 @@ added: v14.5.0
Stops the invocation of event listeners after the current one completes.
#### `event.stopPropagation()`
<!-- YAML
added: v14.5.0
-->
@ -1404,6 +1450,7 @@ added: v14.5.0
This is not used in Node.js and is provided purely for completeness.
#### `event.target`
<!-- YAML
added: v14.5.0
-->
@ -1411,6 +1458,7 @@ added: v14.5.0
* Type: {EventTarget} The `EventTarget` dispatching the event.
#### `event.timeStamp`
<!-- YAML
added: v14.5.0
-->
@ -1420,6 +1468,7 @@ added: v14.5.0
The millisecond timestamp when the `Event` object was created.
#### `event.type`
<!-- YAML
added: v14.5.0
-->
@ -1429,6 +1478,7 @@ added: v14.5.0
The event type identifier.
### Class: `EventTarget`
<!-- YAML
added: v14.5.0
changes:
@ -1439,6 +1489,7 @@ changes:
-->
#### `eventTarget.addEventListener(type, listener[, options])`
<!-- YAML
added: v14.5.0
-->
@ -1481,6 +1532,7 @@ target.removeEventListener('foo', handler, { capture: true });
```
#### `eventTarget.dispatchEvent(event)`
<!-- YAML
added: v14.5.0
-->
@ -1495,6 +1547,7 @@ The registered event listeners is synchronously invoked in the order they
were registered.
#### `eventTarget.removeEventListener(type, listener)`
<!-- YAML
added: v14.5.0
-->
@ -1507,6 +1560,7 @@ added: v14.5.0
Removes the `listener` from the list of handlers for event `type`.
### Class: `NodeEventTarget`
<!-- YAML
added: v14.5.0
-->
@ -1517,12 +1571,15 @@ The `NodeEventTarget` is a Node.js-specific extension to `EventTarget`
that emulates a subset of the `EventEmitter` API.
#### `nodeEventTarget.addListener(type, listener[, options])`
<!-- YAML
added: v14.5.0
-->
* `type` {string}
* `listener` {Function|EventListener}
* `options` {Object}
* `once` {boolean}
@ -1534,16 +1591,18 @@ equivalent `EventEmitter` API. The only difference between `addListener()` and
`EventTarget`.
#### `nodeEventTarget.eventNames()`
<!-- YAML
added: v14.5.0
-->
* 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)`
<!-- YAML
added: v14.5.0
-->
@ -1556,11 +1615,13 @@ Node.js-specific extension to the `EventTarget` class that returns the number
of event listeners registered for the `type`.
#### `nodeEventTarget.off(type, listener)`
<!-- YAML
added: v14.5.0
-->
* `type` {string}
* `listener` {Function|EventListener}
* Returns: {EventTarget} this
@ -1568,12 +1629,15 @@ added: v14.5.0
Node.js-specific alias for `eventTarget.removeListener()`.
#### `nodeEventTarget.on(type, listener[, options])`
<!-- YAML
added: v14.5.0
-->
* `type` {string}
* `listener` {Function|EventListener}
* `options` {Object}
* `once` {boolean}
@ -1582,12 +1646,15 @@ added: v14.5.0
Node.js-specific alias for `eventTarget.addListener()`.
#### `nodeEventTarget.once(type, listener[, options])`
<!-- YAML
added: v14.5.0
-->
* `type` {string}
* `listener` {Function|EventListener}
* `options` {Object}
* Returns: {EventTarget} this
@ -1597,6 +1664,7 @@ listener for the given event `type`. This is equivalent to calling `on`
with the `once` option set to `true`.
#### `nodeEventTarget.removeAllListeners([type])`
<!-- YAML
added: v14.5.0
-->
@ -1610,11 +1678,13 @@ removes all registered listeners for `type`, otherwise removes all registered
listeners.
#### `nodeEventTarget.removeListener(type, listener)`
<!-- YAML
added: v14.5.0
-->
* `type` {string}
* `listener` {Function|EventListener}
* Returns: {EventTarget} this

File diff suppressed because it is too large Load Diff

View File

@ -19,6 +19,7 @@ that are part of the JavaScript language itself, which are also globally
accessible.
## Class: `AbortController`
<!-- YAML
added:
- v15.0.0
@ -46,6 +47,7 @@ console.log(ac.signal.aborted); // Prints True
```
### `abortController.abort()`
<!-- YAML
added:
- v15.0.0
@ -56,6 +58,7 @@ Triggers the abort signal, causing the `abortController.signal` to emit
the `'abort'` event.
### `abortController.signal`
<!-- YAML
added:
- v15.0.0
@ -65,6 +68,7 @@ added:
* Type: {AbortSignal}
### Class: `AbortSignal`
<!-- YAML
added:
- v15.0.0
@ -77,6 +81,7 @@ The `AbortSignal` is used to notify observers when the
`abortController.abort()` method is called.
#### Static method: `AbortSignal.abort()`
<!-- YAML
added:
- v15.12.0
@ -88,6 +93,7 @@ added:
Returns a new already aborted `AbortSignal`.
#### Event: `'abort'`
<!-- YAML
added:
- v15.0.0
@ -124,6 +130,7 @@ removed as soon as the `'abort'` event is handled. Failure to do so may
result in memory leaks.
#### `abortSignal.aborted`
<!-- YAML
added:
- v15.0.0
@ -133,6 +140,7 @@ added:
* Type: {boolean} True after the `AbortController` has been aborted.
#### `abortSignal.onabort`
<!-- YAML
added:
- v15.0.0
@ -145,6 +153,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`
<!-- YAML
added: v0.1.103
-->
@ -164,6 +173,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)`
<!-- YAML
added: v16.0.0
-->
@ -173,6 +183,7 @@ added: v16.0.0
Global alias for [`buffer.atob()`][].
## `btoa(data)`
<!-- YAML
added: v16.0.0
-->
@ -182,6 +193,7 @@ added: v16.0.0
Global alias for [`buffer.btoa()`][].
## `clearImmediate(immediateObject)`
<!-- YAML
added: v0.9.1
-->
@ -191,6 +203,7 @@ added: v0.9.1
[`clearImmediate`][] is described in the [timers][] section.
## `clearInterval(intervalObject)`
<!-- YAML
added: v0.0.1
-->
@ -200,6 +213,7 @@ added: v0.0.1
[`clearInterval`][] is described in the [timers][] section.
## `clearTimeout(timeoutObject)`
<!-- YAML
added: v0.0.1
-->
@ -209,6 +223,7 @@ added: v0.0.1
[`clearTimeout`][] is described in the [timers][] section.
## `console`
<!-- YAML
added: v0.1.100
-->
@ -220,6 +235,7 @@ added: v0.1.100
Used to print to stdout and stderr. See the [`console`][] section.
## `Event`
<!-- YAML
added: v15.0.0
changes:
@ -234,6 +250,7 @@ A browser-compatible implementation of the `Event` class. See
[`EventTarget` and `Event` API][] for more details.
## `EventTarget`
<!-- YAML
added: v15.0.0
changes:
@ -252,6 +269,7 @@ A browser-compatible implementation of the `EventTarget` class. See
This variable may appear to be global but is not. See [`exports`][].
## `global`
<!-- YAML
added: v0.1.27
-->
@ -266,6 +284,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`
<!-- YAML
added: v15.0.0
-->
@ -275,6 +294,7 @@ added: v15.0.0
The `MessageChannel` class. See [`MessageChannel`][] for more details.
## `MessageEvent`
<!-- YAML
added: v15.0.0
-->
@ -284,6 +304,7 @@ added: v15.0.0
The `MessageEvent` class. See [`MessageEvent`][] for more details.
## `MessagePort`
<!-- YAML
added: v15.0.0
-->
@ -301,6 +322,7 @@ This variable may appear to be global but is not. See [`module`][].
The [`perf_hooks.performance`][] object.
## `process`
<!-- YAML
added: v0.1.7
-->
@ -312,6 +334,7 @@ added: v0.1.7
The process object. See the [`process` object][] section.
## `queueMicrotask(callback)`
<!-- YAML
added: v11.0.0
-->
@ -355,6 +378,7 @@ DataHandler.prototype.load = async function load(key) {
This variable may appear to be global but is not. See [`require()`][].
## `setImmediate(callback[, ...args])`
<!-- YAML
added: v0.9.1
-->
@ -364,6 +388,7 @@ added: v0.9.1
[`setImmediate`][] is described in the [timers][] section.
## `setInterval(callback, delay[, ...args])`
<!-- YAML
added: v0.0.1
-->
@ -373,6 +398,7 @@ added: v0.0.1
[`setInterval`][] is described in the [timers][] section.
## `setTimeout(callback, delay[, ...args])`
<!-- YAML
added: v0.0.1
-->
@ -382,6 +408,7 @@ added: v0.0.1
[`setTimeout`][] is described in the [timers][] section.
## `DOMException`
<!-- YAML
added: v17.0.0
-->
@ -391,6 +418,7 @@ added: v17.0.0
The WHATWG `DOMException` class. See [`DOMException`][] for more details.
## `TextDecoder`
<!-- YAML
added: v11.0.0
-->
@ -400,6 +428,7 @@ added: v11.0.0
The WHATWG `TextDecoder` class. See the [`TextDecoder`][] section.
## `TextEncoder`
<!-- YAML
added: v11.0.0
-->
@ -409,6 +438,7 @@ added: v11.0.0
The WHATWG `TextEncoder` class. See the [`TextEncoder`][] section.
## `URL`
<!-- YAML
added: v10.0.0
-->
@ -418,6 +448,7 @@ added: v10.0.0
The WHATWG `URL` class. See the [`URL`][] section.
## `URLSearchParams`
<!-- YAML
added: v10.0.0
-->
@ -427,6 +458,7 @@ added: v10.0.0
The WHATWG `URLSearchParams` class. See the [`URLSearchParams`][] section.
## `WebAssembly`
<!-- YAML
added: v8.0.0
-->

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -10,6 +10,7 @@ HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.
## Class: `https.Agent`
<!-- YAML
added: v0.4.5
changes:
@ -26,6 +27,7 @@ An [`Agent`][] object for HTTPS similar to [`http.Agent`][]. See
[`https.request()`][] for more information.
### `new Agent([options])`
<!-- YAML
changes:
- version: v12.5.0
@ -48,6 +50,7 @@ changes:
See [`Session Resumption`][] for information about TLS session reuse.
#### Event: `'keylog'`
<!-- YAML
added:
- v13.2.0
@ -75,6 +78,7 @@ https.globalAgent.on('keylog', (line, tlsSocket) => {
```
## Class: `https.Server`
<!-- YAML
added: v0.3.4
-->
@ -84,6 +88,7 @@ added: v0.3.4
See [`http.Server`][] for more information.
### `server.close([callback])`
<!-- YAML
added: v0.1.90
-->
@ -94,6 +99,7 @@ added: v0.1.90
See [`server.close()`][`http.close()`] from the HTTP module for details.
### `server.headersTimeout`
<!-- YAML
added: v11.3.0
-->
@ -114,6 +120,7 @@ This method is identical to [`server.listen()`][] from [`net.Server`][].
See [`http.Server#maxHeadersCount`][].
### `server.requestTimeout`
<!-- YAML
added: v14.11.0
-->
@ -123,6 +130,7 @@ added: v14.11.0
See [`http.Server#requestTimeout`][].
### `server.setTimeout([msecs][, callback])`
<!-- YAML
added: v0.11.2
-->
@ -134,6 +142,7 @@ added: v0.11.2
See [`http.Server#setTimeout()`][].
### `server.timeout`
<!-- YAML
added: v0.11.2
changes:
@ -147,6 +156,7 @@ changes:
See [`http.Server#timeout`][].
### `server.keepAliveTimeout`
<!-- YAML
added: v8.0.0
-->
@ -156,6 +166,7 @@ added: v8.0.0
See [`http.Server#keepAliveTimeout`][].
## `https.createServer([options][, requestListener])`
<!-- YAML
added: v0.3.4
-->
@ -199,7 +210,9 @@ https.createServer(options, (req, res) => {
```
## `https.get(options[, callback])`
## `https.get(url[, options][, callback])`
<!-- YAML
added: v0.3.6
changes:
@ -240,6 +253,7 @@ https.get('https://encrypted.google.com/', (res) => {
```
## `https.globalAgent`
<!-- YAML
added: v0.5.9
-->
@ -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])`
<!-- YAML
added: v0.3.6
changes:

View File

@ -11,13 +11,13 @@
<hr class="line"/>
* [Assertion testing](assert.md)
* [Async_context](async_context.md)
* [Async hooks](async_hooks.md)
* [Async\_context](async\_context.md)
* [Async hooks](async\_hooks.md)
* [Buffer](buffer.md)
* [C++ addons](addons.md)
* [C/C++ addons with Node-API](n-api.md)
* [C++ embedder API](embedding.md)
* [Child processes](child_process.md)
* [Child processes](child\_process.md)
* [Cluster](cluster.md)
* [Command-line options](cli.md)
* [Console](console.md)
@ -25,7 +25,7 @@
* [Crypto](crypto.md)
* [Debugger](debugger.md)
* [Deprecated APIs](deprecations.md)
* [Diagnostics Channel](diagnostics_channel.md)
* [Diagnostics Channel](diagnostics\_channel.md)
* [DNS](dns.md)
* [Domain](domain.md)
* [Errors](errors.md)
@ -44,7 +44,7 @@
* [Net](net.md)
* [OS](os.md)
* [Path](path.md)
* [Performance hooks](perf_hooks.md)
* [Performance hooks](perf\_hooks.md)
* [Policies](policy.md)
* [Process](process.md)
* [Punycode](punycode.md)
@ -53,7 +53,7 @@
* [REPL](repl.md)
* [Report](report.md)
* [Stream](stream.md)
* [String decoder](string_decoder.md)
* [String decoder](string\_decoder.md)
* [Timers](timers.md)
* [TLS/SSL](tls.md)
* [Trace events](tracing.md)
@ -66,7 +66,7 @@
* [WASI](wasi.md)
* [Web Crypto API](webcrypto.md)
* [Web Streams API](webstreams.md)
* [Worker threads](worker_threads.md)
* [Worker threads](worker\_threads.md)
* [Zlib](zlib.md)
<hr class="line"/>

View File

@ -38,8 +38,8 @@ console.
* `wait` {boolean} Block until a client has connected. Optional.
**Default:** `false`.
Activate inspector on host and port. Equivalent to `node
--inspect=[[host:]port]`, but can be done programmatically after node has
Activate inspector on host and port. Equivalent to
`node --inspect=[[host:]port]`, but can be done programmatically after node has
started.
If wait is `true`, will block until a client has connected to the inspect port
@ -70,6 +70,7 @@ undefined
```
## `inspector.waitForDebugger()`
<!-- YAML
added: v12.7.0
-->
@ -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()`
<!-- YAML
added: v8.0.0
-->
@ -96,6 +98,7 @@ needs to be connected through [`session.connect()`][] before the messages
can be dispatched to the inspector backend.
### Event: `'inspectorNotification'`
<!-- YAML
added: v8.0.0
-->
@ -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: `<inspector-protocol-method>`;
<!-- YAML
added: v8.0.0
-->
@ -134,6 +138,7 @@ session.on('Debugger.paused', ({ params }) => {
```
### `session.connect()`
<!-- YAML
added: v8.0.0
-->
@ -141,6 +146,7 @@ added: v8.0.0
Connects a session to the inspector back-end.
### `session.connectToMainThread()`
<!-- YAML
added: v12.11.0
-->
@ -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()`
<!-- YAML
added: v8.0.0
-->
@ -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])`
<!-- YAML
added: v8.0.0
-->

View File

@ -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.

View File

@ -15,6 +15,7 @@ Provides general utility methods when interacting with instances of
via `import 'module'` or `require('module')`.
### `module.builtinModules`
<!-- YAML
added:
- v9.3.0
@ -22,7 +23,7 @@ added:
- v6.13.0
-->
* {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)`
<!-- YAML
added: v12.2.0
-->
@ -61,6 +63,7 @@ const siblingModule = require('./sibling-module');
```
### `module.syncBuiltinESMExports()`
<!-- YAML
added: v12.12.0
-->
@ -99,6 +102,7 @@ import('fs').then((esmFS) => {
```
## Source map v3 support
<!-- YAML
added:
- v13.7.0
@ -128,7 +132,9 @@ const { findSourceMap, SourceMap } = require('module');
```
<!-- Anchors to make sure old links find a target -->
<a id="module_module_findsourcemap_path_error"></a>
### `module.findSourceMap(path)`
<!-- YAML
@ -144,6 +150,7 @@ added:
should be fetched.
### Class: `module.SourceMap`
<!-- YAML
added:
- v13.7.0
@ -160,9 +167,9 @@ Creates a new `sourceMap` instance.
* `file`: {string}
* `version`: {number}
* `sources`: {string[]}
* `sourcesContent`: {string[]}
* `names`: {string[]}
* `sources`: {string\[]}
* `sourcesContent`: {string\[]}
* `names`: {string\[]}
* `mappings`: {string}
* `sourceRoot`: {string}

View File

@ -99,7 +99,7 @@ package may itself have dependencies, and in some cases, these may even collide
or form cyclic dependencies.
Because Node.js looks up the `realpath` of any modules it loads (that is, it
resolves symlinks) and then [looks for their dependencies in `node_modules` folders](#loading-from-node_modules-folders),
resolves symlinks) and then [looks for their dependencies in `node_modules` folders](#loading-from-node\_modules-folders),
this situation can be resolved with the following architecture:
* `/usr/lib/node/foo/1.2.3/`: Contents of the `foo` package, version 1.2.3.
@ -268,7 +268,7 @@ function.
Modules are cached based on their resolved filename. Since modules may resolve
to a different filename based on the location of the calling module (loading
from `node_modules` folders), it is not a *guarantee* that `require('foo')` will
from `node_modules` folders), it is not a _guarantee_ that `require('foo')` will
always return the exact same object, if it would resolve to different files.
Additionally, on case-insensitive file systems or operating systems, different
@ -487,7 +487,7 @@ when people are unaware that `NODE_PATH` must be set. Sometimes a
module's dependencies change, causing a different version (or even a
different module) to be loaded as the `NODE_PATH` is searched.
Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:
Additionally, Node.js will search in the following list of GLOBAL\_FOLDERS:
* 1: `$HOME/.node_modules`
* 2: `$HOME/.node_libraries`
@ -528,6 +528,7 @@ By doing this, Node.js achieves a few things:
## The module scope
### `__dirname`
<!-- YAML
added: v0.1.27
-->
@ -549,6 +550,7 @@ console.log(path.dirname(__filename));
```
### `__filename`
<!-- YAML
added: v0.0.1
-->
@ -587,6 +589,7 @@ References to `__filename` within `b.js` will return
`a.js` will return `/Users/mjr/app/a.js`.
### `exports`
<!-- YAML
added: v0.1.12
-->
@ -600,6 +603,7 @@ See the section about the [exports shortcut][] for details on when to use
`exports` and when to use `module.exports`.
### `module`
<!-- YAML
added: v0.1.16
-->
@ -613,6 +617,7 @@ A reference to the current module, see the section about the
a module exports and makes available through `require()`.
### `require(id)`
<!-- YAML
added: v0.1.13
-->
@ -643,6 +648,7 @@ const crypto = require('crypto');
```
#### `require.cache`
<!-- YAML
added: v0.3.0
-->
@ -660,6 +666,7 @@ only `node:`-prefixed require calls are going to receive the native module.
Use with care!
<!-- eslint-disable node-core/no-duplicate-requires -->
```js
const assert = require('assert');
const realFs = require('fs');
@ -672,6 +679,7 @@ assert.strictEqual(require('node:fs'), realFs);
```
#### `require.extensions`
<!-- YAML
added: v0.3.0
deprecated: v0.10.6
@ -698,6 +706,7 @@ Avoid using `require.extensions`. Use could cause subtle bugs and resolving the
extensions gets slower with each registered extension.
#### `require.main`
<!-- YAML
added: v0.1.17
-->
@ -719,6 +728,7 @@ node entry.js
```
<!-- eslint-skip -->
```js
Module {
id: '.',
@ -735,6 +745,7 @@ Module {
```
#### `require.resolve(request[, options])`
<!-- YAML
added: v0.3.0
changes:
@ -745,10 +756,10 @@ changes:
* `request` {string} The module path to resolve.
* `options` {Object}
* `paths` {string[]} Paths to resolve module location from. If present, these
* `paths` {string\[]} Paths to resolve module location from. If present, these
paths are used instead of the default resolution paths, with the exception
of [GLOBAL_FOLDERS][] like `$HOME/.node_modules`, which are always
included. Each of these paths is used as a starting point for
of [GLOBAL\_FOLDERS][GLOBAL_FOLDERS] like `$HOME/.node_modules`, which are
always included. Each of these paths is used as a starting point for
the module resolution algorithm, meaning that the `node_modules` hierarchy
is checked from this location.
* Returns: {string}
@ -759,18 +770,20 @@ but rather than loading the module, just return the resolved filename.
If the module can not be found, a `MODULE_NOT_FOUND` error is thrown.
##### `require.resolve.paths(request)`
<!-- YAML
added: v8.9.0
-->
* `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
<!-- YAML
added: v0.1.16
-->
@ -787,15 +800,17 @@ also accessible via the `exports` module-global. `module` is not actually
a global but rather local to each module.
### `module.children`
<!-- YAML
added: v0.1.16
-->
* {module[]}
* {module\[]}
The module objects required for the first time by this one.
### `module.exports`
<!-- YAML
added: v0.1.16
-->
@ -850,6 +865,7 @@ console.log(x.a);
```
#### `exports` shortcut
<!-- YAML
added: v0.1.16
-->
@ -870,6 +886,7 @@ When the `module.exports` property is being completely replaced by a new
object, it is common to also reassign `exports`:
<!-- eslint-disable func-name-matching -->
```js
module.exports = exports = function Constructor() {
// ... etc.
@ -897,6 +914,7 @@ function require(/* ... */) {
```
### `module.filename`
<!-- YAML
added: v0.1.16
-->
@ -906,6 +924,7 @@ added: v0.1.16
The fully resolved filename of the module.
### `module.id`
<!-- YAML
added: v0.1.16
-->
@ -916,6 +935,7 @@ The identifier for the module. Typically this is the fully resolved
filename.
### `module.isPreloading`
<!-- YAML
added:
- v15.4.0
@ -926,6 +946,7 @@ added:
phase.
### `module.loaded`
<!-- YAML
added: v0.1.16
-->
@ -936,6 +957,7 @@ Whether or not the module is done loading, or is in the process of
loading.
### `module.parent`
<!-- YAML
added: v0.1.16
deprecated:
@ -953,6 +975,7 @@ entry point of the current process, or `undefined` if the module was loaded by
something that is not a CommonJS module (E.G.: REPL or `import`).
### `module.path`
<!-- YAML
added: v11.14.0
-->
@ -963,15 +986,17 @@ The directory name of the module. This is usually the same as the
[`path.dirname()`][] of the [`module.id`][].
### `module.paths`
<!-- YAML
added: v0.4.0
-->
* {string[]}
* {string\[]}
The search paths for the module.
### `module.require(id)`
<!-- YAML
added: v0.5.1
-->
@ -984,7 +1009,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
@ -993,6 +1018,7 @@ This section was moved to
[Modules: `module` core module](module.md#the-module-object).
<!-- Anchors to make sure old links find a target -->
* <a id="modules_module_builtinmodules" href="module.html#modulebuiltinmodules">`module.builtinModules`</a>
* <a id="modules_module_createrequire_filename" href="module.html#modulecreaterequirefilename">`module.createRequire(filename)`</a>
* <a id="modules_module_syncbuiltinesmexports" href="module.html#modulesyncbuiltinesmexports">`module.syncBuiltinESMExports()`</a>
@ -1003,6 +1029,7 @@ This section was moved to
[Modules: `module` core module](module.md#source-map-v3-support).
<!-- Anchors to make sure old links find a target -->
* <a id="modules_module_findsourcemap_path_error" href="module.html#modulefindsourcemappath">`module.findSourceMap(path)`</a>
* <a id="modules_class_module_sourcemap" href="module.html#class-modulesourcemap">Class: `module.SourceMap`</a>
* <a id="modules_new_sourcemap_payload" href="module.html#new-sourcemappayload">`new SourceMap(payload)`</a>

File diff suppressed because it is too large Load Diff

View File

@ -40,11 +40,11 @@ applies when a Node.js API creates a Unix domain socket but the program then
crashes. In short, a Unix domain socket will be visible in the filesystem and
will persist until unlinked.
On Windows, the local domain is implemented using a named pipe. The path *must*
On Windows, the local domain is implemented using a named pipe. The path _must_
refer to an entry in `\\?\pipe\` or `\\.\pipe\`. Any characters are permitted,
but the latter may do some processing of pipe names, such as resolving `..`
sequences. Despite how it might look, the pipe namespace is flat. Pipes will
*not persist*. They are removed when the last reference to them is closed.
_not persist_. They are removed when the last reference to them is closed.
Unlike Unix domain sockets, Windows will close and remove the pipe when the
owning process exits.
@ -57,6 +57,7 @@ net.createServer().listen(
```
## Class: `net.BlockList`
<!-- YAML
added:
- v15.0.0
@ -68,6 +69,7 @@ disabling inbound or outbound access to specific IP addresses, IP ranges, or
IP subnets.
### `blockList.addAddress(address[, type])`
<!-- YAML
added:
- v15.0.0
@ -80,6 +82,7 @@ added:
Adds a rule to block the given IP address.
### `blockList.addRange(start, end[, type])`
<!-- YAML
added:
- v15.0.0
@ -95,6 +98,7 @@ Adds a rule to block a range of IP addresses from `start` (inclusive) to
`end` (inclusive).
### `blockList.addSubnet(net, prefix[, type])`
<!-- YAML
added:
- v15.0.0
@ -110,6 +114,7 @@ added:
Adds a rule to block a range of IP addresses specified as a subnet mask.
### `blockList.check(address[, type])`
<!-- YAML
added:
- v15.0.0
@ -139,23 +144,27 @@ console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true
```
### `blockList.rules`
<!-- YAML
added:
- v15.0.0
- v14.18.0
-->
* Type: {string[]}
* Type: {string\[]}
The list of rules added to the blocklist.
## Class: `net.SocketAddress`
<!-- YAML
added:
- v15.14.0
- v14.18.0
-->
### `new net.SocketAddress([options])`
<!-- YAML
added:
- v15.14.0
@ -166,11 +175,13 @@ added:
* `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`
<!-- YAML
added:
- v15.14.0
@ -180,6 +191,7 @@ added:
* Type {string}
### `socketaddress.family`
<!-- YAML
added:
- v15.14.0
@ -189,6 +201,7 @@ added:
* Type {string} Either `'ipv4'` or `'ipv6'`.
### `socketaddress.flowlabel`
<!-- YAML
added:
- v15.14.0
@ -198,6 +211,7 @@ added:
* Type {number}
### `socketaddress.port`
<!-- YAML
added:
- v15.14.0
@ -207,6 +221,7 @@ added:
* Type {number}
## Class: `net.Server`
<!-- YAML
added: v0.1.90
-->
@ -226,6 +241,7 @@ This class is used to create a TCP or [IPC][] server.
`net.Server` is an [`EventEmitter`][] with the following events:
### Event: `'close'`
<!-- YAML
added: v0.5.0
-->
@ -234,6 +250,7 @@ Emitted when the server closes. If connections exist, this
event is not emitted until all connections are ended.
### Event: `'connection'`
<!-- YAML
added: v0.1.90
-->
@ -244,6 +261,7 @@ Emitted when a new connection is made. `socket` is an instance of
`net.Socket`.
### Event: `'error'`
<!-- YAML
added: v0.1.90
-->
@ -256,6 +274,7 @@ event will **not** be emitted directly following this event unless
[`server.listen()`][].
### Event: `'listening'`
<!-- YAML
added: v0.1.90
-->
@ -263,6 +282,7 @@ added: v0.1.90
Emitted when the server has been bound after calling [`server.listen()`][].
### `server.address()`
<!-- YAML
added: v0.1.90
-->
@ -295,6 +315,7 @@ server.listen(() => {
emitted or after calling `server.close()`.
### `server.close([callback])`
<!-- YAML
added: v0.1.90
-->
@ -310,6 +331,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)`
<!-- YAML
added: v0.9.7
-->
@ -329,15 +351,12 @@ an [IPC][] server depending on what it listens to.
Possible signatures:
<!--lint disable no-undefined-references-->
* [`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
* <a href="#serverlistenport-host-backlog-callback">
<code>server.listen([port[, host[, backlog]]][, callback])</code></a>
* [`server.listen([port[, host[, backlog]]][, callback])`][`server.listen(port)`]
for TCP servers
<!--lint enable no-undefined-references-->
This function is asynchronous. When the server starts listening, the
[`'listening'`][] event will be emitted. The last parameter `callback`
@ -373,6 +392,7 @@ server.on('error', (e) => {
```
#### `server.listen(handle[, backlog][, callback])`
<!-- YAML
added: v0.5.10
-->
@ -392,6 +412,7 @@ valid file descriptor.
Listening on a file descriptor is not supported on Windows.
#### `server.listen(options[, callback])`
<!-- YAML
added: v0.11.14
changes:
@ -423,14 +444,11 @@ changes:
functions.
* Returns: {net.Server}
<!--lint disable no-undefined-references-->
If `port` is specified, it behaves the same as
<a href="#serverlistenport-host-backlog-callback">
<code>server.listen([port[, host[, backlog]]][, callback])</code></a>.
[`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.
<!--lint enable no-undefined-references-->
If `exclusive` is `false` (default), then cluster workers will use the same
underlying handle, allowing connection handling duties to be shared. When
@ -465,6 +483,7 @@ controller.abort();
```
#### `server.listen(path[, backlog][, callback])`
<!-- YAML
added: v0.1.90
-->
@ -478,6 +497,7 @@ added: v0.1.90
Start an [IPC][] server listening for connections on the given `path`.
#### `server.listen([port[, host[, backlog]]][, callback])`
<!-- YAML
added: v0.1.90
-->
@ -503,6 +523,7 @@ may cause the `net.Server` to also listen on the [unspecified IPv4 address][]
(`0.0.0.0`).
### `server.listening`
<!-- YAML
added: v5.7.0
-->
@ -510,6 +531,7 @@ added: v5.7.0
* {boolean} Indicates whether or not the server is listening for connections.
### `server.maxConnections`
<!-- YAML
added: v0.2.0
-->
@ -523,6 +545,7 @@ It is not recommended to use this option once a socket has been sent to a child
with [`child_process.fork()`][].
### `server.ref()`
<!-- YAML
added: v0.9.1
-->
@ -530,10 +553,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()`
<!-- YAML
added: v0.9.1
-->
@ -545,6 +569,7 @@ active server in the event system. If the server is already `unref`ed calling
`unref()` again will have no effect.
## Class: `net.Socket`
<!-- YAML
added: v0.3.4
-->
@ -565,6 +590,7 @@ is received. For example, it is passed to the listeners of a
it to interact with the client.
### `new net.Socket([options])`
<!-- YAML
added: v0.3.4
changes:
@ -594,6 +620,7 @@ The newly created socket can be either a TCP socket or a streaming [IPC][]
endpoint, depending on what it [`connect()`][`socket.connect()`] to.
### Event: `'close'`
<!-- YAML
added: v0.1.90
-->
@ -604,6 +631,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'`
<!-- YAML
added: v0.1.90
-->
@ -612,6 +640,7 @@ Emitted when a socket connection is successfully established.
See [`net.createConnection()`][].
### Event: `'data'`
<!-- YAML
added: v0.1.90
-->
@ -625,6 +654,7 @@ The data will be lost if there is no listener when a `Socket`
emits a `'data'` event.
### Event: `'drain'`
<!-- YAML
added: v0.1.90
-->
@ -634,6 +664,7 @@ Emitted when the write buffer becomes empty. Can be used to throttle uploads.
See also: the return values of `socket.write()`.
### Event: `'end'`
<!-- YAML
added: v0.1.90
-->
@ -650,6 +681,7 @@ allowing the user to write arbitrary amounts of data. The user must call
FIN packet back).
### Event: `'error'`
<!-- YAML
added: v0.1.90
-->
@ -660,6 +692,7 @@ Emitted when an error occurs. The `'close'` event will be called directly
following this event.
### Event: `'lookup'`
<!-- YAML
added: v0.11.3
changes:
@ -677,6 +710,7 @@ Not applicable to Unix sockets.
* `host` {string} The host name.
### Event: `'ready'`
<!-- YAML
added: v9.11.0
-->
@ -686,6 +720,7 @@ Emitted when a socket is ready to be used.
Triggered immediately after `'connect'`.
### Event: `'timeout'`
<!-- YAML
added: v0.1.90
-->
@ -696,6 +731,7 @@ the socket has been idle. The user must manually close the connection.
See also: [`socket.setTimeout()`][].
### `socket.address()`
<!-- YAML
added: v0.1.90
-->
@ -707,6 +743,7 @@ socket as reported by the operating system:
`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`
### `socket.bufferSize`
<!-- YAML
added: v0.3.8
deprecated:
@ -733,6 +770,7 @@ Users who experience large or growing `bufferSize` should attempt to
[`socket.pause()`][] and [`socket.resume()`][].
### `socket.bytesRead`
<!-- YAML
added: v0.5.3
-->
@ -742,6 +780,7 @@ added: v0.5.3
The amount of received bytes.
### `socket.bytesWritten`
<!-- YAML
added: v0.5.3
-->
@ -775,6 +814,7 @@ This function should only be used for reconnecting a socket after
behavior.
#### `socket.connect(options[, connectListener])`
<!-- YAML
added: v0.1.90
changes:
@ -865,6 +905,7 @@ Alias to
called with `{ path: path }` as `options`.
#### `socket.connect(port[, host][, connectListener])`
<!-- YAML
added: v0.1.90
-->
@ -882,6 +923,7 @@ Alias to
called with `{port: port, host: host}` as `options`.
### `socket.connecting`
<!-- YAML
added: v6.1.0
-->
@ -897,6 +939,7 @@ that the
callback is a listener for the `'connect'` event.
### `socket.destroy([error])`
<!-- YAML
added: v0.1.90
-->
@ -917,6 +960,7 @@ See [`writable.destroy()`][] for further details.
See [`writable.destroyed`][] for further details.
### `socket.end([data[, encoding]][, callback])`
<!-- YAML
added: v0.1.90
-->
@ -932,6 +976,7 @@ server will still send some data.
See [`writable.end()`][] for further details.
### `socket.localAddress`
<!-- YAML
added: v0.9.6
-->
@ -944,6 +989,7 @@ connects on `'192.168.1.1'`, the value of `socket.localAddress` would be
`'192.168.1.1'`.
### `socket.localPort`
<!-- YAML
added: v0.9.6
-->
@ -960,6 +1006,7 @@ Pauses the reading of data. That is, [`'data'`][] events will not be emitted.
Useful to throttle back an upload.
### `socket.pending`
<!-- YAML
added:
- v11.2.0
@ -973,6 +1020,7 @@ has not yet been called or because it is still in the process of connecting
(see [`socket.connecting`][]).
### `socket.ref()`
<!-- YAML
added: v0.9.1
-->
@ -980,10 +1028,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`
<!-- YAML
added: v0.5.10
-->
@ -995,6 +1044,7 @@ The string representation of the remote IP address. For example,
the socket is destroyed (for example, if the client disconnected).
### `socket.remoteFamily`
<!-- YAML
added: v0.11.14
-->
@ -1004,6 +1054,7 @@ added: v0.11.14
The string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
### `socket.remotePort`
<!-- YAML
added: v0.5.10
-->
@ -1019,6 +1070,7 @@ The numeric representation of the remote port. For example, `80` or `21`.
Resumes reading after a call to [`socket.pause()`][].
### `socket.setEncoding([encoding])`
<!-- YAML
added: v0.1.90
-->
@ -1030,6 +1082,7 @@ Set the encoding for the socket as a [Readable Stream][]. See
[`readable.setEncoding()`][] for more information.
### `socket.setKeepAlive([enable][, initialDelay])`
<!-- YAML
added: v0.1.92
changes:
@ -1053,12 +1106,14 @@ data packet received and the first keepalive probe. Setting `0` for
(or previous) setting.
Enabling the keep-alive functionality will set the following socket options:
* `SO_KEEPALIVE=1`
* `TCP_KEEPIDLE=initialDelay`
* `TCP_KEEPCNT=10`
* `TCP_KEEPINTVL=1`
### `socket.setNoDelay([noDelay])`
<!-- YAML
added: v0.1.90
-->
@ -1078,6 +1133,7 @@ algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's
algorithm.
### `socket.setTimeout(timeout[, callback])`
<!-- YAML
added: v0.1.90
-->
@ -1107,6 +1163,7 @@ The optional `callback` parameter will be added as a one-time listener for the
[`'timeout'`][] event.
### `socket.timeout`
<!-- YAML
added: v10.7.0
-->
@ -1117,6 +1174,7 @@ The socket timeout in milliseconds as set by [`socket.setTimeout()`][].
It is `undefined` if a timeout has not been set.
### `socket.unref()`
<!-- YAML
added: v0.9.1
-->
@ -1128,6 +1186,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])`
<!-- YAML
added: v0.1.90
-->
@ -1151,6 +1210,7 @@ See `Writable` stream [`write()`][stream_writable_write] method for more
information.
### `socket.readyState`
<!-- YAML
added: v0.5.0
-->
@ -1178,6 +1238,7 @@ Possible signatures:
for TCP connections.
### `net.connect(options[, connectListener])`
<!-- YAML
added: v0.7.0
-->
@ -1190,6 +1251,7 @@ Alias to
[`net.createConnection(options[, connectListener])`][`net.createConnection(options)`].
### `net.connect(path[, connectListener])`
<!-- YAML
added: v0.1.90
-->
@ -1202,6 +1264,7 @@ Alias to
[`net.createConnection(path[, connectListener])`][`net.createConnection(path)`].
### `net.connect(port[, host][, connectListener])`
<!-- YAML
added: v0.1.90
-->
@ -1235,6 +1298,7 @@ Possible signatures:
The [`net.connect()`][] function is an alias to this function.
### `net.createConnection(options[, connectListener])`
<!-- YAML
added: v0.1.90
-->
@ -1284,6 +1348,7 @@ const client = net.createConnection({ path: '/tmp/echo.sock' });
```
### `net.createConnection(path[, connectListener])`
<!-- YAML
added: v0.1.90
-->
@ -1305,6 +1370,7 @@ immediately initiates connection with
then returns the `net.Socket` that starts the connection.
### `net.createConnection(port[, host][, connectListener])`
<!-- YAML
added: v0.1.90
-->
@ -1328,6 +1394,7 @@ immediately initiates connection with
then returns the `net.Socket` that starts the connection.
## `net.createServer([options][, connectionListener])`
<!-- YAML
added: v0.5.0
-->
@ -1404,6 +1471,7 @@ $ nc -U /tmp/echo.sock
```
## `net.isIP(input)`
<!-- YAML
added: v0.3.0
-->
@ -1416,6 +1484,7 @@ returns `4` for IP version 4 addresses, and returns `6` for IP version 6
addresses.
## `net.isIPv4(input)`
<!-- YAML
added: v0.3.0
-->
@ -1426,6 +1495,7 @@ added: v0.3.0
Returns `true` if input is a version 4 IP address, otherwise returns `false`.
## `net.isIPv6(input)`
<!-- YAML
added: v0.3.0
-->
@ -1469,6 +1539,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

View File

@ -14,6 +14,7 @@ const os = require('os');
```
## `os.EOL`
<!-- YAML
added: v0.7.8
-->
@ -26,6 +27,7 @@ The operating system-specific end-of-line marker.
* `\r\n` on Windows
## `os.arch()`
<!-- YAML
added: v0.5.0
-->
@ -39,6 +41,7 @@ compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,
The return value is equivalent to [`process.arch`][].
## `os.constants`
<!-- YAML
added: v6.3.0
-->
@ -50,11 +53,12 @@ process signals, and so on. The specific constants defined are described in
[OS constants](#os-constants).
## `os.cpus()`
<!-- YAML
added: v0.3.3
-->
* 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.
<!-- eslint-disable semi -->
```js
[
{
@ -123,6 +128,7 @@ The properties included on each object include:
are always 0.
## `os.devNull`
<!-- YAML
added:
- v16.3.0
@ -137,6 +143,7 @@ The platform-specific file path of the null device.
* `/dev/null` on POSIX
## `os.endianness()`
<!-- YAML
added: v0.9.4
-->
@ -149,6 +156,7 @@ binary was compiled.
Possible values are `'BE'` for big endian and `'LE'` for little endian.
## `os.freemem()`
<!-- YAML
added: v0.3.3
-->
@ -158,6 +166,7 @@ added: v0.3.3
Returns the amount of free system memory in bytes as an integer.
## `os.getPriority([pid])`
<!-- YAML
added: v10.10.0
-->
@ -170,6 +179,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()`
<!-- YAML
added: v2.3.0
-->
@ -185,6 +195,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()`
<!-- YAML
added: v0.3.3
-->
@ -194,11 +205,12 @@ added: v0.3.3
Returns the host name of the operating system as a string.
## `os.loadavg()`
<!-- YAML
added: v0.3.3
-->
* Returns: {number[]}
* Returns: {number\[]}
Returns an array containing the 1, 5, and 15 minute load averages.
@ -209,6 +221,7 @@ The load average is a Unix-specific concept. On Windows, the return value is
always `[0, 0, 0]`.
## `os.networkInterfaces()`
<!-- YAML
added: v0.6.0
-->
@ -236,6 +249,7 @@ The properties available on the assigned network address object include:
to `null`.
<!-- eslint-skip -->
```js
{
lo: [
@ -280,6 +294,7 @@ The properties available on the assigned network address object include:
```
## `os.platform()`
<!-- YAML
added: v0.5.0
-->
@ -296,6 +311,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()`
<!-- YAML
added: v0.3.3
-->
@ -309,6 +325,7 @@ On POSIX systems, the operating system release is determined by calling
<https://en.wikipedia.org/wiki/Uname#Examples> for more information.
## `os.setPriority([pid, ]priority)`
<!-- YAML
added: v10.10.0
-->
@ -332,6 +349,7 @@ privileges. Otherwise the set priority will be silently reduced to
`PRIORITY_HIGH`.
## `os.tmpdir()`
<!-- YAML
added: v0.9.9
changes:
@ -347,6 +365,7 @@ Returns the operating system's default directory for temporary files as a
string.
## `os.totalmem()`
<!-- YAML
added: v0.3.3
-->
@ -356,6 +375,7 @@ added: v0.3.3
Returns the total amount of system memory in bytes as an integer.
## `os.type()`
<!-- YAML
added: v0.3.3
-->
@ -369,6 +389,7 @@ See <https://en.wikipedia.org/wiki/Uname#Examples> for additional information
about the output of running [`uname(3)`][] on various operating systems.
## `os.uptime()`
<!-- YAML
added: v0.3.3
changes:
@ -383,6 +404,7 @@ changes:
Returns the system uptime in number of seconds.
## `os.userInfo([options])`
<!-- YAML
added: v6.0.0
-->
@ -406,6 +428,7 @@ operating system response.
Throws a [`SystemError`][] if a user has no `username` or `homedir`.
## `os.version()`
<!-- YAML
added:
- v13.11.0
@ -428,6 +451,7 @@ The following constants are exported by `os.constants`.
Not all constants will be available on every operating system.
### Signal constants
<!-- YAML
changes:
- version: v5.11.0
@ -1217,6 +1241,7 @@ information.
</table>
### Priority constants
<!-- YAML
added: v10.10.0
-->

View File

@ -140,6 +140,7 @@ package:
`"commonjs"` package).
### `--input-type` flag
<!-- YAML
added: v12.0.0
-->
@ -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
<!-- YAML
added: v12.7.0
-->
@ -308,6 +310,7 @@ import submodule from 'es-module-package/private-module.js';
```
### Subpath imports
<!-- YAML
added:
- v14.6.0
@ -350,6 +353,7 @@ The resolution rules for the imports field are otherwise
analogous to the exports field.
### Subpath patterns
<!-- YAML
added:
- v14.13.0
@ -423,6 +427,7 @@ import featureX from 'es-module-package/features/x';
```
### Exports sugar
<!-- YAML
added: v12.11.0
-->
@ -450,6 +455,7 @@ can be written:
```
### Conditional exports
<!-- YAML
added:
- v13.2.0
@ -564,6 +570,7 @@ the remaining conditions of the parent condition. In this way nested
conditions behave analogously to nested JavaScript `if` statements.
### Resolving user conditions
<!-- YAML
added:
- v14.9.0
@ -635,6 +642,7 @@ The above definitions may be moved to a dedicated conditions registry in due
course.
### Self-referencing a package using its name
<!-- YAML
added:
- v13.1.0
@ -779,16 +787,16 @@ Every pattern has tradeoffs, but there are two broad approaches that satisfy the
following conditions:
1. The package is usable via both `require` and `import`.
1. The package is usable in both current Node.js and older versions of Node.js
2. The package is usable in both current Node.js and older versions of Node.js
that lack support for ES modules.
1. The package main entry point, e.g. `'pkg'` can be used by both `require` to
3. The package main entry point, e.g. `'pkg'` can be used by both `require` to
resolve to a CommonJS file and by `import` to resolve to an ES module file.
(And likewise for exported paths, e.g. `'pkg/feature'`.)
1. The package provides named exports, e.g. `import { name } from 'pkg'` rather
4. The package provides named exports, e.g. `import { name } from 'pkg'` rather
than `import pkg from 'pkg'; pkg.name`.
1. The package is potentially usable in other ES module environments such as
5. The package is potentially usable in other ES module environments such as
browsers.
1. The hazards described in the previous section are avoided or minimized.
6. The hazards described in the previous section are avoided or minimized.
#### Approach #1: Use an ES module wrapper
@ -844,6 +852,7 @@ export default cjsModule;
```
This approach is appropriate for any of the following use cases:
* The package is currently written in CommonJS and the author would prefer not
to refactor it into ES module syntax, but wishes to provide named exports for
ES module consumers.
@ -924,7 +933,7 @@ CommonJS and ES module instances of the package:
object, or modify a passed-in object, to keep the state external to the
package.
1. Isolate the state in one or more CommonJS files that are shared between the
2. Isolate the state in one or more CommonJS files that are shared between the
CommonJS and ES module versions of the package. For example, if the CommonJS
and ES module entry points are `index.cjs` and `index.mjs`, respectively:
@ -951,6 +960,7 @@ Any plugins that attach to the packages singleton would need to separately
attach to both the CommonJS and ES module singletons.
This approach is appropriate for any of the following use cases:
* The package is currently written in ES module syntax and the package author
wants that version to be used wherever such syntax is supported.
* The package is stateless or its state can be isolated without too much
@ -1000,6 +1010,7 @@ The following fields in `package.json` files are used in Node.js:
itself.
### `"name"`
<!-- YAML
added:
- v13.1.0
@ -1028,6 +1039,7 @@ The `"name"` field can be used in addition to the [`"exports"`][] field to
[self-reference][] a package using its name.
### `"main"`
<!-- YAML
added: v0.4.0
-->
@ -1052,6 +1064,7 @@ When a package has an [`"exports"`][] field, this will take precedence over the
`"main"` field when importing the package by name.
### `"packageManager"`
<!-- YAML
added: v16.9.0
-->
@ -1076,6 +1089,7 @@ This field is currently experimental and needs to be opted-in; check the
[Corepack][] page for details about the procedure.
### `"type"`
<!-- YAML
added: v12.0.0
changes:
@ -1097,7 +1111,7 @@ Files ending with `.js` are loaded as ES modules when the nearest parent
The nearest parent `package.json` is defined as the first `package.json` found
when searching in the current folder, that folders parent, and so on up
until a node_modules folder or the volume root is reached.
until a node\_modules folder or the volume root is reached.
```json
// package.json
@ -1128,6 +1142,7 @@ Regardless of the value of the `"type"` field, `.mjs` files are always treated
as ES modules and `.cjs` files are always treated as CommonJS.
### `"exports"`
<!-- YAML
added: v12.7.0
changes:
@ -1153,7 +1168,7 @@ changes:
description: Implement conditional exports.
-->
* Type: {Object} | {string} | {string[]}
* Type: {Object} | {string} | {string\[]}
```json
{
@ -1175,6 +1190,7 @@ All paths defined in the `"exports"` must be relative file URLs starting with
`./`.
### `"imports"`
<!-- YAML
added:
- v14.6.0

View File

@ -63,6 +63,7 @@ example, `path.resolve('C:\\')` can potentially return a different result than
[this MSDN page][MSDN-Rel-Path].
## `path.basename(path[, ext])`
<!-- YAML
added: v0.1.25
changes:
@ -104,6 +105,7 @@ A [`TypeError`][] is thrown if `path` is not a string or if `ext` is given
and is not a string.
## `path.delimiter`
<!-- YAML
added: v0.9.3
-->
@ -136,6 +138,7 @@ process.env.PATH.split(path.delimiter);
```
## `path.dirname(path)`
<!-- YAML
added: v0.1.16
changes:
@ -159,6 +162,7 @@ path.dirname('/foo/bar/baz/asdf/quux');
A [`TypeError`][] is thrown if `path` is not a string.
## `path.extname(path)`
<!-- YAML
added: v0.1.25
changes:
@ -199,6 +203,7 @@ path.extname('.index.md');
A [`TypeError`][] is thrown if `path` is not a string.
## `path.format(pathObject)`
<!-- YAML
added: v0.11.15
-->
@ -263,6 +268,7 @@ path.format({
```
## `path.isAbsolute(path)`
<!-- YAML
added: v0.11.2
-->
@ -298,6 +304,7 @@ path.isAbsolute('.'); // false
A [`TypeError`][] is thrown if `path` is not a string.
## `path.join([...paths])`
<!-- YAML
added: v0.1.16
-->
@ -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)`
<!-- YAML
added: v0.1.23
-->
@ -366,6 +374,7 @@ path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar');
A [`TypeError`][] is thrown if `path` is not a string.
## `path.parse(path)`
<!-- YAML
added: v0.11.15
-->
@ -432,6 +441,7 @@ path.parse('C:\\path\\dir\\file.txt');
A [`TypeError`][] is thrown if `path` is not a string.
## `path.posix`
<!-- YAML
added: v0.11.15
changes:
@ -448,6 +458,7 @@ of the `path` methods.
The API is accessible via `require('path').posix` or `require('path/posix')`.
## `path.relative(from, to)`
<!-- YAML
added: v0.5.0
changes:
@ -485,6 +496,7 @@ path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb');
A [`TypeError`][] is thrown if either `from` or `to` is not a string.
## `path.resolve([...paths])`
<!-- YAML
added: v0.3.4
-->
@ -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`
<!-- YAML
added: v0.7.9
-->
@ -557,6 +570,7 @@ as path segment separators; however, the `path` methods only add backward
slashes (`\`).
## `path.toNamespacedPath(path)`
<!-- YAML
added: v9.0.0
-->
@ -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`
<!-- YAML
added: v0.11.15
changes:

View File

@ -36,6 +36,7 @@ doSomeLongRunningProcess(() => {
```
## `perf_hooks.performance`
<!-- YAML
added: v8.5.0
-->
@ -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])`
<!-- YAML
added: v8.5.0
-->
@ -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]])`
<!-- YAML
added:
- v14.10.0
@ -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]])`
<!-- YAML
added: v8.5.0
changes:
@ -137,6 +141,7 @@ Creates a new `PerformanceMark` entry in the Performance Timeline. A
to mark specific significant moments in the Performance Timeline.
### `performance.measure(name[, startMarkOrOptions[, endMark]])`
<!-- YAML
added: v8.5.0
changes:
@ -167,18 +172,19 @@ Creates a new `PerformanceMeasure` entry in the Performance Timeline. A
`performanceEntry.duration` measures the number of milliseconds elapsed since
`startMark` and `endMark`.
The `startMark` argument may identify any *existing* `PerformanceMark` in the
Performance Timeline, or *may* identify any of the timestamp properties
The `startMark` argument may identify any _existing_ `PerformanceMark` in the
Performance Timeline, or _may_ identify any of the timestamp properties
provided by the `PerformanceNodeTiming` class. If the named `startMark` does
not exist, an error is thrown.
The optional `endMark` argument must identify any *existing* `PerformanceMark`
The optional `endMark` argument must identify any _existing_ `PerformanceMark`
in the Performance Timeline or any of the timestamp properties provided by the
`PerformanceNodeTiming` class. `endMark` will be `performance.now()`
if no parameter is passed, otherwise if the named `endMark` does not exist, an
error will be thrown.
### `performance.nodeTiming`
<!-- YAML
added: v8.5.0
-->
@ -191,6 +197,7 @@ An instance of the `PerformanceNodeTiming` class that provides performance
metrics for specific Node.js operational milestones.
### `performance.now()`
<!-- YAML
added: v8.5.0
-->
@ -201,6 +208,7 @@ Returns the current high resolution millisecond timestamp, where 0 represents
the start of the current `node` process.
### `performance.timeOrigin`
<!-- YAML
added: v8.5.0
-->
@ -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])`
<!-- YAML
added: v8.5.0
changes:
@ -262,6 +271,7 @@ to the promise and the duration will be reported once the finally handler is
invoked.
### `performance.toJSON()`
<!-- YAML
added: v16.1.0
-->
@ -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`
<!-- YAML
added: v8.5.0
-->
### `performanceEntry.detail`
<!-- YAML
added: v16.0.0
-->
@ -284,6 +296,7 @@ added: v16.0.0
Additional detail specific to the `entryType`.
### `performanceEntry.duration`
<!-- YAML
added: v8.5.0
-->
@ -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`
<!-- YAML
added: v8.5.0
-->
@ -311,6 +325,7 @@ The type of the performance entry. It may be one of:
* `'http'` (Node.js only)
### `performanceEntry.flags`
<!-- YAML
added:
- v13.9.0
@ -339,6 +354,7 @@ The value may be one of:
* `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE`
### `performanceEntry.name`
<!-- YAML
added: v8.5.0
-->
@ -348,6 +364,7 @@ added: v8.5.0
The name of the performance entry.
### `performanceEntry.kind`
<!-- YAML
added: v8.5.0
changes:
@ -371,6 +388,7 @@ The value may be one of:
* `perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB`
### `performanceEntry.startTime`
<!-- YAML
added: v8.5.0
-->
@ -447,6 +465,7 @@ When `performanceEntry.type` is equal to `'function'`, the
the input arguments to the timed function.
## Class: `PerformanceNodeTiming`
<!-- YAML
added: v8.5.0
-->
@ -459,6 +478,7 @@ Provides timing details for Node.js itself. The constructor of this class
is not exposed to users.
### `performanceNodeTiming.bootstrapComplete`
<!-- YAML
added: v8.5.0
-->
@ -470,6 +490,7 @@ completed bootstrapping. If bootstrapping has not yet finished, the property
has the value of -1.
### `performanceNodeTiming.environment`
<!-- YAML
added: v8.5.0
-->
@ -480,6 +501,7 @@ The high resolution millisecond timestamp at which the Node.js environment was
initialized.
### `performanceNodeTiming.idleTime`
<!-- YAML
added:
- v14.10.0
@ -495,6 +517,7 @@ started (e.g., in the first tick of the main script), the property has the
value of 0.
### `performanceNodeTiming.loopExit`
<!-- YAML
added: v8.5.0
-->
@ -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`
<!-- YAML
added: v8.5.0
-->
@ -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`
<!-- YAML
added: v8.5.0
-->
@ -527,6 +552,7 @@ The high resolution millisecond timestamp at which the Node.js process was
initialized.
### `performanceNodeTiming.v8Start`
<!-- YAML
added: v8.5.0
-->
@ -539,6 +565,7 @@ initialized.
## Class: `perf_hooks.PerformanceObserver`
### `new PerformanceObserver(callback)`
<!-- YAML
added: v8.5.0
-->
@ -576,12 +603,15 @@ notified about new `PerformanceEntry` instances. The callback receives a
`PerformanceObserver`.
### `performanceObserver.disconnect()`
<!-- YAML
added: v8.5.0
-->
Disconnects the `PerformanceObserver` instance from all notifications.
### `performanceObserver.observe(options)`
<!-- YAML
added: v8.5.0
changes:
@ -598,7 +628,7 @@ changes:
* `options` {Object}
* `type` {string} A single {PerformanceEntry} type. Must not be given
if `entryTypes` is already specified.
* `entryTypes` {string[]} An array of strings identifying the types of
* `entryTypes` {string\[]} An array of strings identifying the types of
{PerformanceEntry} instances the observer is interested in. If not
provided an error will be thrown.
* `buffered` {boolean} If true, the observer callback is called with a
@ -626,6 +656,7 @@ for (let n = 0; n < 3; n++)
```
## Class: `PerformanceObserverEntryList`
<!-- YAML
added: v8.5.0
-->
@ -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()`
<!-- YAML
added: v8.5.0
-->
* 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])`
<!-- YAML
added: v8.5.0
-->
* `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)`
<!-- YAML
added: v8.5.0
-->
* `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])`
<!-- YAML
added:
- v15.9.0
@ -793,6 +828,7 @@ added:
Returns a {RecordableHistogram}.
## `perf_hooks.monitorEventLoopDelay([options])`
<!-- YAML
added: v11.10.0
-->
@ -829,11 +865,13 @@ console.log(h.percentile(99));
```
## Class: `Histogram`
<!-- YAML
added: v11.10.0
-->
### `histogram.exceeds`
<!-- YAML
added: v11.10.0
-->
@ -844,6 +882,7 @@ The number of times the event loop delay exceeded the maximum 1 hour event
loop delay threshold.
### `histogram.max`
<!-- YAML
added: v11.10.0
-->
@ -853,6 +892,7 @@ added: v11.10.0
The maximum recorded event loop delay.
### `histogram.mean`
<!-- YAML
added: v11.10.0
-->
@ -862,6 +902,7 @@ added: v11.10.0
The mean of the recorded event loop delays.
### `histogram.min`
<!-- YAML
added: v11.10.0
-->
@ -871,6 +912,7 @@ added: v11.10.0
The minimum recorded event loop delay.
### `histogram.percentile(percentile)`
<!-- YAML
added: v11.10.0
-->
@ -881,6 +923,7 @@ added: v11.10.0
Returns the value at the given percentile.
### `histogram.percentiles`
<!-- YAML
added: v11.10.0
-->
@ -890,6 +933,7 @@ added: v11.10.0
Returns a `Map` object detailing the accumulated percentile distribution.
### `histogram.reset()`
<!-- YAML
added: v11.10.0
-->
@ -897,6 +941,7 @@ added: v11.10.0
Resets the collected histogram data.
### `histogram.stddev`
<!-- YAML
added: v11.10.0
-->
@ -910,6 +955,7 @@ The standard deviation of the recorded event loop delays.
A `Histogram` that is periodically updated on a given interval.
### `histogram.disable()`
<!-- YAML
added: v11.10.0
-->
@ -920,6 +966,7 @@ Disables the update interval timer. Returns `true` if the timer was
stopped, `false` if it was already stopped.
### `histogram.enable()`
<!-- YAML
added: v11.10.0
-->
@ -936,6 +983,7 @@ end, the histogram is cloned as a plain {Histogram} object that does not
implement the `enable()` and `disable()` methods.
## Class: `RecordableHistogram extends Histogram`
<!-- YAML
added:
- v15.9.0
@ -943,6 +991,7 @@ added:
-->
### `histogram.record(val)`
<!-- YAML
added:
- v15.9.0
@ -952,6 +1001,7 @@ added:
* `val` {number|bigint} The amount to record in the histogram.
### `histogram.recordDelta()`
<!-- YAML
added:
- v15.9.0
@ -1013,6 +1063,7 @@ The following example measures the duration of `require()` operations to load
dependencies:
<!-- eslint-disable no-global-assign -->
```js
'use strict';
const {

View File

@ -23,6 +23,7 @@ const process = require('process');
The `process` object is an instance of [`EventEmitter`][].
### Event: `'beforeExit'`
<!-- YAML
added: v0.11.12
-->
@ -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'`
<!-- YAML
added: v0.7.7
-->
@ -90,6 +92,7 @@ and [Cluster][] documentation), the `'disconnect'` event will be emitted when
the IPC channel is closed.
### Event: `'exit'`
<!-- YAML
added: v0.1.7
-->
@ -151,6 +154,7 @@ process.on('exit', (code) => {
```
### Event: `'message'`
<!-- YAML
added: v0.5.10
-->
@ -174,6 +178,7 @@ to represent.
See [Advanced serialization for `child_process`][] for more details.
### Event: `'multipleResolves'`
<!-- YAML
added: v10.12.0
-->
@ -254,6 +259,7 @@ main().then(console.log);
```
### Event: `'rejectionHandled'`
<!-- YAML
added: v1.4.1
-->
@ -315,6 +321,7 @@ likely best for long-running application) or upon process exit (which is likely
most convenient for scripts).
### Event: `'uncaughtException'`
<!-- YAML
added: v0.1.18
changes:
@ -389,7 +396,7 @@ default behavior to exit the process by installing a
#### Warning: Using `'uncaughtException'` correctly
`'uncaughtException'` is a crude mechanism for exception handling
intended to be used only as a last resort. The event *should not* be used as
intended to be used only as a last resort. The event _should not_ be used as
an equivalent to `On Error Resume Next`. Unhandled exceptions inherently mean
that an application is in an undefined state. Attempting to resume application
code without properly recovering from the exception can cause additional
@ -414,6 +421,7 @@ in a separate process to detect application failures and recover or restart as
needed.
### Event: `'uncaughtExceptionMonitor'`
<!-- YAML
added:
- v13.7.0
@ -460,6 +468,7 @@ nonexistentFunc();
```
### Event: `'unhandledRejection'`
<!-- YAML
added: v1.4.1
changes:
@ -545,6 +554,7 @@ address such failures, a non-operational
being emitted.
### Event: `'warning'`
<!-- YAML
added: v6.0.0
-->
@ -627,6 +637,7 @@ The `*-deprecation` command-line flags only affect warnings that use the name
`'DeprecationWarning'`.
### Event: `'worker'`
<!-- YAML
added:
- v16.2.0
@ -678,7 +689,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).
@ -737,8 +748,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 <kbd>Ctrl</kbd>+<kbd>C</kbd> (though this may be configurable).
It is not generated when [terminal raw mode][] is enabled and
<kbd>Ctrl</kbd>+<kbd>C</kbd> is used.
It is not generated when [terminal raw mode][] is enabled
and <kbd>Ctrl</kbd>+<kbd>C</kbd> is used.
* `'SIGBREAK'` is delivered on Windows when <kbd>Ctrl</kbd>+<kbd>Break</kbd> is
pressed. On non-Windows platforms, it can be listened on, but there is no way
to send or generate it.
@ -758,6 +769,7 @@ process.on('SIGTERM', handle);
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.
@ -765,6 +777,7 @@ but Node.js offers some emulation with [`process.kill()`][], and
existence of a process.
## `process.abort()`
<!-- YAML
added: v0.7.0
-->
@ -775,6 +788,7 @@ generate a core file.
This feature is not available in [`Worker`][] threads.
## `process.allowedNodeEnvironmentFlags`
<!-- YAML
added: v10.10.0
-->
@ -793,16 +807,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:
@ -832,11 +846,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`
<!-- YAML
added: v0.5.0
-->
@ -860,11 +875,12 @@ console.log(`This processor architecture is ${process.arch}`);
```
## `process.argv`
<!-- YAML
added: v0.1.27
-->
* {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
@ -910,6 +926,7 @@ Would generate the output:
```
## `process.argv0`
<!-- YAML
added: v6.4.0
-->
@ -928,6 +945,7 @@ $ bash -c 'exec -a customArgv0 ./node'
```
## `process.channel`
<!-- YAML
added: v7.1.0
changes:
@ -944,6 +962,7 @@ property is a reference to the IPC channel. If no IPC channel exists, this
property is `undefined`.
### `process.channel.ref()`
<!-- YAML
added: v7.1.0
-->
@ -956,6 +975,7 @@ listeners on the `process` object. However, this method can be used to
explicitly request a specific behavior.
### `process.channel.unref()`
<!-- YAML
added: v7.1.0
-->
@ -968,6 +988,7 @@ listeners on the `process` object. However, this method can be used to
explicitly request a specific behavior.
## `process.chdir(directory)`
<!-- YAML
added: v0.1.17
-->
@ -1005,6 +1026,7 @@ try {
This feature is not available in [`Worker`][] threads.
## `process.config`
<!-- YAML
added: v0.7.7
changes:
@ -1023,6 +1045,7 @@ running the `./configure` script.
An example of the possible output looks like:
<!-- eslint-skip -->
```js
{
target_defaults:
@ -1060,6 +1083,7 @@ Modifying the `process.config` property, or any child-property of the
read-only in a future release.
## `process.connected`
<!-- YAML
added: v0.7.2
-->
@ -1075,6 +1099,7 @@ Once `process.connected` is `false`, it is no longer possible to send messages
over the IPC channel using `process.send()`.
## `process.cpuUsage([previousValue])`
<!-- YAML
added: v6.1.0
-->
@ -1123,6 +1148,7 @@ console.log(cpuUsage(startUsage));
```
## `process.cwd()`
<!-- YAML
added: v0.1.8
-->
@ -1145,6 +1171,7 @@ console.log(`Current directory: ${cwd()}`);
```
## `process.debugPort`
<!-- YAML
added: v0.7.2
-->
@ -1166,6 +1193,7 @@ process.debugPort = 5858;
```
## `process.disconnect()`
<!-- YAML
added: v0.7.2
-->
@ -1182,6 +1210,7 @@ If the Node.js process was not spawned with an IPC channel,
`process.disconnect()` will be `undefined`.
## `process.dlopen(module, filename[, flags])`
<!-- YAML
added: v0.1.16
changes:
@ -1234,6 +1263,7 @@ module.exports.foo();
```
## `process.emitWarning(warning[, options])`
<!-- YAML
added: v8.0.0
-->
@ -1241,7 +1271,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:**
@ -1309,13 +1339,14 @@ process.on('warning', (warning) => {
If `warning` is passed as an `Error` object, the `options` argument is ignored.
## `process.emitWarning(warning[, type[, code]][, ctor])`
<!-- YAML
added: v6.0.0
-->
* `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:**
@ -1480,6 +1511,7 @@ emitMyWarning();
```
## `process.env`
<!-- YAML
added: v0.1.27
changes:
@ -1501,6 +1533,7 @@ See environ(7).
An example of this object looks like:
<!-- eslint-skip -->
```js
{
TERM: 'xterm-256color',
@ -1613,11 +1646,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`
<!-- YAML
added: v0.7.7
-->
* {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
@ -1633,6 +1667,7 @@ $ node --harmony script.js --version
Results in `process.execArgv`:
<!-- eslint-disable semi -->
```js
['--harmony']
```
@ -1640,6 +1675,7 @@ Results in `process.execArgv`:
And `process.argv`:
<!-- eslint-disable semi -->
```js
['/usr/local/bin/node', 'script.js', '--version']
```
@ -1648,6 +1684,7 @@ Refer to [`Worker` constructor][] for the detailed behavior of worker
threads with this property.
## `process.execPath`
<!-- YAML
added: v0.1.100
-->
@ -1658,11 +1695,13 @@ The `process.execPath` property returns the absolute pathname of the executable
that started the Node.js process. Symbolic links, if any, are resolved.
<!-- eslint-disable semi -->
```js
'/usr/local/bin/node'
```
## `process.exit([code])`
<!-- YAML
added: v0.1.13
-->
@ -1697,11 +1736,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:
@ -1726,11 +1765,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:
@ -1757,13 +1796,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`
<!-- YAML
added: v0.11.8
-->
@ -1778,6 +1818,7 @@ Specifying a code to [`process.exit(code)`][`process.exit()`] will override any
previous setting of `process.exitCode`.
## `process.getegid()`
<!-- YAML
added: v2.0.0
-->
@ -1805,6 +1846,7 @@ This function is only available on POSIX platforms (i.e. not Windows or
Android).
## `process.geteuid()`
<!-- YAML
added: v2.0.0
-->
@ -1834,6 +1876,7 @@ This function is only available on POSIX platforms (i.e. not Windows or
Android).
## `process.getgid()`
<!-- YAML
added: v0.1.31
-->
@ -1863,11 +1906,12 @@ This function is only available on POSIX platforms (i.e. not Windows or
Android).
## `process.getgroups()`
<!-- YAML
added: v0.9.4
-->
* 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
@ -1893,6 +1937,7 @@ This function is only available on POSIX platforms (i.e. not Windows or
Android).
## `process.getuid()`
<!-- YAML
added: v0.1.28
-->
@ -1922,6 +1967,7 @@ This function is only available on POSIX platforms (i.e. not Windows or
Android).
## `process.hasUncaughtExceptionCaptureCallback()`
<!-- YAML
added: v9.3.0
-->
@ -1932,14 +1978,15 @@ Indicates whether a callback has been set using
[`process.setUncaughtExceptionCaptureCallback()`][].
## `process.hrtime([time])`
<!-- YAML
added: v0.7.6
-->
> 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.
@ -1991,6 +2038,7 @@ setTimeout(() => {
```
## `process.hrtime.bigint()`
<!-- YAML
added: v10.7.0
-->
@ -2035,6 +2083,7 @@ setTimeout(() => {
```
## `process.initgroups(user, extraGroup)`
<!-- YAML
added: v0.9.4
-->
@ -2074,6 +2123,7 @@ Android).
This feature is not available in [`Worker`][] threads.
## `process.kill(pid[, signal])`
<!-- YAML
added: v0.0.6
-->
@ -2131,6 +2181,7 @@ When `SIGUSR1` is received by a Node.js process, Node.js will start the
debugger. See [Signal Events][].
## `process.mainModule`
<!-- YAML
added: v0.1.17
deprecated: v14.0.0
@ -2150,6 +2201,7 @@ As with [`require.main`][], `process.mainModule` will be `undefined` if there
is no entry script.
## `process.memoryUsage()`
<!-- YAML
added: v0.1.16
changes:
@ -2221,6 +2273,7 @@ information about memory usage which might be slow depending on the
program memory allocations.
## `process.memoryUsage.rss()`
<!-- YAML
added:
- v15.6.0
@ -2254,6 +2307,7 @@ console.log(memoryUsage.rss());
```
## `process.nextTick(callback[, ...args])`
<!-- YAML
added: v0.1.26
changes:
@ -2300,7 +2354,7 @@ console.log('scheduled');
```
This is important when developing APIs in order to give users the opportunity
to assign event handlers *after* an object has been constructed but before any
to assign event handlers _after_ an object has been constructed but before any
I/O has occurred:
```mjs
@ -2426,7 +2480,7 @@ nextTick(() => console.log(1));
// 3
```
For *most* userland use cases, the `queueMicrotask()` API provides a portable
For _most_ userland use cases, the `queueMicrotask()` API provides a portable
and reliable mechanism for deferring execution that works across multiple
JavaScript platform environments and should be favored over `process.nextTick()`.
In simple scenarios, `queueMicrotask()` can be a drop-in replacement for
@ -2473,6 +2527,7 @@ When in doubt, unless the specific capabilities of `process.nextTick()` are
needed, use `queueMicrotask()`.
## `process.noDeprecation`
<!-- YAML
added: v0.8.0
-->
@ -2486,6 +2541,7 @@ the [`'warning'` event][process_warning] and the
flag's behavior.
## `process.pid`
<!-- YAML
added: v0.1.15
-->
@ -2507,6 +2563,7 @@ console.log(`This process is pid ${pid}`);
```
## `process.platform`
<!-- YAML
added: v0.1.16
-->
@ -2543,6 +2600,7 @@ Android operating system. However, Android support in Node.js
[is experimental][Android building].
## `process.ppid`
<!-- YAML
added:
- v9.2.0
@ -2568,6 +2626,7 @@ console.log(`The parent process is pid ${ppid}`);
```
## `process.release`
<!-- YAML
added: v3.0.0
changes:
@ -2602,9 +2661,10 @@ tarball.
that are no longer supported).
* `'Dubnium'` for the 10.x LTS line beginning with 10.13.0.
* `'Erbium'` for the 12.x LTS line beginning with 12.13.0.
For other LTS Release code names, see [Node.js Changelog Archive](https://github.com/nodejs/node/blob/HEAD/doc/changelogs/CHANGELOG_ARCHIVE.md)
For other LTS Release code names, see [Node.js Changelog Archive](https://github.com/nodejs/node/blob/HEAD/doc/changelogs/CHANGELOG\_ARCHIVE.md)
<!-- eslint-skip -->
```js
{
name: 'node',
@ -2620,6 +2680,7 @@ In custom builds from non-release versions of the source tree, only the
relied upon to exist.
## `process.report`
<!-- YAML
added: v11.8.0
changes:
@ -2637,6 +2698,7 @@ reports for the current process. Additional documentation is available in the
[report documentation][].
### `process.report.compact`
<!-- YAML
added:
- v13.12.0
@ -2662,6 +2724,7 @@ console.log(`Reports are compact? ${report.compact}`);
```
### `process.report.directory`
<!-- YAML
added: v11.12.0
changes:
@ -2691,6 +2754,7 @@ console.log(`Report directory is ${report.directory}`);
```
### `process.report.filename`
<!-- YAML
added: v11.12.0
changes:
@ -2720,6 +2784,7 @@ console.log(`Report filename is ${report.filename}`);
```
### `process.report.getReport([err])`
<!-- YAML
added: v11.8.0
changes:
@ -2762,6 +2827,7 @@ fs.writeFileSync('my-report.log', util.inspect(data), 'utf8');
Additional documentation is available in the [report documentation][].
### `process.report.reportOnFatalError`
<!-- YAML
added: v11.12.0
changes:
@ -2790,6 +2856,7 @@ console.log(`Report on fatal error: ${report.reportOnFatalError}`);
```
### `process.report.reportOnSignal`
<!-- YAML
added: v11.12.0
changes:
@ -2818,6 +2885,7 @@ console.log(`Report on signal: ${report.reportOnSignal}`);
```
### `process.report.reportOnUncaughtException`
<!-- YAML
added: v11.12.0
changes:
@ -2845,6 +2913,7 @@ console.log(`Report on exception: ${report.reportOnUncaughtException}`);
```
### `process.report.signal`
<!-- YAML
added: v11.12.0
changes:
@ -2873,6 +2942,7 @@ console.log(`Report signal: ${report.signal}`);
```
### `process.report.writeReport([filename][, err])`
<!-- YAML
added: v11.8.0
changes:
@ -2887,6 +2957,7 @@ changes:
should be a relative path, that will be appended to the directory specified in
`process.report.directory`, or the current working directory of the Node.js
process, if unspecified.
* `err` {Error} A custom error used for reporting the JavaScript stack.
* Returns: {string} Returns the filename of the generated report.
@ -2910,6 +2981,7 @@ report.writeReport();
Additional documentation is available in the [report documentation][].
## `process.resourceUsage()`
<!-- YAML
added: v12.6.0
-->
@ -3012,6 +3084,7 @@ console.log(resourceUsage());
```
## `process.send(message[, sendHandle[, options]][, callback])`
<!-- YAML
added: v0.5.9
-->
@ -3037,6 +3110,7 @@ The message goes through serialization and parsing. The resulting message might
not be the same as what is originally sent.
## `process.setegid(id)`
<!-- YAML
added: v2.0.0
-->
@ -3081,6 +3155,7 @@ Android).
This feature is not available in [`Worker`][] threads.
## `process.seteuid(id)`
<!-- YAML
added: v2.0.0
-->
@ -3125,6 +3200,7 @@ Android).
This feature is not available in [`Worker`][] threads.
## `process.setgid(id)`
<!-- YAML
added: v0.1.31
-->
@ -3169,11 +3245,12 @@ Android).
This feature is not available in [`Worker`][] threads.
## `process.setgroups(groups)`
<!-- YAML
added: v0.9.4
-->
* `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
@ -3212,6 +3289,7 @@ Android).
This feature is not available in [`Worker`][] threads.
## `process.setuid(id)`
<!-- YAML
added: v0.1.28
-->
@ -3256,6 +3334,7 @@ Android).
This feature is not available in [`Worker`][] threads.
## `process.setSourceMapsEnabled(val)`
<!-- YAML
added:
- v16.6.0
@ -3276,6 +3355,7 @@ Only source maps in JavaScript files that are loaded after source maps has been
enabled will be parsed and loaded.
## `process.setUncaughtExceptionCaptureCallback(fn)`
<!-- YAML
added: v9.3.0
-->
@ -3390,9 +3470,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.
@ -3402,7 +3482,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
@ -3430,6 +3510,7 @@ false
See the [TTY][] documentation for more information.
## `process.throwDeprecation`
<!-- YAML
added: v0.9.12
-->
@ -3460,6 +3541,7 @@ Thrown:
```
## `process.title`
<!-- YAML
added: v0.1.104
-->
@ -3484,6 +3566,7 @@ within process manager applications such as macOS Activity Monitor or Windows
Services Manager.
## `process.traceDeprecation`
<!-- YAML
added: v0.8.0
-->
@ -3497,6 +3580,7 @@ documentation for the [`'warning'` event][process_warning] and the
flag's behavior.
## `process.umask()`
<!-- YAML
added: v0.1.19
changes:
@ -3517,6 +3601,7 @@ changes:
processes inherit the mask from the parent process.
## `process.umask(mask)`
<!-- YAML
added: v0.1.19
-->
@ -3549,6 +3634,7 @@ console.log(
In [`Worker`][] threads, `process.umask(mask)` will throw an exception.
## `process.uptime()`
<!-- YAML
added: v0.5.0
-->
@ -3562,6 +3648,7 @@ The return value includes fractions of a second. Use `Math.floor()` to get whole
seconds.
## `process.version`
<!-- YAML
added: v0.1.3
-->
@ -3588,6 +3675,7 @@ To get the version string without the prepended _v_, use
`process.versions.node`.
## `process.versions`
<!-- YAML
added: v0.2.0
changes:

View File

@ -1,4 +1,5 @@
# Punycode
<!-- YAML
deprecated: v7.0.0
-->
@ -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)`
<!-- YAML
added: v0.5.1
-->
@ -54,6 +56,7 @@ punycode.decode('--dqo34k'); // '☃-⌘'
```
## `punycode.encode(string)`
<!-- YAML
added: v0.5.1
-->
@ -69,6 +72,7 @@ punycode.encode('☃-⌘'); // '--dqo34k'
```
## `punycode.toASCII(domain)`
<!-- YAML
added: v0.6.1
-->
@ -88,6 +92,7 @@ punycode.toASCII('example.com'); // 'example.com'
```
## `punycode.toUnicode(domain)`
<!-- YAML
added: v0.6.1
-->
@ -106,11 +111,13 @@ punycode.toUnicode('example.com'); // 'example.com'
```
## `punycode.ucs2`
<!-- YAML
added: v0.7.0
-->
### `punycode.ucs2.decode(string)`
<!-- YAML
added: v0.7.0
-->
@ -127,11 +134,12 @@ punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]
```
### `punycode.ucs2.encode(codePoints)`
<!-- YAML
added: v0.7.0
-->
* `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`
<!-- YAML
added: v0.6.1
-->

View File

@ -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()`
<!-- YAML
added: v0.1.99
-->
@ -26,6 +27,7 @@ added: v0.1.99
The `querystring.decode()` function is an alias for `querystring.parse()`.
## `querystring.encode()`
<!-- YAML
added: v0.1.99
-->
@ -33,6 +35,7 @@ added: v0.1.99
The `querystring.encode()` function is an alias for `querystring.stringify()`.
## `querystring.escape(str)`
<!-- YAML
added: v0.1.25
-->
@ -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]]])`
<!-- YAML
added: v0.1.25
changes:
@ -83,6 +87,7 @@ collection of key and value pairs.
For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into:
<!-- eslint-skip -->
```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]]])`
<!-- YAML
added: v0.1.25
-->
@ -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)`
<!-- YAML
added: v0.1.25
-->

View File

@ -63,7 +63,9 @@ Once this code is invoked, the Node.js application will not terminate until the
received on the `input` stream.
<a id='readline_class_interface'></a>
## Class: `InterfaceConstructor`
<!-- YAML
added: v0.1.104
-->
@ -78,6 +80,7 @@ The `output` stream is used to print prompts for user input that arrives on,
and is read from, the `input` stream.
### Event: `'close'`
<!-- YAML
added: v0.1.98
-->
@ -99,6 +102,7 @@ The `InterfaceConstructor` instance is finished once the `'close'` event is
emitted.
### Event: `'line'`
<!-- YAML
added: v0.1.98
-->
@ -117,6 +121,7 @@ rl.on('line', (input) => {
```
### Event: `'history'`
<!-- YAML
added:
- v15.8.0
@ -141,6 +146,7 @@ rl.on('history', (history) => {
```
### Event: `'pause'`
<!-- YAML
added: v0.7.5
-->
@ -160,6 +166,7 @@ rl.on('pause', () => {
```
### Event: `'resume'`
<!-- YAML
added: v0.7.5
-->
@ -175,6 +182,7 @@ rl.on('resume', () => {
```
### Event: `'SIGCONT'`
<!-- YAML
added: v0.7.5
-->
@ -183,7 +191,7 @@ The `'SIGCONT'` event is emitted when a Node.js process previously moved into
the background using <kbd>Ctrl</kbd>+<kbd>Z</kbd> (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.
@ -198,14 +206,15 @@ rl.on('SIGCONT', () => {
The `'SIGCONT'` event is _not_ supported on Windows.
### Event: `'SIGINT'`
<!-- YAML
added: v0.3.0
-->
The `'SIGINT'` event is emitted whenever the `input` stream receives a
<kbd>Ctrl+C</kbd> 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 <kbd>Ctrl+C</kbd> 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.
@ -218,12 +227,13 @@ rl.on('SIGINT', () => {
```
### Event: `'SIGTSTP'`
<!-- YAML
added: v0.7.5
-->
The `'SIGTSTP'` event is emitted when the `input` stream receives a
<kbd>Ctrl</kbd>+<kbd>Z</kbd> input, typically known as `SIGTSTP`. If there are
The `'SIGTSTP'` event is emitted when the `input` stream receives
a <kbd>Ctrl</kbd>+<kbd>Z</kbd> 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.
@ -246,6 +256,7 @@ rl.on('SIGTSTP', () => {
The `'SIGTSTP'` event is _not_ supported on Windows.
### `rl.close()`
<!-- YAML
added: v0.1.98
-->
@ -258,6 +269,7 @@ Calling `rl.close()` does not immediately stop other events (including `'line'`)
from being emitted by the `InterfaceConstructor` instance.
### `rl.pause()`
<!-- YAML
added: v0.3.4
-->
@ -269,6 +281,7 @@ Calling `rl.pause()` does not immediately pause other events (including
`'line'`) from being emitted by the `InterfaceConstructor` instance.
### `rl.prompt([preserveCursor])`
<!-- YAML
added: v0.1.98
-->
@ -287,6 +300,7 @@ If the `InterfaceConstructor` was created with `output` set to `null` or
`undefined` the prompt is not written.
### `rl.question(query[, options], callback)`
<!-- YAML
added: v0.3.3
-->
@ -358,6 +372,7 @@ questionExample();
```
### `rl.resume()`
<!-- YAML
added: v0.3.4
-->
@ -365,6 +380,7 @@ added: v0.3.4
The `rl.resume()` method resumes the `input` stream if it has been paused.
### `rl.setPrompt(prompt)`
<!-- YAML
added: v0.1.98
-->
@ -375,6 +391,7 @@ The `rl.setPrompt()` method sets the prompt that will be written to `output`
whenever `rl.prompt()` is called.
### `rl.getPrompt()`
<!-- YAML
added:
- v15.3.0
@ -386,6 +403,7 @@ added:
The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`.
### `rl.write(data[, key])`
<!-- YAML
added: v0.1.98
-->
@ -417,9 +435,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]()`
<!-- YAML
added:
- v11.4.0
@ -465,6 +484,7 @@ invoked. Having asynchronous operations between interface creation and
asynchronous iteration may result in missed lines.
### `rl.line`
<!-- YAML
added: v0.1.98
changes:
@ -506,6 +526,7 @@ process.stdin.on('keypress', (c, k) => {
```
### `rl.cursor`
<!-- YAML
added: v0.1.98
-->
@ -520,6 +541,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()`
<!-- YAML
added:
- v13.5.0
@ -535,6 +557,7 @@ prompt + string. Long input (wrapping) strings, as well as multiple
line prompts are included in the calculations.
## Promises API
<!-- YAML
added: v17.0.0
-->
@ -542,6 +565,7 @@ added: v17.0.0
> Stability: 1 - Experimental
### Class: `readlinePromises.Interface`
<!-- YAML
added: v17.0.0
-->
@ -555,6 +579,7 @@ The `output` stream is used to print prompts for user input that arrives on,
and is read from, the `input` stream.
#### `rl.question(query[, options])`
<!-- YAML
added: v17.0.0
-->
@ -601,11 +626,13 @@ setTimeout(() => ac.abort(), 10000);
```
### Class: `readlinePromises.Readline`
<!-- YAML
added: v17.0.0
-->
#### `new readlinePromises.Readline(stream[, options])`
<!-- YAML
added: v17.0.0
-->
@ -615,6 +642,7 @@ added: v17.0.0
* `autoCommit` {boolean} If `true`, no need to call `rl.commit()`.
#### `rl.clearLine(dir)`
<!-- YAML
added: v17.0.0
-->
@ -632,6 +660,7 @@ Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`
was passed to the constructor.
#### `rl.clearScreenDown()`
<!-- YAML
added: v17.0.0
-->
@ -645,6 +674,7 @@ Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`
was passed to the constructor.
#### `rl.commit()`
<!-- YAML
added: v17.0.0
-->
@ -655,6 +685,7 @@ The `rl.commit()` method sends all the pending actions to the associated
`stream` and clears the internal list of pending actions.
#### `rl.cursorTo(x[, y])`
<!-- YAML
added: v17.0.0
-->
@ -669,6 +700,7 @@ Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`
was passed to the constructor.
#### `rl.moveCursor(dx, dy)`
<!-- YAML
added: v17.0.0
-->
@ -678,12 +710,13 @@ added: v17.0.0
* Returns: this
The `rl.moveCursor()` method adds to the internal list of pending action an
action that moves the cursor *relative* to its current position in the
action that moves the cursor _relative_ to its current position in the
associated `stream`.
Call `rl.commit()` to see the effect of this method, unless `autoCommit: true`
was passed to the constructor.
#### `rl.rollback()`
<!-- YAML
added: v17.0.0
-->
@ -694,20 +727,21 @@ The `rl.rollback` methods clears the internal list of pending actions without
sending it to the associated `stream`.
### `readlinePromises.createInterface(options)`
<!-- YAML
added: v17.0.0
-->
* `options` {Object}
* `input` {stream.Readable} The [Readable][] stream to listen to. This option
is *required*.
is _required_.
* `output` {stream.Writable} The [Writable][] stream to write readline data
to.
* `completer` {Function} An optional function used for Tab autocompletion.
* `terminal` {boolean} `true` if the `input` and `output` streams should be
treated like a TTY, and have ANSI/VT100 escape codes written to it.
**Default:** checking `isTTY` on the `output` stream upon instantiation.
* `history` {string[]} Initial list of history lines. This option makes sense
* `history` {string\[]} Initial list of history lines. This option makes sense
only if `terminal` is set to `true` by the user or by an internal `output`
check, otherwise the history caching mechanism is not initialized at all.
**Default:** `[]`.
@ -789,11 +823,13 @@ async function completer(linePartial) {
```
## Callback API
<!-- YAML
added: v0.1.104
-->
### Class: `readline.Interface`
<!-- YAML
added: v0.1.104
changes:
@ -811,6 +847,7 @@ The `output` stream is used to print prompts for user input that arrives on,
and is read from, the `input` stream.
#### `rl.question(query[, options], callback)`
<!-- YAML
added: v0.3.3
-->
@ -882,6 +919,7 @@ questionExample();
```
### `readline.clearLine(stream, dir[, callback])`
<!-- YAML
added: v0.7.7
changes:
@ -904,6 +942,7 @@ The `readline.clearLine()` method clears current line of given [TTY][] stream
in a specified direction identified by `dir`.
### `readline.clearScreenDown(stream[, callback])`
<!-- YAML
added: v0.7.7
changes:
@ -922,6 +961,7 @@ The `readline.clearScreenDown()` method clears the given [TTY][] stream from
the current position of the cursor down.
### `readline.createInterface(options)`
<!-- YAML
added: v0.1.98
changes:
@ -956,14 +996,14 @@ changes:
* `options` {Object}
* `input` {stream.Readable} The [Readable][] stream to listen to. This option
is *required*.
is _required_.
* `output` {stream.Writable} The [Writable][] stream to write readline data
to.
* `completer` {Function} An optional function used for Tab autocompletion.
* `terminal` {boolean} `true` if the `input` and `output` streams should be
treated like a TTY, and have ANSI/VT100 escape codes written to it.
**Default:** checking `isTTY` on the `output` stream upon instantiation.
* `history` {string[]} Initial list of history lines. This option makes sense
* `history` {string\[]} Initial list of history lines. This option makes sense
only if `terminal` is set to `true` by the user or by an internal `output`
check, otherwise the history caching mechanism is not initialized at all.
**Default:** `[]`.
@ -1058,6 +1098,7 @@ function completer(linePartial, callback) {
```
### `readline.cursorTo(stream, x[, y][, callback])`
<!-- YAML
added: v0.7.7
changes:
@ -1078,6 +1119,7 @@ The `readline.cursorTo()` method moves cursor to the specified position in a
given [TTY][] `stream`.
### `readline.moveCursor(stream, dx, dy[, callback])`
<!-- YAML
added: v0.7.7
changes:
@ -1094,10 +1136,11 @@ changes:
the `'drain'` event to be emitted before continuing to write additional data;
otherwise `true`.
The `readline.moveCursor()` method moves the cursor *relative* to its current
The `readline.moveCursor()` method moves the cursor _relative_ to its current
position in a given [TTY][] `stream`.
## `readline.emitKeypressEvents(stream[, interface])`
<!-- YAML
added: v0.7.7
-->

View File

@ -45,8 +45,8 @@ The following special commands are supported by all REPL instances:
`> .save ./file/to/save.js`
* `.load`: Load a file into the current REPL session.
`> .load ./file/to/load.js`
* `.editor`: Enter editor mode (<kbd>Ctrl</kbd>+<kbd>D</kbd> to finish,
<kbd>Ctrl</kbd>+<kbd>C</kbd> to cancel).
* `.editor`: Enter editor mode (<kbd>Ctrl</kbd>+<kbd>D</kbd> to
finish, <kbd>Ctrl</kbd>+<kbd>C</kbd> to cancel).
```console
> .editor
@ -69,8 +69,8 @@ The following key combinations in the REPL have these special effects:
When pressed twice on a blank line, has the same effect as the `.exit`
command.
* <kbd>Ctrl</kbd>+<kbd>D</kbd>: Has the same effect as the `.exit` command.
* <kbd>Tab</kbd>: When pressed on a blank line, displays global and local (scope)
variables. When pressed while entering other input, displays relevant
* <kbd>Tab</kbd>: When pressed on a blank line, displays global and local
(scope) variables. When pressed while entering other input, displays relevant
autocompletion options.
For key bindings related to the reverse-i-search, see [`reverse-i-search`][].
@ -148,6 +148,7 @@ global or scoped variable, the input `fs` will be evaluated on-demand as
```
#### Global uncaught exceptions
<!-- YAML
changes:
- version: v12.3.0
@ -180,6 +181,7 @@ This use of the [`domain`][] module in the REPL has these side effects:
an [`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`][] error.
#### Assignment of the `_` (underscore) variable
<!-- YAML
changes:
- version: v9.8.0
@ -252,6 +254,7 @@ undefined
[`--no-experimental-repl-await`][] shall disable top-level await in REPL.
### Reverse-i-search
<!-- YAML
added:
- v13.6.0
@ -259,15 +262,14 @@ added:
-->
The REPL supports bi-directional reverse-i-search similar to [ZSH][]. It is
triggered with <kbd>Ctrl</kbd>+<kbd>R</kbd> to search backward and
<kbd>Ctrl</kbd>+<kbd>S</kbd> to search
forwards.
triggered with <kbd>Ctrl</kbd>+<kbd>R</kbd> to search backward
and <kbd>Ctrl</kbd>+<kbd>S</kbd> 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 <kbd>Esc</kbd> or
<kbd>Ctrl</kbd>+<kbd>C</kbd>.
with the reverse search. Cancelling is possible by pressing <kbd>Esc</kbd>
or <kbd>Ctrl</kbd>+<kbd>C</kbd>.
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`
<!-- YAML
added: v0.1.91
-->
@ -387,6 +390,7 @@ const secondInstance = new repl.REPLServer(options);
```
### Event: `'exit'`
<!-- YAML
added: v0.7.7
-->
@ -406,12 +410,13 @@ replServer.on('exit', () => {
```
### Event: `'reset'`
<!-- YAML
added: v0.11.0
-->
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)`
<!-- YAML
added: v0.3.0
-->
* `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])`
<!-- YAML
added: v0.1.91
-->
@ -517,6 +524,7 @@ within the action function for commands registered using the
`replServer.defineCommand()` method.
### `replServer.clearBufferedCommand()`
<!-- YAML
added: v9.0.0
-->
@ -527,6 +535,7 @@ called from within the action function for commands registered using the
`replServer.defineCommand()` method.
### `replServer.parseREPLKeyword(keyword[, rest])`
<!-- YAML
added: v0.8.9
deprecated: v9.0.0
@ -542,6 +551,7 @@ An internal method used to parse and execute `REPLServer` keywords.
Returns `true` if `keyword` is a valid keyword, otherwise `false`.
### `replServer.setupHistory(historyPath, callback)`
<!-- YAML
added: v11.10.0
-->
@ -558,15 +568,17 @@ programmatically. Use this method to initialize a history log file when working
with REPL instances programmatically.
## `repl.builtinModules`
<!-- YAML
added: v14.5.0
-->
* {string[]}
* {string\[]}
A list of the names of all Node.js modules, e.g., `'http'`.
## `repl.start([options])`
<!-- YAML
added: v0.1.91
changes:

View File

@ -580,6 +580,7 @@ Specific API documentation can be found under
[`process API documentation`][] section.
## Interaction with workers
<!-- YAML
changes:
- version:

View File

@ -49,6 +49,7 @@ Additionally, this module includes the utility functions
and [`stream.addAbortSignal()`][].
### Streams Promises API
<!-- YAML
added: v15.0.0
-->
@ -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`
<!-- YAML
added: v0.9.4
-->
@ -235,6 +237,7 @@ added: v0.9.4
<!--type=class-->
##### Event: `'close'`
<!-- YAML
added: v0.9.4
changes:
@ -252,6 +255,7 @@ A [`Writable`][] stream will always emit the `'close'` event if it is
created with the `emitClose` option.
##### Event: `'drain'`
<!-- YAML
added: v0.9.4
-->
@ -289,6 +293,7 @@ function writeOneMillionTimes(writer, data, encoding, callback) {
```
##### Event: `'error'`
<!-- YAML
added: v0.9.4
-->
@ -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'`
<!-- YAML
added: v0.9.4
-->
@ -325,6 +331,7 @@ writer.end('This is the end\n');
```
##### Event: `'pipe'`
<!-- YAML
added: v0.9.4
-->
@ -345,6 +352,7 @@ reader.pipe(writer);
```
##### Event: `'unpipe'`
<!-- YAML
added: v0.9.4
-->
@ -371,6 +379,7 @@ reader.unpipe(writer);
```
##### `writable.cork()`
<!-- YAML
added: v0.11.2
-->
@ -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])`
<!-- YAML
added: v8.0.0
changes:
@ -447,6 +457,7 @@ Implementors should not override this method,
but instead implement [`writable._destroy()`][writable-_destroy].
##### `writable.destroyed`
<!-- YAML
added: v8.0.0
-->
@ -466,6 +477,7 @@ console.log(myStream.destroyed); // true
```
##### `writable.end([chunk[, encoding]][, callback])`
<!-- YAML
added: v0.9.4
changes:
@ -509,6 +521,7 @@ file.end('world!');
```
##### `writable.setDefaultEncoding(encoding)`
<!-- YAML
added: v0.11.15
changes:
@ -524,6 +537,7 @@ The `writable.setDefaultEncoding()` method sets the default `encoding` for a
[`Writable`][] stream.
##### `writable.uncork()`
<!-- YAML
added: v0.11.2
-->
@ -562,6 +576,7 @@ process.nextTick(() => {
See also: [`writable.cork()`][].
##### `writable.writable`
<!-- YAML
added: v11.4.0
-->
@ -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`
<!-- YAML
added: v12.9.0
-->
@ -583,6 +599,7 @@ does not indicate whether the data has been flushed, for this use
[`writable.writableFinished`][] instead.
##### `writable.writableCorked`
<!-- YAML
added:
- v13.2.0
@ -595,6 +612,7 @@ Number of times [`writable.uncork()`][stream-uncork] needs to be
called in order to fully uncork the stream.
##### `writable.writableFinished`
<!-- YAML
added: v12.6.0
-->
@ -604,6 +622,7 @@ added: v12.6.0
Is set to `true` immediately before the [`'finish'`][] event is emitted.
##### `writable.writableHighWaterMark`
<!-- YAML
added: v9.3.0
-->
@ -613,6 +632,7 @@ added: v9.3.0
Return the value of `highWaterMark` passed when creating this `Writable`.
##### `writable.writableLength`
<!-- YAML
added: v9.4.0
-->
@ -624,6 +644,7 @@ ready to be written. The value provides introspection data regarding
the status of the `highWaterMark`.
##### `writable.writableNeedDrain`
<!-- YAML
added:
- v15.2.0
@ -635,6 +656,7 @@ added:
Is `true` if the stream's buffer has been full and stream will emit `'drain'`.
##### `writable.writableObjectMode`
<!-- YAML
added: v12.3.0
-->
@ -644,6 +666,7 @@ added: v12.3.0
Getter for the property `objectMode` of a given `Writable` stream.
##### `writable.write(chunk[, encoding][, callback])`
<!-- YAML
added: v0.9.4
changes:
@ -720,7 +743,7 @@ A `Writable` stream in object mode will always ignore the `encoding` argument.
### Readable streams
Readable streams are an abstraction for a *source* from which data is
Readable streams are an abstraction for a _source_ from which data is
consumed.
Examples of `Readable` streams include:
@ -768,13 +791,13 @@ The `Readable` can switch back to paused mode using one of the following:
The important concept to remember is that a `Readable` will not generate data
until a mechanism for either consuming or ignoring that data is provided. If
the consuming mechanism is disabled or taken away, the `Readable` will *attempt*
the consuming mechanism is disabled or taken away, the `Readable` will _attempt_
to stop generating the data.
For backward compatibility reasons, removing [`'data'`][] event handlers will
**not** automatically pause the stream. Also, if there are piped destinations,
then calling [`stream.pause()`][stream-pause] will not guarantee that the
stream will *remain* paused once those destinations drain and ask for more data.
stream will _remain_ paused once those destinations drain and ask for more data.
If a [`Readable`][] is switched into flowing mode and there are no consumers
available to handle the data, that data will be lost. This can occur, for
@ -810,7 +833,7 @@ emitting events as data is generated.
Calling `readable.pause()`, `readable.unpipe()`, or receiving backpressure
will cause the `readable.readableFlowing` to be set as `false`,
temporarily halting the flowing of events but *not* halting the generation of
temporarily halting the flowing of events but _not_ halting the generation of
data. While in this state, attaching a listener for the `'data'` event
will not switch `readable.readableFlowing` to `true`.
@ -835,7 +858,7 @@ within the stream's internal buffer.
The `Readable` stream API evolved across multiple Node.js versions and provides
multiple methods of consuming stream data. In general, developers should choose
*one* of the methods of consuming data and *should never* use multiple methods
_one_ of the methods of consuming data and _should never_ use multiple methods
to consume data from a single stream. Specifically, using a combination
of `on('data')`, `on('readable')`, `pipe()`, or async iterators could
lead to unintuitive behavior.
@ -847,6 +870,7 @@ use the [`EventEmitter`][] and `readable.on('readable')`/`readable.read()`
or the `readable.pause()`/`readable.resume()` APIs.
#### Class: `stream.Readable`
<!-- YAML
added: v0.9.4
-->
@ -854,6 +878,7 @@ added: v0.9.4
<!--type=class-->
##### Event: `'close'`
<!-- YAML
added: v0.9.4
changes:
@ -871,6 +896,7 @@ A [`Readable`][] stream will always emit the `'close'` event if it is
created with the `emitClose` option.
##### Event: `'data'`
<!-- YAML
added: v0.9.4
-->
@ -904,6 +930,7 @@ readable.on('data', (chunk) => {
```
##### Event: `'end'`
<!-- YAML
added: v0.9.4
-->
@ -927,6 +954,7 @@ readable.on('end', () => {
```
##### Event: `'error'`
<!-- YAML
added: v0.9.4
-->
@ -941,6 +969,7 @@ to push an invalid chunk of data.
The listener callback will be passed a single `Error` object.
##### Event: `'pause'`
<!-- YAML
added: v0.9.4
-->
@ -949,6 +978,7 @@ The `'pause'` event is emitted when [`stream.pause()`][stream-pause] is called
and `readableFlowing` is not `false`.
##### Event: `'readable'`
<!-- YAML
added: v0.9.4
changes:
@ -1018,6 +1048,7 @@ will start flowing, i.e. `'data'` events will be emitted without calling
`.resume()`.
##### Event: `'resume'`
<!-- YAML
added: v0.9.4
-->
@ -1026,6 +1057,7 @@ The `'resume'` event is emitted when [`stream.resume()`][stream-resume] is
called and `readableFlowing` is not `true`.
##### `readable.destroy([error])`
<!-- YAML
added: v8.0.0
changes:
@ -1049,6 +1081,7 @@ Implementors should not override this method, but instead implement
[`readable._destroy()`][readable-_destroy].
##### `readable.destroyed`
<!-- YAML
added: v8.0.0
-->
@ -1058,6 +1091,7 @@ added: v8.0.0
Is `true` after [`readable.destroy()`][readable-destroy] has been called.
##### `readable.isPaused()`
<!-- YAML
added: v0.11.14
-->
@ -1080,6 +1114,7 @@ readable.isPaused(); // === false
```
##### `readable.pause()`
<!-- YAML
added: v0.9.4
-->
@ -1107,6 +1142,7 @@ The `readable.pause()` method has no effect if there is a `'readable'`
event listener.
##### `readable.pipe(destination[, options])`
<!-- YAML
added: v0.9.4
-->
@ -1114,7 +1150,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`,
@ -1137,7 +1173,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
@ -1161,14 +1197,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])`
<!-- YAML
added: v0.9.4
-->
@ -1183,7 +1220,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.
@ -1252,6 +1289,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`
<!-- YAML
added: v11.4.0
-->
@ -1262,6 +1300,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`
<!-- YAML
added: v16.8.0
-->
@ -1273,6 +1312,7 @@ added: v16.8.0
Returns whether the stream was destroyed or errored before emitting `'end'`.
##### `readable.readableDidRead`
<!-- YAML
added:
- v16.7.0
@ -1286,6 +1326,7 @@ added:
Returns whether `'data'` has been emitted.
##### `readable.readableEncoding`
<!-- YAML
added: v12.7.0
-->
@ -1296,6 +1337,7 @@ Getter for the property `encoding` of a given `Readable` stream. The `encoding`
property can be set using the [`readable.setEncoding()`][] method.
##### `readable.readableEnded`
<!-- YAML
added: v12.9.0
-->
@ -1305,6 +1347,7 @@ added: v12.9.0
Becomes `true` when [`'end'`][] event is emitted.
##### `readable.readableFlowing`
<!-- YAML
added: v9.4.0
-->
@ -1315,6 +1358,7 @@ This property reflects the current state of a `Readable` stream as described
in the [Three states][] section.
##### `readable.readableHighWaterMark`
<!-- YAML
added: v9.3.0
-->
@ -1324,6 +1368,7 @@ added: v9.3.0
Returns the value of `highWaterMark` passed when creating this `Readable`.
##### `readable.readableLength`
<!-- YAML
added: v9.4.0
-->
@ -1335,6 +1380,7 @@ ready to be read. The value provides introspection data regarding
the status of the `highWaterMark`.
##### `readable.readableObjectMode`
<!-- YAML
added: v12.3.0
-->
@ -1344,6 +1390,7 @@ added: v12.3.0
Getter for the property `objectMode` of a given `Readable` stream.
##### `readable.resume()`
<!-- YAML
added: v0.9.4
changes:
@ -1373,6 +1420,7 @@ The `readable.resume()` method has no effect if there is a `'readable'`
event listener.
##### `readable.setEncoding(encoding)`
<!-- YAML
added: v0.9.4
-->
@ -1405,6 +1453,7 @@ readable.on('data', (chunk) => {
```
##### `readable.unpipe([destination])`
<!-- YAML
added: v0.9.4
-->
@ -1415,7 +1464,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.
@ -1436,6 +1485,7 @@ setTimeout(() => {
```
##### `readable.unshift(chunk[, encoding])`
<!-- YAML
added: v0.9.11
changes:
@ -1514,6 +1564,7 @@ however it is best to simply avoid calling `readable.unshift()` while in the
process of performing a read.
##### `readable.wrap(stream)`
<!-- YAML
added: v0.9.4
-->
@ -1545,6 +1596,7 @@ myReader.on('readable', () => {
```
##### `readable[Symbol.asyncIterator]()`
<!-- YAML
added: v10.0.0
changes:
@ -1578,6 +1630,7 @@ has less then 64 KB of data because no `highWaterMark` option is provided to
[`fs.createReadStream()`][].
##### `readable.iterator([options])`
<!-- YAML
added: v16.3.0
-->
@ -1633,6 +1686,7 @@ showBoth();
### Duplex and transform streams
#### Class: `stream.Duplex`
<!-- YAML
added: v0.9.4
changes:
@ -1654,6 +1708,7 @@ Examples of `Duplex` streams include:
* [crypto streams][crypto]
##### `duplex.allowHalfOpen`
<!-- YAML
added: v0.9.4
-->
@ -1669,6 +1724,7 @@ This can be changed manually to change the half-open behavior of an existing
emitted.
#### Class: `stream.Transform`
<!-- YAML
added: v0.9.4
-->
@ -1685,6 +1741,7 @@ Examples of `Transform` streams include:
* [crypto streams][crypto]
##### `transform.destroy([error])`
<!-- YAML
added: v8.0.0
changes:
@ -1707,6 +1764,7 @@ Once `destroy()` has been called, any further calls will be a no-op and no
further errors except from `_destroy()` may be emitted as `'error'`.
### `stream.finished(stream[, options], callback)`
<!-- YAML
added: v10.0.0
changes:
@ -1740,7 +1798,7 @@ changes:
the stream ends even though the stream might still be writable.
**Default:** `true`.
* `signal` {AbortSignal} allows aborting the wait for the stream finish. The
underlying stream will *not* be aborted if the signal is aborted. The
underlying stream will _not_ be aborted if the signal is aborted. The
callback will get called with an `AbortError`. All registered
listeners added by this function will also be removed.
* `callback` {Function} A callback function that takes an optional error
@ -1802,7 +1860,9 @@ const cleanup = finished(rs, (err) => {
```
### `stream.pipeline(source[, ...transforms], destination, callback)`
### `stream.pipeline(streams, callback)`
<!-- YAML
added: v10.0.0
changes:
@ -1817,7 +1877,7 @@ changes:
description: Add support for async generators.
-->
* `streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]}
* `streams` {Stream\[]|Iterable\[]|AsyncIterable\[]|Function\[]}
* `source` {Stream|Iterable|AsyncIterable|Function}
* Returns: {Iterable|AsyncIterable}
* `...transforms` {Stream|Function}
@ -1947,6 +2007,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'`.
@ -1955,13 +2016,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)`
<!-- YAML
added: v16.9.0
-->
> 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
@ -2044,6 +2106,7 @@ console.log(res); // prints 'HELLOWORLD'
```
### `stream.Readable.from(iterable[, options])`
<!-- YAML
added:
- v12.3.0
@ -2080,6 +2143,7 @@ the strings or buffers be iterated to match the other streams semantics
for performance reasons.
### `stream.Readable.fromWeb(readableStream[, options])`
<!-- YAML
added: v16.11.0
-->
@ -2095,6 +2159,7 @@ added: v16.11.0
* Returns: {stream.Readable}
### `stream.Readable.isDisturbed(stream)`
<!-- YAML
added: v16.8.0
-->
@ -2107,6 +2172,7 @@ added: v16.8.0
Returns whether the stream has been read from or cancelled.
### `stream.Readable.toWeb(streamReadable)`
<!-- YAML
added: v17.0.0
-->
@ -2117,6 +2183,7 @@ added: v17.0.0
* Returns: {ReadableStream}
### `stream.Writable.fromWeb(writableStream[, options])`
<!-- YAML
added: v17.0.0
-->
@ -2132,6 +2199,7 @@ added: v17.0.0
* Returns: {stream.Writable}
### `stream.Writable.toWeb(streamWritable)`
<!-- YAML
added: v17.0.0
-->
@ -2142,6 +2210,7 @@ added: v17.0.0
* Returns: {WritableStream}
### `stream.Duplex.from(src)`
<!-- YAML
added: v16.8.0
-->
@ -2170,6 +2239,7 @@ A utility method for creating duplex streams.
* Returns: {stream.Duplex}
### `stream.Duplex.fromWeb(pair[, options])`
<!-- YAML
added: v17.0.0
-->
@ -2189,6 +2259,7 @@ added: v17.0.0
* Returns: {stream.Duplex}
### `stream.Duplex.toWeb(streamDuplex)`
<!-- YAML
added: v17.0.0
-->
@ -2201,9 +2272,11 @@ added: v17.0.0
* `writable` {WritableStream}
### `stream.addAbortSignal(signal, stream)`
<!-- YAML
added: v15.4.0
-->
* `signal` {AbortSignal} A signal representing possible cancellation
* `stream` {Stream} a stream to attach a signal to
@ -2249,6 +2322,7 @@ const stream = addAbortSignal(
}
})();
```
## API for stream implementers
<!--type=misc-->
@ -2262,6 +2336,7 @@ of the four basic stream classes (`stream.Writable`, `stream.Readable`,
parent class constructor:
<!-- eslint-disable no-useless-constructor -->
```js
const { Writable } = require('stream');
@ -2284,13 +2359,13 @@ 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] |
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.
@ -2303,6 +2378,7 @@ and/or compatibility issues with other streams, stream utilities, and user
expectations.
### Simplified construction
<!-- YAML
added: v1.2.0
-->
@ -2332,11 +2408,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])`
<!-- YAML
changes:
- version: v15.5.0
@ -2392,6 +2469,7 @@ changes:
* `signal` {AbortSignal} A signal representing possible cancellation.
<!-- eslint-disable no-useless-constructor -->
```js
const { Writable } = require('stream');
@ -2453,7 +2531,9 @@ const myWritable = new Writable({
// Later, abort the operation closing the stream
controller.abort();
```
#### `writable._construct(callback)`
<!-- YAML
added: v15.0.0
-->
@ -2503,6 +2583,7 @@ class WriteStream extends Writable {
```
#### `writable._write(chunk, encoding, callback)`
<!-- YAML
changes:
- version: v12.11.0
@ -2558,7 +2639,7 @@ user programs.
#### `writable._writev(chunks, callback)`
* `chunks` {Object[]} The data to be written. The value is an array of {Object}
* `chunks` {Object\[]} The data to be written. The value is an array of {Object}
that each represent a discrete chunk of data to write. The properties of
these objects are:
* `chunk` {Buffer|string} A buffer instance or string containing the data to
@ -2583,6 +2664,7 @@ internal to the class that defines it, and should never be called directly by
user programs.
#### `writable._destroy(err, callback)`
<!-- YAML
added: v8.0.0
-->
@ -2595,6 +2677,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)`
<!-- YAML
added: v8.0.0
-->
@ -2700,10 +2783,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])`
<!-- YAML
changes:
- version: v15.5.0
@ -2742,6 +2826,7 @@ changes:
* `signal` {AbortSignal} A signal representing possible cancellation.
<!-- eslint-disable no-useless-constructor -->
```js
const { Readable } = require('stream');
@ -2798,6 +2883,7 @@ controller.abort();
```
#### `readable._construct(callback)`
<!-- YAML
added: v15.0.0
-->
@ -2855,6 +2941,7 @@ class ReadStream extends Readable {
```
#### `readable._read(size)`
<!-- YAML
added: v0.9.4
-->
@ -2893,6 +2980,7 @@ internal to the class that defines it, and should never be called directly by
user programs.
#### `readable._destroy(err, callback)`
<!-- YAML
added: v8.0.0
-->
@ -2905,6 +2993,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])`
<!-- YAML
changes:
- version: v8.0.0
@ -3036,18 +3125,19 @@ A [`Duplex`][] stream is one that implements both [`Readable`][] and
Because JavaScript does not have support for multiple inheritance, the
`stream.Duplex` class is extended to implement a [`Duplex`][] stream (as opposed
to extending the `stream.Readable` *and* `stream.Writable` classes).
to extending the `stream.Readable` _and_ `stream.Writable` classes).
The `stream.Duplex` class prototypically inherits from `stream.Readable` and
parasitically from `stream.Writable`, but `instanceof` will work properly for
both base classes due to overriding [`Symbol.hasInstance`][] on
`stream.Writable`.
Custom `Duplex` streams *must* call the `new stream.Duplex([options])`
constructor and implement *both* the [`readable._read()`][] and
Custom `Duplex` streams _must_ call the `new stream.Duplex([options])`
constructor and implement _both_ the [`readable._read()`][] and
`writable._write()` methods.
#### `new stream.Duplex(options)`
<!-- YAML
changes:
- version: v8.4.0
@ -3075,6 +3165,7 @@ changes:
of the stream. Has no effect if `highWaterMark` is provided.
<!-- eslint-disable no-useless-constructor -->
```js
const { Duplex } = require('stream');
@ -3252,8 +3343,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
@ -3270,6 +3361,7 @@ output on the `Readable` side is not consumed.
method.
<!-- eslint-disable no-useless-constructor -->
```js
const { Transform } = require('stream');
@ -3336,7 +3428,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.
@ -3519,7 +3611,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
@ -3593,7 +3685,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.

View File

@ -47,6 +47,7 @@ console.log(decoder.end(Buffer.from([0xAC])));
## Class: `StringDecoder`
### `new StringDecoder([encoding])`
<!-- YAML
added: v0.1.99
-->
@ -57,6 +58,7 @@ added: v0.1.99
Creates a new `StringDecoder` instance.
### `stringDecoder.end([buffer])`
<!-- YAML
added: v0.9.3
-->
@ -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)`
<!-- YAML
added: v0.1.99
changes:
@ -88,8 +91,8 @@ changes:
* Returns: {string}
Returns a decoded string, ensuring that any incomplete multibyte characters at
the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the
returned string and stored in an internal buffer for the next call to
`stringDecoder.write()` or `stringDecoder.end()`.
the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the
returned string and stored in an internal buffer for the next call to
`stringDecoder.write()` or `stringDecoder.end()`.
[encoding]: buffer.md#buffers-and-character-encodings

View File

@ -11,6 +11,7 @@
Please see the [Command-line options][] document for more information.
## Example
An example of a [web server][] written with Node.js which responds with
`'Hello, World!'`:
@ -48,7 +49,7 @@ Windows PowerShell:
```
Next, create a new source file in the `projects`
folder and call it `hello-world.js`.
folder and call it `hello-world.js`.
Open `hello-world.js` in any preferred text editor and
paste in the following content:

View File

@ -26,6 +26,7 @@ running as long as the immediate is active. The `Immediate` object returned by
functions that can be used to control this default behavior.
### `immediate.hasRef()`
<!-- YAML
added: v11.0.0
-->
@ -35,13 +36,14 @@ added: v11.0.0
If true, the `Immediate` object will keep the Node.js event loop active.
### `immediate.ref()`
<!-- YAML
added: v9.7.0
-->
* 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()`
<!-- YAML
added: v9.7.0
-->
@ -73,6 +76,7 @@ export both `timeout.ref()` and `timeout.unref()` functions that can be used to
control this default behavior.
### `timeout.close()`
<!-- YAML
added: v0.9.1
-->
@ -84,6 +88,7 @@ added: v0.9.1
Cancels the timeout.
### `timeout.hasRef()`
<!-- YAML
added: v11.0.0
-->
@ -93,19 +98,21 @@ added: v11.0.0
If true, the `Timeout` object will keep the Node.js event loop active.
### `timeout.ref()`
<!-- YAML
added: v0.9.1
-->
* 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()`
<!-- YAML
added: v10.2.0
-->
@ -121,6 +128,7 @@ Using this on a timer that has already called its callback will reactivate the
timer.
### `timeout.unref()`
<!-- YAML
added: v0.9.1
-->
@ -137,6 +145,7 @@ event loop. Creating too many of these can adversely impact performance
of the Node.js application.
### `timeout[Symbol.toPrimitive]()`
<!-- YAML
added:
- v14.9.0
@ -160,6 +169,7 @@ which method was used to create the timer and what other work the Node.js
event loop is doing.
### `setImmediate(callback[, ...args])`
<!-- YAML
added: v0.9.1
-->
@ -184,6 +194,7 @@ This method has a custom variant for promises that is available using
[`timersPromises.setImmediate()`][].
### `setInterval(callback[, delay[, ...args]])`
<!-- YAML
added: v0.0.1
-->
@ -205,6 +216,7 @@ This method has a custom variant for promises that is available using
[`timersPromises.setInterval()`][].
### `setTimeout(callback[, delay[, ...args]])`
<!-- YAML
added: v0.0.1
-->
@ -277,6 +289,7 @@ ac.abort();
```
### `clearImmediate(immediate)`
<!-- YAML
added: v0.9.1
-->
@ -287,6 +300,7 @@ added: v0.9.1
Cancels an `Immediate` object created by [`setImmediate()`][].
### `clearInterval(timeout)`
<!-- YAML
added: v0.0.1
-->
@ -297,6 +311,7 @@ added: v0.0.1
Cancels a `Timeout` object created by [`setInterval()`][].
### `clearTimeout(timeout)`
<!-- YAML
added: v0.0.1
-->
@ -307,6 +322,7 @@ added: v0.0.1
Cancels a `Timeout` object created by [`setTimeout()`][].
## Timers Promises API
<!-- YAML
added: v15.0.0
changes:
@ -336,6 +352,7 @@ const {
```
### `timersPromises.setTimeout([delay[, value[, options]]])`
<!-- YAML
added: v15.0.0
-->
@ -371,6 +388,7 @@ setTimeout(100, 'result').then((res) => {
```
### `timersPromises.setImmediate([value[, options]])`
<!-- YAML
added: v15.0.0
-->
@ -404,6 +422,7 @@ setImmediate('result').then((res) => {
```
### `timersPromises.setInterval([delay[, value[, options]]])`
<!-- YAML
added: v15.9.0
-->

View File

@ -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
@ -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`
<!-- YAML
added: v0.3.4
deprecated: v0.11.3
@ -424,16 +427,18 @@ The `tls.CryptoStream` class represents a stream of encrypted data. This class
is deprecated and should no longer be used.
### `cryptoStream.bytesWritten`
<!-- YAML
added: v0.3.4
deprecated: v0.11.3
-->
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`
<!-- YAML
added: v0.3.2
deprecated: v0.11.3
@ -444,6 +449,7 @@ deprecated: v0.11.3
Returned by [`tls.createSecurePair()`][].
### Event: `'secure'`
<!-- YAML
added: v0.3.2
deprecated: v0.11.3
@ -458,6 +464,7 @@ event, `pair.cleartext.authorized` should be inspected to confirm whether the
certificate used is properly authorized.
## Class: `tls.Server`
<!-- YAML
added: v0.3.2
-->
@ -467,6 +474,7 @@ added: v0.3.2
Accepts encrypted connections using TLS or SSL.
### Event: `'connection'`
<!-- YAML
added: v0.3.2
-->
@ -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'`
<!-- YAML
added:
- v12.3.0
@ -511,6 +520,7 @@ server.on('keylog', (line, tlsSocket) => {
```
### Event: `'newSession'`
<!-- YAML
added: v0.9.2
changes:
@ -534,6 +544,7 @@ Listening for this event will have an effect only on connections established
after the addition of the event listener.
### Event: `'OCSPRequest'`
<!-- YAML
added: v0.11.13
-->
@ -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'`
<!-- YAML
added: v0.9.2
-->
@ -620,6 +632,7 @@ server.on('resumeSession', (id, cb) => {
```
### Event: `'secureConnection'`
<!-- YAML
added: v0.3.2
-->
@ -644,6 +657,7 @@ The `tlsSocket.servername` property is a string containing the server name
requested via SNI.
### Event: `'tlsClientError'`
<!-- YAML
added: v6.0.0
-->
@ -657,6 +671,7 @@ called:
error originated.
### `server.addContext(hostname, context)`
<!-- YAML
added: v0.5.3
-->
@ -673,6 +688,7 @@ When there are multiple matching contexts, the most recently added one is
used.
### `server.address()`
<!-- YAML
added: v0.6.0
-->
@ -684,6 +700,7 @@ server as reported by the operating system. See [`net.Server.address()`][] for
more information.
### `server.close([callback])`
<!-- YAML
added: v0.3.2
-->
@ -698,6 +715,7 @@ This function operates asynchronously. The `'close'` event will be emitted
when the server has no more open connections.
### `server.getTicketKeys()`
<!-- YAML
added: v3.0.0
-->
@ -714,6 +732,7 @@ Starts the server listening for encrypted connections.
This method is identical to [`server.listen()`][] from [`net.Server`][].
### `server.setSecureContext(options)`
<!-- YAML
added: v11.0.0
-->
@ -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)`
<!-- YAML
added: v3.0.0
-->
@ -741,6 +761,7 @@ Existing or currently pending server connections will use the previous keys.
See [Session Resumption][] for more information.
## Class: `tls.TLSSocket`
<!-- YAML
added: v0.11.4
-->
@ -757,6 +778,7 @@ Methods that return TLS connection metadata (e.g.
connection is open.
### `new tls.TLSSocket(socket[, options])`
<!-- YAML
added: v0.11.4
changes:
@ -799,6 +821,7 @@ changes:
Construct a new `tls.TLSSocket` object from an existing TCP socket.
### Event: `'keylog'`
<!-- YAML
added:
- v12.3.0
@ -822,6 +845,7 @@ tlsSocket.on('keylog', (line) => logFile.write(line));
```
### Event: `'OCSPResponse'`
<!-- YAML
added: v0.11.13
-->
@ -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'`
<!-- YAML
added: v0.11.4
-->
@ -854,6 +879,7 @@ The `'secureConnect'` event is not emitted when a {tls.TLSSocket} is created
using the `new tls.TLSSocket()` constructor.
### Event: `'session'`
<!-- YAML
added: v11.10.0
-->
@ -893,6 +919,7 @@ tlsSocket.once('session', (session) => {
```
### `tlsSocket.address()`
<!-- YAML
added: v0.11.4
-->
@ -904,6 +931,7 @@ underlying socket as reported by the operating system:
`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`.
### `tlsSocket.authorizationError`
<!-- YAML
added: v0.11.4
-->
@ -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`
<!-- YAML
added: v0.11.4
-->
@ -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()`
<!-- YAML
added: v8.4.0
-->
@ -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()`
<!-- YAML
added: v12.2.0
-->
@ -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`
<!-- YAML
added: v0.11.4
-->
@ -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])`
<!-- YAML
added:
- v13.10.0
@ -958,9 +991,11 @@ added:
-->
* `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()`
<!-- YAML
added: v11.2.0
-->
@ -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()`
<!-- YAML
added: v0.11.4
changes:
@ -1025,6 +1063,7 @@ changes:
Returns an object containing information on the negotiated cipher suite.
For example:
```json
{
"name": "AES128-SHA256",
@ -1034,10 +1073,11 @@ For example:
```
See
[SSL_CIPHER_get_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html)
[SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL\_CIPHER\_get\_name.html)
for more information.
### `tlsSocket.getEphemeralKeyInfo()`
<!-- YAML
added: v5.0.0
-->
@ -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()`
<!-- YAML
added: v9.9.0
-->
@ -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])`
<!-- YAML
added: v0.11.4
-->
@ -1088,6 +1130,7 @@ If the full certificate chain was requested, each certificate will include an
certificate.
#### Certificate object
<!-- YAML
changes:
- version: v11.4.0
@ -1150,6 +1193,7 @@ For EC keys, the following properties may be defined:
Example certificate:
<!-- eslint-skip -->
```js
{ subject:
{ OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],
@ -1178,6 +1222,7 @@ Example certificate:
```
### `tlsSocket.getPeerFinished()`
<!-- YAML
added: v9.9.0
-->
@ -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()`
<!-- YAML
added: v15.9.0
-->
@ -1207,6 +1253,7 @@ If there is no peer certificate, or the socket has been destroyed,
`undefined` will be returned.
### `tlsSocket.getProtocol()`
<!-- YAML
added: v5.7.0
-->
@ -1229,6 +1276,7 @@ Protocol versions are:
See the OpenSSL [`SSL_get_version`][] documentation for more information.
### `tlsSocket.getSession()`
<!-- YAML
added: v0.11.4
-->
@ -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()`
<!-- YAML
added: v12.11.0
-->
@ -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()`
<!-- YAML
added: v0.11.4
-->
@ -1272,6 +1322,7 @@ It may be useful for debugging.
See [Session Resumption][] for more information.
### `tlsSocket.getX509Certificate()`
<!-- YAML
added: v15.9.0
-->
@ -1284,6 +1335,7 @@ If there is no local certificate, or the socket has been destroyed,
`undefined` will be returned.
### `tlsSocket.isSessionReused()`
<!-- YAML
added: v0.5.6
-->
@ -1293,6 +1345,7 @@ added: v0.5.6
See [Session Resumption][] for more information.
### `tlsSocket.localAddress`
<!-- YAML
added: v0.11.4
-->
@ -1302,6 +1355,7 @@ added: v0.11.4
Returns the string representation of the local IP address.
### `tlsSocket.localPort`
<!-- YAML
added: v0.11.4
-->
@ -1311,6 +1365,7 @@ added: v0.11.4
Returns the numeric representation of the local port.
### `tlsSocket.remoteAddress`
<!-- YAML
added: v0.11.4
-->
@ -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`
<!-- YAML
added: v0.11.4
-->
@ -1330,6 +1386,7 @@ added: v0.11.4
Returns the string representation of the remote IP family. `'IPv4'` or `'IPv6'`.
### `tlsSocket.remotePort`
<!-- YAML
added: v0.11.4
-->
@ -1339,6 +1396,7 @@ added: v0.11.4
Returns the numeric representation of the remote port. For example, `443`.
### `tlsSocket.renegotiate(options, callback)`
<!-- YAML
added: v0.11.8
-->
@ -1349,6 +1407,7 @@ 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
@ -1371,6 +1430,7 @@ For TLSv1.3, renegotiation cannot be initiated, it is not supported by the
protocol.
### `tlsSocket.setMaxSendFragment(size)`
<!-- YAML
added: v0.11.11
-->
@ -1390,6 +1450,7 @@ smaller fragments add extra TLS framing bytes and CPU overhead, which may
decrease overall server throughput.
## `tls.checkServerIdentity(hostname, cert)`
<!-- YAML
added: v0.8.4
-->
@ -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])`
<!-- YAML
added: v0.11.3
changes:
@ -1487,6 +1549,7 @@ changes:
verification fails; `err.code` contains the OpenSSL error code. **Default:**
`true`.
* `pskCallback` {Function}
* hint: {string} optional message sent from the server to help client
decide which identity to use during negotiation.
Always `null` if TLS 1.3 is used.
@ -1504,7 +1567,7 @@ changes:
of the server against the certificate but that's not applicable for PSK
because there won't be a certificate present.
More information can be found in the [RFC 4279][].
* `ALPNProtocols`: {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
@ -1592,6 +1655,7 @@ socket.on('end', () => {
```
## `tls.connect(path[, options][, callback])`
<!-- YAML
added: v0.11.3
-->
@ -1607,6 +1671,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])`
<!-- YAML
added: v0.11.3
-->
@ -1624,6 +1689,7 @@ A port or host option, if specified, will take precedence over any port or host
argument.
## `tls.createSecureContext([options])`
<!-- YAML
added: v0.11.13
changes:
@ -1670,7 +1736,7 @@ changes:
-->
* `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
@ -1688,20 +1754,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
@ -1709,7 +1775,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.
@ -1728,11 +1794,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: <string|buffer>[, passphrase: <string>]}`. 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
@ -1755,7 +1821,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
@ -1772,9 +1838,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
@ -1796,13 +1862,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])`
<!-- YAML
added: v0.3.2
deprecated: v0.11.3
@ -1866,6 +1933,7 @@ secureSocket = tls.TLSSocket(socket, options);
where `secureSocket` has the same API as `pair.cleartext`.
## `tls.createServer([options][, secureConnectionListener])`
<!-- YAML
added: v0.3.2
changes:
@ -1886,7 +1954,7 @@ changes:
-->
* `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
@ -1925,6 +1993,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.
@ -1935,10 +2004,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][].
@ -1992,11 +2061,12 @@ The server can be tested by connecting to it using the example client from
[`tls.connect()`][].
## `tls.getCiphers()`
<!-- YAML
added: v0.10.2
-->
* 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
@ -2010,11 +2080,12 @@ console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
```
## `tls.rootCertificates`
<!-- YAML
added: v12.3.0
-->
* {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.
@ -2023,6 +2094,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`
<!-- YAML
added: v0.11.13
changes:
@ -2036,6 +2108,7 @@ default value is `'auto'`. See [`tls.createSecureContext()`][] for further
information.
## `tls.DEFAULT_MAX_VERSION`
<!-- YAML
added: v11.4.0
-->
@ -2049,6 +2122,7 @@ added: v11.4.0
highest maximum is used.
## `tls.DEFAULT_MIN_VERSION`
<!-- YAML
added: v11.4.0
-->

View File

@ -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
<!-- YAML
added: v10.0.0
-->
### `Tracing` object
<!-- YAML
added: v10.0.0
-->
@ -107,6 +109,7 @@ categories. Calling `tracing.disable()` will remove the categories from the
set of enabled trace event categories.
#### `tracing.categories`
<!-- YAML
added: v10.0.0
-->
@ -117,14 +120,15 @@ A comma-separated list of the trace event categories covered by this
`Tracing` object.
#### `tracing.disable()`
<!-- YAML
added: v10.0.0
-->
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()`
<!-- YAML
added: v10.0.0
-->
@ -151,6 +156,7 @@ Enables this `Tracing` object for the set of categories covered by the
`Tracing` object.
#### `tracing.enabled`
<!-- YAML
added: v10.0.0
-->
@ -158,12 +164,13 @@ added: v10.0.0
* {boolean} `true` only if the `Tracing` object has been enabled.
### `trace_events.createTracing(options)`
<!-- YAML
added: v10.0.0
-->
* `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()`
<!-- YAML
added: v10.0.0
-->
@ -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

View File

@ -33,6 +33,7 @@ manually create instances of the `tty.ReadStream` and `tty.WriteStream`
classes.
## Class: `tty.ReadStream`
<!-- YAML
added: v0.5.8
-->
@ -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`
<!-- YAML
added: v0.7.7
-->
@ -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`
<!-- YAML
added: v0.5.8
-->
@ -59,6 +62,7 @@ added: v0.5.8
A `boolean` that is always `true` for `tty.ReadStream` instances.
### `readStream.setRawMode(mode)`
<!-- YAML
added: v0.7.7
-->
@ -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.
<kbd>Ctrl</kbd>+<kbd>C</kbd> will no longer cause a `SIGINT` when in this mode.
terminal is disabled, including echoing input
characters. <kbd>Ctrl</kbd>+<kbd>C</kbd> will no longer cause a `SIGINT` when
in this mode.
## Class: `tty.WriteStream`
<!-- YAML
added: v0.5.8
-->
@ -89,6 +95,7 @@ Represents the writable side of a TTY. In normal circumstances,
should be no reason to create additional instances.
### Event: `'resize'`
<!-- YAML
added: v0.7.7
-->
@ -105,6 +112,7 @@ process.stdout.on('resize', () => {
```
### `writeStream.clearLine(dir[, callback])`
<!-- YAML
added: v0.7.7
changes:
@ -126,6 +134,7 @@ changes:
direction identified by `dir`.
### `writeStream.clearScreenDown([callback])`
<!-- YAML
added: v0.7.7
changes:
@ -143,6 +152,7 @@ changes:
cursor down.
### `writeStream.columns`
<!-- YAML
added: v0.7.7
-->
@ -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])`
<!-- YAML
added: v0.7.7
changes:
@ -170,6 +181,7 @@ changes:
position.
### `writeStream.getColorDepth([env])`
<!-- YAML
added: v9.9.0
-->
@ -204,11 +216,12 @@ Disabling color support is also possible by using the `NO_COLOR` and
`NODE_DISABLE_COLORS` environment variables.
### `writeStream.getWindowSize()`
<!-- YAML
added: v0.7.7
-->
* 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])`
<!-- YAML
added:
- v11.13.0
@ -247,6 +261,7 @@ process.stdout.hasColors(2 ** 24, { TMUX: '1' });
```
### `writeStream.isTTY`
<!-- YAML
added: v0.5.8
-->
@ -254,6 +269,7 @@ added: v0.5.8
A `boolean` that is always `true`.
### `writeStream.moveCursor(dx, dy[, callback])`
<!-- YAML
added: v0.7.7
changes:
@ -269,10 +285,11 @@ changes:
for the `'drain'` event to be emitted before continuing to write additional
data; otherwise `true`.
`writeStream.moveCursor()` moves this `WriteStream`'s cursor *relative* to its
`writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its
current position.
### `writeStream.rows`
<!-- YAML
added: v0.7.7
-->
@ -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)`
<!-- YAML
added: v0.5.8
-->

View File

@ -105,6 +105,7 @@ console.log(myURL.href);
## The WHATWG URL API
### Class: `URL`
<!-- YAML
added:
- v7.0.0
@ -242,7 +243,7 @@ Invalid host values assigned to the `host` property are ignored.
* {string}
Gets and sets the host name portion of the URL. The key difference between
`url.host` and `url.hostname` is that `url.hostname` does *not* include the
`url.host` and `url.hostname` is that `url.hostname` does _not_ include the
port.
```js
@ -290,6 +291,7 @@ If the value assigned to the `href` property is not a valid URL, a `TypeError`
will be thrown.
#### `url.origin`
<!-- YAML
changes:
- version: v15.0.0
@ -360,6 +362,7 @@ to percent-encode may vary somewhat from what the [`url.parse()`][] and
[`url.format()`][] methods would produce.
#### `url.port`
<!-- YAML
changes:
- version: v15.0.0
@ -467,6 +470,7 @@ console.log(myURL.href);
Invalid URL protocol values assigned to the `protocol` property are ignored.
##### Special schemes
<!-- YAML
changes:
- version: v15.0.0
@ -609,6 +613,7 @@ console.log(JSON.stringify(myURLs));
```
#### `URL.createObjectURL(blob)`
<!-- YAML
added: v16.7.0
-->
@ -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)`
<!-- YAML
added: v16.7.0
-->
@ -656,6 +662,7 @@ added: v16.7.0
Removes the stored {Blob} identified by the given ID.
### Class: `URLSearchParams`
<!-- YAML
added:
- v7.5.0
@ -735,6 +742,7 @@ console.log(params.toString());
```
#### `new URLSearchParams(obj)`
<!-- YAML
added:
- v7.10.0
@ -762,6 +770,7 @@ console.log(params.toString());
```
#### `new URLSearchParams(iterable)`
<!-- YAML
added:
- v7.10.0
@ -869,7 +878,7 @@ are no such pairs, `null` is returned.
#### `urlSearchParams.getAll(name)`
* `name` {string}
* Returns: {string[]}
* Returns: {string\[]}
Returns the values of all name-value pairs whose name is `name`. If there are
no such pairs, an empty array is returned.
@ -922,6 +931,7 @@ console.log(params.toString());
```
#### `urlSearchParams.sort()`
<!-- YAML
added:
- v7.7.0
@ -975,6 +985,7 @@ for (const [name, value] of params) {
```
### `url.domainToASCII(domain)`
<!-- YAML
added:
- v7.4.0
@ -1015,6 +1026,7 @@ console.log(url.domainToASCII('xn--iñvalid.com'));
```
### `url.domainToUnicode(domain)`
<!-- YAML
added:
- v7.4.0
@ -1055,6 +1067,7 @@ console.log(url.domainToUnicode('xn--iñvalid.com'));
```
### `url.fileURLToPath(url)`
<!-- YAML
added: v10.12.0
-->
@ -1099,6 +1112,7 @@ fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
```
### `url.format(URL[, options])`
<!-- YAML
added: v7.6.0
-->
@ -1153,6 +1167,7 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
```
### `url.pathToFileURL(path)`
<!-- YAML
added: v10.12.0
-->
@ -1188,6 +1203,7 @@ pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSI
```
### `url.urlToHttpOptions(url)`
<!-- YAML
added:
- v15.7.0
@ -1253,6 +1269,7 @@ console.log(urlToHttpOptions(myUrl));
```
## Legacy URL API
<!-- YAML
changes:
- version:
@ -1268,6 +1285,7 @@ changes:
> Stability: 3 - Legacy: Use the WHATWG URL API instead.
### Legacy `urlObject`
<!-- YAML
changes:
- version:
@ -1312,7 +1330,7 @@ For example: `'sub.example.com:8080'`.
#### `urlObject.hostname`
The `hostname` property is the lower-cased host name portion of the `host`
component *without* the `port` included.
component _without_ the `port` included.
For example: `'sub.example.com'`.
@ -1383,6 +1401,7 @@ forward-slash characters (`/`) are required following the colon in the
`protocol`.
### `url.format(urlObject)`
<!-- YAML
added: v0.1.25
changes:
@ -1440,7 +1459,7 @@ The formatting process operates as follows:
* If `urlObject.protocol` is a string, it is appended as-is to `result`.
* Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an
[`Error`][] is thrown.
* For all string values of `urlObject.protocol` that *do not end* with an ASCII
* For all string values of `urlObject.protocol` that _do not end_ with an ASCII
colon (`:`) character, the literal string `:` will be appended to `result`.
* If either of the following conditions is true, then the literal string `//`
will be appended to `result`:
@ -1463,7 +1482,7 @@ The formatting process operates as follows:
* Otherwise, if the `urlObject.host` property value is truthy, the value of
`urlObject.host` is coerced to a string and appended to `result`.
* If the `urlObject.pathname` property is a string that is not an empty string:
* If the `urlObject.pathname` *does not start* with an ASCII forward slash
* If the `urlObject.pathname` _does not start_ with an ASCII forward slash
(`/`), then the literal string `'/'` is appended to `result`.
* The value of `urlObject.pathname` is appended to `result`.
* Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an
@ -1473,13 +1492,13 @@ The formatting process operates as follows:
followed by the output of calling the [`querystring`][] module's `stringify()`
method passing the value of `urlObject.query`.
* Otherwise, if `urlObject.search` is a string:
* If the value of `urlObject.search` *does not start* with the ASCII question
* If the value of `urlObject.search` _does not start_ with the ASCII question
mark (`?`) character, the literal string `?` is appended to `result`.
* The value of `urlObject.search` is appended to `result`.
* Otherwise, if `urlObject.search` is not `undefined` and is not a string, an
[`Error`][] is thrown.
* If the `urlObject.hash` property is a string:
* If the value of `urlObject.hash` *does not start* with the ASCII hash (`#`)
* If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`)
character, the literal string `#` is appended to `result`.
* The value of `urlObject.hash` is appended to `result`.
* Otherwise, if the `urlObject.hash` property is not `undefined` and is not a
@ -1487,6 +1506,7 @@ The formatting process operates as follows:
* `result` is returned.
### `url.parse(urlString[, parseQueryString[, slashesDenoteHost]])`
<!-- YAML
added: v0.1.25
changes:
@ -1536,6 +1556,7 @@ issues can be introduced. Specifically, issues with [host name spoofing][] and
incorrect handling of usernames and passwords have been identified.
### `url.resolve(from, to)`
<!-- YAML
added: v0.1.25
changes:
@ -1596,6 +1617,7 @@ resolve('http://example.com/one', '/two'); // 'http://example.com/two'
```
<a id="whatwg-percent-encoding"></a>
## Percent-encoding in URLs
URLs are permitted to only contain a certain range of characters. Any character
@ -1623,29 +1645,29 @@ selecting encoded characters than that used by the Legacy API.
The WHATWG algorithm defines four "percent-encode sets" that describe ranges
of characters that must be percent-encoded:
* The *C0 control percent-encode set* includes code points in range U+0000 to
* The _C0 control percent-encode set_ includes code points in range U+0000 to
U+001F (inclusive) and all code points greater than U+007E.
* The *fragment percent-encode set* includes the *C0 control percent-encode set*
* The _fragment percent-encode set_ includes the _C0 control percent-encode set_
and code points U+0020, U+0022, U+003C, U+003E, and U+0060.
* The *path percent-encode set* includes the *C0 control percent-encode set*
* The _path percent-encode set_ includes the _C0 control percent-encode set_
and code points U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060,
U+007B, and U+007D.
* The *userinfo encode set* includes the *path percent-encode set* and code
* The _userinfo encode set_ includes the _path percent-encode set_ and code
points U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D,
U+005E, and U+007C.
The *userinfo percent-encode set* is used exclusively for username and
passwords encoded within the URL. The *path percent-encode set* is used for the
path of most URLs. The *fragment percent-encode set* is used for URL fragments.
The *C0 control percent-encode set* is used for host and path under certain
The _userinfo percent-encode set_ is used exclusively for username and
passwords encoded within the URL. The _path percent-encode set_ is used for the
path of most URLs. The _fragment percent-encode set_ is used for URL fragments.
The _C0 control percent-encode set_ is used for host and path under certain
specific conditions, in addition to all other cases.
When non-ASCII characters appear within a host name, the host name is encoded
using the [Punycode][] algorithm. Note, however, that a host name *may* contain
*both* Punycode encoded and percent-encoded characters:
using the [Punycode][] algorithm. Note, however, that a host name _may_ contain
_both_ Punycode encoded and percent-encoded characters:
```js
const myURL = new URL('https://%CF%80.example.com/foo');

View File

@ -15,6 +15,7 @@ const util = require('util');
```
## `util.callbackify(original)`
<!-- YAML
added: v8.2.0
-->
@ -71,6 +72,7 @@ callbackFunction((err, ret) => {
```
## `util.debuglog(section[, callback])`
<!-- YAML
added: v0.11.3
-->
@ -137,6 +139,7 @@ let debuglog = util.debuglog('internals', (debug) => {
```
### `debuglog().enabled`
<!-- YAML
added: v14.9.0
-->
@ -165,6 +168,7 @@ hello from foo [123]
```
## `util.debug(section)`
<!-- YAML
added: v14.9.0
-->
@ -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])`
<!-- YAML
added: v0.8.0
changes:
@ -218,7 +223,7 @@ fn2(); // Does not emit a deprecation warning because it has the same code
```
If either the `--no-deprecation` or `--no-warnings` command-line flags are
used, or if the `process.noDeprecation` property is set to `true` *prior* to
used, or if the `process.noDeprecation` property is set to `true` _prior_ to
the first deprecation warning, the `util.deprecate()` method does nothing.
If the `--trace-deprecation` or `--trace-warnings` command-line flags are set,
@ -235,6 +240,7 @@ property take precedence over `--trace-deprecation` and
`process.traceDeprecation`.
## `util.format(format[, ...args])`
<!-- YAML
added: v0.5.3
changes:
@ -340,6 +346,7 @@ Some input values can have a significant performance overhead that can block the
event loop. Use this function with care and never in a hot code path.
## `util.formatWithOptions(inspectOptions, format[, ...args])`
<!-- YAML
added: v10.0.0
-->
@ -358,6 +365,7 @@ util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
```
## `util.getSystemErrorName(err)`
<!-- YAML
added: v9.7.0
-->
@ -377,6 +385,7 @@ fs.access('file/that/does/not/exist', (err) => {
```
## `util.getSystemErrorMap()`
<!-- YAML
added:
- v16.0.0
@ -398,6 +407,7 @@ fs.access('file/that/does/not/exist', (err) => {
```
## `util.inherits(constructor, superConstructor)`
<!-- YAML
added: v0.3.0
changes:
@ -469,7 +479,9 @@ stream.write('With ES6');
```
## `util.inspect(object[, options])`
## `util.inspect(object[, showHidden[, depth[, colors]]])`
<!-- YAML
added: v0.3.0
changes:
@ -894,6 +906,7 @@ util.inspect(obj);
```
### `util.inspect.custom`
<!-- YAML
added: v6.6.0
changes:
@ -933,6 +946,7 @@ console.log(password);
See [Custom inspection functions on Objects][] for more details.
### `util.inspect.defaultOptions`
<!-- YAML
added: v6.4.0
-->
@ -953,6 +967,7 @@ console.log(arr); // logs the full array
```
## `util.isDeepStrictEqual(val1, val2)`
<!-- YAML
added: v9.0.0
-->
@ -968,6 +983,7 @@ See [`assert.deepStrictEqual()`][] for more information about deep strict
equality.
## `util.promisify(original)`
<!-- YAML
added: v8.0.0
-->
@ -1081,6 +1097,7 @@ If `promisify.custom` is defined but is not a function, `promisify()` will
throw an error.
### `util.promisify.custom`
<!-- YAML
added: v8.0.0
changes:
@ -1112,6 +1129,7 @@ doSomething[kCustomPromisifiedSymbol] = (foo) => {
```
## `util.stripVTControlCharacters(str)`
<!-- YAML
added: v16.11.0
-->
@ -1127,6 +1145,7 @@ console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m'));
```
## Class: `util.TextDecoder`
<!-- YAML
added: v8.3.0
-->
@ -1155,7 +1174,7 @@ 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'` |
@ -1194,7 +1213,7 @@ Different Node.js build configurations support different sets of encodings.
#### 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'` | |
@ -1202,7 +1221,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'` |
@ -1210,6 +1229,7 @@ The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][]
is not supported.
### `new TextDecoder([encoding[, options]])`
<!-- YAML
added: v8.3.0
changes:
@ -1271,6 +1291,7 @@ The value will be `true` if the decoding result will include the byte order
mark.
## Class: `util.TextEncoder`
<!-- YAML
added: v8.3.0
changes:
@ -1322,6 +1343,7 @@ const { read, written } = encoder.encodeInto(src, dest);
The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`.
## `util.toUSVString(string)`
<!-- YAML
added:
- v16.8.0
@ -1335,6 +1357,7 @@ Returns the `string` after replacing any surrogate code points
Unicode "replacement character" U+FFFD.
## `util.types`
<!-- YAML
added: v10.0.0
changes:
@ -1355,6 +1378,7 @@ useful for addon developers who prefer to do type checking in JavaScript.
The API is accessible via `require('util').types` or `require('util/types')`.
### `util.types.isAnyArrayBuffer(value)`
<!-- YAML
added: v10.0.0
-->
@ -1374,6 +1398,7 @@ util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true
```
### `util.types.isArrayBufferView(value)`
<!-- YAML
added: v10.0.0
-->
@ -1393,6 +1418,7 @@ util.types.isArrayBufferView(new ArrayBuffer()); // false
```
### `util.types.isArgumentsObject(value)`
<!-- YAML
added: v10.0.0
-->
@ -1403,6 +1429,7 @@ added: v10.0.0
Returns `true` if the value is an `arguments` object.
<!-- eslint-disable prefer-rest-params -->
```js
function foo() {
util.types.isArgumentsObject(arguments); // Returns true
@ -1410,6 +1437,7 @@ function foo() {
```
### `util.types.isArrayBuffer(value)`
<!-- YAML
added: v10.0.0
-->
@ -1418,7 +1446,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
@ -1427,6 +1455,7 @@ util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false
```
### `util.types.isAsyncFunction(value)`
<!-- YAML
added: v10.0.0
-->
@ -1445,6 +1474,7 @@ util.types.isAsyncFunction(async function foo() {}); // Returns true
```
### `util.types.isBigInt64Array(value)`
<!-- YAML
added: v10.0.0
-->
@ -1460,6 +1490,7 @@ util.types.isBigInt64Array(new BigUint64Array()); // Returns false
```
### `util.types.isBigUint64Array(value)`
<!-- YAML
added: v10.0.0
-->
@ -1475,6 +1506,7 @@ util.types.isBigUint64Array(new BigUint64Array()); // Returns true
```
### `util.types.isBooleanObject(value)`
<!-- YAML
added: v10.0.0
-->
@ -1495,6 +1527,7 @@ util.types.isBooleanObject(Boolean(true)); // Returns false
```
### `util.types.isBoxedPrimitive(value)`
<!-- YAML
added: v10.11.0
-->
@ -1516,6 +1549,7 @@ util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
```
### `util.types.isCryptoKey(value)`
<!-- YAML
added: v16.2.0
-->
@ -1526,6 +1560,7 @@ added: v16.2.0
Returns `true` if `value` is a {CryptoKey}, `false` otherwise.
### `util.types.isDataView(value)`
<!-- YAML
added: v10.0.0
-->
@ -1544,6 +1579,7 @@ util.types.isDataView(new Float64Array()); // Returns false
See also [`ArrayBuffer.isView()`][].
### `util.types.isDate(value)`
<!-- YAML
added: v10.0.0
-->
@ -1558,6 +1594,7 @@ util.types.isDate(new Date()); // Returns true
```
### `util.types.isExternal(value)`
<!-- YAML
added: v10.0.0
-->
@ -1603,6 +1640,7 @@ For further information on `napi_create_external`, refer to
[`napi_create_external()`][].
### `util.types.isFloat32Array(value)`
<!-- YAML
added: v10.0.0
-->
@ -1619,6 +1657,7 @@ util.types.isFloat32Array(new Float64Array()); // Returns false
```
### `util.types.isFloat64Array(value)`
<!-- YAML
added: v10.0.0
-->
@ -1635,6 +1674,7 @@ util.types.isFloat64Array(new Float64Array()); // Returns true
```
### `util.types.isGeneratorFunction(value)`
<!-- YAML
added: v10.0.0
-->
@ -1653,6 +1693,7 @@ util.types.isGeneratorFunction(function* foo() {}); // Returns true
```
### `util.types.isGeneratorObject(value)`
<!-- YAML
added: v10.0.0
-->
@ -1673,6 +1714,7 @@ util.types.isGeneratorObject(generator); // Returns true
```
### `util.types.isInt8Array(value)`
<!-- YAML
added: v10.0.0
-->
@ -1689,6 +1731,7 @@ util.types.isInt8Array(new Float64Array()); // Returns false
```
### `util.types.isInt16Array(value)`
<!-- YAML
added: v10.0.0
-->
@ -1705,6 +1748,7 @@ util.types.isInt16Array(new Float64Array()); // Returns false
```
### `util.types.isInt32Array(value)`
<!-- YAML
added: v10.0.0
-->
@ -1721,6 +1765,7 @@ util.types.isInt32Array(new Float64Array()); // Returns false
```
### `util.types.isKeyObject(value)`
<!-- YAML
added: v16.2.0
-->
@ -1731,6 +1776,7 @@ added: v16.2.0
Returns `true` if `value` is a {KeyObject}, `false` otherwise.
### `util.types.isMap(value)`
<!-- YAML
added: v10.0.0
-->
@ -1745,6 +1791,7 @@ util.types.isMap(new Map()); // Returns true
```
### `util.types.isMapIterator(value)`
<!-- YAML
added: v10.0.0
-->
@ -1764,6 +1811,7 @@ util.types.isMapIterator(map[Symbol.iterator]()); // Returns true
```
### `util.types.isModuleNamespaceObject(value)`
<!-- YAML
added: v10.0.0
-->
@ -1774,6 +1822,7 @@ added: v10.0.0
Returns `true` if the value is an instance of a [Module Namespace Object][].
<!-- eslint-skip -->
```js
import * as ns from './a.js';
@ -1781,6 +1830,7 @@ util.types.isModuleNamespaceObject(ns); // Returns true
```
### `util.types.isNativeError(value)`
<!-- YAML
added: v10.0.0
-->
@ -1797,6 +1847,7 @@ util.types.isNativeError(new RangeError()); // Returns true
```
### `util.types.isNumberObject(value)`
<!-- YAML
added: v10.0.0
-->
@ -1813,6 +1864,7 @@ util.types.isNumberObject(new Number(0)); // Returns true
```
### `util.types.isPromise(value)`
<!-- YAML
added: v10.0.0
-->
@ -1827,6 +1879,7 @@ util.types.isPromise(Promise.resolve(42)); // Returns true
```
### `util.types.isProxy(value)`
<!-- YAML
added: v10.0.0
-->
@ -1844,6 +1897,7 @@ util.types.isProxy(proxy); // Returns true
```
### `util.types.isRegExp(value)`
<!-- YAML
added: v10.0.0
-->
@ -1859,6 +1913,7 @@ util.types.isRegExp(new RegExp('abc')); // Returns true
```
### `util.types.isSet(value)`
<!-- YAML
added: v10.0.0
-->
@ -1873,6 +1928,7 @@ util.types.isSet(new Set()); // Returns true
```
### `util.types.isSetIterator(value)`
<!-- YAML
added: v10.0.0
-->
@ -1892,6 +1948,7 @@ util.types.isSetIterator(set[Symbol.iterator]()); // Returns true
```
### `util.types.isSharedArrayBuffer(value)`
<!-- YAML
added: v10.0.0
-->
@ -1900,7 +1957,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
@ -1909,6 +1966,7 @@ util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true
```
### `util.types.isStringObject(value)`
<!-- YAML
added: v10.0.0
-->
@ -1925,6 +1983,7 @@ util.types.isStringObject(new String('foo')); // Returns true
```
### `util.types.isSymbolObject(value)`
<!-- YAML
added: v10.0.0
-->
@ -1942,6 +2001,7 @@ util.types.isSymbolObject(Object(symbol)); // Returns true
```
### `util.types.isTypedArray(value)`
<!-- YAML
added: v10.0.0
-->
@ -1960,6 +2020,7 @@ util.types.isTypedArray(new Float64Array()); // Returns true
See also [`ArrayBuffer.isView()`][].
### `util.types.isUint8Array(value)`
<!-- YAML
added: v10.0.0
-->
@ -1976,6 +2037,7 @@ util.types.isUint8Array(new Float64Array()); // Returns false
```
### `util.types.isUint8ClampedArray(value)`
<!-- YAML
added: v10.0.0
-->
@ -1992,6 +2054,7 @@ util.types.isUint8ClampedArray(new Float64Array()); // Returns false
```
### `util.types.isUint16Array(value)`
<!-- YAML
added: v10.0.0
-->
@ -2008,6 +2071,7 @@ util.types.isUint16Array(new Float64Array()); // Returns false
```
### `util.types.isUint32Array(value)`
<!-- YAML
added: v10.0.0
-->
@ -2024,6 +2088,7 @@ util.types.isUint32Array(new Float64Array()); // Returns false
```
### `util.types.isWeakMap(value)`
<!-- YAML
added: v10.0.0
-->
@ -2038,6 +2103,7 @@ util.types.isWeakMap(new WeakMap()); // Returns true
```
### `util.types.isWeakSet(value)`
<!-- YAML
added: v10.0.0
-->
@ -2052,6 +2118,7 @@ util.types.isWeakSet(new WeakSet()); // Returns true
```
### `util.types.isWebAssemblyCompiledModule(value)`
<!-- YAML
added: v10.0.0
deprecated: v14.0.0
@ -2075,6 +2142,7 @@ The following APIs are deprecated and should no longer be used. Existing
applications and modules should be updated to find alternative approaches.
### `util._extend(target, source)`
<!-- YAML
added: v0.7.5
deprecated: v6.0.0
@ -2092,6 +2160,7 @@ It is deprecated and should not be used in new code. JavaScript comes with very
similar built-in functionality through [`Object.assign()`][].
### `util.isArray(object)`
<!-- YAML
added: v0.6.0
deprecated: v4.0.0
@ -2118,6 +2187,7 @@ util.isArray({});
```
### `util.isBoolean(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2142,6 +2212,7 @@ util.isBoolean(false);
```
### `util.isBuffer(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2166,6 +2237,7 @@ util.isBuffer(Buffer.from('hello world'));
```
### `util.isDate(object)`
<!-- YAML
added: v0.6.0
deprecated: v4.0.0
@ -2190,6 +2262,7 @@ util.isDate({});
```
### `util.isError(object)`
<!-- YAML
added: v0.6.0
deprecated: v4.0.0
@ -2230,6 +2303,7 @@ util.isError(obj);
```
### `util.isFunction(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2258,6 +2332,7 @@ util.isFunction(Bar);
```
### `util.isNull(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2283,6 +2358,7 @@ util.isNull(null);
```
### `util.isNullOrUndefined(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2309,6 +2385,7 @@ util.isNullOrUndefined(null);
```
### `util.isNumber(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2335,6 +2412,7 @@ util.isNumber(NaN);
```
### `util.isObject(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2364,6 +2442,7 @@ util.isObject(() => {});
```
### `util.isPrimitive(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2403,6 +2482,7 @@ util.isPrimitive(new Date());
```
### `util.isRegExp(object)`
<!-- YAML
added: v0.6.0
deprecated: v4.0.0
@ -2427,6 +2507,7 @@ util.isRegExp({});
```
### `util.isString(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2453,6 +2534,7 @@ util.isString(5);
```
### `util.isSymbol(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2477,6 +2559,7 @@ util.isSymbol(Symbol('foo'));
```
### `util.isUndefined(object)`
<!-- YAML
added: v0.11.5
deprecated: v4.0.0
@ -2502,6 +2585,7 @@ util.isUndefined(null);
```
### `util.log(string)`
<!-- YAML
added: v0.3.0
deprecated: v6.0.0

View File

@ -12,6 +12,7 @@ const v8 = require('v8');
```
## `v8.cachedDataVersionTag()`
<!-- YAML
added: v8.0.0
-->
@ -33,6 +34,7 @@ console.log(v8.cachedDataVersionTag()); // 183726201
```
## `v8.getHeapCodeStatistics()`
<!-- YAML
added: v12.8.0
-->
@ -46,6 +48,7 @@ Returns an object with the following properties:
* `external_script_source_size` {number}
<!-- eslint-skip -->
```js
{
code_and_metadata_size: 212208,
@ -55,6 +58,7 @@ Returns an object with the following properties:
```
## `v8.getHeapSnapshot()`
<!-- YAML
added: v11.13.0
-->
@ -75,6 +79,7 @@ stream.pipe(process.stdout);
```
## `v8.getHeapSpaceStatistics()`
<!-- YAML
added: v6.0.0
changes:
@ -83,7 +88,7 @@ changes:
description: Support values exceeding the 32-bit unsigned integer range.
-->
* 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()`
<!-- YAML
added: v1.0.0
changes:
@ -174,15 +180,16 @@ garbage with a bit pattern. The RSS footprint (resident set size) gets bigger
because it continuously touches all heap pages and that makes them less likely
to get swapped out by the operating system.
`number_of_native_contexts` The value of native_context is the number of the
`number_of_native_contexts` The value of native\_context is the number of the
top-level contexts currently active. Increase of this number over time indicates
a memory leak.
`number_of_detached_contexts` The value of detached_context is the number
`number_of_detached_contexts` The value of detached\_context is the number
of contexts that were detached and not yet garbage collected. This number
being non-zero indicates a potential memory leak.
<!-- eslint-skip -->
```js
{
total_heap_size: 7326976,
@ -200,6 +207,7 @@ being non-zero indicates a potential memory leak.
```
## `v8.setFlagsFromString(flags)`
<!-- YAML
added: v1.0.0
-->
@ -256,6 +264,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])`
<!-- YAML
added: v11.13.0
-->
@ -316,6 +325,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)`
<!-- YAML
added: v8.0.0
-->
@ -326,6 +336,7 @@ added: v8.0.0
Uses a [`DefaultSerializer`][] to serialize `value` into a buffer.
### `v8.deserialize(buffer)`
<!-- YAML
added: v8.0.0
-->
@ -336,11 +347,13 @@ Uses a [`DefaultDeserializer`][] with default options to read a JS value
from a buffer.
### Class: `v8.Serializer`
<!-- YAML
added: v8.0.0
-->
#### `new Serializer()`
Creates a new `Serializer` object.
#### `serializer.writeHeader()`
@ -447,6 +460,7 @@ Indicate whether to treat `TypedArray` and `DataView` objects as
host objects, i.e. pass them to [`serializer._writeHostObject()`][].
### Class: `v8.Deserializer`
<!-- YAML
added: v8.0.0
-->
@ -495,7 +509,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.
@ -528,6 +542,7 @@ This method is not present on the `Deserializer` class itself but can be
provided by subclasses.
### Class: `v8.DefaultSerializer`
<!-- YAML
added: v8.0.0
-->
@ -537,6 +552,7 @@ A subclass of [`Serializer`][] that serializes `TypedArray`
stores the part of their underlying `ArrayBuffer`s that they are referring to.
### Class: `v8.DefaultDeserializer`
<!-- YAML
added: v8.0.0
-->

View File

@ -43,6 +43,7 @@ console.log(x); // 1; y is not defined.
```
## Class: `vm.Script`
<!-- YAML
added: v0.3.1
-->
@ -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])`
<!-- YAML
added: v0.3.1
changes:
@ -109,6 +111,7 @@ compiled `vm.Script` can be run later multiple times. The `code` is not bound to
any global object; rather, it is bound before each run, just for that run.
### `script.createCachedData()`
<!-- YAML
added: v10.6.0
-->
@ -136,6 +139,7 @@ const cacheWithX = script.createCachedData();
```
### `script.runInContext(contextifiedObject[, options])`
<!-- YAML
added: v0.3.1
changes:
@ -192,6 +196,7 @@ and corresponding threads being started, which have a non-zero performance
overhead.
### `script.runInNewContext([contextObject[, options]])`
<!-- YAML
added: v0.3.1
changes:
@ -264,6 +269,7 @@ console.log(contexts);
```
### `script.runInThisContext([options])`
<!-- YAML
added: v0.3.1
changes:
@ -288,7 +294,7 @@ changes:
Runs the compiled code contained by the `vm.Script` within the context of the
current `global` object. Running code does not have access to local scope, but
*does* have access to the current `global` object.
_does_ have access to the current `global` object.
The following example compiles code that increments a `global` variable then
executes that code multiple times:
@ -310,6 +316,7 @@ console.log(globalVar);
```
## Class: `vm.Module`
<!-- YAML
added:
- v13.0.0
@ -485,7 +492,7 @@ const contextifiedObject = vm.createContext({
### `module.dependencySpecifiers`
* {string[]}
* {string\[]}
The specifiers of all dependencies of this module. The returned array is frozen
to disallow any changes to it.
@ -548,6 +555,7 @@ The identifier of the current module, as set in the constructor.
import foo from 'foo';
// ^^^^^ the module specifier
```
* `extra` {Object}
* `assert` {Object} The data from the assertion:
<!-- eslint-skip -->
@ -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`
<!-- YAML
added: v9.6.0
-->
@ -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])`
<!-- YAML
changes:
- version: v17.0.0
@ -750,6 +761,7 @@ const contextifiedObject = vm.createContext({ secret: 42 });
```
### `sourceTextModule.createCachedData()`
<!-- YAML
added:
- v13.7.0
@ -774,6 +786,7 @@ const module2 = new vm.SourceTextModule('const a = 1;', { cachedData });
```
## Class: `vm.SyntheticModule`
<!-- YAML
added:
- v13.0.0
@ -805,13 +818,15 @@ const module = new vm.SyntheticModule(['default'], function() {
```
### `new vm.SyntheticModule(exportNames, evaluateCallback[, options])`
<!-- YAML
added:
- v13.0.0
- v12.16.0
-->
* `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)`
<!-- YAML
added:
- v13.0.0
@ -866,6 +882,7 @@ const vm = require('vm');
```
## `vm.compileFunction(code[, params[, options]])`
<!-- YAML
added: v10.10.0
changes:
@ -888,7 +905,7 @@ changes:
-->
* `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
@ -904,7 +921,7 @@ changes:
**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]])`
<!-- YAML
added: v0.3.1
changes:
@ -1002,6 +1020,7 @@ The provided `name` and `origin` of the context are made visible through the
Inspector API.
## `vm.isContext(object)`
<!-- YAML
added: v0.11.7
-->
@ -1089,6 +1108,7 @@ vm.measureMemory({ mode: 'detailed', execution: 'eager' })
```
## `vm.runInContext(code, contextifiedObject[, options])`
<!-- YAML
added: v0.3.1
changes:
@ -1151,7 +1171,7 @@ changes:
The `vm.runInContext()` method compiles `code`, runs it within the context of
the `contextifiedObject`, then returns the result. Running code does not have
access to the local scope. The `contextifiedObject` object *must* have been
access to the local scope. The `contextifiedObject` object _must_ have been
previously [contextified][] using the [`vm.createContext()`][] method.
If `options` is a string, then it specifies the filename.
@ -1173,6 +1193,7 @@ console.log(contextObject);
```
## `vm.runInNewContext(code[, contextObject[, options]])`
<!-- YAML
added: v0.3.1
changes:
@ -1282,6 +1303,7 @@ console.log(contextObject);
```
## `vm.runInThisContext(code[, options])`
<!-- YAML
added: v0.3.1
changes:
@ -1350,6 +1372,7 @@ The following example illustrates using both `vm.runInThisContext()` and
the JavaScript [`eval()`][] function to run the same code:
<!-- eslint-disable prefer-const -->
```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')`.

View File

@ -107,6 +107,7 @@ The `--experimental-wasi-unstable-preview1` CLI argument is needed for this
example to run.
## Class: `WASI`
<!-- YAML
added:
- v13.3.0
@ -120,6 +121,7 @@ instance must have its command-line arguments, environment variables, and
sandbox directory structure configured explicitly.
### `new WASI([options])`
<!-- YAML
added:
- v13.3.0
@ -148,6 +150,7 @@ added:
WebAssembly application. **Default:** `2`.
### `wasi.start(instance)`
<!-- YAML
added:
- v13.3.0
@ -166,6 +169,7 @@ Attempt to begin execution of `instance` as a WASI command by invoking its
If `start()` is called more than once, an exception is thrown.
### `wasi.initialize(instance)`
<!-- YAML
added:
- v14.6.0
@ -184,6 +188,7 @@ export, then an exception is thrown.
If `initialize()` is called more than once, an exception is thrown.
### `wasi.wasiImport`
<!-- YAML
added:
- v13.3.0

File diff suppressed because it is too large Load Diff

View File

@ -98,16 +98,19 @@ const stream = new ReadableStream({
## API
### Class: `ReadableStream`
<!-- YAML
added: v16.5.0
-->
#### `new ReadableStream([underlyingSource [, strategy]])`
<!-- YAML
added: v16.5.0
-->
<!--lint disable maximum-line-length remark-lint-->
* `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}
<!--lint enable maximum-line-length remark-lint-->
#### `readableStream.locked`
<!-- YAML
added: v16.5.0
-->
@ -148,6 +153,7 @@ switch to `true` while there is an active reader consuming the
stream's data.
#### `readableStream.cancel([reason])`
<!-- YAML
added: v16.5.0
-->
@ -157,6 +163,7 @@ added: v16.5.0
been completed.
#### `readableStream.getReader([options])`
<!-- YAML
added: v16.5.0
-->
@ -188,6 +195,7 @@ reader.read().then(console.log);
Causes the `readableStream.locked` to be `true`.
#### `readableStream.pipeThrough(transform[, options])`
<!-- YAML
added: v16.5.0
-->
@ -270,6 +278,7 @@ const transformedStream = stream.pipeThrough(transform);
```
#### `readableStream.pipeTo(destination, options)`
<!-- YAML
added: v16.5.0
-->
@ -292,11 +301,12 @@ Causes the `readableStream.locked` to be `true` while the pipe operation
is active.
#### `readableStream.tee()`
<!-- YAML
added: v16.5.0
-->
* 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])`
<!-- YAML
added: v16.5.0
-->
@ -373,6 +384,7 @@ port2.postMessage(stream, [stream]);
```
### Class: `ReadableStreamDefaultReader`
<!-- YAML
added: v16.5.0
-->
@ -384,6 +396,7 @@ values, which allows the {ReadableStream} to work with generally any
JavaScript value.
#### `new ReadableStreamDefaultReader(stream)`
<!-- YAML
added: v16.5.0
-->
@ -394,6 +407,7 @@ Creates a new {ReadableStreamDefaultReader} that is locked to the
given {ReadableStream}.
#### `readableStreamDefaultReader.cancel([reason])`
<!-- YAML
added: v16.5.0
-->
@ -405,6 +419,7 @@ Cancels the {ReadableStream} and returns a promise that is fulfilled
when the underlying stream has been canceled.
#### `readableStreamDefaultReader.closed`
<!-- YAML
added: v16.5.0
-->
@ -413,6 +428,7 @@ added: v16.5.0
{ReadableStream} is closed or this reader's lock is released.
#### `readableStreamDefaultReader.read()`
<!-- YAML
added: v16.5.0
-->
@ -426,6 +442,7 @@ and returns a promise that is fulfilled with the data once it is
available.
#### `readableStreamDefaultReader.releaseLock()`
<!-- YAML
added: v16.5.0
-->
@ -433,13 +450,14 @@ added: v16.5.0
Releases this reader's lock on the underlying {ReadableStream}.
### Class: `ReadableStreamBYOBReader`
<!-- YAML
added: v16.5.0
-->
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)`
<!-- YAML
added: v16.5.0
-->
@ -515,6 +534,7 @@ Creates a new `ReadableStreamBYOBReader` that is locked to the
given {ReadableStream}.
#### `readableStreamBYOBReader.cancel([reason])`
<!-- YAML
added: v16.5.0
-->
@ -526,6 +546,7 @@ Cancels the {ReadableStream} and returns a promise that is fulfilled
when the underlying stream has been canceled.
#### `readableStreamBYOBReader.closed`
<!-- YAML
added: v16.5.0
-->
@ -534,6 +555,7 @@ added: v16.5.0
{ReadableStream} is closed or this reader's lock is released.
#### `readableStreamBYOBReader.read(view)`
<!-- YAML
added: v16.5.0
-->
@ -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()`
<!-- YAML
added: v16.5.0
-->
@ -566,6 +589,7 @@ added: v16.5.0
Releases this reader's lock on the underlying {ReadableStream}.
### Class: `ReadableStreamDefaultController`
<!-- YAML
added: v16.5.0
-->
@ -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()`
<!-- YAML
added: v16.5.0
-->
@ -583,6 +608,7 @@ added: v16.5.0
Closes the {ReadableStream} to which this controller is associated.
#### `readableStreamDefaultController.desiredSize`
<!-- YAML
added: v16.5.0
-->
@ -593,6 +619,7 @@ Returns the amount of data remaining to fill the {ReadableStream}'s
queue.
#### `readableStreamDefaultController.enqueue(chunk)`
<!-- YAML
added: v16.5.0
-->
@ -602,6 +629,7 @@ added: v16.5.0
Appends a new chunk of data to the {ReadableStream}'s queue.
#### `readableStreamDefaultController.error(error)`
<!-- YAML
added: v16.5.0
-->
@ -611,6 +639,7 @@ added: v16.5.0
Signals an error that causes the {ReadableStream} to error and close.
### Class: `ReadableByteStreamController`
<!-- YAML
added: v16.5.0
-->
@ -620,6 +649,7 @@ the internal state and management of the stream's queue. The
`ReadableByteStreamController` is for byte-oriented `ReadableStream`s.
#### `readableByteStreamController.byobRequest`
<!-- YAML
added: v16.5.0
-->
@ -627,6 +657,7 @@ added: v16.5.0
* Type: {ReadableStreamBYOBRequest}
#### `readableByteStreamController.close()`
<!-- YAML
added: v16.5.0
-->
@ -634,6 +665,7 @@ added: v16.5.0
Closes the {ReadableStream} to which this controller is associated.
#### `readableByteStreamController.desiredSize`
<!-- YAML
added: v16.5.0
-->
@ -644,6 +676,7 @@ Returns the amount of data remaining to fill the {ReadableStream}'s
queue.
#### `readableByteStreamController.enqueue(chunk)`
<!-- YAML
added: v16.5.0
-->
@ -653,6 +686,7 @@ added: v16.5.0
Appends a new chunk of data to the {ReadableStream}'s queue.
#### `readableByteStreamController.error(error)`
<!-- YAML
added: v16.5.0
-->
@ -662,6 +696,7 @@ added: v16.5.0
Signals an error that causes the {ReadableStream} to error and close.
### Class: `ReadableStreamBYOBRequest`
<!-- YAML
added: v16.5.0
-->
@ -677,6 +712,7 @@ and provides methods for signaling that the data has
been provided.
#### `readableStreamBYOBRequest.respond(bytesWritten)`
<!-- YAML
added: v16.5.0
-->
@ -687,6 +723,7 @@ Signals that a `bytesWritten` number of bytes have been written
to `readableStreamBYOBRequest.view`.
#### `readableStreamBYOBRequest.respondWithNewView(view)`
<!-- YAML
added: v16.5.0
-->
@ -697,6 +734,7 @@ Signals that the request has been fulfilled with bytes written
to a new `Buffer`, `TypedArray`, or `DataView`.
#### `readableStreamBYOBRequest.view`
<!-- YAML
added: v16.5.0
-->
@ -704,6 +742,7 @@ added: v16.5.0
* Type: {Buffer|TypedArray|DataView}
### Class: `WritableStream`
<!-- YAML
added: v16.5.0
-->
@ -725,6 +764,7 @@ await stream.getWriter().write('Hello World');
```
#### `new WritableStream([underlyingSink[, strategy]])`
<!-- YAML
added: v16.5.0
-->
@ -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])`
<!-- YAML
added: v16.5.0
-->
@ -768,6 +809,7 @@ Abruptly terminates the `WritableStream`. All queued writes will be
canceled with their associated promises rejected.
#### `writableStream.close()`
<!-- YAML
added: v16.5.0
-->
@ -777,6 +819,7 @@ added: v16.5.0
Closes the `WritableStream` when no additional writes are expected.
#### `writableStream.getWriter()`
<!-- YAML
added: v16.5.0
-->
@ -787,6 +830,7 @@ Creates and creates a new writer instance that can be used to write
data into the `WritableStream`.
#### `writableStream.locked`
<!-- YAML
added: v16.5.0
-->
@ -814,11 +858,13 @@ port2.postMessage(stream, [stream]);
```
### Class: `WritableStreamDefaultWriter`
<!-- YAML
added: v16.5.0
-->
#### `new WritableStreamDefaultWriter(stream)`
<!-- YAML
added: v16.5.0
-->
@ -829,6 +875,7 @@ Creates a new `WritableStreamDefaultWriter` that is locked to the given
`WritableStream`.
#### `writableStreamDefaultWriter.abort([reason])`
<!-- YAML
added: v16.5.0
-->
@ -840,6 +887,7 @@ Abruptly terminates the `WritableStream`. All queued writes will be
canceled with their associated promises rejected.
#### `writableStreamDefaultWriter.close()`
<!-- YAML
added: v16.5.0
-->
@ -849,6 +897,7 @@ added: v16.5.0
Closes the `WritableStream` when no additional writes are expected.
#### `writableStreamDefaultWriter.closed`
<!-- YAML
added: v16.5.0
-->
@ -858,6 +907,7 @@ added: v16.5.0
released.
#### `writableStreamDefaultWriter.desiredSize`
<!-- YAML
added: v16.5.0
-->
@ -867,6 +917,7 @@ added: v16.5.0
The amount of data required to fill the {WritableStream}'s queue.
#### `writableStreamDefaultWriter.ready`
<!-- YAML
added: v16.5.0
-->
@ -875,6 +926,7 @@ added: v16.5.0
writer is ready to be used.
#### `writableStreamDefaultWriter.releaseLock()`
<!-- YAML
added: v16.5.0
-->
@ -882,6 +934,7 @@ added: v16.5.0
Releases this writer's lock on the underlying {ReadableStream}.
#### `writableStreamDefaultWriter.write([chunk])`
<!-- YAML
added: v16.5.0
-->
@ -892,6 +945,7 @@ added: v16.5.0
Appends a new chunk of data to the {WritableStream}'s queue.
### Class: `WritableStreamDefaultController`
<!-- YAML
added: v16.5.0
-->
@ -904,6 +958,7 @@ internal state.
* Type: {any} The `reason` value passed to `writableStream.abort()`.
#### `writableStreamDefaultController.error(error)`
<!-- YAML
added: v16.5.0
-->
@ -920,6 +975,7 @@ with currently pending writes canceled.
write or close operations when a {WritableStream} is aborted.
### Class: `TransformStream`
<!-- YAML
added: v16.5.0
-->
@ -947,6 +1003,7 @@ await Promise.all([
```
#### `new TransformStream([transformer[, writableStrategy[, readableStrategy]]])`
<!-- YAML
added: v16.5.0
-->
@ -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`
<!-- YAML
added: v16.5.0
-->
@ -994,6 +1052,7 @@ added: v16.5.0
* Type: {ReadableStream}
#### `transformStream.writable`
<!-- YAML
added: v16.5.0
-->
@ -1018,6 +1077,7 @@ port2.postMessage(stream, [stream]);
```
### Class: `TransformStreamDefaultController`
<!-- YAML
added: v16.5.0
-->
@ -1026,6 +1086,7 @@ The `TransformStreamDefaultController` manages the internal state
of the `TransformStream`.
#### `transformStreamDefaultController.desiredSize`
<!-- YAML
added: v16.5.0
-->
@ -1035,6 +1096,7 @@ added: v16.5.0
The amount of data required to fill the readable side's queue.
#### `transformStreamDefaultController.enqueue([chunk])`
<!-- YAML
added: v16.5.0
-->
@ -1044,6 +1106,7 @@ added: v16.5.0
Appends a chunk of data to the readable side's queue.
#### `transformStreamDefaultController.error([reason])`
<!-- YAML
added: v16.5.0
-->
@ -1055,6 +1118,7 @@ while processing the transform data, causing both sides to be abruptly
closed.
#### `transformStreamDefaultController.terminate()`
<!-- YAML
added: v16.5.0
-->
@ -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`
<!-- YAML
added: v16.5.0
-->
#### `new ByteLengthQueuingStrategy(options)`
<!-- YAML
added: v16.5.0
-->
@ -1076,6 +1142,7 @@ added: v16.5.0
* `highWaterMark` {number}
#### `byteLengthQueuingStrategy.highWaterMark`
<!-- YAML
added: v16.5.0
-->
@ -1083,6 +1150,7 @@ added: v16.5.0
* Type: {number}
#### `byteLengthQueuingStrategy.size`
<!-- YAML
added: v16.5.0
-->
@ -1092,11 +1160,13 @@ added: v16.5.0
* Returns: {number}
### Class: `CountQueuingStrategy`
<!-- YAML
added: v16.5.0
-->
#### `new CountQueuingStrategy(options)`
<!-- YAML
added: v16.5.0
-->
@ -1105,6 +1175,7 @@ added: v16.5.0
* `highWaterMark` {number}
#### `countQueuingStrategy.highWaterMark`
<!-- YAML
added: v16.5.0
-->
@ -1112,6 +1183,7 @@ added: v16.5.0
* Type: {number}
#### `countQueuingStrategy.size`
<!-- YAML
added: v16.5.0
-->
@ -1121,11 +1193,13 @@ added: v16.5.0
* Returns: {number}
### Class: `TextEncoderStream`
<!-- YAML
added: v16.6.0
-->
#### `new TextEncoderStream()`
<!-- YAML
added: v16.6.0
-->
@ -1133,6 +1207,7 @@ added: v16.6.0
Creates a new `TextEncoderStream` instance.
#### `textEncoderStream.encoding`
<!-- YAML
added: v16.6.0
-->
@ -1142,6 +1217,7 @@ added: v16.6.0
The encoding supported by the `TextEncoderStream` instance.
#### `textEncoderStream.readable`
<!-- YAML
added: v16.6.0
-->
@ -1149,6 +1225,7 @@ added: v16.6.0
* Type: {ReadableStream}
#### `textEncoderStream.writable`
<!-- YAML
added: v16.6.0
-->
@ -1156,11 +1233,13 @@ added: v16.6.0
* Type: {WritableStream}
### Class: `TextDecoderStream`
<!-- YAML
added: v16.6.0
-->
#### `new TextDecoderStream([encoding[, options]])`
<!-- YAML
added: v16.6.0
-->
@ -1177,6 +1256,7 @@ added: v16.6.0
Creates a new `TextDecoderStream` instance.
#### `textDecoderStream.encoding`
<!-- YAML
added: v16.6.0
-->
@ -1186,6 +1266,7 @@ added: v16.6.0
The encoding supported by the `TextDecoderStream` instance.
#### `textDecoderStream.fatal`
<!-- YAML
added: v16.6.0
-->
@ -1196,6 +1277,7 @@ The value will be `true` if decoding errors result in a `TypeError` being
thrown.
#### `textDecoderStream.ignoreBOM`
<!-- YAML
added: v16.6.0
-->
@ -1206,6 +1288,7 @@ The value will be `true` if the decoding result will include the byte order
mark.
#### `textDecoderStream.readable`
<!-- YAML
added: v16.6.0
-->
@ -1213,6 +1296,7 @@ added: v16.6.0
* Type: {ReadableStream}
#### `textDecoderStream.writable`
<!-- YAML
added: v16.6.0
-->
@ -1220,10 +1304,13 @@ added: v16.6.0
* Type: {WritableStream}
### Class: `CompressionStream`
<!-- YAML
added: v17.0.0
-->
#### `new CompressionStream(format)`
<!-- YAML
added: v17.0.0
-->
@ -1231,6 +1318,7 @@ added: v17.0.0
* `format` {string} One of either `'deflate'` or `'gzip'`.
#### `compressionStream.readable`
<!-- YAML
added: v17.0.0
-->
@ -1238,6 +1326,7 @@ added: v17.0.0
* Type: {ReadableStream}
#### `compressionStream.writable`
<!-- YAML
added: v17.0.0
-->
@ -1245,11 +1334,13 @@ added: v17.0.0
* Type: {WritableStream}
### Class: `DecompressionStream`
<!-- YAML
added: v17.0.0
-->
#### `new DecompressionStream(format)`
<!-- YAML
added: v17.0.0
-->
@ -1257,6 +1348,7 @@ added: v17.0.0
* `format` {string} One of either `'deflate'` or `'gzip'`.
#### `decompressionStream.readable`
<!-- YAML
added: v17.0.0
-->
@ -1264,6 +1356,7 @@ added: v17.0.0
* Type: {ReadableStream}
#### `decompressionStream.writable`
<!-- YAML
added: v17.0.0
-->
@ -1271,6 +1364,7 @@ added: v17.0.0
* Type: {WritableStream}
### Utility Consumers
<!-- YAML
added: v16.7.0
-->
@ -1299,6 +1393,7 @@ const {
```
#### `streamConsumers.arrayBuffer(stream)`
<!-- YAML
added: v16.7.0
-->
@ -1308,6 +1403,7 @@ added: v16.7.0
contents of the stream.
#### `streamConsumers.blob(stream)`
<!-- YAML
added: v16.7.0
-->
@ -1317,6 +1413,7 @@ added: v16.7.0
of the stream.
#### `streamConsumers.buffer(stream)`
<!-- YAML
added: v16.7.0
-->
@ -1326,6 +1423,7 @@ added: v16.7.0
contents of the stream.
#### `streamConsumers.json(stream)`
<!-- YAML
added: v16.7.0
-->
@ -1335,6 +1433,7 @@ added: v16.7.0
UTF-8 encoded string that is then passed through `JSON.parse()`.
#### `streamConsumers.text(stream)`
<!-- YAML
added: v16.7.0
-->

View File

@ -62,6 +62,7 @@ Worker threads inherit non-process-specific options by default. Refer to
specifically `argv` and `execArgv` options.
## `worker.getEnvironmentData(key)`
<!-- YAML
added:
- v15.12.0
@ -96,6 +97,7 @@ if (isMainThread) {
```
## `worker.isMainThread`
<!-- YAML
added: v10.5.0
-->
@ -117,6 +119,7 @@ if (isMainThread) {
```
## `worker.markAsUntransferable(object)`
<!-- YAML
added:
- v14.5.0
@ -156,11 +159,13 @@ console.log(typedArray2);
There is no equivalent to this API in browsers.
## `worker.moveMessagePortToContext(port, contextifiedSandbox)`
<!-- YAML
added: v11.13.0
-->
* `port` {MessagePort} The message port to transfer.
* `contextifiedSandbox` {Object} A [contextified][] object as returned by the
`vm.createContext()` method.
@ -180,6 +185,7 @@ However, the created `MessagePort` no longer inherits from
events using it.
## `worker.parentPort`
<!-- YAML
added: v10.5.0
-->
@ -211,6 +217,7 @@ if (isMainThread) {
```
## `worker.receiveMessageOnPort(port)`
<!-- YAML
added: v12.3.0
changes:
@ -243,6 +250,7 @@ When this function is used, no `'message'` event is emitted and the
`onmessage` listener is not invoked.
## `worker.resourceLimits`
<!-- YAML
added:
- v13.2.0
@ -262,6 +270,7 @@ this matches its values.
If this is used in the main thread, its value is an empty object.
## `worker.SHARE_ENV`
<!-- YAML
added: v11.14.0
-->
@ -281,6 +290,7 @@ new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
```
## `worker.setEnvironmentData(key[, value])`
<!-- YAML
added:
- v15.12.0
@ -300,6 +310,7 @@ The `worker.setEnvironmentData()` API sets the content of
instances spawned from the current context.
## `worker.threadId`
<!-- YAML
added: v10.5.0
-->
@ -311,6 +322,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`
<!-- YAML
added: v10.5.0
-->
@ -332,6 +344,7 @@ if (isMainThread) {
```
## Class: `BroadcastChannel extends EventTarget`
<!-- YAML
added: v15.4.0
-->
@ -367,14 +380,16 @@ if (isMainThread) {
```
### `new BroadcastChannel(name)`
<!-- YAML
added: v15.4.0
-->
* `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()`
<!-- YAML
added: v15.4.0
-->
@ -382,6 +397,7 @@ added: v15.4.0
Closes the `BroadcastChannel` connection.
### `broadcastChannel.onmessage`
<!-- YAML
added: v15.4.0
-->
@ -390,6 +406,7 @@ added: v15.4.0
when a message is received.
### `broadcastChannel.onmessageerror`
<!-- YAML
added: v15.4.0
-->
@ -398,6 +415,7 @@ added: v15.4.0
deserialized.
### `broadcastChannel.postMessage(message)`
<!-- YAML
added: v15.4.0
-->
@ -405,16 +423,18 @@ added: v15.4.0
* `message` {any} Any cloneable JavaScript value.
### `broadcastChannel.ref()`
<!-- YAML
added: v15.4.0
-->
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()`
<!-- YAML
added: v15.4.0
-->
@ -424,6 +444,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`
<!-- YAML
added: v10.5.0
-->
@ -444,6 +465,7 @@ port2.postMessage({ foo: 'bar' });
```
## Class: `MessagePort`
<!-- YAML
added: v10.5.0
changes:
@ -464,6 +486,7 @@ structured data, memory regions and other `MessagePort`s between different
This implementation matches [browser `MessagePort`][]s.
### Event: `'close'`
<!-- YAML
added: v10.5.0
-->
@ -486,6 +509,7 @@ port1.close();
```
### Event: `'message'`
<!-- YAML
added: v10.5.0
-->
@ -499,6 +523,7 @@ Listeners on this event receive a clone of the `value` parameter as passed
to `postMessage()` and no further arguments.
### Event: `'messageerror'`
<!-- YAML
added:
- v14.5.0
@ -516,6 +541,7 @@ are received in a `vm.Context` (where Node.js APIs are currently
unavailable).
### `port.close()`
<!-- YAML
added: v10.5.0
-->
@ -528,6 +554,7 @@ The [`'close'` event][] is emitted on both `MessagePort` instances that
are part of the channel.
### `port.postMessage(value[, transferList])`
<!-- YAML
added: v10.5.0
changes:
@ -560,7 +587,7 @@ changes:
-->
* `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
@ -731,12 +758,13 @@ port2.postMessage(new URL('https://example.org'));
```
### `port.ref()`
<!-- YAML
added: v10.5.0
-->
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
@ -744,6 +772,7 @@ is `ref()`ed and `unref()`ed automatically depending on whether
listeners for the event exist.
### `port.start()`
<!-- YAML
added: v10.5.0
-->
@ -759,6 +788,7 @@ automatically calls `.start()`, but unsetting it lets messages queue up
until a new handler is set or the port is discarded.
### `port.unref()`
<!-- YAML
added: v10.5.0
-->
@ -772,6 +802,7 @@ If listeners are attached or removed using `.on('message')`, the port is
listeners for the event exist.
## Class: `Worker`
<!-- YAML
added: v10.5.0
-->
@ -847,6 +878,7 @@ if (isMainThread) {
```
### `new Worker(filename[, options])`
<!-- YAML
added: v10.5.0
changes:
@ -894,7 +926,7 @@ changes:
If `options.eval` is `true`, this is a string containing JavaScript code
rather than a path.
* `options` {Object}
* `argv` {any[]} List of arguments which would be stringified and appended to
* `argv` {any\[]} List of arguments which would be stringified and appended to
`process.argv` in the worker. This is mostly similar to the `workerData`
but the values are available on the global `process.argv` as if they
were passed as CLI options to the script.
@ -906,7 +938,7 @@ changes:
* `eval` {boolean} If `true` and the first argument is a `string`, interpret
the first argument to the constructor as a script that is executed once the
worker is online.
* `execArgv` {string[]} List of node CLI options passed to the worker.
* `execArgv` {string\[]} List of node CLI options passed to the worker.
V8 options (such as `--max-old-space-size`) and options that affect the
process (such as `--title`) are not supported. If set, this is provided
as [`process.execArgv`][] inside the worker. By default, options are
@ -929,7 +961,7 @@ changes:
resources like network sockets or file descriptors managed through
the [`FileHandle`][] API. This option is automatically inherited by all
nested `Worker`s. **Default:** `true`.
* `transferList` {Object[]} If one or more `MessagePort`-like objects
* `transferList` {Object\[]} If one or more `MessagePort`-like objects
are passed in `workerData`, a `transferList` is required for those
items or [`ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST`][] is thrown.
See [`port.postMessage()`][] for more information.
@ -947,6 +979,7 @@ changes:
Small values may lead to unusable Worker instances. **Default:** `4`.
### Event: `'error'`
<!-- YAML
added: v10.5.0
-->
@ -957,6 +990,7 @@ The `'error'` event is emitted if the worker thread throws an uncaught
exception. In that case, the worker is terminated.
### Event: `'exit'`
<!-- YAML
added: v10.5.0
-->
@ -971,6 +1005,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'`
<!-- YAML
added: v10.5.0
-->
@ -985,6 +1020,7 @@ All messages sent from the worker thread are emitted before the
[`'exit'` event][] is emitted on the `Worker` object.
### Event: `'messageerror'`
<!-- YAML
added:
- v14.5.0
@ -996,6 +1032,7 @@ added:
The `'messageerror'` event is emitted when deserializing a message failed.
### Event: `'online'`
<!-- YAML
added: v10.5.0
-->
@ -1004,6 +1041,7 @@ The `'online'` event is emitted when the worker thread has started executing
JavaScript code.
### `worker.getHeapSnapshot()`
<!-- YAML
added:
- v13.9.0
@ -1021,6 +1059,7 @@ If the Worker thread is no longer running, which may occur before the
immediately with an [`ERR_WORKER_NOT_RUNNING`][] error.
### `worker.performance`
<!-- YAML
added:
- v15.1.0
@ -1032,6 +1071,7 @@ An object that can be used to query performance information from a worker
instance. Similar to [`perf_hooks.performance`][].
#### `performance.eventLoopUtilization([utilization1[, utilization2]])`
<!-- YAML
added:
- v15.1.0
@ -1086,28 +1126,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])`
<!-- YAML
added: v10.5.0
-->
* `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()`
<!-- YAML
added: v10.5.0
-->
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`
<!-- YAML
added:
- v13.2.0
@ -1127,6 +1170,7 @@ this matches its values.
If the worker has stopped, the return value is an empty object.
### `worker.stderr`
<!-- YAML
added: v10.5.0
-->
@ -1139,6 +1183,7 @@ inside the worker thread. If `stderr: true` was not passed to the
[`process.stderr`][] stream.
### `worker.stdin`
<!-- YAML
added: v10.5.0
-->
@ -1150,6 +1195,7 @@ writable stream. The data written to this stream will be made available in
the worker thread as [`process.stdin`][].
### `worker.stdout`
<!-- YAML
added: v10.5.0
-->
@ -1162,6 +1208,7 @@ inside the worker thread. If `stdout: true` was not passed to the
[`process.stdout`][] stream.
### `worker.terminate()`
<!-- YAML
added: v10.5.0
changes:
@ -1180,6 +1227,7 @@ Returns a Promise for the exit code that is fulfilled when the
[`'exit'` event][] is emitted.
### `worker.threadId`
<!-- YAML
added: v10.5.0
-->
@ -1191,6 +1239,7 @@ it is available as [`require('worker_threads').threadId`][].
This value is unique for each `Worker` instance inside a single process.
### `worker.unref()`
<!-- YAML
added: v10.5.0
-->

View File

@ -265,6 +265,7 @@ From `zlib/zconf.h`, modified for Node.js usage:
The memory requirements for deflate are (in bytes):
<!-- eslint-disable semi -->
```js
(1 << (windowBits + 2)) + (1 << (memLevel + 9))
```
@ -354,6 +355,7 @@ http.createServer((request, response) => {
```
## Constants
<!-- YAML
added: v0.5.8
-->
@ -412,6 +414,7 @@ Compression strategy.
* `zlib.constants.Z_DEFAULT_STRATEGY`
### Brotli constants
<!-- YAML
added:
- v11.7.0
@ -485,6 +488,7 @@ These advanced options are available for controlling decompression:
Brotli format as standardized in [RFC 7932][]).
## Class: `Options`
<!-- YAML
added: v0.11.1
changes:
@ -528,6 +532,7 @@ See the [`deflateInit2` and `inflateInit2`][] documentation for more
information.
## Class: `BrotliOptions`
<!-- YAML
added: v11.7.0
changes:
@ -563,6 +568,7 @@ const stream = zlib.createBrotliCompress({
```
## Class: `zlib.BrotliCompress`
<!-- YAML
added:
- v11.7.0
@ -572,6 +578,7 @@ added:
Compress data using the Brotli algorithm.
## Class: `zlib.BrotliDecompress`
<!-- YAML
added:
- v11.7.0
@ -581,6 +588,7 @@ added:
Decompress data using the Brotli algorithm.
## Class: `zlib.Deflate`
<!-- YAML
added: v0.5.8
-->
@ -588,6 +596,7 @@ added: v0.5.8
Compress data using deflate.
## Class: `zlib.DeflateRaw`
<!-- YAML
added: v0.5.8
-->
@ -595,6 +604,7 @@ added: v0.5.8
Compress data using deflate, and do not append a `zlib` header.
## Class: `zlib.Gunzip`
<!-- YAML
added: v0.5.8
changes:
@ -613,6 +623,7 @@ changes:
Decompress a gzip stream.
## Class: `zlib.Gzip`
<!-- YAML
added: v0.5.8
-->
@ -620,6 +631,7 @@ added: v0.5.8
Compress data using gzip.
## Class: `zlib.Inflate`
<!-- YAML
added: v0.5.8
changes:
@ -631,6 +643,7 @@ changes:
Decompress a deflate stream.
## Class: `zlib.InflateRaw`
<!-- YAML
added: v0.5.8
changes:
@ -645,6 +658,7 @@ changes:
Decompress a raw deflate stream.
## Class: `zlib.Unzip`
<!-- YAML
added: v0.5.8
-->
@ -653,6 +667,7 @@ Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
the header.
## Class: `zlib.ZlibBase`
<!-- YAML
added: v0.5.8
changes:
@ -670,6 +685,7 @@ This class inherits from [`stream.Transform`][], allowing `zlib` objects to be
used in pipes and similar stream operations.
### `zlib.bytesRead`
<!-- YAML
added: v8.1.0
deprecated: v10.0.0
@ -685,6 +701,7 @@ read by the engine, but is inconsistent with other streams in Node.js that
expose values under these names.
### `zlib.bytesWritten`
<!-- YAML
added: v10.0.0
-->
@ -696,6 +713,7 @@ the engine, before the bytes are processed (compressed or decompressed,
as appropriate for the derived class).
### `zlib.close([callback])`
<!-- YAML
added: v0.9.4
-->
@ -705,6 +723,7 @@ added: v0.9.4
Close the underlying handle.
### `zlib.flush([kind, ]callback)`
<!-- YAML
added: v0.5.8
-->
@ -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)`
<!-- YAML
added: v0.11.4
-->
@ -736,6 +756,7 @@ Dynamically update the compression level and compression strategy.
Only applicable to deflate algorithm.
### `zlib.reset()`
<!-- YAML
added: v0.7.0
-->
@ -744,6 +765,7 @@ Reset the compressor/decompressor to factory defaults. Only applicable to
the inflate and deflate algorithms.
## `zlib.constants`
<!-- YAML
added: v7.0.0
-->
@ -751,6 +773,7 @@ added: v7.0.0
Provides an object enumerating Zlib-related constants.
## `zlib.createBrotliCompress([options])`
<!-- YAML
added:
- v11.7.0
@ -762,6 +785,7 @@ added:
Creates and returns a new [`BrotliCompress`][] object.
## `zlib.createBrotliDecompress([options])`
<!-- YAML
added:
- v11.7.0
@ -773,6 +797,7 @@ added:
Creates and returns a new [`BrotliDecompress`][] object.
## `zlib.createDeflate([options])`
<!-- YAML
added: v0.5.8
-->
@ -782,6 +807,7 @@ added: v0.5.8
Creates and returns a new [`Deflate`][] object.
## `zlib.createDeflateRaw([options])`
<!-- YAML
added: v0.5.8
-->
@ -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])`
<!-- YAML
added: v0.5.8
-->
@ -807,6 +834,7 @@ added: v0.5.8
Creates and returns a new [`Gunzip`][] object.
## `zlib.createGzip([options])`
<!-- YAML
added: v0.5.8
-->
@ -817,6 +845,7 @@ Creates and returns a new [`Gzip`][] object.
See [example][zlib.createGzip example].
## `zlib.createInflate([options])`
<!-- YAML
added: v0.5.8
-->
@ -826,6 +855,7 @@ added: v0.5.8
Creates and returns a new [`Inflate`][] object.
## `zlib.createInflateRaw([options])`
<!-- YAML
added: v0.5.8
-->
@ -835,6 +865,7 @@ added: v0.5.8
Creates and returns a new [`InflateRaw`][] object.
## `zlib.createUnzip([options])`
<!-- YAML
added: v0.5.8
-->
@ -856,6 +887,7 @@ Every method has a `*Sync` counterpart, which accept the same arguments, but
without a callback.
### `zlib.brotliCompress(buffer[, options], callback)`
<!-- YAML
added:
- v11.7.0
@ -867,6 +899,7 @@ added:
* `callback` {Function}
### `zlib.brotliCompressSync(buffer[, options])`
<!-- YAML
added:
- v11.7.0
@ -879,6 +912,7 @@ added:
Compress a chunk of data with [`BrotliCompress`][].
### `zlib.brotliDecompress(buffer[, options], callback)`
<!-- YAML
added:
- v11.7.0
@ -890,6 +924,7 @@ added:
* `callback` {Function}
### `zlib.brotliDecompressSync(buffer[, options])`
<!-- YAML
added:
- v11.7.0
@ -902,6 +937,7 @@ added:
Decompress a chunk of data with [`BrotliDecompress`][].
### `zlib.deflate(buffer[, options], callback)`
<!-- YAML
added: v0.6.0
changes:
@ -921,6 +957,7 @@ changes:
* `callback` {Function}
### `zlib.deflateSync(buffer[, options])`
<!-- YAML
added: v0.11.12
changes:
@ -941,6 +978,7 @@ changes:
Compress a chunk of data with [`Deflate`][].
### `zlib.deflateRaw(buffer[, options], callback)`
<!-- YAML
added: v0.6.0
changes:
@ -957,6 +995,7 @@ changes:
* `callback` {Function}
### `zlib.deflateRawSync(buffer[, options])`
<!-- YAML
added: v0.11.12
changes:
@ -977,6 +1016,7 @@ changes:
Compress a chunk of data with [`DeflateRaw`][].
### `zlib.gunzip(buffer[, options], callback)`
<!-- YAML
added: v0.6.0
changes:
@ -996,6 +1036,7 @@ changes:
* `callback` {Function}
### `zlib.gunzipSync(buffer[, options])`
<!-- YAML
added: v0.11.12
changes:
@ -1016,6 +1057,7 @@ changes:
Decompress a chunk of data with [`Gunzip`][].
### `zlib.gzip(buffer[, options], callback)`
<!-- YAML
added: v0.6.0
changes:
@ -1035,6 +1077,7 @@ changes:
* `callback` {Function}
### `zlib.gzipSync(buffer[, options])`
<!-- YAML
added: v0.11.12
changes:
@ -1055,6 +1098,7 @@ changes:
Compress a chunk of data with [`Gzip`][].
### `zlib.inflate(buffer[, options], callback)`
<!-- YAML
added: v0.6.0
changes:
@ -1074,6 +1118,7 @@ changes:
* `callback` {Function}
### `zlib.inflateSync(buffer[, options])`
<!-- YAML
added: v0.11.12
changes:
@ -1094,6 +1139,7 @@ changes:
Decompress a chunk of data with [`Inflate`][].
### `zlib.inflateRaw(buffer[, options], callback)`
<!-- YAML
added: v0.6.0
changes:
@ -1113,6 +1159,7 @@ changes:
* `callback` {Function}
### `zlib.inflateRawSync(buffer[, options])`
<!-- YAML
added: v0.11.12
changes:
@ -1133,6 +1180,7 @@ changes:
Decompress a chunk of data with [`InflateRaw`][].
### `zlib.unzip(buffer[, options], callback)`
<!-- YAML
added: v0.6.0
changes:
@ -1152,6 +1200,7 @@ changes:
* `callback` {Function}
### `zlib.unzipSync(buffer[, options])`
<!-- YAML
added: v0.11.12
changes: