text
stringlengths 2
4k
|
---|
length of a string when encoded using `encoding`.
* This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account
* for the encoding that is used to convert the string into bytes.
*
* For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input.
* For strings that contain non-base64/hex-encoded data (e.g. whitespace), the
* return value might be greater than the length of a `Buffer` created from the
* string.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const str = '\u00bd + \u00bc = \u00be';
*
* console.log(`${str}: ${str.length} characters, ` +
* `${Buffer.byteLength(str, 'utf8')} bytes`);
* // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
* ```
*
* When `string` is a
* `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/-
* Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop-
* er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned.
* @since v0.1.90
* @param string A value to calculate the length of.
* @param [encoding='utf8'] If `string` is a string, this is its encoding.
* @return The number of bytes contained within `string`.
*/
byteLength(
string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
encoding?: BufferEncoding,
): number;
/**
* Returns a new `Buffer` which is the result of concatenating all the `Buffer`instances in the `list` together.
*
* If the list has no items, or if the `totalLength` is 0, then a new zero-length`Buffer` is returned.
*
* If `totalLength` is not provided, it is calculated from the `Buffer` instances
* in `list` by adding their lengths.
*
* If `totalLength` is provided, it is coerced to an unsigned integer. If the
* combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
* truncated to `totalLength`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create a single `Buffer` from a list of three `Buffer` instances.
*
* const buf1 = Buffer.alloc(10);
* const buf2 = Buffer.alloc(14);
* const buf3 = Buffer.alloc(18);
* const totalLength = buf1.length + buf2.length + buf3.length;
*
* console.log(totalLength);
* // Prints: 42
*
* const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
*
* console.log(bufA);
* // Prints: <Buffer 00 00 00 00 ...>
* console.log(bufA.length);
* // Prints: 42
* ```
*
* `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does.
* @since v0.7.11
* @param list List of `Buffer` or {@link Uint8Array} instances to concatenate.
* @param totalLength Total length of the `Buffer` instances in `list` when concatenated.
*/
concat(list: readonly Uint8Array[], totalLength?: number): Buffer;
/**
|
* Copies the underlying memory of `view` into a new `Buffer`.
*
* ```js
* const u16 = new Uint16Array([0, 0xffff]);
* const buf = Buffer.copyBytesFrom(u16, 1, 1);
* u16[1] = 0;
* console.log(buf.length); // 2
* console.log(buf[0]); // 255
* console.log(buf[1]); // 255
* ```
* @since v19.8.0
* @param view The {TypedArray} to copy.
* @param [offset=': 0'] The starting offset within `view`.
* @param [length=view.length - offset] The number of elements from `view` to copy.
*/
copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer;
/**
* Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from('1234');
* const buf2 = Buffer.from('0123');
* const arr = [buf1, buf2];
*
* console.log(arr.sort(Buffer.compare));
* // Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]
* // (This result is equal to: [buf2, buf1].)
* ```
* @since v0.11.13
* @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details.
*/
compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1;
/**
* Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(5);
*
* console.log(buf);
* // Prints: <Buffer 00 00 00 00 00>
* ```
*
* If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
*
* If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(5, 'a');
*
* console.log(buf);
* // Prints: <Buffer 61 61 61 61 61>
* ```
*
* If both `fill` and `encoding` are specified, the allocated `Buffer` will be
* initialized by calling `buf.fill(fill, encoding)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
*
* console.log(buf);
* // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
* ```
*
* Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance
* contents will never contain sensitive data from previous allocations, including
* data that might not have been allocated for `Buffer`s.
*
* A `TypeError` will be thrown if `size` is not a number.
* @since v5.10.0
* @param size The desired length of the new `Buffer`.
* @param [fill=0] A value to pre-fill the new `Buffer` with.
* @param [encoding='utf8'] If `fill` is a string, this is its encoding.
*/
alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer;
/**
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_O |
UT_OF_RANGE` is thrown.
*
* The underlying memory for `Buffer` instances created in this way is _not_
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(10);
*
* console.log(buf);
* // Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
*
* buf.fill(0);
*
* console.log(buf);
* // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
* ```
*
* A `TypeError` will be thrown if `size` is not a number.
*
* The `Buffer` module pre-allocates an internal `Buffer` instance of
* size `Buffer.poolSize` that is used as a pool for the fast allocation of new`Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`,
* and `Buffer.concat()` only when `size` is less than`Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two).
*
* Use of this pre-allocated internal memory pool is a key difference between
* calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
* Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less
* than or equal to half `Buffer.poolSize`. The
* difference is subtle but can be important when an application requires the
* additional performance that `Buffer.allocUnsafe()` provides.
* @since v5.10.0
* @param size The desired length of the new `Buffer`.
*/
allocUnsafe(size: number): Buffer;
/**
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` 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)` to initialize
* such `Buffer` instances with zeroes.
*
* When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
* allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This
* allows applications to avoid the garbage collection overhead of creating many
* individually allocated `Buffer` instances. This approach improves both
* performance and memory usage by eliminating the need to track and clean up as
* many individual `ArrayBuffer` objects.
*
* However, in the case where a developer may need to retain a small chunk of
* memory from a pool for an indeterminate amount of time, it may be appropriate
* to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and
* then copying out the relevant bits.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Need to keep around a few small chunks of memory.
* const store = [];
*
* socket.on('readable', () => {
* let data;
* while (null !== (data = readable.read())) {
* // Allocate for retained data.
* const sb = Buffer.allocUnsafeSlow(10);
*
* // Copy the data into the new allocation.
|
* data.copy(sb, 0, 0, 10);
*
* store.push(sb);
* }
* });
* ```
*
* A `TypeError` will be thrown if `size` is not a number.
* @since v5.12.0
* @param size The desired length of the new `Buffer`.
*/
allocUnsafeSlow(size: number): Buffer;
/**
* This is the size (in bytes) of pre-allocated internal `Buffer` instances used
* for pooling. This value may be modified.
* @since v0.11.3
*/
poolSize: number;
}
interface Buffer extends Uint8Array {
/**
* Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did
* not contain enough space to fit the entire string, only part of `string` will be
* written. However, partially encoded characters will not be written.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.alloc(256);
*
* const len = buf.write('\u00bd + \u00bc = \u00be', 0);
*
* console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
* // Prints: 12 bytes: ½ + ¼ = ¾
*
* const buffer = Buffer.alloc(10);
*
* const length = buffer.write('abcd', 8);
*
* console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
* // Prints: 2 bytes : ab
* ```
* @since v0.1.90
* @param string String to write to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write `string`.
* @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`).
* @param [encoding='utf8'] The character encoding of `string`.
* @return Number of bytes written.
*/
write(string: string, encoding?: BufferEncoding): number;
write(string: string, offset: number, encoding?: BufferEncoding): number;
write(string: string, offset: number, length: number, encoding?: BufferEncoding): number;
/**
* Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`.
*
* If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8,
* then each invalid byte is replaced with the replacement character `U+FFFD`.
*
* The maximum length of a string instance (in UTF-16 code units) is available
* as {@link constants.MAX_STRING_LENGTH}.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.allocUnsafe(26);
*
* for (let i = 0; i < 26; i++) {
* // 97 is the decimal ASCII value for 'a'.
* buf1[i] = i + 97;
* }
*
* console.log(buf1.toString('utf8'));
* // Prints: abcdefghijklmnopqrstuvwxyz
* console.log(buf1.toString('utf8', 0, 5));
* // Prints: abcde
*
* const buf2 = Buffer.from('tést');
*
* console.log(buf2.toString('hex'));
* // Prints: 74c3a97374
* console.log(buf2.toString('utf8', 0, 3));
* // Prints: té
* console.log(buf2.toString(undefined, 0, 3));
* // Prints: té
* ```
* @since v0.1.90
* @param [encoding='utf8'] The character encoding to use.
* @param |
[start=0] The byte offset to start decoding at.
* @param [end=buf.length] The byte offset to stop decoding at (not inclusive).
*/
toString(encoding?: BufferEncoding, start?: number, end?: number): string;
/**
* Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls
* this function when stringifying a `Buffer` instance.
*
* `Buffer.from()` accepts objects in the format returned from this method.
* In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
* const json = JSON.stringify(buf);
*
* console.log(json);
* // Prints: {"type":"Buffer","data":[1,2,3,4,5]}
*
* const copy = JSON.parse(json, (key, value) => {
* return value && value.type === 'Buffer' ?
* Buffer.from(value) :
* value;
* });
*
* console.log(copy);
* // Prints: <Buffer 01 02 03 04 05>
* ```
* @since v0.9.2
*/
toJSON(): {
type: "Buffer";
data: number[];
};
/**
* Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from('ABC');
* const buf2 = Buffer.from('414243', 'hex');
* const buf3 = Buffer.from('ABCD');
*
* console.log(buf1.equals(buf2));
* // Prints: true
* console.log(buf1.equals(buf3));
* // Prints: false
* ```
* @since v0.11.13
* @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`.
*/
equals(otherBuffer: Uint8Array): boolean;
/**
* Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order.
* Comparison is based on the actual sequence of bytes in each `Buffer`.
*
* * `0` is returned if `target` is the same as `buf`
* * `1` is returned if `target` should come _before_`buf` when sorted.
* * `-1` is returned if `target` should come _after_`buf` when sorted.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from('ABC');
* const buf2 = Buffer.from('BCD');
* const buf3 = Buffer.from('ABCD');
*
* console.log(buf1.compare(buf1));
* // Prints: 0
* console.log(buf1.compare(buf2));
* // Prints: -1
* console.log(buf1.compare(buf3));
* // Prints: -1
* console.log(buf2.compare(buf1));
* // Prints: 1
* console.log(buf2.compare(buf3));
* // Prints: 1
* console.log([buf1, buf2, buf3].sort(Buffer.compare));
* // Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
* // (This result is equal to: [buf1, buf3, buf2].)
* ```
*
* The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd`arguments can be used to limit the comparison to specific ranges within `target`and `buf` respectively.
*
* ```js
|
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
* const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
*
* console.log(buf1.compare(buf2, 5, 9, 0, 4));
* // Prints: 0
* console.log(buf1.compare(buf2, 0, 6, 4));
* // Prints: -1
* console.log(buf1.compare(buf2, 5, 6, 5));
* // Prints: 1
* ```
*
* `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`,`targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`.
* @since v0.11.13
* @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`.
* @param [targetStart=0] The offset within `target` at which to begin comparison.
* @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive).
* @param [sourceStart=0] The offset within `buf` at which to begin comparison.
* @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive).
*/
compare(
target: Uint8Array,
targetStart?: number,
targetEnd?: number,
sourceStart?: number,
sourceEnd?: number,
): -1 | 0 | 1;
/**
* Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`.
*
* [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available
* for all TypedArrays, including Node.js `Buffer`s, although it takes
* different function arguments.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create two `Buffer` instances.
* const buf1 = Buffer.allocUnsafe(26);
* const buf2 = Buffer.allocUnsafe(26).fill('!');
*
* for (let i = 0; i < 26; i++) {
* // 97 is the decimal ASCII value for 'a'.
* buf1[i] = i + 97;
* }
*
* // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.
* buf1.copy(buf2, 8, 16, 20);
* // This is equivalent to:
* // buf2.set(buf1.subarray(16, 20), 8);
*
* console.log(buf2.toString('ascii', 0, 25));
* // Prints: !!!!!!!!qrst!!!!!!!!!!!!!
* ```
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create a `Buffer` and copy data from one region to an overlapping region
* // within the same `Buffer`.
*
* const buf = Buffer.allocUnsafe(26);
*
* for (let i = 0; i < 26; i++) {
* // 97 is the decimal ASCII value for 'a'.
* buf[i] = i + 97;
* }
*
* buf.copy(buf, 0, 4, 10);
*
* console.log(buf.toString());
* // Prints: efghijghijklmnopqrstuvwxyz
* ```
* @since v0.1.90
* @param target A `Buffer` or {@link Uint8Array} to copy into.
* @param [targetStart=0] The offset within `target` at which to begin writing.
* @param [sourceStart=0] The offset within `buf` from which to begin copying.
* @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive).
* @return The number of bytes copied.
*/
copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
|
/**
* Returns a new `Buffer` that references the same memory as the original, but
* offset and cropped by the `start` and `end` indices.
*
* This method is not compatible with the `Uint8Array.prototype.slice()`,
* which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* const copiedBuf = Uint8Array.prototype.slice.call(buf);
* copiedBuf[0]++;
* console.log(copiedBuf.toString());
* // Prints: cuffer
*
* console.log(buf.toString());
* // Prints: buffer
*
* // With buf.slice(), the original buffer is modified.
* const notReallyCopiedBuf = buf.slice();
* notReallyCopiedBuf[0]++;
* console.log(notReallyCopiedBuf.toString());
* // Prints: cuffer
* console.log(buf.toString());
* // Also prints: cuffer (!)
* ```
* @since v0.3.0
* @deprecated Use `subarray` instead.
* @param [start=0] Where the new `Buffer` will start.
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
*/
slice(start?: number, end?: number): Buffer;
/**
* Returns a new `Buffer` that references the same memory as the original, but
* offset and cropped by the `start` and `end` indices.
*
* Specifying `end` greater than `buf.length` will return the same result as
* that of `end` equal to `buf.length`.
*
* This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray).
*
* Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
* // from the original `Buffer`.
*
* const buf1 = Buffer.allocUnsafe(26);
*
* for (let i = 0; i < 26; i++) {
* // 97 is the decimal ASCII value for 'a'.
* buf1[i] = i + 97;
* }
*
* const buf2 = buf1.subarray(0, 3);
*
* console.log(buf2.toString('ascii', 0, buf2.length));
* // Prints: abc
*
* buf1[0] = 33;
*
* console.log(buf2.toString('ascii', 0, buf2.length));
* // Prints: !bc
* ```
*
* Specifying negative indexes causes the slice to be generated relative to the
* end of `buf` rather than the beginning.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* console.log(buf.subarray(-6, -1).toString());
* // Prints: buffe
* // (Equivalent to buf.subarray(0, 5).)
*
* console.log(buf.subarray(-6, -2).toString());
* // Prints: buff
* // (Equivalent to buf.subarray(0, 4).)
*
* console.log(buf.subarray(-5, -2).toString());
* // Prints: uff
* // (Equivalent to buf.subarray(1, 4).)
* ```
* @since v3.0.0
* @param [start=0] Where the new `Buffer` will start.
* @param [end=buf.length] Where th |
e new `Buffer` will end (not inclusive).
*/
subarray(start?: number, end?: number): Buffer;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian.
*
* `value` is interpreted and written as a two's complement signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeBigInt64BE(0x0102030405060708n, 0);
*
* console.log(buf);
* // Prints: <Buffer 01 02 03 04 05 06 07 08>
* ```
* @since v12.0.0, v10.20.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeBigInt64BE(value: bigint, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian.
*
* `value` is interpreted and written as a two's complement signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeBigInt64LE(0x0102030405060708n, 0);
*
* console.log(buf);
* // Prints: <Buffer 08 07 06 05 04 03 02 01>
* ```
* @since v12.0.0, v10.20.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeBigInt64LE(value: bigint, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian.
*
* This function is also available under the `writeBigUint64BE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
*
* console.log(buf);
* // Prints: <Buffer de ca fa fe ca ce fa de>
* ```
* @since v12.0.0, v10.20.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeBigUInt64BE(value: bigint, offset?: number): number;
/**
* @alias Buffer.writeBigUInt64BE
* @since v14.10.0, v12.19.0
*/
writeBigUint64BE(value: bigint, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
*
* console.log(buf);
* // Prints: <Buffer de fa ce ca fe fa ca de>
* ```
*
* This function is also available under the `writeBigUint64LE` alias.
* @since v12.0.0, v10.20.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeBigUInt64LE( |
value: bigint, offset?: number): number;
/**
* @alias Buffer.writeBigUInt64LE
* @since v14.10.0, v12.19.0
*/
writeBigUint64LE(value: bigint, offset?: number): number;
/**
* Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
* when `value` is anything other than an unsigned integer.
*
* This function is also available under the `writeUintLE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(6);
*
* buf.writeUIntLE(0x1234567890ab, 0, 6);
*
* console.log(buf);
* // Prints: <Buffer ab 90 78 56 34 12>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`.
* @return `offset` plus the number of bytes written.
*/
writeUIntLE(value: number, offset: number, byteLength: number): number;
/**
* @alias Buffer.writeUIntLE
* @since v14.9.0, v12.19.0
*/
writeUintLE(value: number, offset: number, byteLength: number): number;
/**
* Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined
* when `value` is anything other than an unsigned integer.
*
* This function is also available under the `writeUintBE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(6);
*
* buf.writeUIntBE(0x1234567890ab, 0, 6);
*
* console.log(buf);
* // Prints: <Buffer 12 34 56 78 90 ab>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`.
* @return `offset` plus the number of bytes written.
*/
writeUIntBE(value: number, offset: number, byteLength: number): number;
/**
* @alias Buffer.writeUIntBE
* @since v14.9.0, v12.19.0
*/
writeUintBE(value: number, offset: number, byteLength: number): number;
/**
* Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
* when `value` is anything other than a signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(6);
*
* buf.writeIntLE(0x1234567890ab, 0, 6);
*
* console.log(buf);
* // Prints: <Buffer ab 90 78 56 34 12>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`.
* @return `offset` plus the number of bytes written.
*/
writeIntLE(value: number, offset: numbe |
r, byteLength: number): number;
/**
* Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a
* signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(6);
*
* buf.writeIntBE(0x1234567890ab, 0, 6);
*
* console.log(buf);
* // Prints: <Buffer 12 34 56 78 90 ab>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`.
* @return `offset` plus the number of bytes written.
*/
writeIntBE(value: number, offset: number, byteLength: number): number;
/**
* Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readBigUint64BE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
*
* console.log(buf.readBigUInt64BE(0));
* // Prints: 4294967295n
* ```
* @since v12.0.0, v10.20.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`.
*/
readBigUInt64BE(offset?: number): bigint;
/**
* @alias Buffer.readBigUInt64BE
* @since v14.10.0, v12.19.0
*/
readBigUint64BE(offset?: number): bigint;
/**
* Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readBigUint64LE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);
*
* console.log(buf.readBigUInt64LE(0));
* // Prints: 18446744069414584320n
* ```
* @since v12.0.0, v10.20.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`.
*/
readBigUInt64LE(offset?: number): bigint;
/**
* @alias Buffer.readBigUInt64LE
* @since v14.10.0, v12.19.0
*/
readBigUint64LE(offset?: number): bigint;
/**
* Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed
* values.
* @since v12.0.0, v10.20.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`.
*/
readBigInt64BE(offset?: number): bigint;
/**
* Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed
* values.
* @since v12.0.0, v10.20.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`.
*/
readBigInt64LE(offset?: number): bigint;
/**
* Reads `byteLength` number |
of bytes from `buf` at the specified `offset`and interprets the result as an unsigned, little-endian integer supporting
* up to 48 bits of accuracy.
*
* This function is also available under the `readUintLE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
*
* console.log(buf.readUIntLE(0, 6).toString(16));
* // Prints: ab9078563412
* ```
* @since v0.11.15
* @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`.
*/
readUIntLE(offset: number, byteLength: number): number;
/**
* @alias Buffer.readUIntLE
* @since v14.9.0, v12.19.0
*/
readUintLE(offset: number, byteLength: number): number;
/**
* Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as an unsigned big-endian integer supporting
* up to 48 bits of accuracy.
*
* This function is also available under the `readUintBE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
*
* console.log(buf.readUIntBE(0, 6).toString(16));
* // Prints: 1234567890ab
* console.log(buf.readUIntBE(1, 6).toString(16));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.11.15
* @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`.
*/
readUIntBE(offset: number, byteLength: number): number;
/**
* @alias Buffer.readUIntBE
* @since v14.9.0, v12.19.0
*/
readUintBE(offset: number, byteLength: number): number;
/**
* Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a little-endian, two's complement signed value
* supporting up to 48 bits of accuracy.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
*
* console.log(buf.readIntLE(0, 6).toString(16));
* // Prints: -546f87a9cbee
* ```
* @since v0.11.15
* @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`.
*/
readIntLE(offset: number, byteLength: number): number;
/**
* Reads `byteLength` number of bytes from `buf` at the specified `offset`and interprets the result as a big-endian, two's complement signed value
* supporting up to 48 bits of accuracy.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);
*
* console.log(buf.readIntBE(0, 6).toString(16));
* // Prints: 1234567890ab
* console.log(buf.readIntBE(1, 6).toString(16));
* // Throws ERR_OUT_OF_RANGE.
* console.log(buf.readIntBE(1, 0).toString(16));
* // Throws ERR_OUT_OF_RANGE.
* ```
|
* @since v0.11.15
* @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`.
* @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`.
*/
readIntBE(offset: number, byteLength: number): number;
/**
* Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
*
* This function is also available under the `readUint8` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([1, -2]);
*
* console.log(buf.readUInt8(0));
* // Prints: 1
* console.log(buf.readUInt8(1));
* // Prints: 254
* console.log(buf.readUInt8(2));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.5.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`.
*/
readUInt8(offset?: number): number;
/**
* @alias Buffer.readUInt8
* @since v14.9.0, v12.19.0
*/
readUint8(offset?: number): number;
/**
* Reads an unsigned, little-endian 16-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readUint16LE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56]);
*
* console.log(buf.readUInt16LE(0).toString(16));
* // Prints: 3412
* console.log(buf.readUInt16LE(1).toString(16));
* // Prints: 5634
* console.log(buf.readUInt16LE(2).toString(16));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.
*/
readUInt16LE(offset?: number): number;
/**
* @alias Buffer.readUInt16LE
* @since v14.9.0, v12.19.0
*/
readUint16LE(offset?: number): number;
/**
* Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readUint16BE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56]);
*
* console.log(buf.readUInt16BE(0).toString(16));
* // Prints: 1234
* console.log(buf.readUInt16BE(1).toString(16));
* // Prints: 3456
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.
*/
readUInt16BE(offset?: number): number;
/**
* @alias Buffer.readUInt16BE
* @since v14.9.0, v12.19.0
*/
readUint16BE(offset?: number): number;
/**
* Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readUint32LE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
*
* console.log(buf.readUInt32LE(0).toString(16));
* // Prints: 78563412
* console.log(buf.readUInt32LE(1).toString(16));
* // Throws ERR_OUT_OF_RANGE.
|
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readUInt32LE(offset?: number): number;
/**
* @alias Buffer.readUInt32LE
* @since v14.9.0, v12.19.0
*/
readUint32LE(offset?: number): number;
/**
* Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`.
*
* This function is also available under the `readUint32BE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);
*
* console.log(buf.readUInt32BE(0).toString(16));
* // Prints: 12345678
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readUInt32BE(offset?: number): number;
/**
* @alias Buffer.readUInt32BE
* @since v14.9.0, v12.19.0
*/
readUint32BE(offset?: number): number;
/**
* Reads a signed 8-bit integer from `buf` at the specified `offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed values.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([-1, 5]);
*
* console.log(buf.readInt8(0));
* // Prints: -1
* console.log(buf.readInt8(1));
* // Prints: 5
* console.log(buf.readInt8(2));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.5.0
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`.
*/
readInt8(offset?: number): number;
/**
* Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed values.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0, 5]);
*
* console.log(buf.readInt16LE(0));
* // Prints: 1280
* console.log(buf.readInt16LE(1));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.
*/
readInt16LE(offset?: number): number;
/**
* Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed values.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0, 5]);
*
* console.log(buf.readInt16BE(0));
* // Prints: 5
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`.
*/
readInt16BE(offset?: number): number;
/**
* Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed values.
*
* ```js
* import { Buffer } from 'node:buffer';
*
|
* const buf = Buffer.from([0, 0, 0, 5]);
*
* console.log(buf.readInt32LE(0));
* // Prints: 83886080
* console.log(buf.readInt32LE(1));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readInt32LE(offset?: number): number;
/**
* Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`.
*
* Integers read from a `Buffer` are interpreted as two's complement signed values.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([0, 0, 0, 5]);
*
* console.log(buf.readInt32BE(0));
* // Prints: 5
* ```
* @since v0.5.5
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readInt32BE(offset?: number): number;
/**
* Reads a 32-bit, little-endian float from `buf` at the specified `offset`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([1, 2, 3, 4]);
*
* console.log(buf.readFloatLE(0));
* // Prints: 1.539989614439558e-36
* console.log(buf.readFloatLE(1));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.11.15
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readFloatLE(offset?: number): number;
/**
* Reads a 32-bit, big-endian float from `buf` at the specified `offset`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([1, 2, 3, 4]);
*
* console.log(buf.readFloatBE(0));
* // Prints: 2.387939260590663e-38
* ```
* @since v0.11.15
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`.
*/
readFloatBE(offset?: number): number;
/**
* Reads a 64-bit, little-endian double from `buf` at the specified `offset`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
*
* console.log(buf.readDoubleLE(0));
* // Prints: 5.447603722011605e-270
* console.log(buf.readDoubleLE(1));
* // Throws ERR_OUT_OF_RANGE.
* ```
* @since v0.11.15
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`.
*/
readDoubleLE(offset?: number): number;
/**
* Reads a 64-bit, big-endian double from `buf` at the specified `offset`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
*
* console.log(buf.readDoubleBE(0));
* // Prints: 8.20788039913184e-304
* ```
* @since v0.11.15
* @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`.
*/
readDoubleBE(offset?: number): number;
reverse(): this;
/**
* Interprets `buf` as an array of unsigned 16-bit integers and swaps the
|
* byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
*
* console.log(buf1);
* // Prints: <Buffer 01 02 03 04 05 06 07 08>
*
* buf1.swap16();
*
* console.log(buf1);
* // Prints: <Buffer 02 01 04 03 06 05 08 07>
*
* const buf2 = Buffer.from([0x1, 0x2, 0x3]);
*
* buf2.swap16();
* // Throws ERR_INVALID_BUFFER_SIZE.
* ```
*
* One convenient use of `buf.swap16()` is to perform a fast in-place conversion
* between UTF-16 little-endian and UTF-16 big-endian:
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
* buf.swap16(); // Convert to big-endian UTF-16 text.
* ```
* @since v5.10.0
* @return A reference to `buf`.
*/
swap16(): Buffer;
/**
* Interprets `buf` as an array of unsigned 32-bit integers and swaps the
* byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
*
* console.log(buf1);
* // Prints: <Buffer 01 02 03 04 05 06 07 08>
*
* buf1.swap32();
*
* console.log(buf1);
* // Prints: <Buffer 04 03 02 01 08 07 06 05>
*
* const buf2 = Buffer.from([0x1, 0x2, 0x3]);
*
* buf2.swap32();
* // Throws ERR_INVALID_BUFFER_SIZE.
* ```
* @since v5.10.0
* @return A reference to `buf`.
*/
swap32(): Buffer;
/**
* 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.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
*
* console.log(buf1);
* // Prints: <Buffer 01 02 03 04 05 06 07 08>
*
* buf1.swap64();
*
* console.log(buf1);
* // Prints: <Buffer 08 07 06 05 04 03 02 01>
*
* const buf2 = Buffer.from([0x1, 0x2, 0x3]);
*
* buf2.swap64();
* // Throws ERR_INVALID_BUFFER_SIZE.
* ```
* @since v6.3.0
* @return A reference to `buf`.
*/
swap64(): Buffer;
/**
* Writes `value` to `buf` at the specified `offset`. `value` must be a
* valid unsigned 8-bit integer. Behavior is undefined when `value` is anything
* other than an unsigned 8-bit integer.
*
* This function is also available under the `writeUint8` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeUInt8(0x3, 0);
* buf.writeUInt8(0x4, 1);
* buf.writeUInt8(0x23, 2);
* buf.writeUInt8(0x42, 3);
*
* console.log(buf);
* // Prints: <Buffer 03 04 23 42>
|
* ```
* @since v0.5.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`.
* @return `offset` plus the number of bytes written.
*/
writeUInt8(value: number, offset?: number): number;
/**
* @alias Buffer.writeUInt8
* @since v14.9.0, v12.19.0
*/
writeUint8(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is
* anything other than an unsigned 16-bit integer.
*
* This function is also available under the `writeUint16LE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeUInt16LE(0xdead, 0);
* buf.writeUInt16LE(0xbeef, 2);
*
* console.log(buf);
* // Prints: <Buffer ad de ef be>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.
* @return `offset` plus the number of bytes written.
*/
writeUInt16LE(value: number, offset?: number): number;
/**
* @alias Buffer.writeUInt16LE
* @since v14.9.0, v12.19.0
*/
writeUint16LE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an
* unsigned 16-bit integer.
*
* This function is also available under the `writeUint16BE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeUInt16BE(0xdead, 0);
* buf.writeUInt16BE(0xbeef, 2);
*
* console.log(buf);
* // Prints: <Buffer de ad be ef>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.
* @return `offset` plus the number of bytes written.
*/
writeUInt16BE(value: number, offset?: number): number;
/**
* @alias Buffer.writeUInt16BE
* @since v14.9.0, v12.19.0
*/
writeUint16BE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is
* anything other than an unsigned 32-bit integer.
*
* This function is also available under the `writeUint32LE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeUInt32LE(0xfeedface, 0);
*
* console.log(buf);
* // Prints: <Buffer ce fa ed fe>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @r |
eturn `offset` plus the number of bytes written.
*/
writeUInt32LE(value: number, offset?: number): number;
/**
* @alias Buffer.writeUInt32LE
* @since v14.9.0, v12.19.0
*/
writeUint32LE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an
* unsigned 32-bit integer.
*
* This function is also available under the `writeUint32BE` alias.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeUInt32BE(0xfeedface, 0);
*
* console.log(buf);
* // Prints: <Buffer fe ed fa ce>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @return `offset` plus the number of bytes written.
*/
writeUInt32BE(value: number, offset?: number): number;
/**
* @alias Buffer.writeUInt32BE
* @since v14.9.0, v12.19.0
*/
writeUint32BE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset`. `value` must be a valid
* signed 8-bit integer. Behavior is undefined when `value` is anything other than
* a signed 8-bit integer.
*
* `value` is interpreted and written as a two's complement signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(2);
*
* buf.writeInt8(2, 0);
* buf.writeInt8(-2, 1);
*
* console.log(buf);
* // Prints: <Buffer 02 fe>
* ```
* @since v0.5.0
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`.
* @return `offset` plus the number of bytes written.
*/
writeInt8(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is
* anything other than a signed 16-bit integer.
*
* The `value` is interpreted and written as a two's complement signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(2);
*
* buf.writeInt16LE(0x0304, 0);
*
* console.log(buf);
* // Prints: <Buffer 04 03>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.
* @return `offset` plus the number of bytes written.
*/
writeInt16LE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 16-bit integer. Behavior is undefined when `value` is
* anything other than a signed 16-bit integer.
*
* The `value` is interpreted and written as a two's complement signed integer.
*
|
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(2);
*
* buf.writeInt16BE(0x0102, 0);
*
* console.log(buf);
* // Prints: <Buffer 01 02>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`.
* @return `offset` plus the number of bytes written.
*/
writeInt16BE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is
* anything other than a signed 32-bit integer.
*
* The `value` is interpreted and written as a two's complement signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeInt32LE(0x05060708, 0);
*
* console.log(buf);
* // Prints: <Buffer 08 07 06 05>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @return `offset` plus the number of bytes written.
*/
writeInt32LE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a valid signed 32-bit integer. Behavior is undefined when `value` is
* anything other than a signed 32-bit integer.
*
* The `value` is interpreted and written as a two's complement signed integer.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeInt32BE(0x01020304, 0);
*
* console.log(buf);
* // Prints: <Buffer 01 02 03 04>
* ```
* @since v0.5.5
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @return `offset` plus the number of bytes written.
*/
writeInt32BE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is
* undefined when `value` is anything other than a JavaScript number.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4);
*
* buf.writeFloatLE(0xcafebabe, 0);
*
* console.log(buf);
* // Prints: <Buffer bb fe 4a 4f>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @return `offset` plus the number of bytes written.
*/
writeFloatLE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is
* undefined when `value` is anything other than a JavaScript number.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(4 |
);
*
* buf.writeFloatBE(0xcafebabe, 0);
*
* console.log(buf);
* // Prints: <Buffer 4f 4a fe bb>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`.
* @return `offset` plus the number of bytes written.
*/
writeFloatBE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as little-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything
* other than a JavaScript number.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeDoubleLE(123.456, 0);
*
* console.log(buf);
* // Prints: <Buffer 77 be 9f 1a 2f dd 5e 40>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeDoubleLE(value: number, offset?: number): number;
/**
* Writes `value` to `buf` at the specified `offset` as big-endian. The `value`must be a JavaScript number. Behavior is undefined when `value` is anything
* other than a JavaScript number.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(8);
*
* buf.writeDoubleBE(123.456, 0);
*
* console.log(buf);
* // Prints: <Buffer 40 5e dd 2f 1a 9f be 77>
* ```
* @since v0.11.15
* @param value Number to be written to `buf`.
* @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`.
* @return `offset` plus the number of bytes written.
*/
writeDoubleBE(value: number, offset?: number): number;
/**
* Fills `buf` with the specified `value`. If the `offset` and `end` are not given,
* the entire `buf` will be filled:
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Fill a `Buffer` with the ASCII character 'h'.
*
* const b = Buffer.allocUnsafe(50).fill('h');
*
* console.log(b.toString());
* // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
*
* // Fill a buffer with empty string
* const c = Buffer.allocUnsafe(5).fill('');
*
* console.log(c.fill(''));
* // Prints: <Buffer 00 00 00 00 00>
* ```
*
* `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or
* integer. If the resulting integer is greater than `255` (decimal), `buf` will be
* filled with `value & 255`.
*
* If the final write of a `fill()` operation falls on a multi-byte character,
* then only the bytes of that character that fit into `buf` are written:
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Fill a `Buffer` with character that takes up two bytes in UTF-8.
*
* console.log(Buffer.allocUnsafe(5).fill('\u0222'));
* // Prints: <Buffer c8 a2 c8 a2 c8>
* ```
|
*
* If `value` contains invalid characters, it is truncated; if no valid
* fill data remains, an exception is thrown:
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.allocUnsafe(5);
*
* console.log(buf.fill('a'));
* // Prints: <Buffer 61 61 61 61 61>
* console.log(buf.fill('aazz', 'hex'));
* // Prints: <Buffer aa aa aa aa aa>
* console.log(buf.fill('zz', 'hex'));
* // Throws an exception.
* ```
* @since v0.5.0
* @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`.
* @param [offset=0] Number of bytes to skip before starting to fill `buf`.
* @param [end=buf.length] Where to stop filling `buf` (not inclusive).
* @param [encoding='utf8'] The encoding for `value` if `value` is a string.
* @return A reference to `buf`.
*/
fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this;
/**
* If `value` is:
*
* * a string, `value` is interpreted according to the character encoding in`encoding`.
* * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety.
* To compare a partial `Buffer`, use `buf.subarray`.
* * a number, `value` will be interpreted as an unsigned 8-bit integer
* value between `0` and `255`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('this is a buffer');
*
* console.log(buf.indexOf('this'));
* // Prints: 0
* console.log(buf.indexOf('is'));
* // Prints: 2
* console.log(buf.indexOf(Buffer.from('a buffer')));
* // Prints: 8
* console.log(buf.indexOf(97));
* // Prints: 8 (97 is the decimal ASCII value for 'a')
* console.log(buf.indexOf(Buffer.from('a buffer example')));
* // Prints: -1
* console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
* // Prints: 8
*
* const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
*
* console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
* // Prints: 4
* console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
* // Prints: 6
* ```
*
* If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value,
* an integer between 0 and 255.
*
* If `byteOffset` is not a number, it will be coerced to a number. If the result
* of coercion is `NaN` or `0`, then the entire buffer will be searched. This
* behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf).
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const b = Buffer.from('abcdef');
*
* // Passing a value that's a number, but not a valid byte.
* // Prints: 2, equivalent to searching for 99 or 'c'.
* console.log(b.indexOf(99.9));
* console.log(b.indexOf(256 + 99));
*
* // Passing a byteOffset that coerces to NaN or 0.
* // Prints: 1, searching the whole buffer.
* console.log(b. |
indexOf('b', undefined));
* console.log(b.indexOf('b', {}));
* console.log(b.indexOf('b', null));
* console.log(b.indexOf('b', []));
* ```
*
* If `value` is an empty string or empty `Buffer` and `byteOffset` is less
* than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned.
* @since v1.5.0
* @param value What to search for.
* @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`.
* @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`.
* @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.
*/
indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number;
/**
* Identical to `buf.indexOf()`, except the last occurrence of `value` is found
* rather than the first occurrence.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('this buffer is a buffer');
*
* console.log(buf.lastIndexOf('this'));
* // Prints: 0
* console.log(buf.lastIndexOf('buffer'));
* // Prints: 17
* console.log(buf.lastIndexOf(Buffer.from('buffer')));
* // Prints: 17
* console.log(buf.lastIndexOf(97));
* // Prints: 15 (97 is the decimal ASCII value for 'a')
* console.log(buf.lastIndexOf(Buffer.from('yolo')));
* // Prints: -1
* console.log(buf.lastIndexOf('buffer', 5));
* // Prints: 5
* console.log(buf.lastIndexOf('buffer', 4));
* // Prints: -1
*
* const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');
*
* console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
* // Prints: 6
* console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
* // Prints: 4
* ```
*
* If `value` is not a string, number, or `Buffer`, this method will throw a`TypeError`. If `value` is a number, it will be coerced to a valid byte value,
* an integer between 0 and 255.
*
* If `byteOffset` is not a number, it will be coerced to a number. Any arguments
* that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer.
* This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf).
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const b = Buffer.from('abcdef');
*
* // Passing a value that's a number, but not a valid byte.
* // Prints: 2, equivalent to searching for 99 or 'c'.
* console.log(b.lastIndexOf(99.9));
* console.log(b.lastIndexOf(256 + 99));
*
* // Passing a byteOffset that coerces to NaN.
* // Prints: 1, searching the whole buffer.
* console.log(b.lastIndexOf('b', undefined));
* console.log(b.lastIndexOf('b', {}));
*
* // Passing a byteOffset that coerces to 0.
* // Prints: -1, equivalent to passing 0.
* console.log(b.lastIndexOf('b', null));
* console.log(b.lastIndexOf('b', []));
* ```
*
* If `value` is an |
empty string or empty `Buffer`, `byteOffset` will be returned.
* @since v6.0.0
* @param value What to search for.
* @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`.
* @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`.
* @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.
*/
lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number;
/**
* Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents
* of `buf`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Log the entire contents of a `Buffer`.
*
* const buf = Buffer.from('buffer');
*
* for (const pair of buf.entries()) {
* console.log(pair);
* }
* // Prints:
* // [0, 98]
* // [1, 117]
* // [2, 102]
* // [3, 102]
* // [4, 101]
* // [5, 114]
* ```
* @since v1.1.0
*/
entries(): IterableIterator<[number, number]>;
/**
* Equivalent to `buf.indexOf() !== -1`.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('this is a buffer');
*
* console.log(buf.includes('this'));
* // Prints: true
* console.log(buf.includes('is'));
* // Prints: true
* console.log(buf.includes(Buffer.from('a buffer')));
* // Prints: true
* console.log(buf.includes(97));
* // Prints: true (97 is the decimal ASCII value for 'a')
* console.log(buf.includes(Buffer.from('a buffer example')));
* // Prints: false
* console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
* // Prints: true
* console.log(buf.includes('this', 4));
* // Prints: false
* ```
* @since v5.3.0
* @param value What to search for.
* @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`.
* @param [encoding='utf8'] If `value` is a string, this is its encoding.
* @return `true` if `value` was found in `buf`, `false` otherwise.
*/
includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean;
/**
* Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices).
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* for (const key of buf.keys()) {
* console.log(key);
* }
* // Prints:
* // 0
* // 1
* // 2
* // 3
* // 4
* // 5
* ```
* @since v1.1.0
*/
keys(): IterableIterator<number>;
/**
* Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is
* called autom |
atically when a `Buffer` is used in a `for..of` statement.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* const buf = Buffer.from('buffer');
*
* for (const value of buf.values()) {
* console.log(value);
* }
* // Prints:
* // 98
* // 117
* // 102
* // 102
* // 101
* // 114
*
* for (const value of buf) {
* console.log(value);
* }
* // Prints:
* // 98
* // 117
* // 102
* // 102
* // 101
* // 114
* ```
* @since v1.1.0
*/
values(): IterableIterator<number>;
}
var Buffer: BufferConstructor;
/**
* Decodes a string of Base64-encoded data into bytes, and encodes those bytes
* into a string using Latin-1 (ISO-8859-1).
*
* The `data` may be any JavaScript-value that can be coerced into a string.
*
* **This function is only provided for compatibility with legacy web platform APIs**
* **and should never be used in new code, because they use strings to represent**
* **binary data and predate the introduction of typed arrays in JavaScript.**
* **For code running using Node.js APIs, converting between base64-encoded strings**
* **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.**
* @since v15.13.0, v14.17.0
* @legacy Use `Buffer.from(data, 'base64')` instead.
* @param data The Base64-encoded input string.
*/
function atob(data: string): string;
/**
* Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes
* into a string using Base64.
*
* The `data` may be any JavaScript-value that can be coerced into a string.
*
* **This function is only provided for compatibility with legacy web platform APIs**
* **and should never be used in new code, because they use strings to represent**
* **binary data and predate the introduction of typed arrays in JavaScript.**
* **For code running using Node.js APIs, converting between base64-encoded strings**
* **and binary data should be performed using `Buffer.from(str, 'base64')` and`buf.toString('base64')`.**
* @since v15.13.0, v14.17.0
* @legacy Use `buf.toString('base64')` instead.
* @param data An ASCII (Latin1) string.
*/
function btoa(data: string): string;
interface Blob extends __Blob {}
/**
* `Blob` class is a global reference for `require('node:buffer').Blob`
* https://nodejs.org/api/buffer.html#class-blob
* @since v18.0.0
*/
var Blob: typeof globalThis extends {
onmessage: any;
Blob: infer T;
} ? T
: typeof NodeBlob;
}
}
declare module "node:buffer" {
export * from "buffer";
}
|
/**
* The `node:worker_threads` module enables the use of threads that execute
* JavaScript in parallel. To access it:
*
* ```js
* const worker = require('node:worker_threads');
* ```
*
* Workers (threads) are useful for performing CPU-intensive JavaScript operations.
* They do not help much with I/O-intensive work. The Node.js built-in
* asynchronous I/O operations are more efficient than Workers can be.
*
* Unlike `child_process` or `cluster`, `worker_threads` can share memory. They do
* so by transferring `ArrayBuffer` instances or sharing `SharedArrayBuffer`instances.
*
* ```js
* const {
* Worker, isMainThread, parentPort, workerData,
* } = require('node:worker_threads');
*
* if (isMainThread) {
* module.exports = function parseJSAsync(script) {
* return new Promise((resolve, reject) => {
* const worker = new Worker(__filename, {
* workerData: script,
* });
* worker.on('message', resolve);
* worker.on('error', reject);
* worker.on('exit', (code) => {
* if (code !== 0)
* reject(new Error(`Worker stopped with exit code ${code}`));
* });
* });
* };
* } else {
* const { parse } = require('some-js-parsing-library');
* const script = workerData;
* parentPort.postMessage(parse(script));
* }
* ```
*
* The above example spawns a Worker thread for each `parseJSAsync()` call. In
* practice, use a pool of Workers for these kinds of tasks. Otherwise, the
* overhead of creating Workers would likely exceed their benefit.
*
* When implementing a worker pool, use the `AsyncResource` API to inform
* diagnostic tools (e.g. to provide asynchronous stack traces) about the
* correlation between tasks and their outcomes. See `"Using AsyncResource for a Worker thread pool"` in the `async_hooks` documentation for an example implementation.
*
* Worker threads inherit non-process-specific options by default. Refer to `Worker constructor options` to know how to customize worker thread options,
* specifically `argv` and `execArgv` options.
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/worker_threads.js)
*/
declare module "worker_threads" {
import { Blob } from "node:buffer";
import { Context } from "node:vm";
import { EventEmitter } from "node:events";
import { EventLoopUtilityFunction } from "node:perf_hooks";
import { FileHandle } from "node:fs/promises";
import { Readable, Writable } from "node:stream";
import { URL } from "node:url";
import { X509Certificate } from "node:crypto";
const isMainThread: boolean;
const parentPort: null | MessagePort;
const resourceLimits: ResourceLimits;
const SHARE_ENV: unique symbol;
const threadId: number;
const workerData: any;
/**
* Instances of the `worker.MessageChannel` class represent an asynchronous,
* two-way communications channel.
* The `MessageChannel` has no methods of its own. `new MessageChannel()`yields an object with `port1` and `port2` properties, which refer to linked `MessagePort` instances.
*
* ```js
* const { MessageChannel } = require('node:worker_threads');
*
* const { port1, port2 } = new MessageChannel();
* port1.on('message', (message) => console.log('received', message));
* port2.postMessage({ foo: 'bar' });
* // Prints: received { foo: 'bar' } from the `port1.on('message')` listener
* ```
* @since v10.5.0
*/
class MessageChannel {
readonly port1: MessagePort;
readonly port2: MessagePort;
}
interface WorkerPerformance {
eventLoopUtilization: EventLoopUtilityFunction;
}
type TransferListItem = ArrayBuffer | MessagePort | FileHandle | X509Certificate | Blob;
/**
* Instances of the `worker.MessagePort` class represent one end of an
* asynchronous, two-way communications channel. It can be used to transfer
* structured data, memory regions and other `Mess |
agePort`s between different `Worker` s.
*
* This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s.
* @since v10.5.0
*/
class MessagePort extends EventEmitter {
/**
* Disables further sending of messages on either side of the connection.
* This method can be called when no further communication will happen over this`MessagePort`.
*
* The `'close' event` is emitted on both `MessagePort` instances that
* are part of the channel.
* @since v10.5.0
*/
close(): void;
/**
* Sends a JavaScript value to the receiving side of this channel.`value` is transferred in a way which is compatible with
* the [HTML structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
*
* In particular, the significant differences to `JSON` are:
*
* * `value` may contain circular references.
* * `value` may contain instances of builtin JS types such as `RegExp`s,`BigInt`s, `Map`s, `Set`s, etc.
* * `value` may contain typed arrays, both using `ArrayBuffer`s
* and `SharedArrayBuffer`s.
* * `value` may contain [`WebAssembly.Module`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module) instances.
* * `value` may not contain native (C++-backed) objects other than:
*
* ```js
* const { MessageChannel } = require('node:worker_threads');
* const { port1, port2 } = new MessageChannel();
*
* port1.on('message', (message) => console.log(message));
*
* const circularData = {};
* circularData.foo = circularData;
* // Prints: { foo: [Circular] }
* port2.postMessage(circularData);
* ```
*
* `transferList` may be a list of [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), `MessagePort`, and `FileHandle` objects.
* After transferring, they are not usable on the sending side of the channel
* anymore (even if they are not contained in `value`). Unlike with `child processes`, transferring handles such as network sockets is currently
* not supported.
*
* If `value` contains [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances, those are accessible
* from either thread. They cannot be listed in `transferList`.
*
* `value` may still contain `ArrayBuffer` instances that are not in`transferList`; in that case, the underlying memory is copied rather than moved.
*
* ```js
* const { MessageChannel } = require('node:worker_threads');
* const { port1, port2 } = new MessageChannel();
*
* port1.on('message', (message) => console.log(message));
*
* const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
* // This posts a copy of `uint8Array`:
* port2.postMessage(uint8Array);
* // This does not copy data, but renders `uint8Array` unusable:
* port2.postMessage(uint8Array, [ uint8Array.buffer ]);
*
* // The memory for the `sharedUint8Array` is accessible from both the
* // original and the copy received by `.on('message')`:
* const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
* port2.postMessage(sharedUint8Array);
*
* // This transfers a freshly created message port to the receiver.
* // This can be used, for example, to create communication channels between
* // multiple `Worker` threads that are children of the same parent thread.
* const otherChannel = new MessageChannel();
|
* port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
* ```
*
* The message object is cloned immediately, and can be modified after
* posting without having side effects.
*
* For more information on the serialization and deserialization mechanisms
* behind this API, see the `serialization API of the node:v8 module`.
* @since v10.5.0
*/
postMessage(value: any, transferList?: readonly TransferListItem[]): void;
/**
* 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
* behavior). If the port is `ref()`ed, calling `ref()` again has no effect.
*
* If listeners are attached or removed using `.on('message')`, the port
* is `ref()`ed and `unref()`ed automatically depending on whether
* listeners for the event exist.
* @since v10.5.0
*/
ref(): void;
/**
* Calling `unref()` on a port allows the thread to exit if this is the only
* active handle in the event system. If the port is already `unref()`ed calling`unref()` again has no effect.
*
* If listeners are attached or removed using `.on('message')`, the port is`ref()`ed and `unref()`ed automatically depending on whether
* listeners for the event exist.
* @since v10.5.0
*/
unref(): void;
/**
* Starts receiving messages on this `MessagePort`. When using this port
* as an event emitter, this is called automatically once `'message'`listeners are attached.
*
* This method exists for parity with the Web `MessagePort` API. In Node.js,
* it is only useful for ignoring messages when no event listener is present.
* Node.js also diverges in its handling of `.onmessage`. Setting it
* automatically calls `.start()`, but unsetting it lets messages queue up
* until a new handler is set or the port is discarded.
* @since v10.5.0
*/
start(): void;
addListener(event: "close", listener: () => void): this;
addListener(event: "message", listener: (value: any) => void): this;
addListener(event: "messageerror", listener: (error: Error) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "close"): boolean;
emit(event: "message", value: any): boolean;
emit(event: "messageerror", error: Error): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "close", listener: () => void): this;
on(event: "message", listener: (value: any) => void): this;
on(event: "messageerror", listener: (error: Error) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "message", listener: (value: any) => void): this;
once(event: "messageerror", listener: (error: Error) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "message", listener: (value: any) => void): this;
prependListener(event: "messageerror", listener: (error: Error) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "message", listener: (value: any) => void): this;
prependOnceListener(event: "messageerror", listener: (error: Error) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: "close", listen |
er: () => void): this;
removeListener(event: "message", listener: (value: any) => void): this;
removeListener(event: "messageerror", listener: (error: Error) => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
off(event: "close", listener: () => void): this;
off(event: "message", listener: (value: any) => void): this;
off(event: "messageerror", listener: (error: Error) => void): this;
off(event: string | symbol, listener: (...args: any[]) => void): this;
}
interface WorkerOptions {
/**
* 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 will be available on the global `process.argv` as if they
* were passed as CLI options to the script.
*/
argv?: any[] | undefined;
env?: NodeJS.Dict<string> | typeof SHARE_ENV | undefined;
eval?: boolean | undefined;
workerData?: any;
stdin?: boolean | undefined;
stdout?: boolean | undefined;
stderr?: boolean | undefined;
execArgv?: string[] | undefined;
resourceLimits?: ResourceLimits | undefined;
/**
* Additional data to send in the first worker message.
*/
transferList?: TransferListItem[] | undefined;
/**
* @default true
*/
trackUnmanagedFds?: boolean | undefined;
/**
* An optional `name` to be appended to the worker title
* for debuggin/identification purposes, making the final title as
* `[worker ${id}] ${name}`.
*/
name?: string | undefined;
}
interface ResourceLimits {
/**
* The maximum size of a heap space for recently created objects.
*/
maxYoungGenerationSizeMb?: number | undefined;
/**
* The maximum size of the main heap in MB.
*/
maxOldGenerationSizeMb?: number | undefined;
/**
* The size of a pre-allocated memory range used for generated code.
*/
codeRangeSizeMb?: number | undefined;
/**
* The default maximum stack size for the thread. Small values may lead to unusable Worker instances.
* @default 4
*/
stackSizeMb?: number | undefined;
}
/**
* The `Worker` class represents an independent JavaScript execution thread.
* Most Node.js APIs are available inside of it.
*
* Notable differences inside a Worker environment are:
*
* * The `process.stdin`, `process.stdout`, and `process.stderr` streams may be redirected by the parent thread.
* * The `require('node:worker_threads').isMainThread` property is set to `false`.
* * The `require('node:worker_threads').parentPort` message port is available.
* * `process.exit()` does not stop the whole program, just the single thread,
* and `process.abort()` is not available.
* * `process.chdir()` and `process` methods that set group or user ids
* are not available.
* * `process.env` is a copy of the parent thread's environment variables,
* unless otherwise specified. Changes to one copy are not visible in other
* threads, and are not visible to native add-ons (unless `worker.SHARE_ENV` is passed as the `env` option to the `Worker` constructor). On Windows, unlike the main thread, a copy of the
* environment variables operates in a case-sensitive manner.
* * `process.title` cannot be modified.
* * Signals are not delivered through `process.on('...')`.
* * Execution may stop at any point as a result of `worker.terminate()` being invoked.
* * IPC channels from parent processes are not accessible.
* * The `trace_events` module is not supported.
* * Native add-ons can only be loaded from multiple threads if they fulfill `certain conditions |
`.
*
* Creating `Worker` instances inside of other `Worker`s is possible.
*
* Like [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and the `node:cluster module`, two-way communication
* can be achieved through inter-thread message passing. Internally, a `Worker` has
* a built-in pair of `MessagePort` s that are already associated with each
* other when the `Worker` is created. While the `MessagePort` object on the parent
* side is not directly exposed, its functionalities are exposed through `worker.postMessage()` and the `worker.on('message')` event
* on the `Worker` object for the parent thread.
*
* To create custom messaging channels (which is encouraged over using the default
* global channel because it facilitates separation of concerns), users can create
* a `MessageChannel` object on either thread and pass one of the`MessagePort`s on that `MessageChannel` to the other thread through a
* pre-existing channel, such as the global one.
*
* See `port.postMessage()` for more information on how messages are passed,
* and what kind of JavaScript values can be successfully transported through
* the thread barrier.
*
* ```js
* const assert = require('node:assert');
* const {
* Worker, MessageChannel, MessagePort, isMainThread, parentPort,
* } = require('node:worker_threads');
* if (isMainThread) {
* const worker = new Worker(__filename);
* const subChannel = new MessageChannel();
* worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);
* subChannel.port2.on('message', (value) => {
* console.log('received:', value);
* });
* } else {
* parentPort.once('message', (value) => {
* assert(value.hereIsYourPort instanceof MessagePort);
* value.hereIsYourPort.postMessage('the worker is sending this');
* value.hereIsYourPort.close();
* });
* }
* ```
* @since v10.5.0
*/
class Worker extends EventEmitter {
/**
* If `stdin: true` was passed to the `Worker` constructor, this is a
* writable stream. The data written to this stream will be made available in
* the worker thread as `process.stdin`.
* @since v10.5.0
*/
readonly stdin: Writable | null;
/**
* This is a readable stream which contains data written to `process.stdout` inside the worker thread. If `stdout: true` was not passed to the `Worker` constructor, then data is piped to the
* parent thread's `process.stdout` stream.
* @since v10.5.0
*/
readonly stdout: Readable;
/**
* This is a readable stream which contains data written to `process.stderr` inside the worker thread. If `stderr: true` was not passed to the `Worker` constructor, then data is piped to the
* parent thread's `process.stderr` stream.
* @since v10.5.0
*/
readonly stderr: Readable;
/**
* An integer identifier for the referenced thread. Inside the worker thread,
* it is available as `require('node:worker_threads').threadId`.
* This value is unique for each `Worker` instance inside a single process.
* @since v10.5.0
*/
readonly threadId: number;
/**
* Provides the set of JS engine resource constraints for this Worker thread.
* If the `resourceLimits` option was passed to the `Worker` constructor,
* this matches its values.
*
* If the worker has stopped, the return value is an empty object.
* @since v13.2.0, v12.16.0
*/
readonly resourceLimits?: ResourceLimits | undefined;
/**
* An object that can be used to query performance information from a worker
* instance. Similar to `perf_hooks.performance`.
* |
@since v15.1.0, v14.17.0, v12.22.0
*/
readonly performance: WorkerPerformance;
/**
* @param filename The path to the Worker’s main script or module.
* Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with ./ or ../,
* or a WHATWG URL object using file: protocol. If options.eval is true, this is a string containing JavaScript code rather than a path.
*/
constructor(filename: string | URL, options?: WorkerOptions);
/**
* Send a message to the worker that is received via `require('node:worker_threads').parentPort.on('message')`.
* See `port.postMessage()` for more details.
* @since v10.5.0
*/
postMessage(value: any, transferList?: readonly TransferListItem[]): void;
/**
* 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
* behavior). If the worker is `ref()`ed, calling `ref()` again has
* no effect.
* @since v10.5.0
*/
ref(): void;
/**
* Calling `unref()` on a worker allows the thread to exit if this is the only
* active handle in the event system. If the worker is already `unref()`ed calling`unref()` again has no effect.
* @since v10.5.0
*/
unref(): void;
/**
* Stop all JavaScript execution in the worker thread as soon as possible.
* Returns a Promise for the exit code that is fulfilled when the `'exit' event` is emitted.
* @since v10.5.0
*/
terminate(): Promise<number>;
/**
* Returns a readable stream for a V8 snapshot of the current state of the Worker.
* See `v8.getHeapSnapshot()` for more details.
*
* If the Worker thread is no longer running, which may occur before the `'exit' event` is emitted, the returned `Promise` is rejected
* immediately with an `ERR_WORKER_NOT_RUNNING` error.
* @since v13.9.0, v12.17.0
* @return A promise for a Readable Stream containing a V8 heap snapshot
*/
getHeapSnapshot(): Promise<Readable>;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "exit", listener: (exitCode: number) => void): this;
addListener(event: "message", listener: (value: any) => void): this;
addListener(event: "messageerror", listener: (error: Error) => void): this;
addListener(event: "online", listener: () => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "error", err: Error): boolean;
emit(event: "exit", exitCode: number): boolean;
emit(event: "message", value: any): boolean;
emit(event: "messageerror", error: Error): boolean;
emit(event: "online"): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "error", listener: (err: Error) => void): this;
on(event: "exit", listener: (exitCode: number) => void): this;
on(event: "message", listener: (value: any) => void): this;
on(event: "messageerror", listener: (error: Error) => void): this;
on(event: "online", listener: () => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "exit", listener: (exitCode: number) => void): this;
once(event: "message", listener: (value: any) => void): this;
once(event: "messageerror", listener: (error: Error) => void): this;
once(event: "online", listener: () => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "error", |
listener: (err: Error) => void): this;
prependListener(event: "exit", listener: (exitCode: number) => void): this;
prependListener(event: "message", listener: (value: any) => void): this;
prependListener(event: "messageerror", listener: (error: Error) => void): this;
prependListener(event: "online", listener: () => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "exit", listener: (exitCode: number) => void): this;
prependOnceListener(event: "message", listener: (value: any) => void): this;
prependOnceListener(event: "messageerror", listener: (error: Error) => void): this;
prependOnceListener(event: "online", listener: () => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: "error", listener: (err: Error) => void): this;
removeListener(event: "exit", listener: (exitCode: number) => void): this;
removeListener(event: "message", listener: (value: any) => void): this;
removeListener(event: "messageerror", listener: (error: Error) => void): this;
removeListener(event: "online", listener: () => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
off(event: "error", listener: (err: Error) => void): this;
off(event: "exit", listener: (exitCode: number) => void): this;
off(event: "message", listener: (value: any) => void): this;
off(event: "messageerror", listener: (error: Error) => void): this;
off(event: "online", listener: () => void): this;
off(event: string | symbol, listener: (...args: any[]) => void): this;
}
interface BroadcastChannel extends NodeJS.RefCounted {}
/**
* Instances of `BroadcastChannel` allow asynchronous one-to-many communication
* with all other `BroadcastChannel` instances bound to the same channel name.
*
* ```js
* 'use strict';
*
* const {
* isMainThread,
* BroadcastChannel,
* Worker,
* } = require('node:worker_threads');
*
* const bc = new BroadcastChannel('hello');
*
* if (isMainThread) {
* let c = 0;
* bc.onmessage = (event) => {
* console.log(event.data);
* if (++c === 10) bc.close();
* };
* for (let n = 0; n < 10; n++)
* new Worker(__filename);
* } else {
* bc.postMessage('hello from every worker');
* bc.close();
* }
* ```
* @since v15.4.0
*/
class BroadcastChannel {
readonly name: string;
/**
* Invoked with a single \`MessageEvent\` argument when a message is received.
* @since v15.4.0
*/
onmessage: (message: unknown) => void;
/**
* Invoked with a received message cannot be deserialized.
* @since v15.4.0
*/
onmessageerror: (message: unknown) => void;
constructor(name: string);
/**
* Closes the `BroadcastChannel` connection.
* @since v15.4.0
*/
close(): void;
/**
* @since v15.4.0
* @param message Any cloneable JavaScript value.
*/
postMessage(message: unknown): void;
}
/**
* Mark an object as not transferable. If `object` occurs in the transfer list of
* a `port.postMessage()` call, it is ignored.
*
* In particular, this makes sense for objects that can be cloned, rather than
* transferred, and which are used by other objects on the sending side.
* For example, Node.js marks the `ArrayBuffer`s it uses for its `Buffer pool` with this.
*
* This operation cannot be undone.
*
* ```js
* const { MessageChannel, markAsUntransferable } = |
require('node:worker_threads');
*
* const pooledBuffer = new ArrayBuffer(8);
* const typedArray1 = new Uint8Array(pooledBuffer);
* const typedArray2 = new Float64Array(pooledBuffer);
*
* markAsUntransferable(pooledBuffer);
*
* const { port1 } = new MessageChannel();
* port1.postMessage(typedArray1, [ typedArray1.buffer ]);
*
* // The following line prints the contents of typedArray1 -- it still owns
* // its memory and has been cloned, not transferred. Without
* // `markAsUntransferable()`, this would print an empty Uint8Array.
* // typedArray2 is intact as well.
* console.log(typedArray1);
* console.log(typedArray2);
* ```
*
* There is no equivalent to this API in browsers.
* @since v14.5.0, v12.19.0
*/
function markAsUntransferable(object: object): void;
/**
* Transfer a `MessagePort` to a different `vm` Context. The original `port`object is rendered unusable, and the returned `MessagePort` instance
* takes its place.
*
* The returned `MessagePort` is an object in the target context and
* inherits from its global `Object` class. Objects passed to the [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) listener are also created in the
* target context
* and inherit from its global `Object` class.
*
* However, the created `MessagePort` no longer inherits from [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget), and only
* [`port.onmessage()`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage) can be used to receive
* events using it.
* @since v11.13.0
* @param port The message port to transfer.
* @param contextifiedSandbox A `contextified` object as returned by the `vm.createContext()` method.
*/
function moveMessagePortToContext(port: MessagePort, contextifiedSandbox: Context): MessagePort;
/**
* Receive a single message from a given `MessagePort`. If no message is available,`undefined` is returned, otherwise an object with a single `message` property
* that contains the message payload, corresponding to the oldest message in the`MessagePort`'s queue.
*
* ```js
* const { MessageChannel, receiveMessageOnPort } = require('node:worker_threads');
* const { port1, port2 } = new MessageChannel();
* port1.postMessage({ hello: 'world' });
*
* console.log(receiveMessageOnPort(port2));
* // Prints: { message: { hello: 'world' } }
* console.log(receiveMessageOnPort(port2));
* // Prints: undefined
* ```
*
* When this function is used, no `'message'` event is emitted and the`onmessage` listener is not invoked.
* @since v12.3.0
*/
function receiveMessageOnPort(port: MessagePort):
| {
message: any;
}
| undefined;
type Serializable = string | object | number | boolean | bigint;
/**
* Within a worker thread, `worker.getEnvironmentData()` returns a clone
* of data passed to the spawning thread's `worker.setEnvironmentData()`.
* Every new `Worker` receives its own copy of the environment data
* automatically.
*
* ```js
* const {
* Worker,
* isMainThread,
* setEnvironmentData,
* getEnvironmentData,
* } = require('node:worker_threads');
*
* if (isMainThread) {
* setEnvironmentData('Hello', 'World!');
* const worker = new Worker(__filename);
* } else {
* console.log(getEnvironmentData('Hello')); // Prints 'World!'.
* }
* ```
* @since v15.12.0, v14.18.0
* @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.
*/
function getEnvironmentData(key: Serializable): Serializable;
/**
* The `worker.setEnvironmentData()` API sets the content of`worker.getEnvironmentData()` in |
the current thread and all new `Worker`instances spawned from the current context.
* @since v15.12.0, v14.18.0
* @param key Any arbitrary, cloneable JavaScript value that can be used as a {Map} key.
* @param value Any arbitrary, cloneable JavaScript value that will be cloned and passed automatically to all new `Worker` instances. If `value` is passed as `undefined`, any previously set value
* for the `key` will be deleted.
*/
function setEnvironmentData(key: Serializable, value: Serializable): void;
import {
BroadcastChannel as _BroadcastChannel,
MessageChannel as _MessageChannel,
MessagePort as _MessagePort,
} from "worker_threads";
global {
/**
* `BroadcastChannel` class is a global reference for `require('worker_threads').BroadcastChannel`
* https://nodejs.org/api/globals.html#broadcastchannel
* @since v18.0.0
*/
var BroadcastChannel: typeof globalThis extends {
onmessage: any;
BroadcastChannel: infer T;
} ? T
: typeof _BroadcastChannel;
/**
* `MessageChannel` class is a global reference for `require('worker_threads').MessageChannel`
* https://nodejs.org/api/globals.html#messagechannel
* @since v15.0.0
*/
var MessageChannel: typeof globalThis extends {
onmessage: any;
MessageChannel: infer T;
} ? T
: typeof _MessageChannel;
/**
* `MessagePort` class is a global reference for `require('worker_threads').MessagePort`
* https://nodejs.org/api/globals.html#messageport
* @since v15.0.0
*/
var MessagePort: typeof globalThis extends {
onmessage: any;
MessagePort: infer T;
} ? T
: typeof _MessagePort;
}
}
declare module "node:worker_threads" {
export * from "worker_threads";
}
|
/**
* We strongly discourage the use of the `async_hooks` API.
* Other APIs that can cover most of its use cases include:
*
* * `AsyncLocalStorage` tracks async context
* * `process.getActiveResourcesInfo()` tracks active resources
*
* The `node:async_hooks` module provides an API to track asynchronous resources.
* It can be accessed using:
*
* ```js
* import async_hooks from 'node:async_hooks';
* ```
* @experimental
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/async_hooks.js)
*/
declare module "async_hooks" {
/**
* ```js
* import { executionAsyncId } from 'node:async_hooks';
* import fs from 'node:fs';
*
* console.log(executionAsyncId()); // 1 - bootstrap
* const path = '.';
* fs.open(path, 'r', (err, fd) => {
* console.log(executionAsyncId()); // 6 - open()
* });
* ```
*
* The ID returned from `executionAsyncId()` is related to execution timing, not
* causality (which is covered by `triggerAsyncId()`):
*
* ```js
* const server = net.createServer((conn) => {
* // Returns the ID of the server, not of the new connection, because the
* // callback runs in the execution scope of the server's MakeCallback().
* async_hooks.executionAsyncId();
*
* }).listen(port, () => {
* // Returns the ID of a TickObject (process.nextTick()) because all
* // callbacks passed to .listen() are wrapped in a nextTick().
* async_hooks.executionAsyncId();
* });
* ```
*
* Promise contexts may not get precise `executionAsyncIds` by default.
* See the section on `promise execution tracking`.
* @since v8.1.0
* @return The `asyncId` of the current execution context. Useful to track when something calls.
*/
function executionAsyncId(): number;
/**
* Resource objects returned by `executionAsyncResource()` are most often internal
* Node.js handle objects with undocumented APIs. Using any functions or properties
* on the object is likely to crash your application and should be avoided.
*
* Using `executionAsyncResource()` in the top-level execution context will
* return an empty object as there is no handle or request object to use,
* but having an object representing the top-level can be helpful.
*
* ```js
* import { open } from 'node:fs';
* import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
*
* console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
* open(new URL(import.meta.url), 'r', (err, fd) => {
* console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
* });
* ```
*
* This can be used to implement continuation local storage without the
* use of a tracking `Map` to store the metadata:
*
* ```js
* import { createServer } from 'node:http';
* import {
* executionAsyncId,
* executionAsyncResource,
* createHook,
* } from 'async_hooks';
* const sym = Symbol('state'); // Private symbol to avoid pollution
*
* createHook({
* init(asyncId, type, triggerAsyncId, resource) {
* const cr = executionAsyncResource();
* if (cr) {
* resource[sym] = cr[sym];
* }
* },
* }).enable();
*
* const server = createServer((req, res) => {
* executionAsyncResource()[sym] = { state: req.url };
* setTimeout(function() {
* res.end(JSON.stringify(executionAsyncResource()[sym]));
* }, 100);
* }).listen(3000);
* ```
* @since v13.9.0, v12.17.0
* @return The resource representing the current execution. Useful to store data within the resource.
*/
function executionAsyncResource(): object;
/**
* ```js
* const server = net.createServer((conn) => {
* // The resource that caused (or triggered) this callback to be calle |
d
* // was that of the new connection. Thus the return value of triggerAsyncId()
* // is the asyncId of "conn".
* async_hooks.triggerAsyncId();
*
* }).listen(port, () => {
* // Even though all callbacks passed to .listen() are wrapped in a nextTick()
* // the callback itself exists because the call to the server's .listen()
* // was made. So the return value would be the ID of the server.
* async_hooks.triggerAsyncId();
* });
* ```
*
* Promise contexts may not get valid `triggerAsyncId`s by default. See
* the section on `promise execution tracking`.
* @return The ID of the resource responsible for calling the callback that is currently being executed.
*/
function triggerAsyncId(): number;
interface HookCallbacks {
/**
* Called when a class is constructed that has the possibility to emit an asynchronous event.
* @param asyncId a unique ID for the async resource
* @param type the type of the async resource
* @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created
* @param resource reference to the resource representing the async operation, needs to be released during destroy
*/
init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void;
/**
* When an asynchronous operation is initiated or completes a callback is called to notify the user.
* The before callback is called just before said callback is executed.
* @param asyncId the unique identifier assigned to the resource about to execute the callback.
*/
before?(asyncId: number): void;
/**
* Called immediately after the callback specified in before is completed.
* @param asyncId the unique identifier assigned to the resource which has executed the callback.
*/
after?(asyncId: number): void;
/**
* Called when a promise has resolve() called. This may not be in the same execution id
* as the promise itself.
* @param asyncId the unique id for the promise that was resolve()d.
*/
promiseResolve?(asyncId: number): void;
/**
* Called after the resource corresponding to asyncId is destroyed
* @param asyncId a unique ID for the async resource
*/
destroy?(asyncId: number): void;
}
interface AsyncHook {
/**
* Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop.
*/
enable(): this;
/**
* Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.
*/
disable(): this;
}
/**
* Registers functions to be called for different lifetime events of each async
* operation.
*
* The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the
* respective asynchronous event during a resource's lifetime.
*
* All callbacks are optional. For example, if only resource cleanup needs to
* be tracked, then only the `destroy` callback needs to be passed. The
* specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section.
*
* ```js
* import { createHook } from 'node:async_hooks';
*
* const asyncHook = createHook({
* init(asyncId, type, triggerAsyncId, resource) { },
* destroy(asyncId) { },
* });
* ```
*
* The callbacks will be inherited via the prototype chain:
*
* ```js
* class MyAsyncCallbacks {
* init(asyncId, type, triggerAsyncId, resource) { }
* destroy(asyncId) {}
* }
*
* class MyAddedCallbacks extends MyAsyncCallbacks {
|
* before(asyncId) { }
* after(asyncId) { }
* }
*
* const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
* ```
*
* Because promises are asynchronous resources whose lifecycle is tracked
* via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises.
* @since v8.1.0
* @param callbacks The `Hook Callbacks` to register
* @return Instance used for disabling and enabling hooks
*/
function createHook(callbacks: HookCallbacks): AsyncHook;
interface AsyncResourceOptions {
/**
* The ID of the execution context that created this async event.
* @default executionAsyncId()
*/
triggerAsyncId?: number | undefined;
/**
* Disables automatic `emitDestroy` when the object is garbage collected.
* This usually does not need to be set (even if `emitDestroy` is called
* manually), unless the resource's `asyncId` is retrieved and the
* sensitive API's `emitDestroy` is called with it.
* @default false
*/
requireManualDestroy?: boolean | undefined;
}
/**
* The class `AsyncResource` is designed to be extended by the embedder's async
* resources. Using this, users can easily trigger the lifetime events of their
* own resources.
*
* The `init` hook will trigger when an `AsyncResource` is instantiated.
*
* The following is an overview of the `AsyncResource` API.
*
* ```js
* import { AsyncResource, executionAsyncId } from 'node:async_hooks';
*
* // AsyncResource() is meant to be extended. Instantiating a
* // new AsyncResource() also triggers init. If triggerAsyncId is omitted then
* // async_hook.executionAsyncId() is used.
* const asyncResource = new AsyncResource(
* type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },
* );
*
* // Run a function in the execution context of the resource. This will
* // * establish the context of the resource
* // * trigger the AsyncHooks before callbacks
* // * call the provided function `fn` with the supplied arguments
* // * trigger the AsyncHooks after callbacks
* // * restore the original execution context
* asyncResource.runInAsyncScope(fn, thisArg, ...args);
*
* // Call AsyncHooks destroy callbacks.
* asyncResource.emitDestroy();
*
* // Return the unique ID assigned to the AsyncResource instance.
* asyncResource.asyncId();
*
* // Return the trigger ID for the AsyncResource instance.
* asyncResource.triggerAsyncId();
* ```
*/
class AsyncResource {
/**
* AsyncResource() is meant to be extended. Instantiating a
* new AsyncResource() also triggers init. If triggerAsyncId is omitted then
* async_hook.executionAsyncId() is used.
* @param type The type of async event.
* @param triggerAsyncId The ID of the execution context that created
* this async event (default: `executionAsyncId()`), or an
* AsyncResourceOptions object (since v9.3.0)
*/
constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions);
/**
* Binds the given function to the current execution context.
* @since v14.8.0, v12.19.0
* @param fn The function to bind to the current execution context.
* @param type An optional name to associate with the underlying `AsyncResource`.
*/
static bind<Func extends (this: ThisArg, ...args: any[]) => any, ThisArg>(
fn: Func,
type?: string,
thisArg?: ThisArg,
): Func;
/**
* Binds the given function to execute to this `AsyncResource`'s scope.
* @since v14.8.0, v12.19.0
* @param fn The function to bi |
nd to the current `AsyncResource`.
*/
bind<Func extends (...args: any[]) => any>(fn: Func): Func;
/**
* Call the provided function with the provided arguments in the execution context
* of the async resource. This will establish the context, trigger the AsyncHooks
* before callbacks, call the function, trigger the AsyncHooks after callbacks, and
* then restore the original execution context.
* @since v9.6.0
* @param fn The function to call in the execution context of this async resource.
* @param thisArg The receiver to be used for the function call.
* @param args Optional arguments to pass to the function.
*/
runInAsyncScope<This, Result>(
fn: (this: This, ...args: any[]) => Result,
thisArg?: This,
...args: any[]
): Result;
/**
* Call all `destroy` hooks. This should only ever be called once. An error will
* be thrown if it is called more than once. This **must** be manually called. If
* the resource is left to be collected by the GC then the `destroy` hooks will
* never be called.
* @return A reference to `asyncResource`.
*/
emitDestroy(): this;
/**
* @return The unique `asyncId` assigned to the resource.
*/
asyncId(): number;
/**
* @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor.
*/
triggerAsyncId(): number;
}
/**
* This class creates stores that stay coherent through asynchronous operations.
*
* While you can create your own implementation on top of the `node:async_hooks`module, `AsyncLocalStorage` should be preferred as it is a performant and memory
* safe implementation that involves significant optimizations that are non-obvious
* to implement.
*
* The following example uses `AsyncLocalStorage` to build a simple logger
* that assigns IDs to incoming HTTP requests and includes them in messages
* logged within each request.
*
* ```js
* import http from 'node:http';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const asyncLocalStorage = new AsyncLocalStorage();
*
* function logWithId(msg) {
* const id = asyncLocalStorage.getStore();
* console.log(`${id !== undefined ? id : '-'}:`, msg);
* }
*
* let idSeq = 0;
* http.createServer((req, res) => {
* asyncLocalStorage.run(idSeq++, () => {
* logWithId('start');
* // Imagine any chain of async operations here
* setImmediate(() => {
* logWithId('finish');
* res.end();
* });
* });
* }).listen(8080);
*
* http.get('http://localhost:8080');
* http.get('http://localhost:8080');
* // Prints:
* // 0: start
* // 1: start
* // 0: finish
* // 1: finish
* ```
*
* Each instance of `AsyncLocalStorage` maintains an independent storage context.
* Multiple instances can safely exist simultaneously without risk of interfering
* with each other's data.
* @since v13.10.0, v12.17.0
*/
class AsyncLocalStorage<T> {
/**
* Binds the given function to the current execution context.
* @since v19.8.0
* @experimental
* @param fn The function to bind to the current execution context.
* @return A new function that calls `fn` within the captured execution context.
*/
static bind<Func extends (...args: any[]) => any>(fn: Func): Func;
/**
* Captures the current execution context and returns a function that accepts a
* function as an argument. Whenever the returned function is called, it
* calls the function passed to it within the captured context.
*
* ```js
|
* const asyncLocalStorage = new AsyncLocalStorage();
* const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot());
* const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
* console.log(result); // returns 123
* ```
*
* AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
* async context tracking purposes, for example:
*
* ```js
* class Foo {
* #runInAsyncScope = AsyncLocalStorage.snapshot();
*
* get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
* }
*
* const foo = asyncLocalStorage.run(123, () => new Foo());
* console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
* ```
* @since v19.8.0
* @experimental
* @return A new function with the signature `(fn: (...args) : R, ...args) : R`.
*/
static snapshot(): <R, TArgs extends any[]>(fn: (...args: TArgs) => R, ...args: TArgs) => R;
/**
* Disables the instance of `AsyncLocalStorage`. All subsequent calls
* to `asyncLocalStorage.getStore()` will return `undefined` until`asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again.
*
* When calling `asyncLocalStorage.disable()`, all current contexts linked to the
* instance will be exited.
*
* Calling `asyncLocalStorage.disable()` is required before the`asyncLocalStorage` can be garbage collected. This does not apply to stores
* provided by the `asyncLocalStorage`, as those objects are garbage collected
* along with the corresponding async resources.
*
* Use this method when the `asyncLocalStorage` is not in use anymore
* in the current process.
* @since v13.10.0, v12.17.0
* @experimental
*/
disable(): void;
/**
* Returns the current store.
* If called outside of an asynchronous context initialized by
* calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it
* returns `undefined`.
* @since v13.10.0, v12.17.0
*/
getStore(): T | undefined;
/**
* Runs a function synchronously within a context and returns its
* return value. The store is not accessible outside of the callback function.
* The store is accessible to any asynchronous operations created within the
* callback.
*
* The optional `args` are passed to the callback function.
*
* If the callback function throws an error, the error is thrown by `run()` too.
* The stacktrace is not impacted by this call and the context is exited.
*
* Example:
*
* ```js
* const store = { id: 2 };
* try {
* asyncLocalStorage.run(store, () => {
* asyncLocalStorage.getStore(); // Returns the store object
* setTimeout(() => {
* asyncLocalStorage.getStore(); // Returns the store object
* }, 200);
* throw new Error();
* });
* } catch (e) {
* asyncLocalStorage.getStore(); // Returns undefined
* // The error will be caught here
* }
* ```
* @since v13.10.0, v12.17.0
*/
run<R>(store: T, callback: () => R): R;
run<R, TArgs extends any[]>(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R;
/**
* Runs a function synchronously outside of a context and returns its
* return value. The store is not accessible within the callback function or
* the asynchronous operations created within the callback. Any `getStore()`call done within the callback function will always retur |
n `undefined`.
*
* The optional `args` are passed to the callback function.
*
* If the callback function throws an error, the error is thrown by `exit()` too.
* The stacktrace is not impacted by this call and the context is re-entered.
*
* Example:
*
* ```js
* // Within a call to run
* try {
* asyncLocalStorage.getStore(); // Returns the store object or value
* asyncLocalStorage.exit(() => {
* asyncLocalStorage.getStore(); // Returns undefined
* throw new Error();
* });
* } catch (e) {
* asyncLocalStorage.getStore(); // Returns the same object or value
* // The error will be caught here
* }
* ```
* @since v13.10.0, v12.17.0
* @experimental
*/
exit<R, TArgs extends any[]>(callback: (...args: TArgs) => R, ...args: TArgs): R;
/**
* Transitions into the context for the remainder of the current
* synchronous execution and then persists the store through any following
* asynchronous calls.
*
* Example:
*
* ```js
* const store = { id: 1 };
* // Replaces previous store with the given store object
* asyncLocalStorage.enterWith(store);
* asyncLocalStorage.getStore(); // Returns the store object
* someAsyncOperation(() => {
* asyncLocalStorage.getStore(); // Returns the same object
* });
* ```
*
* This transition will continue for the _entire_ synchronous execution.
* This means that if, for example, the context is entered within an event
* handler subsequent event handlers will also run within that context unless
* specifically bound to another context with an `AsyncResource`. That is why`run()` should be preferred over `enterWith()` unless there are strong reasons
* to use the latter method.
*
* ```js
* const store = { id: 1 };
*
* emitter.on('my-event', () => {
* asyncLocalStorage.enterWith(store);
* });
* emitter.on('my-event', () => {
* asyncLocalStorage.getStore(); // Returns the same object
* });
*
* asyncLocalStorage.getStore(); // Returns undefined
* emitter.emit('my-event');
* asyncLocalStorage.getStore(); // Returns the same object
* ```
* @since v13.11.0, v12.17.0
* @experimental
*/
enterWith(store: T): void;
}
}
declare module "node:async_hooks" {
export * from "async_hooks";
}
|
/**
* The `node:dns` module enables name resolution. For example, use it to look up IP
* addresses of host names.
*
* Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the
* DNS protocol for lookups. {@link lookup} uses the operating system
* facilities to perform name resolution. It may not need to perform any network
* communication. To perform name resolution the way other applications on the same
* system do, use {@link lookup}.
*
* ```js
* const dns = require('node:dns');
*
* dns.lookup('example.org', (err, address, family) => {
* console.log('address: %j family: IPv%s', address, family);
* });
* // address: "93.184.216.34" family: IPv4
* ```
*
* All other functions in the `node:dns` module connect to an actual DNS server to
* perform name resolution. They will always use the network to perform DNS
* queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform
* DNS queries, bypassing other name-resolution facilities.
*
* ```js
* const dns = require('node:dns');
*
* dns.resolve4('archive.org', (err, addresses) => {
* if (err) throw err;
*
* console.log(`addresses: ${JSON.stringify(addresses)}`);
*
* addresses.forEach((a) => {
* dns.reverse(a, (err, hostnames) => {
* if (err) {
* throw err;
* }
* console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
* });
* });
* });
* ```
*
* See the `Implementation considerations section` for more information.
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/dns.js)
*/
declare module "dns" {
import * as dnsPromises from "node:dns/promises";
// Supported getaddrinfo flags.
export const ADDRCONFIG: number;
export const V4MAPPED: number;
/**
* If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as
* well as IPv4 mapped IPv6 addresses.
*/
export const ALL: number;
export interface LookupOptions {
family?: number | undefined;
hints?: number | undefined;
all?: boolean | undefined;
/**
* @default true
*/
verbatim?: boolean | undefined;
}
export interface LookupOneOptions extends LookupOptions {
all?: false | undefined;
}
export interface LookupAllOptions extends LookupOptions {
all: true;
}
export interface LookupAddress {
address: string;
family: number;
}
/**
* Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
* AAAA (IPv6) record. All `option` properties are optional. If `options` is an
* integer, then it must be `4` or `6` – if `options` is `0` or not provided, then
* IPv4 and IPv6 addresses are both returned if found.
*
* With the `all` option set to `true`, the arguments for `callback` change to`(err, addresses)`, with `addresses` being an array of objects with the
* properties `address` and `family`.
*
* On error, `err` is an `Error` object, where `err.code` is the error code.
* Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
* the host name does not exist but also when the lookup fails in other ways
* such as no available file descriptors.
*
* `dns.lookup()` does not necessarily have anything to do with the DNS protocol.
* The implementation uses an operating system facility that can associate names
* with addresses and vice versa. This implementation can have subtle but
* important consequences on the behavior of any Node.js program. Please take some
* time to consult the `Implementation considerations section` before using`dns.lookup()`.
*
* Example usage:
*
* ```js
* const dns = require('node:dns');
* const options = {
* family: 6,
* hints: dns.ADDRCONFIG |
| dns.V4MAPPED,
* };
* dns.lookup('example.com', options, (err, address, family) =>
* console.log('address: %j family: IPv%s', address, family));
* // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
*
* // When options.all is true, the result will be an Array.
* options.all = true;
* dns.lookup('example.com', options, (err, addresses) =>
* console.log('addresses: %j', addresses));
* // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
* ```
*
* If this method is invoked as its `util.promisify()` ed version, and `all`is not set to `true`, it returns a `Promise` for an `Object` with `address` and`family` properties.
* @since v0.1.90
*/
export function lookup(
hostname: string,
family: number,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
): void;
export function lookup(
hostname: string,
options: LookupOneOptions,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
): void;
export function lookup(
hostname: string,
options: LookupAllOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void,
): void;
export function lookup(
hostname: string,
options: LookupOptions,
callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void,
): void;
export function lookup(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
): void;
export namespace lookup {
function __promisify__(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<LookupAddress>;
function __promisify__(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
}
/**
* Resolves the given `address` and `port` into a host name and service using
* the operating system's underlying `getnameinfo` implementation.
*
* If `address` is not a valid IP address, a `TypeError` will be thrown.
* The `port` will be coerced to a number. If it is not a legal port, a `TypeError`will be thrown.
*
* On an error, `err` is an `Error` object, where `err.code` is the error code.
*
* ```js
* const dns = require('node:dns');
* dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
* console.log(hostname, service);
* // Prints: localhost ssh
* });
* ```
*
* If this method is invoked as its `util.promisify()` ed version, it returns a`Promise` for an `Object` with `hostname` and `service` properties.
* @since v0.11.14
*/
export function lookupService(
address: string,
port: number,
callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void,
): void;
export namespace lookupService {
function __promisify__(
address: string,
port: number,
): Promise<{
hostname: string;
service: string;
}>;
}
export interface ResolveOptions {
ttl: boolean;
}
export interface ResolveWithTtlOptions extends ResolveOptions {
ttl: true;
}
export interface RecordWithTtl {
address: string;
ttl: number;
}
/** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */
export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord;
export interface AnyARecord extends RecordWithTtl {
type: "A";
}
export interface AnyAaaaRecord extends RecordWithTtl {
type: "AAAA";
}
export interface CaaRecord {
critical: number;
issue?: string | undefined;
iss |
uewild?: string | undefined;
iodef?: string | undefined;
contactemail?: string | undefined;
contactphone?: string | undefined;
}
export interface MxRecord {
priority: number;
exchange: string;
}
export interface AnyMxRecord extends MxRecord {
type: "MX";
}
export interface NaptrRecord {
flags: string;
service: string;
regexp: string;
replacement: string;
order: number;
preference: number;
}
export interface AnyNaptrRecord extends NaptrRecord {
type: "NAPTR";
}
export interface SoaRecord {
nsname: string;
hostmaster: string;
serial: number;
refresh: number;
retry: number;
expire: number;
minttl: number;
}
export interface AnySoaRecord extends SoaRecord {
type: "SOA";
}
export interface SrvRecord {
priority: number;
weight: number;
port: number;
name: string;
}
export interface AnySrvRecord extends SrvRecord {
type: "SRV";
}
export interface AnyTxtRecord {
type: "TXT";
entries: string[];
}
export interface AnyNsRecord {
type: "NS";
value: string;
}
export interface AnyPtrRecord {
type: "PTR";
value: string;
}
export interface AnyCnameRecord {
type: "CNAME";
value: string;
}
export type AnyRecord =
| AnyARecord
| AnyAaaaRecord
| AnyCnameRecord
| AnyMxRecord
| AnyNaptrRecord
| AnyNsRecord
| AnyPtrRecord
| AnySoaRecord
| AnySrvRecord
| AnyTxtRecord;
/**
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
* of the resource records. The `callback` function has arguments`(err, records)`. When successful, `records` will be an array of resource
* records. The type and structure of individual results varies based on `rrtype`:
*
* <omitted>
*
* On error, `err` is an `Error` object, where `err.code` is one of the `DNS error codes`.
* @since v0.1.27
* @param hostname Host name to resolve.
* @param [rrtype='A'] Resource record type.
*/
export function resolve(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "A",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "AAAA",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "ANY",
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "CNAME",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "MX",
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "NAPTR",
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "NS",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "PTR",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "SOA",
callback: (err: NodeJS.ErrnoException | null, addresse |
s: SoaRecord) => void,
): void;
export function resolve(
hostname: string,
rrtype: "SRV",
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "TXT",
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void,
): void;
export function resolve(
hostname: string,
rrtype: string,
callback: (
err: NodeJS.ErrnoException | null,
addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[],
) => void,
): void;
export namespace resolve {
function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function __promisify__(
hostname: string,
rrtype: string,
): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>;
}
/**
* Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the`hostname`. The `addresses` argument passed to the `callback` function
* will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
* @since v0.1.16
* @param hostname Host name to resolve.
*/
export function resolve4(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve4(
hostname: string,
options: ResolveWithTtlOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void,
): void;
export function resolve4(
hostname: string,
options: ResolveOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void,
): void;
export namespace resolve4 {
function __promisify__(hostname: string): Promise<string[]>;
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
}
/**
* Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the`hostname`. The `addresses` argument passed to the `callback` function
* will contain an array of IPv6 addresses.
* @since v0.1.16
* @param hostname Host name to resolve.
*/
export function resolve6(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve6(
hostname: string,
options: ResolveWithTtlOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void,
): void;
export function resolve6(
hostname: string,
options: ResolveOptions,
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void,
): void;
export namespace resolve6 {
function __promisify__(hostname: string): Promise<string[]>;
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
}
/**
* Uses the DNS protocol to resolve |
`CNAME` records for the `hostname`. The`addresses` argument passed to the `callback` function
* will contain an array of canonical name records available for the `hostname`(e.g. `['bar.example.com']`).
* @since v0.3.2
*/
export function resolveCname(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export namespace resolveCname {
function __promisify__(hostname: string): Promise<string[]>;
}
/**
* Uses the DNS protocol to resolve `CAA` records for the `hostname`. The`addresses` argument passed to the `callback` function
* will contain an array of certification authority authorization records
* available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`).
* @since v15.0.0, v14.17.0
*/
export function resolveCaa(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void,
): void;
export namespace resolveCaa {
function __promisify__(hostname: string): Promise<CaaRecord[]>;
}
/**
* Uses the DNS protocol to resolve mail exchange records (`MX` records) for the`hostname`. The `addresses` argument passed to the `callback` function will
* contain an array of objects containing both a `priority` and `exchange`property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
* @since v0.1.27
*/
export function resolveMx(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void,
): void;
export namespace resolveMx {
function __promisify__(hostname: string): Promise<MxRecord[]>;
}
/**
* Uses the DNS protocol to resolve regular expression-based records (`NAPTR`records) for the `hostname`. The `addresses` argument passed to the `callback`function will contain an array of
* objects with the following properties:
*
* * `flags`
* * `service`
* * `regexp`
* * `replacement`
* * `order`
* * `preference`
*
* ```js
* {
* flags: 's',
* service: 'SIP+D2U',
* regexp: '',
* replacement: '_sip._udp.example.com',
* order: 30,
* preference: 100
* }
* ```
* @since v0.9.12
*/
export function resolveNaptr(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
): void;
export namespace resolveNaptr {
function __promisify__(hostname: string): Promise<NaptrRecord[]>;
}
/**
* Uses the DNS protocol to resolve name server records (`NS` records) for the`hostname`. The `addresses` argument passed to the `callback` function will
* contain an array of name server records available for `hostname`(e.g. `['ns1.example.com', 'ns2.example.com']`).
* @since v0.1.90
*/
export function resolveNs(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export namespace resolveNs {
function __promisify__(hostname: string): Promise<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.
* @since v6.0.0
*/
export function resolvePtr(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export namespace resolvePtr {
function __promisify__(hostname: string): Promise<string[]>;
}
/**
* Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
* the `hostname`. The `address` argument passed to the `callback` function will
* be an object with the following properties:
* |
* * `nsname`
* * `hostmaster`
* * `serial`
* * `refresh`
* * `retry`
* * `expire`
* * `minttl`
*
* ```js
* {
* nsname: 'ns.example.com',
* hostmaster: 'root.example.com',
* serial: 2013101809,
* refresh: 10000,
* retry: 2400,
* expire: 604800,
* minttl: 3600
* }
* ```
* @since v0.11.10
*/
export function resolveSoa(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void,
): void;
export namespace resolveSoa {
function __promisify__(hostname: string): Promise<SoaRecord>;
}
/**
* Uses the DNS protocol to resolve service records (`SRV` records) for the`hostname`. The `addresses` argument passed to the `callback` function will
* be an array of objects with the following properties:
*
* * `priority`
* * `weight`
* * `port`
* * `name`
*
* ```js
* {
* priority: 10,
* weight: 5,
* port: 21223,
* name: 'service.example.com'
* }
* ```
* @since v0.1.27
*/
export function resolveSrv(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
): void;
export namespace resolveSrv {
function __promisify__(hostname: string): Promise<SrvRecord[]>;
}
/**
* Uses the DNS protocol to resolve text queries (`TXT` records) for the`hostname`. The `records` argument passed to the `callback` function is a
* two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
* one record. Depending on the use case, these could be either joined together or
* treated separately.
* @since v0.1.27
*/
export function resolveTxt(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void,
): void;
export namespace resolveTxt {
function __promisify__(hostname: string): Promise<string[][]>;
}
/**
* 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
* various types of records. Each object has a property `type` that indicates the
* type of the current record. And depending on the `type`, additional properties
* will be present on the object:
*
* <omitted>
*
* Here is an example of the `ret` object passed to the callback:
*
* ```js
* [ { type: 'A', address: '127.0.0.1', ttl: 299 },
* { type: 'CNAME', value: 'example.com' },
* { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
* { type: 'NS', value: 'ns1.example.com' },
* { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
* { type: 'SOA',
* nsname: 'ns1.example.com',
* hostmaster: 'admin.example.com',
* serial: 156696742,
* refresh: 900,
* retry: 900,
* expire: 1800,
* minttl: 60 } ]
* ```
*
* DNS server operators may choose not to respond to `ANY`queries. It may be better to call individual methods like {@link resolve4},{@link resolveMx}, and so on. For more details, see [RFC
* 8482](https://tools.ietf.org/html/rfc8482).
*/
export function resolveAny(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void,
): void;
export namespace resolveAny {
function __promisify__(hostname: string): Promise<AnyRecord[]>;
}
/**
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
* array of host names.
*
* On error, `err` is an `Error` object, where `err.code` is
* one of the `DNS error codes`.
* @since v0. |
1.16
*/
export function reverse(
ip: string,
callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void,
): void;
/**
* Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be:
*
* * `ipv4first`: for `verbatim` defaulting to `false`.
* * `verbatim`: for `verbatim` defaulting to `true`.
* @since v20.1.0
*/
export function getDefaultResultOrder(): "ipv4first" | "verbatim";
/**
* Sets the IP address and port of servers to be used when performing DNS
* resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
* addresses. If the port is the IANA default DNS port (53) it can be omitted.
*
* ```js
* dns.setServers([
* '4.4.4.4',
* '[2001:4860:4860::8888]',
* '4.4.4.4:1053',
* '[2001:4860:4860::8888]:1053',
* ]);
* ```
*
* An error will be thrown if an invalid address is provided.
*
* The `dns.setServers()` method must not be called while a DNS query is in
* progress.
*
* The {@link setServers} method affects only {@link resolve},`dns.resolve*()` and {@link reverse} (and specifically _not_ {@link 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
* subsequent servers provided. Fallback DNS servers will only be used if the
* earlier ones time out or result in some other error.
* @since v0.11.3
* @param servers array of `RFC 5952` formatted addresses
*/
export function setServers(servers: readonly string[]): void;
/**
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
* that are currently configured for DNS resolution. A string will include a port
* section if a custom port is used.
*
* ```js
* [
* '4.4.4.4',
* '2001:4860:4860::8888',
* '4.4.4.4:1053',
* '[2001:4860:4860::8888]:1053',
* ]
* ```
* @since v0.11.3
*/
export function getServers(): string[];
/**
* Set the default value of `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be:
*
* * `ipv4first`: sets default `verbatim` `false`.
* * `verbatim`: sets default `verbatim` `true`.
*
* The default is `verbatim` and {@link setDefaultResultOrder} have higher
* priority than `--dns-result-order`. When using `worker threads`,{@link setDefaultResultOrder} from the main thread won't affect the default
* dns orders in workers.
* @since v16.4.0, v14.18.0
* @param order must be `'ipv4first'` or `'verbatim'`.
*/
export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void;
// Error codes
export const NODATA: string;
export const FORMERR: string;
export const SERVFAIL: string;
export const NOTFOUND: string;
export const NOTIMP: string;
export const REFUSED: string;
export const BADQUERY: string;
export const BADNAME: string;
export const BADFAMILY: string;
export const BADRESP: string;
export const CONNREFUSED: string;
export const TIMEOUT: string;
export const EOF: string;
export const FILE: string;
export const NOMEM: string;
export const DESTRUCTION: string;
export const BADSTR: string;
export const BADFLAGS: string;
export const NONAME: string;
export const BADHINTS: string;
export const NOTINITIALIZED: string;
export const LOADIPHLPAPI: string;
export const ADDRGETNETWORKPARAMS: string;
export const CANCELLED: string;
export interface ResolverOptions {
timeout?: number | un |
defined;
/**
* @default 4
*/
tries?: number;
}
/**
* An independent resolver for DNS requests.
*
* Creating a new resolver uses the default server settings. Setting
* the servers used for a resolver using `resolver.setServers()` does not affect
* other resolvers:
*
* ```js
* const { Resolver } = require('node:dns');
* const resolver = new Resolver();
* resolver.setServers(['4.4.4.4']);
*
* // This request will use the server at 4.4.4.4, independent of global settings.
* resolver.resolve4('example.org', (err, addresses) => {
* // ...
* });
* ```
*
* The following methods from the `node:dns` module are available:
*
* * `resolver.getServers()`
* * `resolver.resolve()`
* * `resolver.resolve4()`
* * `resolver.resolve6()`
* * `resolver.resolveAny()`
* * `resolver.resolveCaa()`
* * `resolver.resolveCname()`
* * `resolver.resolveMx()`
* * `resolver.resolveNaptr()`
* * `resolver.resolveNs()`
* * `resolver.resolvePtr()`
* * `resolver.resolveSoa()`
* * `resolver.resolveSrv()`
* * `resolver.resolveTxt()`
* * `resolver.reverse()`
* * `resolver.setServers()`
* @since v8.3.0
*/
export class Resolver {
constructor(options?: ResolverOptions);
/**
* Cancel all outstanding DNS queries made by this resolver. The corresponding
* callbacks will be called with an error with code `ECANCELLED`.
* @since v8.3.0
*/
cancel(): void;
getServers: typeof getServers;
resolve: typeof resolve;
resolve4: typeof resolve4;
resolve6: typeof resolve6;
resolveAny: typeof resolveAny;
resolveCaa: typeof resolveCaa;
resolveCname: typeof resolveCname;
resolveMx: typeof resolveMx;
resolveNaptr: typeof resolveNaptr;
resolveNs: typeof resolveNs;
resolvePtr: typeof resolvePtr;
resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv;
resolveTxt: typeof resolveTxt;
reverse: typeof reverse;
/**
* The resolver instance will send its requests from the specified IP address.
* This allows programs to specify outbound interfaces when used on multi-homed
* systems.
*
* If a v4 or v6 address is not specified, it is set to the default and the
* operating system will choose a local address automatically.
*
* The resolver will use the v4 local address when making requests to IPv4 DNS
* 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.
* @since v15.1.0, v14.17.0
* @param [ipv4='0.0.0.0'] A string representation of an IPv4 address.
* @param [ipv6='::0'] A string representation of an IPv6 address.
*/
setLocalAddress(ipv4?: string, ipv6?: string): void;
setServers: typeof setServers;
}
export { dnsPromises as promises };
}
declare module "node:dns" {
export * from "dns";
}
|
/**
* The `node:vm` module enables compiling and running code within V8 Virtual
* Machine contexts.
*
* **The `node:vm` module is not a security**
* **mechanism. Do not use it to run untrusted code.**
*
* JavaScript code can be compiled and run immediately or
* compiled, saved, and run later.
*
* A common use case is to run the code in a different V8 Context. This means
* invoked code has a different global object than the invoking code.
*
* One can provide the context by `contextifying` an
* object. The invoked code treats any property in the context like a
* global variable. Any changes to global variables caused by the invoked
* code are reflected in the context object.
*
* ```js
* const vm = require('node:vm');
*
* const x = 1;
*
* const context = { x: 2 };
* vm.createContext(context); // Contextify the object.
*
* const code = 'x += 40; var y = 17;';
* // `x` and `y` are global variables in the context.
* // Initially, x has the value 2 because that is the value of context.x.
* vm.runInContext(code, context);
*
* console.log(context.x); // 42
* console.log(context.y); // 17
*
* console.log(x); // 1; y is not defined.
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/vm.js)
*/
declare module "vm" {
import { ImportAttributes } from "node:module";
interface Context extends NodeJS.Dict<any> {}
interface BaseOptions {
/**
* Specifies the filename used in stack traces produced by this script.
* Default: `''`.
*/
filename?: string | undefined;
/**
* Specifies the line number offset that is displayed in stack traces produced by this script.
* Default: `0`.
*/
lineOffset?: number | undefined;
/**
* Specifies the column number offset that is displayed in stack traces produced by this script.
* @default 0
*/
columnOffset?: number | undefined;
}
interface ScriptOptions extends BaseOptions {
/**
* V8's code cache data for the supplied source.
*/
cachedData?: Buffer | NodeJS.ArrayBufferView | undefined;
/** @deprecated in favor of `script.createCachedData()` */
produceCachedData?: boolean | undefined;
/**
* Called during evaluation of this module when `import()` is called.
* If this option is not specified, calls to `import()` will reject with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`.
*/
importModuleDynamically?:
| ((specifier: string, script: Script, importAttributes: ImportAttributes) => Module)
| undefined;
}
interface RunningScriptOptions extends BaseOptions {
/**
* When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace.
* Default: `true`.
*/
displayErrors?: boolean | undefined;
/**
* Specifies the number of milliseconds to execute code before terminating execution.
* If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer.
*/
timeout?: number | undefined;
/**
* If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received.
* Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that.
* If execution is terminated, an `Error` will be thrown.
* Default: `false`.
*/
breakOnSigint?: boolean | undefined;
}
interface RunningScriptInNewContextOptions extends RunningScriptOptions {
/**
* Human-readable name of the newly created context.
*/
contextName?: CreateContextOptions["name"];
/**
* Origin corresponding to the newly created context for display purposes. The origin should b |
e formatted like a URL,
* but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object.
* Most notably, this string should omit the trailing slash, as that denotes a path.
*/
contextOrigin?: CreateContextOptions["origin"];
contextCodeGeneration?: CreateContextOptions["codeGeneration"];
/**
* If set to `afterEvaluate`, microtasks will be run immediately after the script has run.
*/
microtaskMode?: CreateContextOptions["microtaskMode"];
}
interface RunningCodeOptions extends RunningScriptOptions {
cachedData?: ScriptOptions["cachedData"];
importModuleDynamically?: ScriptOptions["importModuleDynamically"];
}
interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions {
cachedData?: ScriptOptions["cachedData"];
importModuleDynamically?: ScriptOptions["importModuleDynamically"];
}
interface CompileFunctionOptions extends BaseOptions {
/**
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: Buffer | undefined;
/**
* Specifies whether to produce new cache data.
* Default: `false`,
*/
produceCachedData?: boolean | undefined;
/**
* The sandbox/context in which the said function should be compiled in.
*/
parsingContext?: Context | undefined;
/**
* An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling
*/
contextExtensions?: Object[] | undefined;
}
interface CreateContextOptions {
/**
* Human-readable name of the newly created context.
* @default 'VM Context i' Where i is an ascending numerical index of the created context.
*/
name?: string | undefined;
/**
* Corresponds to the newly created context for display purposes.
* The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary),
* like the value of the `url.origin` property of a URL object.
* Most notably, this string should omit the trailing slash, as that denotes a path.
* @default ''
*/
origin?: string | undefined;
codeGeneration?:
| {
/**
* If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc)
* will throw an EvalError.
* @default true
*/
strings?: boolean | undefined;
/**
* If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError.
* @default true
*/
wasm?: boolean | undefined;
}
| undefined;
/**
* If set to `afterEvaluate`, microtasks will be run immediately after the script has run.
*/
microtaskMode?: "afterEvaluate" | undefined;
}
type MeasureMemoryMode = "summary" | "detailed";
interface MeasureMemoryOptions {
/**
* @default 'summary'
*/
mode?: MeasureMemoryMode | undefined;
/**
* @default 'default'
*/
execution?: "default" | "eager" | undefined;
}
interface MemoryMeasurement {
total: {
jsMemoryEstimate: number;
jsMemoryRange: [number, number];
};
}
/**
* Instances of the `vm.Script` class contain precompiled scripts that can be
* executed in specific contexts.
* @since v0.3.1
*/
class Script {
constructor(code: string, options?: ScriptOptions | string);
/**
* Runs the compiled code contained by the `vm.Script` object within the given`contex |
tifiedObject` and returns the result. Running code does not have access
* to local scope.
*
* The following example compiles code that increments a global variable, sets
* the value of another global variable, then execute the code multiple times.
* The globals are contained in the `context` object.
*
* ```js
* const vm = require('node:vm');
*
* const context = {
* animal: 'cat',
* count: 2,
* };
*
* const script = new vm.Script('count += 1; name = "kitty";');
*
* vm.createContext(context);
* for (let i = 0; i < 10; ++i) {
* script.runInContext(context);
* }
*
* console.log(context);
* // Prints: { animal: 'cat', count: 12, name: 'kitty' }
* ```
*
* Using the `timeout` or `breakOnSigint` options will result in new event loops
* and corresponding threads being started, which have a non-zero performance
* overhead.
* @since v0.3.1
* @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method.
* @return the result of the very last statement executed in the script.
*/
runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any;
/**
* First contextifies the given `contextObject`, runs the compiled code contained
* by the `vm.Script` object within the created context, and returns the result.
* Running code does not have access to local scope.
*
* The following example compiles code that sets a global variable, then executes
* the code multiple times in different contexts. The globals are set on and
* contained within each individual `context`.
*
* ```js
* const vm = require('node:vm');
*
* const script = new vm.Script('globalVar = "set"');
*
* const contexts = [{}, {}, {}];
* contexts.forEach((context) => {
* script.runInNewContext(context);
* });
*
* console.log(contexts);
* // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
* ```
* @since v0.3.1
* @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created.
* @return the result of the very last statement executed in the script.
*/
runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any;
/**
* 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.
*
* The following example compiles code that increments a `global` variable then
* executes that code multiple times:
*
* ```js
* const vm = require('node:vm');
*
* global.globalVar = 0;
*
* const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
*
* for (let i = 0; i < 1000; ++i) {
* script.runInThisContext();
* }
*
* console.log(globalVar);
*
* // 1000
* ```
* @since v0.3.1
* @return the result of the very last statement executed in the script.
*/
runInThisContext(options?: RunningScriptOptions): any;
/**
* Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any
* time and any number of times.
*
* The code cache of the `Script` doesn't contain any JavaScript observable
* states. The code cache is safe to b |
e saved along side the script source and
* used to construct new `Script` instances multiple times.
*
* Functions in the `Script` source can be marked as lazily compiled and they are
* not compiled at construction of the `Script`. These functions are going to be
* compiled when they are invoked the first time. The code cache serializes the
* metadata that V8 currently knows about the `Script` that it can use to speed up
* future compilations.
*
* ```js
* const script = new vm.Script(`
* function add(a, b) {
* return a + b;
* }
*
* const x = add(1, 2);
* `);
*
* const cacheWithoutAdd = script.createCachedData();
* // In `cacheWithoutAdd` the function `add()` is marked for full compilation
* // upon invocation.
*
* script.runInThisContext();
*
* const cacheWithAdd = script.createCachedData();
* // `cacheWithAdd` contains fully compiled function `add()`.
* ```
* @since v10.6.0
*/
createCachedData(): Buffer;
/** @deprecated in favor of `script.createCachedData()` */
cachedDataProduced?: boolean | undefined;
/**
* When `cachedData` is supplied to create the `vm.Script`, this value will be set
* to either `true` or `false` depending on acceptance of the data by V8\.
* Otherwise the value is `undefined`.
* @since v5.7.0
*/
cachedDataRejected?: boolean | undefined;
cachedData?: Buffer | undefined;
/**
* When the script is compiled from a source that contains a source map magic
* comment, this property will be set to the URL of the source map.
*
* ```js
* import vm from 'node:vm';
*
* const script = new vm.Script(`
* function myFunc() {}
* //# sourceMappingURL=sourcemap.json
* `);
*
* console.log(script.sourceMapURL);
* // Prints: sourcemap.json
* ```
* @since v19.1.0, v18.13.0
*/
sourceMapURL?: string | undefined;
}
/**
* If given a `contextObject`, the `vm.createContext()` method will `prepare
* that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts,
* the `contextObject` will be the global object, retaining all of its existing
* properties but also having the built-in objects and functions any standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables
* will remain unchanged.
*
* ```js
* const vm = require('node:vm');
*
* global.globalVar = 3;
*
* const context = { globalVar: 1 };
* vm.createContext(context);
*
* vm.runInContext('globalVar *= 2;', context);
*
* console.log(context);
* // Prints: { globalVar: 2 }
*
* console.log(global.globalVar);
* // Prints: 3
* ```
*
* If `contextObject` is omitted (or passed explicitly as `undefined`), a new,
* empty `contextified` object will be returned.
*
* The `vm.createContext()` method is primarily useful for creating a single
* context that can be used to run multiple scripts. For instance, if emulating a
* web browser, the method can be used to create a single context representing a
* window's global object, then run all `<script>` tags together within that
* context.
*
* The provided `name` and `origin` of the context are made visible through the
* Inspector API.
* @since v0.3.1
* @return contextified object.
*/
function createContext(sandbox?: Context, options?: CreateContextOptions): Context;
/**
* Returns `true` if the given `object` object has been `contextified` us |
ing {@link createContext}.
* @since v0.11.7
*/
function isContext(sandbox: Context): boolean;
/**
* 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
* previously `contextified` using the {@link createContext} method.
*
* If `options` is a string, then it specifies the filename.
*
* The following example compiles and executes different scripts using a single `contextified` object:
*
* ```js
* const vm = require('node:vm');
*
* const contextObject = { globalVar: 1 };
* vm.createContext(contextObject);
*
* for (let i = 0; i < 10; ++i) {
* vm.runInContext('globalVar *= 2;', contextObject);
* }
* console.log(contextObject);
* // Prints: { globalVar: 1024 }
* ```
* @since v0.3.1
* @param code The JavaScript code to compile and run.
* @param contextifiedObject The `contextified` object that will be used as the `global` when the `code` is compiled and run.
* @return the result of the very last statement executed in the script.
*/
function runInContext(code: string, contextifiedObject: Context, options?: RunningCodeOptions | string): any;
/**
* The `vm.runInNewContext()` first contextifies the given `contextObject` (or
* creates a new `contextObject` if passed as `undefined`), compiles the `code`,
* runs it within the created context, then returns the result. Running code
* does not have access to the local scope.
*
* If `options` is a string, then it specifies the filename.
*
* The following example compiles and executes code that increments a global
* variable and sets a new one. These globals are contained in the `contextObject`.
*
* ```js
* const vm = require('node:vm');
*
* const contextObject = {
* animal: 'cat',
* count: 2,
* };
*
* vm.runInNewContext('count += 1; name = "kitty"', contextObject);
* console.log(contextObject);
* // Prints: { animal: 'cat', count: 3, name: 'kitty' }
* ```
* @since v0.3.1
* @param code The JavaScript code to compile and run.
* @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created.
* @return the result of the very last statement executed in the script.
*/
function runInNewContext(
code: string,
contextObject?: Context,
options?: RunningCodeInNewContextOptions | string,
): any;
/**
* `vm.runInThisContext()` compiles `code`, runs it within the context of the
* current `global` and returns the result. Running code does not have access to
* local scope, but does have access to the current `global` object.
*
* If `options` is a string, then it specifies the filename.
*
* The following example illustrates using both `vm.runInThisContext()` and
* the JavaScript [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) function to run the same code:
*
* ```js
* const vm = require('node:vm');
* let localVar = 'initial value';
*
* const vmResult = vm.runInThisContext('localVar = "vm";');
* console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);
* // Prints: vmResult: 'vm', localVar: 'initial value'
*
* const evalResult = eval('localVar = "eval";');
* console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);
* // Prints: evalResult: 'eval', localVar: 'eval'
* ```
*
* Because `vm.runInThisContext()` does not have access to the local scope,`localVar` is unchanged. In contrast,
* [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](https://es5.github.io/#x10.4.2), e.g.`(0,eval)('code')`.
*
* ## Example: Running an HTTP server within a VM
*
* When using either `script.runInThisContext()` or {@link runInThisContext}, the code is executed within the current V8 global
* context. The code passed to this VM context will have its own isolated scope.
*
* In order to run a simple web server using the `node:http` module the code passed
* to the context must either call `require('node:http')` on its own, or have a
* reference to the `node:http` module passed to it. For instance:
*
* ```js
* 'use strict';
* const vm = require('node:vm');
*
* const code = `
* ((require) => {
* const http = require('node:http');
*
* http.createServer((request, response) => {
* response.writeHead(200, { 'Content-Type': 'text/plain' });
* response.end('Hello World\\n');
* }).listen(8124);
*
* console.log('Server running at http://127.0.0.1:8124/');
* })`;
*
* vm.runInThisContext(code)(require);
* ```
*
* The `require()` in the above case shares the state with the context it is
* passed from. This may introduce risks when untrusted code is executed, e.g.
* altering objects in the context in unwanted ways.
* @since v0.3.1
* @param code The JavaScript code to compile and run.
* @return the result of the very last statement executed in the script.
*/
function runInThisContext(code: string, options?: RunningCodeOptions | string): any;
/**
* Compiles the given code into the provided context (if no context is
* supplied, the current context is used), and returns it wrapped inside a
* function with the given `params`.
* @since v10.10.0
* @param code The body of the function to compile.
* @param params An array of strings containing all parameters for the function.
*/
function compileFunction(
code: string,
params?: readonly string[],
options?: CompileFunctionOptions,
): Function & {
cachedData?: Script["cachedData"] | undefined;
cachedDataProduced?: Script["cachedDataProduced"] | undefined;
cachedDataRejected?: Script["cachedDataRejected"] | undefined;
};
/**
* Measure the memory known to V8 and used by all contexts known to the
* current V8 isolate, or the main context.
*
* The format of the object that the returned Promise may resolve with is
* specific to the V8 engine and may change from one version of V8 to the next.
*
* The returned result is different from the statistics returned by`v8.getHeapSpaceStatistics()` in that `vm.measureMemory()` measure the
* memory reachable by each V8 specific contexts in the current instance of
* the V8 engine, while the result of `v8.getHeapSpaceStatistics()` measure
* the memory occupied by each heap space in the current V8 instance.
*
* ```js
* const vm = require('node:vm');
* // Measure the memory used by the main context.
* vm.measureMemory({ mode: 'summary' })
* // This is the same as vm.measureMemory()
* .then((result) => {
* // The current format is:
* // {
* // total: {
* // jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]
* // }
* // }
* console.log(result);
* });
*
* const context = vm.createContext({ a: 1 });
* vm.measureMemory({ mode: 'detailed', execution: 'eager' })
* .then((result) => {
* // Reference the context here so that it won't be GC'ed
* // until the measurement is complete.
* console.log(context.a);
* // {
* // total: {
* // |
jsMemoryEstimate: 2574732,
* // jsMemoryRange: [ 2574732, 2904372 ]
* // },
* // current: {
* // jsMemoryEstimate: 2438996,
* // jsMemoryRange: [ 2438996, 2768636 ]
* // },
* // other: [
* // {
* // jsMemoryEstimate: 135736,
* // jsMemoryRange: [ 135736, 465376 ]
* // }
* // ]
* // }
* console.log(result);
* });
* ```
* @since v13.10.0
* @experimental
*/
function measureMemory(options?: MeasureMemoryOptions): Promise<MemoryMeasurement>;
interface ModuleEvaluateOptions {
timeout?: RunningScriptOptions["timeout"] | undefined;
breakOnSigint?: RunningScriptOptions["breakOnSigint"] | undefined;
}
type ModuleLinker = (
specifier: string,
referencingModule: Module,
extra: {
/** @deprecated Use `attributes` instead */
assert: ImportAttributes;
attributes: ImportAttributes;
},
) => Module | Promise<Module>;
type ModuleStatus = "unlinked" | "linking" | "linked" | "evaluating" | "evaluated" | "errored";
/**
* This feature is only available with the `--experimental-vm-modules` command
* flag enabled.
*
* The `vm.Module` class provides a low-level interface for using
* ECMAScript modules in VM contexts. It is the counterpart of the `vm.Script`class that closely mirrors [Module Record](https://262.ecma-international.org/14.0/#sec-abstract-module-records) s as
* defined in the ECMAScript
* specification.
*
* Unlike `vm.Script` however, every `vm.Module` object is bound to a context from
* its creation. Operations on `vm.Module` objects are intrinsically asynchronous,
* in contrast with the synchronous nature of `vm.Script` objects. The use of
* 'async' functions can help with manipulating `vm.Module` objects.
*
* Using a `vm.Module` object requires three distinct steps: creation/parsing,
* linking, and evaluation. These three steps are illustrated in the following
* example.
*
* This implementation lies at a lower level than the `ECMAScript Module
* loader`. There is also no way to interact with the Loader yet, though
* support is planned.
*
* ```js
* import vm from 'node:vm';
*
* const contextifiedObject = vm.createContext({
* secret: 42,
* print: console.log,
* });
*
* // Step 1
* //
* // Create a Module by constructing a new `vm.SourceTextModule` object. This
* // parses the provided source text, throwing a `SyntaxError` if anything goes
* // wrong. By default, a Module is created in the top context. But here, we
* // specify `contextifiedObject` as the context this Module belongs to.
* //
* // Here, we attempt to obtain the default export from the module "foo", and
* // put it into local binding "secret".
*
* const bar = new vm.SourceTextModule(`
* import s from 'foo';
* s;
* print(s);
* `, { context: contextifiedObject });
*
* // Step 2
* //
* // "Link" the imported dependencies of this Module to it.
* //
* // The provided linking callback (the "linker") accepts two arguments: the
* // parent module (`bar` in this case) and the string that is the specifier of
* // the imported module. The callback is expected to return a Module that
* // corresponds to the provided specifier, with certain requirements documented
* // in `module.link()`.
* //
* // If linking has not started for the returned Module, the same linker
* // callback will be called on the returned Module.
* //
* // Even top-level Modules without dependencies must be explicitly linked. The
* // callback provided would never be called, however.
* //
* // The |
link() method returns a Promise that will be resolved when all the
* // Promises returned by the linker resolve.
* //
* // Note: This is a contrived example in that the linker function creates a new
* // "foo" module every time it is called. In a full-fledged module system, a
* // cache would probably be used to avoid duplicated modules.
*
* async function linker(specifier, referencingModule) {
* if (specifier === 'foo') {
* return new vm.SourceTextModule(`
* // The "secret" variable refers to the global variable we added to
* // "contextifiedObject" when creating the context.
* export default secret;
* `, { context: referencingModule.context });
*
* // Using `contextifiedObject` instead of `referencingModule.context`
* // here would work as well.
* }
* throw new Error(`Unable to resolve dependency: ${specifier}`);
* }
* await bar.link(linker);
*
* // Step 3
* //
* // Evaluate the Module. The evaluate() method returns a promise which will
* // resolve after the module has finished evaluating.
*
* // Prints 42.
* await bar.evaluate();
* ```
* @since v13.0.0, v12.16.0
* @experimental
*/
class Module {
/**
* The specifiers of all dependencies of this module. The returned array is frozen
* to disallow any changes to it.
*
* Corresponds to the `[[RequestedModules]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in
* the ECMAScript specification.
*/
dependencySpecifiers: readonly string[];
/**
* If the `module.status` is `'errored'`, this property contains the exception
* thrown by the module during evaluation. If the status is anything else,
* accessing this property will result in a thrown exception.
*
* The value `undefined` cannot be used for cases where there is not a thrown
* exception due to possible ambiguity with `throw undefined;`.
*
* Corresponds to the `[[EvaluationError]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s
* in the ECMAScript specification.
*/
error: any;
/**
* The identifier of the current module, as set in the constructor.
*/
identifier: string;
context: Context;
/**
* The namespace object of the module. This is only available after linking
* (`module.link()`) has completed.
*
* Corresponds to the [GetModuleNamespace](https://tc39.es/ecma262/#sec-getmodulenamespace) abstract operation in the ECMAScript
* specification.
*/
namespace: Object;
/**
* The current status of the module. Will be one of:
*
* * `'unlinked'`: `module.link()` has not yet been called.
* * `'linking'`: `module.link()` has been called, but not all Promises returned
* by the linker function have been resolved yet.
* * `'linked'`: The module has been linked successfully, and all of its
* dependencies are linked, but `module.evaluate()` has not yet been called.
* * `'evaluating'`: The module is being evaluated through a `module.evaluate()` on
* itself or a parent module.
* * `'evaluated'`: The module has been successfully evaluated.
* * `'errored'`: The module has been evaluated, but an exception was thrown.
*
* Other than `'errored'`, this status string corresponds to the specification's [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)'s `[[Status]]` field. `'errored'`
* corresponds to`'evaluated'` in the specification, but with `[[EvaluationError]]` set to a
* value that is not `undefined`.
*/
s |
tatus: ModuleStatus;
/**
* Evaluate the module.
*
* This must be called after the module has been linked; otherwise it will reject.
* It could be called also when the module has already been evaluated, in which
* case it will either do nothing if the initial evaluation ended in success
* (`module.status` is `'evaluated'`) or it will re-throw the exception that the
* initial evaluation resulted in (`module.status` is `'errored'`).
*
* This method cannot be called while the module is being evaluated
* (`module.status` is `'evaluating'`).
*
* Corresponds to the [Evaluate() concrete method](https://tc39.es/ecma262/#sec-moduleevaluation) field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in the
* ECMAScript specification.
* @return Fulfills with `undefined` upon success.
*/
evaluate(options?: ModuleEvaluateOptions): Promise<void>;
/**
* Link module dependencies. This method must be called before evaluation, and
* can only be called once per module.
*
* The function is expected to return a `Module` object or a `Promise` that
* eventually resolves to a `Module` object. The returned `Module` must satisfy the
* following two invariants:
*
* * It must belong to the same context as the parent `Module`.
* * Its `status` must not be `'errored'`.
*
* If the returned `Module`'s `status` is `'unlinked'`, this method will be
* recursively called on the returned `Module` with the same provided `linker`function.
*
* `link()` returns a `Promise` that will either get resolved when all linking
* instances resolve to a valid `Module`, or rejected if the linker function either
* throws an exception or returns an invalid `Module`.
*
* The linker function roughly corresponds to the implementation-defined [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) abstract operation in the
* ECMAScript
* specification, with a few key differences:
*
* * The linker function is allowed to be asynchronous while [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) is synchronous.
*
* The actual [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation used during module
* linking is one that returns the modules linked during linking. Since at
* that point all modules would have been fully linked already, the [HostResolveImportedModule](https://tc39.es/ecma262/#sec-hostresolveimportedmodule) implementation is fully synchronous per
* specification.
*
* Corresponds to the [Link() concrete method](https://tc39.es/ecma262/#sec-moduledeclarationlinking) field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in
* the ECMAScript specification.
*/
link(linker: ModuleLinker): Promise<void>;
}
interface SourceTextModuleOptions {
/**
* String used in stack traces.
* @default 'vm:module(i)' where i is a context-specific ascending index.
*/
identifier?: string | undefined;
cachedData?: ScriptOptions["cachedData"] | undefined;
context?: Context | undefined;
lineOffset?: BaseOptions["lineOffset"] | undefined;
columnOffset?: BaseOptions["columnOffset"] | undefined;
/**
* Called during evaluation of this module to initialize the `import.meta`.
*/
initializeImportMeta?: ((meta: ImportMeta, module: SourceTextModule) => void) | undefined;
importModuleDynamically?: ScriptOptions["importModuleDynamically"] | undefined;
}
/**
* This feature is only a |
vailable with the `--experimental-vm-modules` command
* flag enabled.
*
* The `vm.SourceTextModule` class provides the [Source Text Module Record](https://tc39.es/ecma262/#sec-source-text-module-records) as
* defined in the ECMAScript specification.
* @since v9.6.0
* @experimental
*/
class SourceTextModule extends Module {
/**
* Creates a new `SourceTextModule` instance.
* @param code JavaScript Module code to parse
*/
constructor(code: string, options?: SourceTextModuleOptions);
}
interface SyntheticModuleOptions {
/**
* String used in stack traces.
* @default 'vm:module(i)' where i is a context-specific ascending index.
*/
identifier?: string | undefined;
/**
* The contextified object as returned by the `vm.createContext()` method, to compile and evaluate this module in.
*/
context?: Context | undefined;
}
/**
* This feature is only available with the `--experimental-vm-modules` command
* flag enabled.
*
* The `vm.SyntheticModule` class provides the [Synthetic Module Record](https://heycam.github.io/webidl/#synthetic-module-records) as
* defined in the WebIDL specification. The purpose of synthetic modules is to
* provide a generic interface for exposing non-JavaScript sources to ECMAScript
* module graphs.
*
* ```js
* const vm = require('node:vm');
*
* const source = '{ "a": 1 }';
* const module = new vm.SyntheticModule(['default'], function() {
* const obj = JSON.parse(source);
* this.setExport('default', obj);
* });
*
* // Use `module` in linking...
* ```
* @since v13.0.0, v12.16.0
* @experimental
*/
class SyntheticModule extends Module {
/**
* Creates a new `SyntheticModule` instance.
* @param exportNames Array of names that will be exported from the module.
* @param evaluateCallback Called when the module is evaluated.
*/
constructor(
exportNames: string[],
evaluateCallback: (this: SyntheticModule) => void,
options?: SyntheticModuleOptions,
);
/**
* This method is used after the module is linked to set the values of exports. If
* it is called before the module is linked, an `ERR_VM_MODULE_STATUS` error
* will be thrown.
*
* ```js
* import vm from 'node:vm';
*
* const m = new vm.SyntheticModule(['x'], () => {
* m.setExport('x', 1);
* });
*
* await m.link(() => {});
* await m.evaluate();
*
* assert.strictEqual(m.namespace.x, 1);
* ```
* @since v13.0.0, v12.16.0
* @param name Name of the export to set.
* @param value The value to set the export to.
*/
setExport(name: string, value: any): void;
}
}
declare module "node:vm" {
export * from "vm";
}
|
/**
* The `node:test` module facilitates the creation of JavaScript tests.
* To access it:
*
* ```js
* import test from 'node:test';
* ```
*
* This module is only available under the `node:` scheme. The following will not
* work:
*
* ```js
* import test from 'test';
* ```
*
* Tests created via the `test` module consist of a single function that is
* processed in one of three ways:
*
* 1. A synchronous function that is considered failing if it throws an exception,
* and is considered passing otherwise.
* 2. A function that returns a `Promise` that is considered failing if the`Promise` rejects, and is considered passing if the `Promise` fulfills.
* 3. A function that receives a callback function. If the callback receives any
* truthy value as its first argument, the test is considered failing. If a
* falsy value is passed as the first argument to the callback, the test is
* considered passing. If the test function receives a callback function and
* also returns a `Promise`, the test will fail.
*
* The following example illustrates how tests are written using the`test` module.
*
* ```js
* test('synchronous passing test', (t) => {
* // This test passes because it does not throw an exception.
* assert.strictEqual(1, 1);
* });
*
* test('synchronous failing test', (t) => {
* // This test fails because it throws an exception.
* assert.strictEqual(1, 2);
* });
*
* test('asynchronous passing test', async (t) => {
* // This test passes because the Promise returned by the async
* // function is settled and not rejected.
* assert.strictEqual(1, 1);
* });
*
* test('asynchronous failing test', async (t) => {
* // This test fails because the Promise returned by the async
* // function is rejected.
* assert.strictEqual(1, 2);
* });
*
* test('failing test using Promises', (t) => {
* // Promises can be used directly as well.
* return new Promise((resolve, reject) => {
* setImmediate(() => {
* reject(new Error('this will cause the test to fail'));
* });
* });
* });
*
* test('callback passing test', (t, done) => {
* // done() is the callback function. When the setImmediate() runs, it invokes
* // done() with no arguments.
* setImmediate(done);
* });
*
* test('callback failing test', (t, done) => {
* // When the setImmediate() runs, done() is invoked with an Error object and
* // the test fails.
* setImmediate(() => {
* done(new Error('callback failure'));
* });
* });
* ```
*
* If any tests fail, the process exit code is set to `1`.
* @since v18.0.0, v16.17.0
* @see [source](https://github.com/nodejs/node/blob/v20.4.0/lib/test.js)
*/
declare module "node:test" {
import { Readable } from "node:stream";
import { AsyncResource } from "node:async_hooks";
/**
* **Note:**`shard` is used to horizontally parallelize test running across
* machines or processes, ideal for large-scale executions across varied
* environments. It's incompatible with `watch` mode, tailored for rapid
* code iteration by automatically rerunning tests on file changes.
*
* ```js
* import { tap } from 'node:test/reporters';
* import { run } from 'node:test';
* import process from 'node:process';
* import path from 'node:path';
*
* run({ files: [path.resolve('./tests/test.js')] })
* .compose(tap)
* .pipe(process.stdout);
* ```
* @since v18.9.0, v16.19.0
* @param options Configuration options for running tests. The following properties are supported:
*/
function run(options?: RunOptions): TestsStream;
/**
* The `test()` function is the value imported from the `test` module. Each
* invocation of this function results in reporting the test to the `TestsStream`.
*
* The `TestContext` object passed to the `fn` argument can be used to perform
* actions related to the current test. Examples include skipping the test, add |
ing
* additional diagnostic information, or creating subtests.
*
* `test()` returns a `Promise` that fulfills once the test completes.
* if `test()` is called within a `describe()` block, it fulfills immediately.
* The return value can usually be discarded for top level tests.
* However, the return value from subtests should be used to prevent the parent
* test from finishing first and cancelling the subtest
* as shown in the following example.
*
* ```js
* test('top level test', async (t) => {
* // The setTimeout() in the following subtest would cause it to outlive its
* // parent test if 'await' is removed on the next line. Once the parent test
* // completes, it will cancel any outstanding subtests.
* await t.test('longer running subtest', async (t) => {
* return new Promise((resolve, reject) => {
* setTimeout(resolve, 1000);
* });
* });
* });
* ```
*
* The `timeout` option can be used to fail the test if it takes longer than`timeout` milliseconds to complete. However, it is not a reliable mechanism for
* canceling tests because a running test might block the application thread and
* thus prevent the scheduled cancellation.
* @since v18.0.0, v16.17.0
* @param [name='The name'] The name of the test, which is displayed when reporting test results.
* @param options Configuration options for the test. The following properties are supported:
* @param [fn='A no-op function'] The function under test. The first argument to this function is a {@link TestContext} object. If the test uses callbacks, the callback function is passed as the
* second argument.
* @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within {@link describe}.
*/
function test(name?: string, fn?: TestFn): Promise<void>;
function test(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
function test(options?: TestOptions, fn?: TestFn): Promise<void>;
function test(fn?: TestFn): Promise<void>;
namespace test {
export { after, afterEach, before, beforeEach, describe, it, mock, only, run, skip, test, todo };
}
/**
* The `describe()` function imported from the `node:test` module. Each
* invocation of this function results in the creation of a Subtest.
* After invocation of top level `describe` functions,
* all top level tests and suites will execute.
* @param [name='The name'] The name of the suite, which is displayed when reporting test results.
* @param options Configuration options for the suite. supports the same options as `test([name][, options][, fn])`.
* @param [fn='A no-op function'] The function under suite declaring all subtests and subsuites. The first argument to this function is a {@link SuiteContext} object.
* @return Immediately fulfilled with `undefined`.
*/
function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
function describe(name?: string, fn?: SuiteFn): Promise<void>;
function describe(options?: TestOptions, fn?: SuiteFn): Promise<void>;
function describe(fn?: SuiteFn): Promise<void>;
namespace describe {
/**
* Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`.
*/
function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
function skip(name?: string, fn?: SuiteFn): Promise<void>;
function skip(options?: TestOptions, fn?: SuiteFn): Promise<void>;
function skip(fn?: SuiteFn): Promise<void>;
/**
* Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`.
*/
function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
function todo(name?: string, fn?: SuiteFn): Promise<void>;
|
function todo(options?: TestOptions, fn?: SuiteFn): Promise<void>;
function todo(fn?: SuiteFn): Promise<void>;
/**
* Shorthand for marking a suite as `only`, same as `describe([name], { only: true }[, fn])`.
* @since v18.15.0
*/
function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
function only(name?: string, fn?: SuiteFn): Promise<void>;
function only(options?: TestOptions, fn?: SuiteFn): Promise<void>;
function only(fn?: SuiteFn): Promise<void>;
}
/**
* Shorthand for `test()`.
*
* The `it()` function is imported from the `node:test` module.
* @since v18.6.0, v16.17.0
*/
function it(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
function it(name?: string, fn?: TestFn): Promise<void>;
function it(options?: TestOptions, fn?: TestFn): Promise<void>;
function it(fn?: TestFn): Promise<void>;
namespace it {
/**
* Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`.
*/
function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
function skip(name?: string, fn?: TestFn): Promise<void>;
function skip(options?: TestOptions, fn?: TestFn): Promise<void>;
function skip(fn?: TestFn): Promise<void>;
/**
* Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`.
*/
function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
function todo(name?: string, fn?: TestFn): Promise<void>;
function todo(options?: TestOptions, fn?: TestFn): Promise<void>;
function todo(fn?: TestFn): Promise<void>;
/**
* Shorthand for marking a test as `only`, same as `it([name], { only: true }[, fn])`.
* @since v18.15.0
*/
function only(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
function only(name?: string, fn?: TestFn): Promise<void>;
function only(options?: TestOptions, fn?: TestFn): Promise<void>;
function only(fn?: TestFn): Promise<void>;
}
/**
* Shorthand for skipping a test, same as `test([name], { skip: true }[, fn])`.
* @since v20.2.0
*/
function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
function skip(name?: string, fn?: TestFn): Promise<void>;
function skip(options?: TestOptions, fn?: TestFn): Promise<void>;
function skip(fn?: TestFn): Promise<void>;
/**
* Shorthand for marking a test as `TODO`, same as `test([name], { todo: true }[, fn])`.
* @since v20.2.0
*/
function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
function todo(name?: string, fn?: TestFn): Promise<void>;
function todo(options?: TestOptions, fn?: TestFn): Promise<void>;
function todo(fn?: TestFn): Promise<void>;
/**
* Shorthand for marking a test as `only`, same as `test([name], { only: true }[, fn])`.
* @since v20.2.0
*/
function only(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
function only(name?: string, fn?: TestFn): Promise<void>;
function only(options?: TestOptions, fn?: TestFn): Promise<void>;
function only(fn?: TestFn): Promise<void>;
/**
* The type of a function under test. The first argument to this function is a
* {@link TestContext} object. If the test uses callbacks, the callback function is passed as
* the second argument.
*/
type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise<void>;
/**
* The type of a function under Suite.
*/
type SuiteFn = (s: SuiteContext) => void | Promise<void>;
interface TestShard {
/**
* A positive integer between 1 and `<total>` that specifies the index of the shard to run.
*/
index: number; |
/**
* A positive integer that specifies the total number of shards to split the test files to.
*/
total: number;
}
interface RunOptions {
/**
* If a number is provided, then that many files would run in parallel.
* If truthy, it would run (number of cpu cores - 1) files in parallel.
* If falsy, it would only run one file at a time.
* If unspecified, subtests inherit this value from their parent.
* @default true
*/
concurrency?: number | boolean | undefined;
/**
* An array containing the list of files to run.
* If unspecified, the test runner execution model will be used.
*/
files?: readonly string[] | undefined;
/**
* Allows aborting an in-progress test execution.
* @default undefined
*/
signal?: AbortSignal | undefined;
/**
* A number of milliseconds the test will fail after.
* If unspecified, subtests inherit this value from their parent.
* @default Infinity
*/
timeout?: number | undefined;
/**
* Sets inspector port of test child process.
* If a nullish value is provided, each process gets its own port,
* incremented from the primary's `process.debugPort`.
*/
inspectPort?: number | (() => number) | undefined;
/**
* That can be used to only run tests whose name matches the provided pattern.
* Test name patterns are interpreted as JavaScript regular expressions.
* For each test that is executed, any corresponding test hooks, such as `beforeEach()`, are also run.
*/
testNamePatterns?: string | RegExp | string[] | RegExp[];
/**
* If truthy, the test context will only run tests that have the `only` option set
*/
only?: boolean;
/**
* A function that accepts the TestsStream instance and can be used to setup listeners before any tests are run.
*/
setup?: (root: Test) => void | Promise<void>;
/**
* Whether to run in watch mode or not.
* @default false
*/
watch?: boolean | undefined;
/**
* Running tests in a specific shard.
* @default undefined
*/
shard?: TestShard | undefined;
}
class Test extends AsyncResource {
concurrency: number;
nesting: number;
only: boolean;
reporter: TestsStream;
runOnlySubtests: boolean;
testNumber: number;
timeout: number | null;
}
/**
* A successful call to `run()` method will return a new `TestsStream` object, streaming a series of events representing the execution of the tests.`TestsStream` will emit events, in the
* order of the tests definition
* @since v18.9.0, v16.19.0
*/
class TestsStream extends Readable implements NodeJS.ReadableStream {
addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this;
addListener(event: "test:fail", listener: (data: TestFail) => void): this;
addListener(event: "test:pass", listener: (data: TestPass) => void): this;
addListener(event: "test:plan", listener: (data: TestPlan) => void): this;
addListener(event: "test:start", listener: (data: TestStart) => void): this;
addListener(event: "test:stderr", listener: (data: TestStderr) => void): this;
addListener(event: "test:stdout", listener: (data: TestStdout) => void): this;
addListener(event: string, listener: (...args: any[]) => void): this;
emit(event: "test:diagnostic", data: DiagnosticData): boolean;
emit(event: "test:fail", data: TestFail): boolean;
emit(event: "test:pass", data: TestPass): boolean;
emit(event: "test:plan", data: TestPlan): boolean;
emit(event: "test:start", data: TestStart): boo |
lean;
emit(event: "test:stderr", data: TestStderr): boolean;
emit(event: "test:stdout", data: TestStdout): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this;
on(event: "test:fail", listener: (data: TestFail) => void): this;
on(event: "test:pass", listener: (data: TestPass) => void): this;
on(event: "test:plan", listener: (data: TestPlan) => void): this;
on(event: "test:start", listener: (data: TestStart) => void): this;
on(event: "test:stderr", listener: (data: TestStderr) => void): this;
on(event: "test:stdout", listener: (data: TestStdout) => void): this;
on(event: string, listener: (...args: any[]) => void): this;
once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this;
once(event: "test:fail", listener: (data: TestFail) => void): this;
once(event: "test:pass", listener: (data: TestPass) => void): this;
once(event: "test:plan", listener: (data: TestPlan) => void): this;
once(event: "test:start", listener: (data: TestStart) => void): this;
once(event: "test:stderr", listener: (data: TestStderr) => void): this;
once(event: "test:stdout", listener: (data: TestStdout) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this;
prependListener(event: "test:fail", listener: (data: TestFail) => void): this;
prependListener(event: "test:pass", listener: (data: TestPass) => void): this;
prependListener(event: "test:plan", listener: (data: TestPlan) => void): this;
prependListener(event: "test:start", listener: (data: TestStart) => void): this;
prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this;
prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this;
prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this;
prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this;
prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this;
prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this;
prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this;
prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
}
/**
* An instance of `TestContext` is passed to each test function in order to
* interact with the test runner. However, the `TestContext` constructor is not
* exposed as part of the API.
* @since v18.0.0, v16.17.0
*/
class TestContext {
/**
* This function is used to create a hook running before subtest of the current test.
* @param fn The hook function. If the hook uses callbacks, the callback function is passed as
* the second argument. Default: A no-op function.
* @param options Configuration options for the hook.
* @since v20.1.0
*/
before: typeof before;
/**
* This function is used to create a hook running before each subtest of the current test.
* @param fn The hook function. If the hook uses callbacks, the callback function is passed as
* the second argument. Default: A no-op function.
* @param options Configuration options for the hook.
* @since v18.8.0
*/
beforeEach: typeof beforeEach;
/**
|
* This function is used to create a hook that runs after the current test finishes.
* @param fn The hook function. If the hook uses callbacks, the callback function is passed as
* the second argument. Default: A no-op function.
* @param options Configuration options for the hook.
* @since v18.13.0
*/
after: typeof after;
/**
* This function is used to create a hook running after each subtest of the current test.
* @param fn The hook function. If the hook uses callbacks, the callback function is passed as
* the second argument. Default: A no-op function.
* @param options Configuration options for the hook.
* @since v18.8.0
*/
afterEach: typeof afterEach;
/**
* This function is used to write diagnostics to the output. Any diagnostic
* information is included at the end of the test's results. This function does
* not return a value.
*
* ```js
* test('top level test', (t) => {
* t.diagnostic('A diagnostic message');
* });
* ```
* @since v18.0.0, v16.17.0
* @param message Message to be reported.
*/
diagnostic(message: string): void;
/**
* The name of the test.
* @since v18.8.0, v16.18.0
*/
readonly name: string;
/**
* If `shouldRunOnlyTests` is truthy, the test context will only run tests that
* have the `only` option set. Otherwise, all tests are run. If Node.js was not
* started with the `--test-only` command-line option, this function is a
* no-op.
*
* ```js
* test('top level test', (t) => {
* // The test context can be set to run subtests with the 'only' option.
* t.runOnly(true);
* return Promise.all([
* t.test('this subtest is now skipped'),
* t.test('this subtest is run', { only: true }),
* ]);
* });
* ```
* @since v18.0.0, v16.17.0
* @param shouldRunOnlyTests Whether or not to run `only` tests.
*/
runOnly(shouldRunOnlyTests: boolean): void;
/**
* ```js
* test('top level test', async (t) => {
* await fetch('some/uri', { signal: t.signal });
* });
* ```
* @since v18.7.0, v16.17.0
*/
readonly signal: AbortSignal;
/**
* This function causes the test's output to indicate the test as skipped. If`message` is provided, it is included in the output. Calling `skip()` does
* not terminate execution of the test function. This function does not return a
* value.
*
* ```js
* test('top level test', (t) => {
* // Make sure to return here as well if the test contains additional logic.
* t.skip('this is skipped');
* });
* ```
* @since v18.0.0, v16.17.0
* @param message Optional skip message.
*/
skip(message?: string): void;
/**
* This function adds a `TODO` directive to the test's output. If `message` is
* provided, it is included in the output. Calling `todo()` does not terminate
* execution of the test function. This function does not return a value.
*
* ```js
* test('top level test', (t) => {
* // This test is marked as `TODO`
* t.todo('this is a todo');
* });
* ```
* @since v18.0.0, v16.17.0
* @param message Optional `TODO` message.
*/
todo(message?: string): void;
/**
* This function is used to create subtests under the current test. This function behaves in
* the same fashion as the top level {@link test} function.
* @since v18.0.0
* @param name The name of th |
e test, which is displayed when reporting test results.
* Default: The `name` property of fn, or `'<anonymous>'` if `fn` does not have a name.
* @param options Configuration options for the test
* @param fn The function under test. This first argument to this function is a
* {@link TestContext} object. If the test uses callbacks, the callback function is
* passed as the second argument. Default: A no-op function.
* @returns A {@link Promise} resolved with `undefined` once the test completes.
*/
test: typeof test;
/**
* Each test provides its own MockTracker instance.
*/
readonly mock: MockTracker;
}
/**
* An instance of `SuiteContext` is passed to each suite function in order to
* interact with the test runner. However, the `SuiteContext` constructor is not
* exposed as part of the API.
* @since v18.7.0, v16.17.0
*/
class SuiteContext {
/**
* The name of the suite.
* @since v18.8.0, v16.18.0
*/
readonly name: string;
/**
* Can be used to abort test subtasks when the test has been aborted.
* @since v18.7.0, v16.17.0
*/
readonly signal: AbortSignal;
}
interface TestOptions {
/**
* If a number is provided, then that many tests would run in parallel.
* If truthy, it would run (number of cpu cores - 1) tests in parallel.
* For subtests, it will be `Infinity` tests in parallel.
* If falsy, it would only run one test at a time.
* If unspecified, subtests inherit this value from their parent.
* @default false
*/
concurrency?: number | boolean | undefined;
/**
* If truthy, and the test context is configured to run `only` tests, then this test will be
* run. Otherwise, the test is skipped.
* @default false
*/
only?: boolean | undefined;
/**
* Allows aborting an in-progress test.
* @since v18.8.0
*/
signal?: AbortSignal | undefined;
/**
* If truthy, the test is skipped. If a string is provided, that string is displayed in the
* test results as the reason for skipping the test.
* @default false
*/
skip?: boolean | string | undefined;
/**
* A number of milliseconds the test will fail after. If unspecified, subtests inherit this
* value from their parent.
* @default Infinity
* @since v18.7.0
*/
timeout?: number | undefined;
/**
* If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in
* the test results as the reason why the test is `TODO`.
* @default false
*/
todo?: boolean | string | undefined;
}
/**
* This function is used to create a hook running before running a suite.
*
* ```js
* describe('tests', async () => {
* before(() => console.log('about to run some test'));
* it('is a subtest', () => {
* assert.ok('some relevant assertion here');
* });
* });
* ```
* @since v18.8.0, v16.18.0
* @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
* @param options Configuration options for the hook. The following properties are supported:
*/
function before(fn?: HookFn, options?: HookOptions): void;
/**
* This function is used to create a hook running after running a suite.
*
* ```js
* describe('tests', async () => {
* after(() => console.log('finished running tests'));
* it('is a subtest', () => {
* assert.ok('some relevant assertion here');
* });
* });
* ```
* @since v18.8.0, v16.18.0
* @param |
[fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
* @param options Configuration options for the hook. The following properties are supported:
*/
function after(fn?: HookFn, options?: HookOptions): void;
/**
* This function is used to create a hook running
* before each subtest of the current suite.
*
* ```js
* describe('tests', async () => {
* beforeEach(() => console.log('about to run a test'));
* it('is a subtest', () => {
* assert.ok('some relevant assertion here');
* });
* });
* ```
* @since v18.8.0, v16.18.0
* @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
* @param options Configuration options for the hook. The following properties are supported:
*/
function beforeEach(fn?: HookFn, options?: HookOptions): void;
/**
* This function is used to create a hook running
* after each subtest of the current test.
*
* ```js
* describe('tests', async () => {
* afterEach(() => console.log('finished running a test'));
* it('is a subtest', () => {
* assert.ok('some relevant assertion here');
* });
* });
* ```
* @since v18.8.0, v16.18.0
* @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
* @param options Configuration options for the hook. The following properties are supported:
*/
function afterEach(fn?: HookFn, options?: HookOptions): void;
/**
* The hook function. If the hook uses callbacks, the callback function is passed as the
* second argument.
*/
type HookFn = (s: SuiteContext, done: (result?: any) => void) => any;
/**
* Configuration options for hooks.
* @since v18.8.0
*/
interface HookOptions {
/**
* Allows aborting an in-progress hook.
*/
signal?: AbortSignal | undefined;
/**
* A number of milliseconds the hook will fail after. If unspecified, subtests inherit this
* value from their parent.
* @default Infinity
*/
timeout?: number | undefined;
}
interface MockFunctionOptions {
/**
* The number of times that the mock will use the behavior of `implementation`.
* Once the mock function has been called `times` times,
* it will automatically restore the behavior of `original`.
* This value must be an integer greater than zero.
* @default Infinity
*/
times?: number | undefined;
}
interface MockMethodOptions extends MockFunctionOptions {
/**
* If `true`, `object[methodName]` is treated as a getter.
* This option cannot be used with the `setter` option.
*/
getter?: boolean | undefined;
/**
* If `true`, `object[methodName]` is treated as a setter.
* This option cannot be used with the `getter` option.
*/
setter?: boolean | undefined;
}
type Mock<F extends Function> = F & {
mock: MockFunctionContext<F>;
};
type NoOpFunction = (...args: any[]) => undefined;
type FunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? K : never;
}[keyof T];
/**
* The `MockTracker` class is used to manage mocking functionality. The test runner
* module provides a top level `mock` export which is a `MockTracker` instance.
* Each test also provides its own `MockTracker` instance via the test context's`mock` property.
* @since v19.1.0, v18.13.0
*/
class MockTracker {
/**
* This function is used to create a mock function.
*
* The following example creates a mock function that increments a counter by o |
ne
* on each invocation. The `times` option is used to modify the mock behavior such
* that the first two invocations add two to the counter instead of one.
*
* ```js
* test('mocks a counting function', (t) => {
* let cnt = 0;
*
* function addOne() {
* cnt++;
* return cnt;
* }
*
* function addTwo() {
* cnt += 2;
* return cnt;
* }
*
* const fn = t.mock.fn(addOne, addTwo, { times: 2 });
*
* assert.strictEqual(fn(), 2);
* assert.strictEqual(fn(), 4);
* assert.strictEqual(fn(), 5);
* assert.strictEqual(fn(), 6);
* });
* ```
* @since v19.1.0, v18.13.0
* @param [original='A no-op function'] An optional function to create a mock on.
* @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and
* then restore the behavior of `original`.
* @param options Optional configuration options for the mock function. The following properties are supported:
* @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the
* behavior of the mocked function.
*/
fn<F extends Function = NoOpFunction>(original?: F, options?: MockFunctionOptions): Mock<F>;
fn<F extends Function = NoOpFunction, Implementation extends Function = F>(
original?: F,
implementation?: Implementation,
options?: MockFunctionOptions,
): Mock<F | Implementation>;
/**
* This function is used to create a mock on an existing object method. The
* following example demonstrates how a mock is created on an existing object
* method.
*
* ```js
* test('spies on an object method', (t) => {
* const number = {
* value: 5,
* subtract(a) {
* return this.value - a;
* },
* };
*
* t.mock.method(number, 'subtract');
* assert.strictEqual(number.subtract.mock.calls.length, 0);
* assert.strictEqual(number.subtract(3), 2);
* assert.strictEqual(number.subtract.mock.calls.length, 1);
*
* const call = number.subtract.mock.calls[0];
*
* assert.deepStrictEqual(call.arguments, [3]);
* assert.strictEqual(call.result, 2);
* assert.strictEqual(call.error, undefined);
* assert.strictEqual(call.target, undefined);
* assert.strictEqual(call.this, number);
* });
* ```
* @since v19.1.0, v18.13.0
* @param object The object whose method is being mocked.
* @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown.
* @param implementation An optional function used as the mock implementation for `object[methodName]`.
* @param options Optional configuration options for the mock method. The following properties are supported:
* @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the
* behavior of the mocked method.
*/
method<
MockedObject extends object,
MethodName extends FunctionPropertyNames<MockedObject>,
>(
object: MockedObject,
methodName: MethodName,
options?: MockFunctionOptions,
): MockedObject[MethodName] extends Function ? Mock<MockedObject[Method |
Name]>
: never;
method<
MockedObject extends object,
MethodName extends FunctionPropertyNames<MockedObject>,
Implementation extends Function,
>(
object: MockedObject,
methodName: MethodName,
implementation: Implementation,
options?: MockFunctionOptions,
): MockedObject[MethodName] extends Function ? Mock<MockedObject[MethodName] | Implementation>
: never;
method<MockedObject extends object>(
object: MockedObject,
methodName: keyof MockedObject,
options: MockMethodOptions,
): Mock<Function>;
method<MockedObject extends object>(
object: MockedObject,
methodName: keyof MockedObject,
implementation: Function,
options: MockMethodOptions,
): Mock<Function>;
/**
* This function is syntax sugar for `MockTracker.method` with `options.getter`set to `true`.
* @since v19.3.0, v18.13.0
*/
getter<
MockedObject extends object,
MethodName extends keyof MockedObject,
>(
object: MockedObject,
methodName: MethodName,
options?: MockFunctionOptions,
): Mock<() => MockedObject[MethodName]>;
getter<
MockedObject extends object,
MethodName extends keyof MockedObject,
Implementation extends Function,
>(
object: MockedObject,
methodName: MethodName,
implementation?: Implementation,
options?: MockFunctionOptions,
): Mock<(() => MockedObject[MethodName]) | Implementation>;
/**
* This function is syntax sugar for `MockTracker.method` with `options.setter`set to `true`.
* @since v19.3.0, v18.13.0
*/
setter<
MockedObject extends object,
MethodName extends keyof MockedObject,
>(
object: MockedObject,
methodName: MethodName,
options?: MockFunctionOptions,
): Mock<(value: MockedObject[MethodName]) => void>;
setter<
MockedObject extends object,
MethodName extends keyof MockedObject,
Implementation extends Function,
>(
object: MockedObject,
methodName: MethodName,
implementation?: Implementation,
options?: MockFunctionOptions,
): Mock<((value: MockedObject[MethodName]) => void) | Implementation>;
/**
* This function restores the default behavior of all mocks that were previously
* created by this `MockTracker` and disassociates the mocks from the`MockTracker` instance. Once disassociated, the mocks can still be used, but the`MockTracker` instance can no longer be
* used to reset their behavior or
* otherwise interact with them.
*
* After each test completes, this function is called on the test context's`MockTracker`. If the global `MockTracker` is used extensively, calling this
* function manually is recommended.
* @since v19.1.0, v18.13.0
*/
reset(): void;
/**
* This function restores the default behavior of all mocks that were previously
* created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does
* not disassociate the mocks from the `MockTracker` instance.
* @since v19.1.0, v18.13.0
*/
restoreAll(): void;
timers: MockTimers;
}
const mock: MockTracker;
interface MockFunctionCall<
F extends Function,
ReturnType = F extends (...args: any) => infer T ? T
: F extends abstract new(...args: any) => infer T ? T
: unknown,
Args = F extends (...args: infer Y) => any ? Y
: F extends abstract new(...args: infer Y) => any ? Y
|
: unknown[],
> {
/**
* An array of the arguments passed to the mock function.
*/
arguments: Args;
/**
* If the mocked function threw then this property contains the thrown value.
*/
error: unknown | undefined;
/**
* The value returned by the mocked function.
*
* If the mocked function threw, it will be `undefined`.
*/
result: ReturnType | undefined;
/**
* An `Error` object whose stack can be used to determine the callsite of the mocked function invocation.
*/
stack: Error;
/**
* If the mocked function is a constructor, this field contains the class being constructed.
* Otherwise this will be `undefined`.
*/
target: F extends abstract new(...args: any) => any ? F : undefined;
/**
* The mocked function's `this` value.
*/
this: unknown;
}
/**
* The `MockFunctionContext` class is used to inspect or manipulate the behavior of
* mocks created via the `MockTracker` APIs.
* @since v19.1.0, v18.13.0
*/
class MockFunctionContext<F extends Function> {
/**
* A getter that returns a copy of the internal array used to track calls to the
* mock. Each entry in the array is an object with the following properties.
* @since v19.1.0, v18.13.0
*/
readonly calls: Array<MockFunctionCall<F>>;
/**
* This function returns the number of times that this mock has been invoked. This
* function is more efficient than checking `ctx.calls.length` because `ctx.calls`is a getter that creates a copy of the internal call tracking array.
* @since v19.1.0, v18.13.0
* @return The number of times that this mock has been invoked.
*/
callCount(): number;
/**
* This function is used to change the behavior of an existing mock.
*
* The following example creates a mock function using `t.mock.fn()`, calls the
* mock function, and then changes the mock implementation to a different function.
*
* ```js
* test('changes a mock behavior', (t) => {
* let cnt = 0;
*
* function addOne() {
* cnt++;
* return cnt;
* }
*
* function addTwo() {
* cnt += 2;
* return cnt;
* }
*
* const fn = t.mock.fn(addOne);
*
* assert.strictEqual(fn(), 1);
* fn.mock.mockImplementation(addTwo);
* assert.strictEqual(fn(), 3);
* assert.strictEqual(fn(), 5);
* });
* ```
* @since v19.1.0, v18.13.0
* @param implementation The function to be used as the mock's new implementation.
*/
mockImplementation(implementation: Function): void;
/**
* This function is used to change the behavior of an existing mock for a single
* invocation. Once invocation `onCall` has occurred, the mock will revert to
* whatever behavior it would have used had `mockImplementationOnce()` not been
* called.
*
* The following example creates a mock function using `t.mock.fn()`, calls the
* mock function, changes the mock implementation to a different function for the
* next invocation, and then resumes its previous behavior.
*
* ```js
* test('changes a mock behavior once', (t) => {
* let cnt = 0;
*
* function addOne() {
* cnt++;
* return cnt;
* }
*
* function addTwo() {
* cnt += 2;
* return cnt;
* }
*
* const fn = t.mock.fn(addOne);
*
* assert.strictEqual(fn(), 1);
|
* fn.mock.mockImplementationOnce(addTwo);
* assert.strictEqual(fn(), 3);
* assert.strictEqual(fn(), 4);
* });
* ```
* @since v19.1.0, v18.13.0
* @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`.
* @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown.
*/
mockImplementationOnce(implementation: Function, onCall?: number): void;
/**
* Resets the call history of the mock function.
* @since v19.3.0, v18.13.0
*/
resetCalls(): void;
/**
* Resets the implementation of the mock function to its original behavior. The
* mock can still be used after calling this function.
* @since v19.1.0, v18.13.0
*/
restore(): void;
}
type Timer = "setInterval" | "setTimeout" | "setImmediate" | "Date";
interface MockTimersOptions {
apis: Timer[];
now?: number | Date;
}
/**
* Mocking timers is a technique commonly used in software testing to simulate and
* control the behavior of timers, such as `setInterval` and `setTimeout`,
* without actually waiting for the specified time intervals.
*
* The MockTimers API also allows for mocking of the `Date` constructor and
* `setImmediate`/`clearImmediate` functions.
*
* The `MockTracker` provides a top-level `timers` export
* which is a `MockTimers` instance.
* @since v20.4.0
* @experimental
*/
class MockTimers {
/**
* Enables timer mocking for the specified timers.
*
* **Note:** When you enable mocking for a specific timer, its associated
* clear function will also be implicitly mocked.
*
* **Note:** Mocking `Date` will affect the behavior of the mocked timers
* as they use the same internal clock.
*
* Example usage without setting initial time:
*
* ```js
* import { mock } from 'node:test';
* mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 });
* ```
*
* The above example enables mocking for the `Date` constructor, `setInterval` timer and
* implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`,
* `setInterval` and `clearInterval` functions from `node:timers`,`node:timers/promises`, and `globalThis` will be mocked.
*
* Example usage with initial time set
*
* ```js
* import { mock } from 'node:test';
* mock.timers.enable({ apis: ['Date'], now: 1000 });
* ```
*
* Example usage with initial Date object as time set
*
* ```js
* import { mock } from 'node:test';
* mock.timers.enable({ apis: ['Date'], now: new Date() });
* ```
*
* Alternatively, if you call `mock.timers.enable()` without any parameters:
*
* All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`)
* will be mocked.
*
* The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`,
* and `globalThis` will be mocked.
* The `Date` constructor from `globalThis` will be mocked.
*
* If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date object. It can either be a positive integer, or another Date object.
* @since v20.4.0
|
*/
enable(options?: MockTimersOptions): void;
/**
* You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer.
* Note: This method will execute any mocked timers that are in the past from the new time.
* In the below example we are setting a new time for the mocked date.
* ```js
* import assert from 'node:assert';
* import { test } from 'node:test';
* test('sets the time of a date object', (context) => {
* // Optionally choose what to mock
* context.mock.timers.enable({ apis: ['Date'], now: 100 });
* assert.strictEqual(Date.now(), 100);
* // Advance in time will also advance the date
* context.mock.timers.setTime(1000);
* context.mock.timers.tick(200);
* assert.strictEqual(Date.now(), 1200);
* });
* ```
*/
setTime(time: number): void;
/**
* This function restores the default behavior of all mocks that were previously
* created by this `MockTimers` instance and disassociates the mocks
* from the `MockTracker` instance.
*
* **Note:** After each test completes, this function is called on
* the test context's `MockTracker`.
*
* ```js
* import { mock } from 'node:test';
* mock.timers.reset();
* ```
* @since v20.4.0
*/
reset(): void;
/**
* Advances time for all mocked timers.
*
* **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts
* only positive numbers. In Node.js, `setTimeout` with negative numbers is
* only supported for web compatibility reasons.
*
* The following example mocks a `setTimeout` function and
* by using `.tick` advances in
* time triggering all pending timers.
*
* ```js
* import assert from 'node:assert';
* import { test } from 'node:test';
*
* test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
* const fn = context.mock.fn();
*
* context.mock.timers.enable({ apis: ['setTimeout'] });
*
* setTimeout(fn, 9999);
*
* assert.strictEqual(fn.mock.callCount(), 0);
*
* // Advance in time
* context.mock.timers.tick(9999);
*
* assert.strictEqual(fn.mock.callCount(), 1);
* });
* ```
*
* Alternativelly, the `.tick` function can be called many times
*
* ```js
* import assert from 'node:assert';
* import { test } from 'node:test';
*
* test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
* const fn = context.mock.fn();
* context.mock.timers.enable({ apis: ['setTimeout'] });
* const nineSecs = 9000;
* setTimeout(fn, nineSecs);
*
* const twoSeconds = 3000;
* context.mock.timers.tick(twoSeconds);
* context.mock.timers.tick(twoSeconds);
* context.mock.timers.tick(twoSeconds);
*
* assert.strictEqual(fn.mock.callCount(), 1);
* });
* ```
*
* Advancing time using `.tick` will also advance the time for any `Date` object
* created after the mock was enabled (if `Date` was also set to be mocked).
*
* ```js
* import assert from 'node:assert';
* import { test } from 'node:test';
*
* test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
* const fn = context.mock.fn();
*
* |
context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
* setTimeout(fn, 9999);
*
* assert.strictEqual(fn.mock.callCount(), 0);
* assert.strictEqual(Date.now(), 0);
*
* // Advance in time
* context.mock.timers.tick(9999);
* assert.strictEqual(fn.mock.callCount(), 1);
* assert.strictEqual(Date.now(), 9999);
* });
* ```
* @since v20.4.0
*/
tick(milliseconds: number): void;
/**
* Triggers all pending mocked timers immediately. If the `Date` object is also
* mocked, it will also advance the `Date` object to the furthest timer's time.
*
* The example below triggers all pending timers immediately,
* causing them to execute without any delay.
*
* ```js
* import assert from 'node:assert';
* import { test } from 'node:test';
*
* test('runAll functions following the given order', (context) => {
* context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
* const results = [];
* setTimeout(() => results.push(1), 9999);
*
* // Notice that if both timers have the same timeout,
* // the order of execution is guaranteed
* setTimeout(() => results.push(3), 8888);
* setTimeout(() => results.push(2), 8888);
*
* assert.deepStrictEqual(results, []);
*
* context.mock.timers.runAll();
* assert.deepStrictEqual(results, [3, 2, 1]);
* // The Date object is also advanced to the furthest timer's time
* assert.strictEqual(Date.now(), 9999);
* });
* ```
*
* **Note:** The `runAll()` function is specifically designed for
* triggering timers in the context of timer mocking.
* It does not have any effect on real-time system
* clocks or actual timers outside of the mocking environment.
* @since v20.4.0
*/
runAll(): void;
/**
* Calls {@link MockTimers.reset()}.
*/
[Symbol.dispose](): void;
}
export {
after,
afterEach,
before,
beforeEach,
describe,
it,
Mock,
mock,
only,
run,
skip,
test,
test as default,
todo,
};
}
interface TestLocationInfo {
/**
* The column number where the test is defined, or
* `undefined` if the test was run through the REPL.
*/
column?: number;
/**
* The path of the test file, `undefined` if test is not ran through a file.
*/
file?: string;
/**
* The line number where the test is defined, or
* `undefined` if the test was run through the REPL.
*/
line?: number;
}
interface DiagnosticData extends TestLocationInfo {
/**
* The diagnostic message.
*/
message: string;
/**
* The nesting level of the test.
*/
nesting: number;
}
interface TestFail extends TestLocationInfo {
/**
* Additional execution metadata.
*/
details: {
/**
* The duration of the test in milliseconds.
*/
duration_ms: number;
/**
* The error thrown by the test.
*/
error: Error;
/**
* The type of the test, used to denote whether this is a suite.
* @since 20.0.0, 19.9.0, 18.17.0
*/
type?: "suite";
};
/**
* The test name.
*/
name: string;
/**
* The nesting level of the test.
*/
nesting: number;
/**
* The ordinal number of the test.
*/
testNumber: number;
/**
* Present if `context.todo` is called.
*/
todo?: string | boolean;
/**
* Present if `context.skip` is called.
*/
skip?: string | boolean;
}
interface TestPass ext |
ends TestLocationInfo {
/**
* Additional execution metadata.
*/
details: {
/**
* The duration of the test in milliseconds.
*/
duration_ms: number;
/**
* The type of the test, used to denote whether this is a suite.
* @since 20.0.0, 19.9.0, 18.17.0
*/
type?: "suite";
};
/**
* The test name.
*/
name: string;
/**
* The nesting level of the test.
*/
nesting: number;
/**
* The ordinal number of the test.
*/
testNumber: number;
/**
* Present if `context.todo` is called.
*/
todo?: string | boolean;
/**
* Present if `context.skip` is called.
*/
skip?: string | boolean;
}
interface TestPlan extends TestLocationInfo {
/**
* The nesting level of the test.
*/
nesting: number;
/**
* The number of subtests that have ran.
*/
count: number;
}
interface TestStart extends TestLocationInfo {
/**
* The test name.
*/
name: string;
/**
* The nesting level of the test.
*/
nesting: number;
}
interface TestStderr extends TestLocationInfo {
/**
* The message written to `stderr`
*/
message: string;
}
interface TestStdout extends TestLocationInfo {
/**
* The message written to `stdout`
*/
message: string;
}
interface TestEnqueue extends TestLocationInfo {
/**
* The test name
*/
name: string;
/**
* The nesting level of the test.
*/
nesting: number;
}
interface TestDequeue extends TestLocationInfo {
/**
* The test name
*/
name: string;
/**
* The nesting level of the test.
*/
nesting: number;
}
/**
* The `node:test/reporters` module exposes the builtin-reporters for `node:test`.
* To access it:
*
* ```js
* import test from 'node:test/reporters';
* ```
*
* This module is only available under the `node:` scheme. The following will not
* work:
*
* ```js
* import test from 'test/reporters';
* ```
* @since v19.9.0
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/test/reporters.js)
*/
declare module "node:test/reporters" {
import { Transform, TransformOptions } from "node:stream";
type TestEvent =
| { type: "test:diagnostic"; data: DiagnosticData }
| { type: "test:fail"; data: TestFail }
| { type: "test:pass"; data: TestPass }
| { type: "test:plan"; data: TestPlan }
| { type: "test:start"; data: TestStart }
| { type: "test:stderr"; data: TestStderr }
| { type: "test:stdout"; data: TestStdout }
| { type: "test:enqueue"; data: TestEnqueue }
| { type: "test:dequeue"; data: TestDequeue }
| { type: "test:watch:drained" };
type TestEventGenerator = AsyncGenerator<TestEvent, void>;
/**
* The `dot` reporter outputs the test results in a compact format,
* where each passing test is represented by a `.`,
* and each failing test is represented by a `X`.
*/
function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>;
/**
* The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format.
*/
function tap(source: TestEventGenerator): AsyncGenerator<string, void>;
/**
* The `spec` reporter outputs the test results in a human-readable format.
*/
class Spec extends Transform {
constructor();
}
/**
* The `junit` reporter outputs test results in a jUnit XML format
*/
function junit(source: TestEventGenerator): AsyncGenerator<string, void>;
class Lcov extends Transform {
constructor(opts?: TransformOptions);
}
export { dot, junit, Lcov as lcov, Spec as spec, tap, TestEvent };
}
|
/**
* The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol.
* It can be accessed using:
*
* ```js
* const http2 = require('node:http2');
* ```
* @since v8.4.0
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http2.js)
*/
declare module "http2" {
import EventEmitter = require("node:events");
import * as fs from "node:fs";
import * as net from "node:net";
import * as stream from "node:stream";
import * as tls from "node:tls";
import * as url from "node:url";
import {
IncomingHttpHeaders as Http1IncomingHttpHeaders,
IncomingMessage,
OutgoingHttpHeaders,
ServerResponse,
} from "node:http";
export { OutgoingHttpHeaders } from "node:http";
export interface IncomingHttpStatusHeader {
":status"?: number | undefined;
}
export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders {
":path"?: string | undefined;
":method"?: string | undefined;
":authority"?: string | undefined;
":scheme"?: string | undefined;
}
// Http2Stream
export interface StreamPriorityOptions {
exclusive?: boolean | undefined;
parent?: number | undefined;
weight?: number | undefined;
silent?: boolean | undefined;
}
export interface StreamState {
localWindowSize?: number | undefined;
state?: number | undefined;
localClose?: number | undefined;
remoteClose?: number | undefined;
sumDependencyWeight?: number | undefined;
weight?: number | undefined;
}
export interface ServerStreamResponseOptions {
endStream?: boolean | undefined;
waitForTrailers?: boolean | undefined;
}
export interface StatOptions {
offset: number;
length: number;
}
export interface ServerStreamFileResponseOptions {
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean;
waitForTrailers?: boolean | undefined;
offset?: number | undefined;
length?: number | undefined;
}
export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions {
onError?(err: NodeJS.ErrnoException): void;
}
export interface Http2Stream extends stream.Duplex {
/**
* Set to `true` if the `Http2Stream` instance was aborted abnormally. When set,
* the `'aborted'` event will have been emitted.
* @since v8.4.0
*/
readonly aborted: boolean;
/**
* This property shows the number of characters currently buffered to be written.
* See `net.Socket.bufferSize` for details.
* @since v11.2.0, v10.16.0
*/
readonly bufferSize: number;
/**
* Set to `true` if the `Http2Stream` instance has been closed.
* @since v9.4.0
*/
readonly closed: boolean;
/**
* Set to `true` if the `Http2Stream` instance has been destroyed and is no longer
* usable.
* @since v8.4.0
*/
readonly destroyed: boolean;
/**
* Set to `true` if the `END_STREAM` flag was set in the request or response
* HEADERS frame received, indicating that no additional data should be received
* and the readable side of the `Http2Stream` will be closed.
* @since v10.11.0
*/
readonly endAfterHeaders: boolean;
/**
* The numeric stream identifier of this `Http2Stream` instance. Set to `undefined`if the stream identifier has not yet been assigned.
* @since v8.4.0
*/
readonly id?: number | undefined;
/**
* Set to `true` if the `Http2Stream` instance has not yet been assigned a
* numeric stream identifier.
|
* @since v9.4.0
*/
readonly pending: boolean;
/**
* Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is
* destroyed after either receiving an `RST_STREAM` frame from the connected peer,
* calling `http2stream.close()`, or `http2stream.destroy()`. Will be`undefined` if the `Http2Stream` has not been closed.
* @since v8.4.0
*/
readonly rstCode: number;
/**
* An object containing the outbound headers sent for this `Http2Stream`.
* @since v9.5.0
*/
readonly sentHeaders: OutgoingHttpHeaders;
/**
* An array of objects containing the outbound informational (additional) headers
* sent for this `Http2Stream`.
* @since v9.5.0
*/
readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined;
/**
* An object containing the outbound trailers sent for this `HttpStream`.
* @since v9.5.0
*/
readonly sentTrailers?: OutgoingHttpHeaders | undefined;
/**
* A reference to the `Http2Session` instance that owns this `Http2Stream`. The
* value will be `undefined` after the `Http2Stream` instance is destroyed.
* @since v8.4.0
*/
readonly session: Http2Session | undefined;
/**
* Provides miscellaneous information about the current state of the`Http2Stream`.
*
* A current state of this `Http2Stream`.
* @since v8.4.0
*/
readonly state: StreamState;
/**
* Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the
* connected HTTP/2 peer.
* @since v8.4.0
* @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code.
* @param callback An optional function registered to listen for the `'close'` event.
*/
close(code?: number, callback?: () => void): void;
/**
* Updates the priority for this `Http2Stream` instance.
* @since v8.4.0
*/
priority(options: StreamPriorityOptions): void;
/**
* ```js
* const http2 = require('node:http2');
* const client = http2.connect('http://example.org:8000');
* const { NGHTTP2_CANCEL } = http2.constants;
* const req = client.request({ ':path': '/' });
*
* // Cancel the stream if there's no activity after 5 seconds
* req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));
* ```
* @since v8.4.0
*/
setTimeout(msecs: number, callback?: () => void): void;
/**
* Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method
* will cause the `Http2Stream` to be immediately closed and must only be
* called after the `'wantTrailers'` event has been emitted. When sending a
* request or sending a response, the `options.waitForTrailers` option must be set
* in order to keep the `Http2Stream` open after the final `DATA` frame so that
* trailers can be sent.
*
* ```js
* const http2 = require('node:http2');
* const server = http2.createServer();
* server.on('stream', (stream) => {
* stream.respond(undefined, { waitForTrailers: true });
* stream.on('wantTrailers', () => {
* stream.sendTrailers({ xyz: 'abc' });
* });
* stream.end('Hello World');
* });
* ```
*
* The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header
* fields (e.g. `':method'`, `':path'`, etc).
* @since v10.0.0
*/
sendTrailers(headers: OutgoingHttpHeaders): void;
addListener(event: "aborted", listener: () => void): this;
addListener(event: "close", listener: () => void): this;
|
addListener(event: "data", listener: (chunk: Buffer | string) => void): this;
addListener(event: "drain", listener: () => void): this;
addListener(event: "end", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "finish", listener: () => void): this;
addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
addListener(event: "pipe", listener: (src: stream.Readable) => void): this;
addListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
addListener(event: "streamClosed", listener: (code: number) => void): this;
addListener(event: "timeout", listener: () => void): this;
addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this;
addListener(event: "wantTrailers", listener: () => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "aborted"): boolean;
emit(event: "close"): boolean;
emit(event: "data", chunk: Buffer | string): boolean;
emit(event: "drain"): boolean;
emit(event: "end"): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "finish"): boolean;
emit(event: "frameError", frameType: number, errorCode: number): boolean;
emit(event: "pipe", src: stream.Readable): boolean;
emit(event: "unpipe", src: stream.Readable): boolean;
emit(event: "streamClosed", code: number): boolean;
emit(event: "timeout"): boolean;
emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean;
emit(event: "wantTrailers"): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "aborted", listener: () => void): this;
on(event: "close", listener: () => void): this;
on(event: "data", listener: (chunk: Buffer | string) => void): this;
on(event: "drain", listener: () => void): this;
on(event: "end", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "finish", listener: () => void): this;
on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
on(event: "pipe", listener: (src: stream.Readable) => void): this;
on(event: "unpipe", listener: (src: stream.Readable) => void): this;
on(event: "streamClosed", listener: (code: number) => void): this;
on(event: "timeout", listener: () => void): this;
on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this;
on(event: "wantTrailers", listener: () => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "aborted", listener: () => void): this;
once(event: "close", listener: () => void): this;
once(event: "data", listener: (chunk: Buffer | string) => void): this;
once(event: "drain", listener: () => void): this;
once(event: "end", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "finish", listener: () => void): this;
once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
once(event: "pipe", listener: (src: stream.Readable) => void): this;
once(event: "unpipe", listener: (src: stream.Readable) => void): this;
once(event: "streamClosed", listener: (code: number) => void): this;
once(event: "timeout", listener: () => void): this;
once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this;
once(event: "wantTrailers", listener: () => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prepe |
ndListener(event: "aborted", listener: () => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependListener(event: "drain", listener: () => void): this;
prependListener(event: "end", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "finish", listener: () => void): this;
prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
prependListener(event: "pipe", listener: (src: stream.Readable) => void): this;
prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
prependListener(event: "streamClosed", listener: (code: number) => void): this;
prependListener(event: "timeout", listener: () => void): this;
prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this;
prependListener(event: "wantTrailers", listener: () => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "aborted", listener: () => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependOnceListener(event: "drain", listener: () => void): this;
prependOnceListener(event: "end", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "finish", listener: () => void): this;
prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this;
prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this;
prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
prependOnceListener(event: "streamClosed", listener: (code: number) => void): this;
prependOnceListener(event: "timeout", listener: () => void): this;
prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this;
prependOnceListener(event: "wantTrailers", listener: () => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface ClientHttp2Stream extends Http2Stream {
addListener(event: "continue", listener: () => {}): this;
addListener(
event: "headers",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
): this;
addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
addListener(
event: "response",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "continue"): boolean;
emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean;
emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean;
emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "continue", listener: () => {}): this;
on(
event: "headers",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
): this;
on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
on(
event: "response",
lis |
tener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "continue", listener: () => {}): this;
once(
event: "headers",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
): this;
once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
once(
event: "response",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "continue", listener: () => {}): this;
prependListener(
event: "headers",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
): this;
prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
prependListener(
event: "response",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "continue", listener: () => {}): this;
prependOnceListener(
event: "headers",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
): this;
prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
prependOnceListener(
event: "response",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void,
): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface ServerHttp2Stream extends Http2Stream {
/**
* True if headers were sent, false otherwise (read-only).
* @since v8.4.0
*/
readonly headersSent: boolean;
/**
* Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote
* client's most recent `SETTINGS` frame. Will be `true` if the remote peer
* accepts push streams, `false` otherwise. Settings are the same for every`Http2Stream` in the same `Http2Session`.
* @since v8.4.0
*/
readonly pushAllowed: boolean;
/**
* Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer.
* @since v8.4.0
*/
additionalHeaders(headers: OutgoingHttpHeaders): void;
/**
* Initiates a push stream. The callback is invoked with the new `Http2Stream`instance created for the push stream passed as the second argument, or an`Error` passed as the first argument.
*
* ```js
* const http2 = require('node:http2');
* const server = http2.createServer();
* server.on('stream', (stream) => {
* stream.respond({ ':status': 200 });
* stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {
* if (err) throw err;
* pushStream.respond({ ':status': 200 });
* pushStream.end('some pushed data');
* });
* stream.end('some data');
* });
* ```
*
* Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass
* a `weight` value to `http2stream.priority` with the `silent` option set to`true` to enable server-side bandwidth balancing between concurrent streams.
*
* Calling `http2stream.pushStream()` from within a pushed stream is not permitted
* and will throw an error.
* @since v8.4.0
|
* @param callback Callback that is called once the push stream has been initiated.
*/
pushStream(
headers: OutgoingHttpHeaders,
callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void,
): void;
pushStream(
headers: OutgoingHttpHeaders,
options?: StreamPriorityOptions,
callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void,
): void;
/**
* ```js
* const http2 = require('node:http2');
* const server = http2.createServer();
* server.on('stream', (stream) => {
* stream.respond({ ':status': 200 });
* stream.end('some data');
* });
* ```
*
* Initiates a response. When the `options.waitForTrailers` option is set, the`'wantTrailers'` event will be emitted immediately after queuing the last chunk
* of payload data to be sent. The `http2stream.sendTrailers()` method can then be
* used to sent trailing header fields to the peer.
*
* When `options.waitForTrailers` is set, the `Http2Stream` will not automatically
* close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`.
*
* ```js
* const http2 = require('node:http2');
* const server = http2.createServer();
* server.on('stream', (stream) => {
* stream.respond({ ':status': 200 }, { waitForTrailers: true });
* stream.on('wantTrailers', () => {
* stream.sendTrailers({ ABC: 'some value to send' });
* });
* stream.end('some data');
* });
* ```
* @since v8.4.0
*/
respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void;
/**
* Initiates a response whose data is read from the given file descriptor. No
* validation is performed on the given file descriptor. If an error occurs while
* attempting to read data using the file descriptor, the `Http2Stream` will be
* closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code.
*
* When used, the `Http2Stream` object's `Duplex` interface will be closed
* automatically.
*
* ```js
* const http2 = require('node:http2');
* const fs = require('node:fs');
*
* const server = http2.createServer();
* server.on('stream', (stream) => {
* const fd = fs.openSync('/some/file', 'r');
*
* const stat = fs.fstatSync(fd);
* const headers = {
* 'content-length': stat.size,
* 'last-modified': stat.mtime.toUTCString(),
* 'content-type': 'text/plain; charset=utf-8',
* };
* stream.respondWithFD(fd, headers);
* stream.on('close', () => fs.closeSync(fd));
* });
* ```
*
* The optional `options.statCheck` function may be specified to give user code
* an opportunity to set additional content headers based on the `fs.Stat` details
* of the given fd. If the `statCheck` function is provided, the`http2stream.respondWithFD()` method will perform an `fs.fstat()` call to
* collect details on the provided file descriptor.
*
* The `offset` and `length` options may be used to limit the response to a
* specific range subset. This can be used, for instance, to support HTTP Range
* requests.
*
* The file descriptor or `FileHandle` is not closed when the stream is closed,
* so it will need to be closed manually once it is no longer needed.
* Using the same file descriptor concurrently for multiple streams
|
* is not supported and may result in data loss. Re-using a file descriptor
* after a stream has finished is supported.
*
* When the `options.waitForTrailers` option is set, the `'wantTrailers'` event
* will be emitted immediately after queuing the last chunk of payload data to be
* sent. The `http2stream.sendTrailers()` method can then be used to sent trailing
* header fields to the peer.
*
* When `options.waitForTrailers` is set, the `Http2Stream` will not automatically
* close when the final `DATA` frame is transmitted. User code _must_ call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`.
*
* ```js
* const http2 = require('node:http2');
* const fs = require('node:fs');
*
* const server = http2.createServer();
* server.on('stream', (stream) => {
* const fd = fs.openSync('/some/file', 'r');
*
* const stat = fs.fstatSync(fd);
* const headers = {
* 'content-length': stat.size,
* 'last-modified': stat.mtime.toUTCString(),
* 'content-type': 'text/plain; charset=utf-8',
* };
* stream.respondWithFD(fd, headers, { waitForTrailers: true });
* stream.on('wantTrailers', () => {
* stream.sendTrailers({ ABC: 'some value to send' });
* });
*
* stream.on('close', () => fs.closeSync(fd));
* });
* ```
* @since v8.4.0
* @param fd A readable file descriptor.
*/
respondWithFD(
fd: number | fs.promises.FileHandle,
headers?: OutgoingHttpHeaders,
options?: ServerStreamFileResponseOptions,
): void;
/**
* Sends a regular file as the response. The `path` must specify a regular file
* or an `'error'` event will be emitted on the `Http2Stream` object.
*
* When used, the `Http2Stream` object's `Duplex` interface will be closed
* automatically.
*
* The optional `options.statCheck` function may be specified to give user code
* an opportunity to set additional content headers based on the `fs.Stat` details
* of the given file:
*
* If an error occurs while attempting to read the file data, the `Http2Stream`will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR`code. If the `onError` callback is
* defined, then it will be called. Otherwise
* the stream will be destroyed.
*
* Example using a file path:
*
* ```js
* const http2 = require('node:http2');
* const server = http2.createServer();
* server.on('stream', (stream) => {
* function statCheck(stat, headers) {
* headers['last-modified'] = stat.mtime.toUTCString();
* }
*
* function onError(err) {
* // stream.respond() can throw if the stream has been destroyed by
* // the other side.
* try {
* if (err.code === 'ENOENT') {
* stream.respond({ ':status': 404 });
* } else {
* stream.respond({ ':status': 500 });
* }
* } catch (err) {
* // Perform actual error handling.
* console.error(err);
* }
* stream.end();
* }
*
* stream.respondWithFile('/some/file',
* { 'content-type': 'text/plain; charset=utf-8' },
* { statCheck, onError });
* });
* ```
*
* The `options.statCheck` function may also be used to cancel the send operation
* by returning `false`. For instance, a conditional request may check |
the stat
* results to determine if the file has been modified to return an appropriate`304` response:
*
* ```js
* const http2 = require('node:http2');
* const server = http2.createServer();
* server.on('stream', (stream) => {
* function statCheck(stat, headers) {
* // Check the stat here...
* stream.respond({ ':status': 304 });
* return false; // Cancel the send operation
* }
* stream.respondWithFile('/some/file',
* { 'content-type': 'text/plain; charset=utf-8' },
* { statCheck });
* });
* ```
*
* The `content-length` header field will be automatically set.
*
* The `offset` and `length` options may be used to limit the response to a
* specific range subset. This can be used, for instance, to support HTTP Range
* requests.
*
* The `options.onError` function may also be used to handle all the errors
* that could happen before the delivery of the file is initiated. The
* default behavior is to destroy the stream.
*
* When the `options.waitForTrailers` option is set, the `'wantTrailers'` event
* will be emitted immediately after queuing the last chunk of payload data to be
* sent. The `http2stream.sendTrailers()` method can then be used to sent trailing
* header fields to the peer.
*
* When `options.waitForTrailers` is set, the `Http2Stream` will not automatically
* close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`.
*
* ```js
* const http2 = require('node:http2');
* const server = http2.createServer();
* server.on('stream', (stream) => {
* stream.respondWithFile('/some/file',
* { 'content-type': 'text/plain; charset=utf-8' },
* { waitForTrailers: true });
* stream.on('wantTrailers', () => {
* stream.sendTrailers({ ABC: 'some value to send' });
* });
* });
* ```
* @since v8.4.0
*/
respondWithFile(
path: string,
headers?: OutgoingHttpHeaders,
options?: ServerStreamFileResponseOptionsWithError,
): void;
}
// Http2Session
export interface Settings {
headerTableSize?: number | undefined;
enablePush?: boolean | undefined;
initialWindowSize?: number | undefined;
maxFrameSize?: number | undefined;
maxConcurrentStreams?: number | undefined;
maxHeaderListSize?: number | undefined;
enableConnectProtocol?: boolean | undefined;
}
export interface ClientSessionRequestOptions {
endStream?: boolean | undefined;
exclusive?: boolean | undefined;
parent?: number | undefined;
weight?: number | undefined;
waitForTrailers?: boolean | undefined;
signal?: AbortSignal | undefined;
}
export interface SessionState {
effectiveLocalWindowSize?: number | undefined;
effectiveRecvDataLength?: number | undefined;
nextStreamID?: number | undefined;
localWindowSize?: number | undefined;
lastProcStreamID?: number | undefined;
remoteWindowSize?: number | undefined;
outboundQueueSize?: number | undefined;
deflateDynamicTableSize?: number | undefined;
inflateDynamicTableSize?: number | undefined;
}
export interface Http2Session extends EventEmitter {
/**
* Value will be `undefined` if the `Http2Session` is not yet connected to a
* socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or
* will re |
turn the value of the connected `TLSSocket`'s own `alpnProtocol`property.
* @since v9.4.0
*/
readonly alpnProtocol?: string | undefined;
/**
* Will be `true` if this `Http2Session` instance has been closed, otherwise`false`.
* @since v9.4.0
*/
readonly closed: boolean;
/**
* Will be `true` if this `Http2Session` instance is still connecting, will be set
* to `false` before emitting `connect` event and/or calling the `http2.connect`callback.
* @since v10.0.0
*/
readonly connecting: boolean;
/**
* Will be `true` if this `Http2Session` instance has been destroyed and must no
* longer be used, otherwise `false`.
* @since v8.4.0
*/
readonly destroyed: boolean;
/**
* Value is `undefined` if the `Http2Session` session socket has not yet been
* connected, `true` if the `Http2Session` is connected with a `TLSSocket`,
* and `false` if the `Http2Session` is connected to any other kind of socket
* or stream.
* @since v9.4.0
*/
readonly encrypted?: boolean | undefined;
/**
* A prototype-less object describing the current local settings of this`Http2Session`. The local settings are local to _this_`Http2Session` instance.
* @since v8.4.0
*/
readonly localSettings: Settings;
/**
* If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property
* will return an `Array` of origins for which the `Http2Session` may be
* considered authoritative.
*
* The `originSet` property is only available when using a secure TLS connection.
* @since v9.4.0
*/
readonly originSet?: string[] | undefined;
/**
* Indicates whether the `Http2Session` is currently waiting for acknowledgment of
* a sent `SETTINGS` frame. Will be `true` after calling the`http2session.settings()` method. Will be `false` once all sent `SETTINGS`frames have been acknowledged.
* @since v8.4.0
*/
readonly pendingSettingsAck: boolean;
/**
* A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer.
* @since v8.4.0
*/
readonly remoteSettings: Settings;
/**
* Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but
* limits available methods to ones safe to use with HTTP/2.
*
* `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw
* an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information.
*
* `setTimeout` method will be called on this `Http2Session`.
*
* All other interactions will be routed directly to the socket.
* @since v8.4.0
*/
readonly socket: net.Socket | tls.TLSSocket;
/**
* Provides miscellaneous information about the current state of the`Http2Session`.
*
* An object describing the current status of this `Http2Session`.
* @since v8.4.0
*/
readonly state: SessionState;
/**
* The `http2session.type` will be equal to`http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a
* server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a
* client.
* @since v8.4.0
*/
readonly type: number;
/**
* Gracefully closes the `Http2Session`, allowing any existing streams to
* complete on their own and preventing new `Http2Stream` instances from being
* created. Once closed, `http2session.destroy()`_might_ be called if there
* are no open `Http2Stream |
` instances.
*
* If specified, the `callback` function is registered as a handler for the`'close'` event.
* @since v9.4.0
*/
close(callback?: () => void): void;
/**
* Immediately terminates the `Http2Session` and the associated `net.Socket` or`tls.TLSSocket`.
*
* Once destroyed, the `Http2Session` will emit the `'close'` event. If `error`is not undefined, an `'error'` event will be emitted immediately before the`'close'` event.
*
* If there are any remaining open `Http2Streams` associated with the`Http2Session`, those will also be destroyed.
* @since v8.4.0
* @param error An `Error` object if the `Http2Session` is being destroyed due to an error.
* @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`.
*/
destroy(error?: Error, code?: number): void;
/**
* Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`.
* @since v9.4.0
* @param code An HTTP/2 error code
* @param lastStreamID The numeric ID of the last processed `Http2Stream`
* @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame.
*/
goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void;
/**
* Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must
* be provided. The method will return `true` if the `PING` was sent, `false`otherwise.
*
* The maximum number of outstanding (unacknowledged) pings is determined by the`maxOutstandingPings` configuration option. The default maximum is 10.
*
* If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView`containing 8 bytes of data that will be transmitted with the `PING` and
* returned with the ping acknowledgment.
*
* The callback will be invoked with three arguments: an error argument that will
* be `null` if the `PING` was successfully acknowledged, a `duration` argument
* that reports the number of milliseconds elapsed since the ping was sent and the
* acknowledgment was received, and a `Buffer` containing the 8-byte `PING`payload.
*
* ```js
* session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {
* if (!err) {
* console.log(`Ping acknowledged in ${duration} milliseconds`);
* console.log(`With payload '${payload.toString()}'`);
* }
* });
* ```
*
* If the `payload` argument is not specified, the default payload will be the
* 64-bit timestamp (little endian) marking the start of the `PING` duration.
* @since v8.9.3
* @param payload Optional ping payload.
*/
ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean;
ping(
payload: NodeJS.ArrayBufferView,
callback: (err: Error | null, duration: number, payload: Buffer) => void,
): boolean;
/**
* Calls `ref()` on this `Http2Session`instance's underlying `net.Socket`.
* @since v9.4.0
*/
ref(): void;
/**
* Sets the local endpoint's window size.
* The `windowSize` is the total window size to set, not
* the delta.
*
* ```js
* const http2 = require('node:http2');
*
* const server = http2.createServer();
* const expectedWindowSize = 2 ** 20;
* server.on('connect', (session) => {
*
* // Set local window size to be 2 ** 20
* session.setLocalWindowSize(expectedWindowS |
ize);
* });
* ```
* @since v15.3.0, v14.18.0
*/
setLocalWindowSize(windowSize: number): void;
/**
* Used to set a callback function that is called when there is no activity on
* the `Http2Session` after `msecs` milliseconds. The given `callback` is
* registered as a listener on the `'timeout'` event.
* @since v8.4.0
*/
setTimeout(msecs: number, callback?: () => void): void;
/**
* Updates the current local settings for this `Http2Session` and sends a new`SETTINGS` frame to the connected HTTP/2 peer.
*
* Once called, the `http2session.pendingSettingsAck` property will be `true`while the session is waiting for the remote peer to acknowledge the new
* settings.
*
* The new settings will not become effective until the `SETTINGS` acknowledgment
* is received and the `'localSettings'` event is emitted. It is possible to send
* multiple `SETTINGS` frames while acknowledgment is still pending.
* @since v8.4.0
* @param callback Callback that is called once the session is connected or right away if the session is already connected.
*/
settings(
settings: Settings,
callback?: (err: Error | null, settings: Settings, duration: number) => void,
): void;
/**
* Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`.
* @since v9.4.0
*/
unref(): void;
addListener(event: "close", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(
event: "frameError",
listener: (frameType: number, errorCode: number, streamID: number) => void,
): this;
addListener(
event: "goaway",
listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void,
): this;
addListener(event: "localSettings", listener: (settings: Settings) => void): this;
addListener(event: "ping", listener: () => void): this;
addListener(event: "remoteSettings", listener: (settings: Settings) => void): this;
addListener(event: "timeout", listener: () => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "close"): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean;
emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean;
emit(event: "localSettings", settings: Settings): boolean;
emit(event: "ping"): boolean;
emit(event: "remoteSettings", settings: Settings): boolean;
emit(event: "timeout"): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "close", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this;
on(event: "localSettings", listener: (settings: Settings) => void): this;
on(event: "ping", listener: () => void): this;
on(event: "remoteSettings", listener: (settings: Settings) => void): this;
on(event: "timeout", listener: () => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
once(event: "goaway", listener: (errorCode: |
number, lastStreamID: number, opaqueData?: Buffer) => void): this;
once(event: "localSettings", listener: (settings: Settings) => void): this;
once(event: "ping", listener: () => void): this;
once(event: "remoteSettings", listener: (settings: Settings) => void): this;
once(event: "timeout", listener: () => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(
event: "frameError",
listener: (frameType: number, errorCode: number, streamID: number) => void,
): this;
prependListener(
event: "goaway",
listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void,
): this;
prependListener(event: "localSettings", listener: (settings: Settings) => void): this;
prependListener(event: "ping", listener: () => void): this;
prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this;
prependListener(event: "timeout", listener: () => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(
event: "frameError",
listener: (frameType: number, errorCode: number, streamID: number) => void,
): this;
prependOnceListener(
event: "goaway",
listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void,
): this;
prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this;
prependOnceListener(event: "ping", listener: () => void): this;
prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this;
prependOnceListener(event: "timeout", listener: () => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface ClientHttp2Session extends Http2Session {
/**
* For HTTP/2 Client `Http2Session` instances only, the `http2session.request()`creates and returns an `Http2Stream` instance that can be used to send an
* HTTP/2 request to the connected server.
*
* When a `ClientHttp2Session` is first created, the socket may not yet be
* connected. if `clienthttp2session.request()` is called during this time, the
* actual request will be deferred until the socket is ready to go.
* If the `session` is closed before the actual request be executed, an`ERR_HTTP2_GOAWAY_SESSION` is thrown.
*
* This method is only available if `http2session.type` is equal to`http2.constants.NGHTTP2_SESSION_CLIENT`.
*
* ```js
* const http2 = require('node:http2');
* const clientSession = http2.connect('https://localhost:1234');
* const {
* HTTP2_HEADER_PATH,
* HTTP2_HEADER_STATUS,
* } = http2.constants;
*
* const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });
* req.on('response', (headers) => {
* console.log(headers[HTTP2_HEADER_STATUS]);
* req.on('data', (chunk) => { // .. });
* req.on('end', () => { // .. });
* });
* ```
*
* When the `options.waitForTrailers` option is set, the `'wantTrailers'` event
* is emitted immediately after queuing the last chunk of payload data to be sent.
* The `http2stream.sendTrailers()` method can then be called to send trailing
* headers to the peer.
*
* When `options.waitForTrai |
lers` is set, the `Http2Stream` will not automatically
* close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`.
*
* When `options.signal` is set with an `AbortSignal` and then `abort` on the
* corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error.
*
* The `:method` and `:path` pseudo-headers are not specified within `headers`,
* they respectively default to:
*
* * `:method` \= `'GET'`
* * `:path` \= `/`
* @since v8.4.0
*/
request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream;
addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
addListener(event: "origin", listener: (origins: string[]) => void): this;
addListener(
event: "connect",
listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
): this;
addListener(
event: "stream",
listener: (
stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
) => void,
): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "altsvc", alt: string, origin: string, stream: number): boolean;
emit(event: "origin", origins: readonly string[]): boolean;
emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean;
emit(
event: "stream",
stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
on(event: "origin", listener: (origins: string[]) => void): this;
on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
on(
event: "stream",
listener: (
stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
) => void,
): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
once(event: "origin", listener: (origins: string[]) => void): this;
once(
event: "connect",
listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
): this;
once(
event: "stream",
listener: (
stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
) => void,
): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
prependListener(event: "origin", listener: (origins: string[]) => void): this;
prependListener(
event: "connect",
listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
): this;
prependListener(
event: "stream",
listener: (
stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
) => void,
): this;
prependListener(event: string | symbol, |
listener: (...args: any[]) => void): this;
prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
prependOnceListener(event: "origin", listener: (origins: string[]) => void): this;
prependOnceListener(
event: "connect",
listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
): this;
prependOnceListener(
event: "stream",
listener: (
stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
) => void,
): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface AlternativeServiceOptions {
origin: number | string | url.URL;
}
export interface ServerHttp2Session extends Http2Session {
readonly server: Http2Server | Http2SecureServer;
/**
* Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client.
*
* ```js
* const http2 = require('node:http2');
*
* const server = http2.createServer();
* server.on('session', (session) => {
* // Set altsvc for origin https://example.org:80
* session.altsvc('h2=":8000"', 'https://example.org:80');
* });
*
* server.on('stream', (stream) => {
* // Set altsvc for a specific stream
* stream.session.altsvc('h2=":8000"', stream.id);
* });
* ```
*
* Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate
* service is associated with the origin of the given `Http2Stream`.
*
* The `alt` and origin string _must_ contain only ASCII bytes and are
* strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given
* domain.
*
* When a string is passed for the `originOrStream` argument, it will be parsed as
* a URL and the origin will be derived. For instance, the origin for the
* HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string
* cannot be parsed as a URL or if a valid origin cannot be derived.
*
* A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be
* used. The value of the `origin` property _must_ be a properly serialized
* ASCII origin.
* @since v9.4.0
* @param alt A description of the alternative service configuration as defined by `RFC 7838`.
* @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the
* `http2stream.id` property.
*/
altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void;
/**
* Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client
* to advertise the set of origins for which the server is capable of providing
* authoritative responses.
*
* ```js
* const http2 = require('node:http2');
* const options = getSecureOptionsSomehow();
* const server = http2.createSecureServer(options);
* server.on('stream', (stream) => {
* stream.respond();
* stream.end('ok');
* });
* server.on('session', (session) => {
* session.origin('https://example.com', 'https://example.org');
* });
|
* ```
*
* When a string is passed as an `origin`, it will be parsed as a URL and the
* origin will be derived. For instance, the origin for the HTTP URL`'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given
* string
* cannot be parsed as a URL or if a valid origin cannot be derived.
*
* A `URL` object, or any object with an `origin` property, may be passed as
* an `origin`, in which case the value of the `origin` property will be
* used. The value of the `origin` property _must_ be a properly serialized
* ASCII origin.
*
* Alternatively, the `origins` option may be used when creating a new HTTP/2
* server using the `http2.createSecureServer()` method:
*
* ```js
* const http2 = require('node:http2');
* const options = getSecureOptionsSomehow();
* options.origins = ['https://example.com', 'https://example.org'];
* const server = http2.createSecureServer(options);
* server.on('stream', (stream) => {
* stream.respond();
* stream.end('ok');
* });
* ```
* @since v10.12.0
* @param origins One or more URL Strings passed as separate arguments.
*/
origin(
...origins: Array<
| string
| url.URL
| {
origin: string;
}
>
): void;
addListener(
event: "connect",
listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
): this;
addListener(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean;
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this;
on(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(
event: "connect",
listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
): this;
once(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(
event: "connect",
listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
): this;
prependListener(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(
event: "connect",
listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void,
): this;
prependOnceListener(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
// Http2Server
export interface SessionOptions {
maxDefl |
ateDynamicTableSize?: number | undefined;
maxSessionMemory?: number | undefined;
maxHeaderListPairs?: number | undefined;
maxOutstandingPings?: number | undefined;
maxSendHeaderBlockLength?: number | undefined;
paddingStrategy?: number | undefined;
peerMaxConcurrentStreams?: number | undefined;
settings?: Settings | undefined;
/**
* Specifies a timeout in milliseconds that
* a server should wait when an [`'unknownProtocol'`][] is emitted. If the
* socket has not been destroyed by that time the server will destroy it.
* @default 100000
*/
unknownProtocolTimeout?: number | undefined;
selectPadding?(frameLen: number, maxFrameLen: number): number;
}
export interface ClientSessionOptions extends SessionOptions {
maxReservedRemoteStreams?: number | undefined;
createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined;
protocol?: "http:" | "https:" | undefined;
}
export interface ServerSessionOptions extends SessionOptions {
Http1IncomingMessage?: typeof IncomingMessage | undefined;
Http1ServerResponse?: typeof ServerResponse | undefined;
Http2ServerRequest?: typeof Http2ServerRequest | undefined;
Http2ServerResponse?: typeof Http2ServerResponse | undefined;
}
export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {}
export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {}
export interface ServerOptions extends ServerSessionOptions {}
export interface SecureServerOptions extends SecureServerSessionOptions {
allowHTTP1?: boolean | undefined;
origins?: string[] | undefined;
}
interface HTTP2ServerCommon {
setTimeout(msec?: number, callback?: () => void): this;
/**
* Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values.
* Throws ERR_INVALID_ARG_TYPE for invalid settings argument.
*/
updateSettings(settings: Settings): void;
}
export interface Http2Server extends net.Server, HTTP2ServerCommon {
addListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
addListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
addListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
addListener(event: "sessionError", listener: (err: Error) => void): this;
addListener(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
addListener(event: "timeout", listener: () => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
emit(event: "session", session: ServerHttp2Session): boolean;
emit(event: "sessionError", err: Error): boolean;
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean;
emit(event: "timeout"): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
on(event: "session", listener: (session: ServerHttp2Session) => void): this;
on(event: "ses |
sionError", listener: (err: Error) => void): this;
on(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
on(event: "timeout", listener: () => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
once(event: "session", listener: (session: ServerHttp2Session) => void): this;
once(event: "sessionError", listener: (err: Error) => void): this;
once(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
once(event: "timeout", listener: () => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
prependListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
prependListener(event: "sessionError", listener: (err: Error) => void): this;
prependListener(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
prependListener(event: "timeout", listener: () => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
prependOnceListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
prependOnceListener(event: "sessionError", listener: (err: Error) => void): this;
prependOnceListener(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
prependOnceListener(event: "timeout", listener: () => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon {
addListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
addListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
addListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
addListener(event: "sessionError", listener: (err: Error) => void): this;
addListener(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
addListener(event: "timeout", listener: () => void): this;
addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean;
emit(event: "request", request: Http2ServerRequ |
est, response: Http2ServerResponse): boolean;
emit(event: "session", session: ServerHttp2Session): boolean;
emit(event: "sessionError", err: Error): boolean;
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean;
emit(event: "timeout"): boolean;
emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
on(event: "session", listener: (session: ServerHttp2Session) => void): this;
on(event: "sessionError", listener: (err: Error) => void): this;
on(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
on(event: "timeout", listener: () => void): this;
on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this;
once(event: "session", listener: (session: ServerHttp2Session) => void): this;
once(event: "sessionError", listener: (err: Error) => void): this;
once(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
once(event: "timeout", listener: () => void): this;
once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
prependListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
prependListener(event: "sessionError", listener: (err: Error) => void): this;
prependListener(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
prependListener(event: "timeout", listener: () => void): this;
prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(
event: "checkContinue",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
prependOnceListener(
event: "request",
listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): this;
prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this;
prependOnceListener(event: "sessionError", listener: (err: Error) => void): this;
prependOnceListener(
event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void,
): this;
prependOnceListener(event: "timeout", listener: () => void): this;
prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this;
prependOnceListener(event: string | |
symbol, listener: (...args: any[]) => void): this;
}
/**
* A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status,
* headers, and
* data.
* @since v8.4.0
*/
export class Http2ServerRequest extends stream.Readable {
constructor(
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
options: stream.ReadableOptions,
rawHeaders: readonly string[],
);
/**
* The `request.aborted` property will be `true` if the request has
* been aborted.
* @since v10.1.0
*/
readonly aborted: boolean;
/**
* The request authority pseudo header field. Because HTTP/2 allows requests
* to set either `:authority` or `host`, this value is derived from`req.headers[':authority']` if present. Otherwise, it is derived from`req.headers['host']`.
* @since v8.4.0
*/
readonly authority: string;
/**
* See `request.socket`.
* @since v8.4.0
* @deprecated Since v13.0.0 - Use `socket`.
*/
readonly connection: net.Socket | tls.TLSSocket;
/**
* The `request.complete` property will be `true` if the request has
* been completed, aborted, or destroyed.
* @since v12.10.0
*/
readonly complete: boolean;
/**
* The request/response headers object.
*
* Key-value pairs of header names and values. Header names are lower-cased.
*
* ```js
* // Prints something like:
* //
* // { 'user-agent': 'curl/7.22.0',
* // host: '127.0.0.1:8000',
* // accept: '*' }
* console.log(request.headers);
* ```
*
* See `HTTP/2 Headers Object`.
*
* In HTTP/2, the request path, host name, protocol, and method are represented as
* special headers prefixed with the `:` character (e.g. `':path'`). These special
* headers will be included in the `request.headers` object. Care must be taken not
* to inadvertently modify these special headers or errors may occur. For instance,
* removing all headers from the request will cause errors to occur:
*
* ```js
* removeAllHeaders(request.headers);
* assert(request.url); // Fails because the :path header has been removed
* ```
* @since v8.4.0
*/
readonly headers: IncomingHttpHeaders;
/**
* In case of server request, the HTTP version sent by the client. In the case of
* client response, the HTTP version of the connected-to server. Returns`'2.0'`.
*
* Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second.
* @since v8.4.0
*/
readonly httpVersion: string;
readonly httpVersionMinor: number;
readonly httpVersionMajor: number;
/**
* The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`.
* @since v8.4.0
*/
readonly method: string;
/**
* The raw request/response headers list exactly as they were received.
*
* The keys and values are in the same list. It is _not_ a
* list of tuples. So, the even-numbered offsets are key values, and the
* odd-numbered offsets are the associated values.
*
* Header names are not lowercased, and duplicates are not merged.
*
* ```js
* // Prints something like:
* //
* // [ 'user-agent',
* // 'this is invalid because there can be only one',
* // 'User-Agent',
* // 'curl/7.22.0',
* // 'Host',
* // '127.0.0. |
1:8000',
* // 'ACCEPT',
* // '*' ]
* console.log(request.rawHeaders);
* ```
* @since v8.4.0
*/
readonly rawHeaders: string[];
/**
* The raw request/response trailer keys and values exactly as they were
* received. Only populated at the `'end'` event.
* @since v8.4.0
*/
readonly rawTrailers: string[];
/**
* The request scheme pseudo header field indicating the scheme
* portion of the target URL.
* @since v8.4.0
*/
readonly scheme: string;
/**
* Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but
* applies getters, setters, and methods based on HTTP/2 logic.
*
* `destroyed`, `readable`, and `writable` properties will be retrieved from and
* set on `request.stream`.
*
* `destroy`, `emit`, `end`, `on` and `once` methods will be called on`request.stream`.
*
* `setTimeout` method will be called on `request.stream.session`.
*
* `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for
* more information.
*
* All other interactions will be routed directly to the socket. With TLS support,
* use `request.socket.getPeerCertificate()` to obtain the client's
* authentication details.
* @since v8.4.0
*/
readonly socket: net.Socket | tls.TLSSocket;
/**
* The `Http2Stream` object backing the request.
* @since v8.4.0
*/
readonly stream: ServerHttp2Stream;
/**
* The request/response trailers object. Only populated at the `'end'` event.
* @since v8.4.0
*/
readonly trailers: IncomingHttpHeaders;
/**
* Request URL string. This contains only the URL that is present in the actual
* HTTP request. If the request is:
*
* ```http
* GET /status?name=ryan HTTP/1.1
* Accept: text/plain
* ```
*
* Then `request.url` will be:
*
* ```js
* '/status?name=ryan'
* ```
*
* To parse the url into its parts, `new URL()` can be used:
*
* ```console
* $ node
* > new URL('/status?name=ryan', 'http://example.com')
* URL {
* href: 'http://example.com/status?name=ryan',
* origin: 'http://example.com',
* protocol: 'http:',
* username: '',
* password: '',
* host: 'example.com',
* hostname: 'example.com',
* port: '',
* pathname: '/status',
* search: '?name=ryan',
* searchParams: URLSearchParams { 'name' => 'ryan' },
* hash: ''
* }
* ```
* @since v8.4.0
*/
url: string;
/**
* Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is
* provided, then it is added as a listener on the `'timeout'` event on
* the response object.
*
* If no `'timeout'` listener is added to the request, the response, or
* the server, then `Http2Stream` s are destroyed when they time out. If a
* handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly.
* @since v8.4.0
*/
setTimeout(msecs: number, callback?: () => void): void;
read(size?: number): Buffer | string | null;
addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "data", listener: (chunk: Buffer | string) => void): this;
addListen |
er(event: "end", listener: () => void): this;
addListener(event: "readable", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "aborted", hadError: boolean, code: number): boolean;
emit(event: "close"): boolean;
emit(event: "data", chunk: Buffer | string): boolean;
emit(event: "end"): boolean;
emit(event: "readable"): boolean;
emit(event: "error", err: Error): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
on(event: "close", listener: () => void): this;
on(event: "data", listener: (chunk: Buffer | string) => void): this;
on(event: "end", listener: () => void): this;
on(event: "readable", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
once(event: "close", listener: () => void): this;
once(event: "data", listener: (chunk: Buffer | string) => void): this;
once(event: "end", listener: () => void): this;
once(event: "readable", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependListener(event: "end", listener: () => void): this;
prependListener(event: "readable", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this;
prependOnceListener(event: "end", listener: () => void): this;
prependOnceListener(event: "readable", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
/**
* This object is created internally by an HTTP server, not by the user. It is
* passed as the second parameter to the `'request'` event.
* @since v8.4.0
*/
export class Http2ServerResponse extends stream.Writable {
constructor(stream: ServerHttp2Stream);
/**
* See `response.socket`.
* @since v8.4.0
* @deprecated Since v13.0.0 - Use `socket`.
*/
readonly connection: net.Socket | tls.TLSSocket;
/**
* Boolean value that indicates whether the response has completed. Starts
* as `false`. After `response.end()` executes, the value will be `true`.
* @since v8.4.0
* @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`.
*/
readonly finished: boolean;
/**
* True if headers were sent, false otherwise (read-only).
* @since v8.4.0
*/
readonly headersSent: boolean;
/**
* A reference to the original HTTP2 `request` object.
* @since v15.7.0
*/
readonly req: Http2ServerRequest;
/**
* Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocke |
t`) but
* applies getters, setters, and methods based on HTTP/2 logic.
*
* `destroyed`, `readable`, and `writable` properties will be retrieved from and
* set on `response.stream`.
*
* `destroy`, `emit`, `end`, `on` and `once` methods will be called on`response.stream`.
*
* `setTimeout` method will be called on `response.stream.session`.
*
* `pause`, `read`, `resume`, and `write` will throw an error with code`ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for
* more information.
*
* All other interactions will be routed directly to the socket.
*
* ```js
* const http2 = require('node:http2');
* const server = http2.createServer((req, res) => {
* const ip = req.socket.remoteAddress;
* const port = req.socket.remotePort;
* res.end(`Your IP address is ${ip} and your source port is ${port}.`);
* }).listen(3000);
* ```
* @since v8.4.0
*/
readonly socket: net.Socket | tls.TLSSocket;
/**
* The `Http2Stream` object backing the response.
* @since v8.4.0
*/
readonly stream: ServerHttp2Stream;
/**
* When true, the Date header will be automatically generated and sent in
* the response if it is not already present in the headers. Defaults to true.
*
* This should only be disabled for testing; HTTP requires the Date header
* in responses.
* @since v8.4.0
*/
sendDate: boolean;
/**
* When using implicit headers (not calling `response.writeHead()` explicitly),
* this property controls the status code that will be sent to the client when
* the headers get flushed.
*
* ```js
* response.statusCode = 404;
* ```
*
* After response header was sent to the client, this property indicates the
* status code which was sent out.
* @since v8.4.0
*/
statusCode: number;
/**
* Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns
* an empty string.
* @since v8.4.0
*/
statusMessage: "";
/**
* This method adds HTTP trailing headers (a header but at the end of the
* message) to the response.
*
* Attempting to set a header field name or value that contains invalid characters
* will result in a `TypeError` being thrown.
* @since v8.4.0
*/
addTrailers(trailers: OutgoingHttpHeaders): void;
/**
* This method signals to the server that all of the response headers and body
* have been sent; that server should consider this message complete.
* The method, `response.end()`, MUST be called on each response.
*
* If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`.
*
* If `callback` is specified, it will be called when the response stream
* is finished.
* @since v8.4.0
*/
end(callback?: () => void): this;
end(data: string | Uint8Array, callback?: () => void): this;
end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this;
/**
* Reads out a header that has already been queued but not sent to the client.
* The name is case-insensitive.
*
* ```js
* const contentType = response.getHeader('content-type');
* ```
* @since v8.4.0
*/
getHeader(name: string): string;
/**
* Returns an array containing the unique names of the current outgoing headers.
* All header names are lowercase.
*
* ```js
* re |
sponse.setHeader('Foo', 'bar');
* response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
*
* const headerNames = response.getHeaderNames();
* // headerNames === ['foo', 'set-cookie']
* ```
* @since v8.4.0
*/
getHeaderNames(): string[];
/**
* Returns a shallow copy of the current outgoing headers. Since a shallow copy
* is used, array values may be mutated without additional calls to various
* header-related http module methods. The keys of the returned object are the
* header names and the values are the respective header values. All header names
* are lowercase.
*
* The object returned by the `response.getHeaders()` method _does not_prototypically inherit from the JavaScript `Object`. This means that typical`Object` methods such as `obj.toString()`,
* `obj.hasOwnProperty()`, and others
* are not defined and _will not work_.
*
* ```js
* response.setHeader('Foo', 'bar');
* response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
*
* const headers = response.getHeaders();
* // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
* ```
* @since v8.4.0
*/
getHeaders(): OutgoingHttpHeaders;
/**
* Returns `true` if the header identified by `name` is currently set in the
* outgoing headers. The header name matching is case-insensitive.
*
* ```js
* const hasContentType = response.hasHeader('content-type');
* ```
* @since v8.4.0
*/
hasHeader(name: string): boolean;
/**
* Removes a header that has been queued for implicit sending.
*
* ```js
* response.removeHeader('Content-Encoding');
* ```
* @since v8.4.0
*/
removeHeader(name: string): void;
/**
* Sets a single header value for implicit headers. If this header already exists
* in the to-be-sent headers, its value will be replaced. Use an array of strings
* here to send multiple headers with the same name.
*
* ```js
* response.setHeader('Content-Type', 'text/html; charset=utf-8');
* ```
*
* or
*
* ```js
* response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
* ```
*
* Attempting to set a header field name or value that contains invalid characters
* will result in a `TypeError` being thrown.
*
* When headers have been set with `response.setHeader()`, they will be merged
* with any headers passed to `response.writeHead()`, with the headers passed
* to `response.writeHead()` given precedence.
*
* ```js
* // Returns content-type = text/plain
* const server = http2.createServer((req, res) => {
* res.setHeader('Content-Type', 'text/html; charset=utf-8');
* res.setHeader('X-Foo', 'bar');
* res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
* res.end('ok');
* });
* ```
* @since v8.4.0
*/
setHeader(name: string, value: number | string | readonly string[]): void;
/**
* Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is
* provided, then it is added as a listener on the `'timeout'` event on
* the response object.
*
* If no `'timeout'` listener is added to the request, the response, or
* the server, then `Http2Stream` s are destroyed when they time out. If a
* handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly.
* @since v8.4.0
*/
setTi |
meout(msecs: number, callback?: () => void): void;
/**
* If this method is called and `response.writeHead()` has not been called,
* it will switch to implicit header mode and flush the implicit headers.
*
* This sends a chunk of the response body. This method may
* be called multiple times to provide successive parts of the body.
*
* In the `node:http` module, the response body is omitted when the
* request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body.
*
* `chunk` can be a string or a buffer. If `chunk` is a string,
* the second parameter specifies how to encode it into a byte stream.
* By default the `encoding` is `'utf8'`. `callback` will be called when this chunk
* of data is flushed.
*
* This is the raw HTTP body and has nothing to do with higher-level multi-part
* body encodings that may be used.
*
* The first time `response.write()` is called, it will send the buffered
* header information and the first chunk of the body to the client. The second
* time `response.write()` is called, Node.js assumes data will be streamed,
* and sends the new data separately. That is, the response is buffered up to the
* first chunk of the body.
*
* Returns `true` if the entire data was flushed successfully to the kernel
* buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again.
* @since v8.4.0
*/
write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean;
write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean;
/**
* Sends a status `100 Continue` to the client, indicating that the request body
* should be sent. See the `'checkContinue'` event on `Http2Server` and`Http2SecureServer`.
* @since v8.4.0
*/
writeContinue(): void;
/**
* Sends a status `103 Early Hints` to the client with a Link header,
* indicating that the user agent can preload/preconnect the linked resources.
* The `hints` is an object containing the values of headers to be sent with
* early hints message.
*
* **Example**
*
* ```js
* const earlyHintsLink = '</styles.css>; rel=preload; as=style';
* response.writeEarlyHints({
* 'link': earlyHintsLink,
* });
*
* const earlyHintsLinks = [
* '</styles.css>; rel=preload; as=style',
* '</scripts.js>; rel=preload; as=script',
* ];
* response.writeEarlyHints({
* 'link': earlyHintsLinks,
* });
* ```
* @since v18.11.0
*/
writeEarlyHints(hints: Record<string, string | string[]>): void;
/**
* Sends a response header to the request. The status code is a 3-digit HTTP
* status code, like `404`. The last argument, `headers`, are the response headers.
*
* Returns a reference to the `Http2ServerResponse`, so that calls can be chained.
*
* For compatibility with `HTTP/1`, a human-readable `statusMessage` may be
* passed as the second argument. However, because the `statusMessage` has no
* meaning within HTTP/2, the argument will have no effect and a process warning
* will be emitted.
*
* ```js
* const body = 'hello world';
* response.writeHead(200, {
* 'Content-Length': Buffer.byteLength(body),
* 'Content-Type': 'text/plain; charset=utf-8',
* });
* ```
*
* `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be |
used to determine the number of bytes in a
* given encoding. On outbound messages, Node.js does not check if Content-Length
* and the length of the body being transmitted are equal or not. However, when
* receiving messages, Node.js will automatically reject messages when the`Content-Length` does not match the actual payload size.
*
* This method may be called at most one time on a message before `response.end()` is called.
*
* If `response.write()` or `response.end()` are called before calling
* this, the implicit/mutable headers will be calculated and call this function.
*
* When headers have been set with `response.setHeader()`, they will be merged
* with any headers passed to `response.writeHead()`, with the headers passed
* to `response.writeHead()` given precedence.
*
* ```js
* // Returns content-type = text/plain
* const server = http2.createServer((req, res) => {
* res.setHeader('Content-Type', 'text/html; charset=utf-8');
* res.setHeader('X-Foo', 'bar');
* res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
* res.end('ok');
* });
* ```
*
* Attempting to set a header field name or value that contains invalid characters
* will result in a `TypeError` being thrown.
* @since v8.4.0
*/
writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this;
writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this;
/**
* Call `http2stream.pushStream()` with the given headers, and wrap the
* given `Http2Stream` on a newly created `Http2ServerResponse` as the callback
* parameter if successful. When `Http2ServerRequest` is closed, the callback is
* called with an error `ERR_HTTP2_INVALID_STREAM`.
* @since v8.4.0
* @param headers An object describing the headers
* @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of
* `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method
*/
createPushResponse(
headers: OutgoingHttpHeaders,
callback: (err: Error | null, res: Http2ServerResponse) => void,
): void;
addListener(event: "close", listener: () => void): this;
addListener(event: "drain", listener: () => void): this;
addListener(event: "error", listener: (error: Error) => void): this;
addListener(event: "finish", listener: () => void): this;
addListener(event: "pipe", listener: (src: stream.Readable) => void): this;
addListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "close"): boolean;
emit(event: "drain"): boolean;
emit(event: "error", error: Error): boolean;
emit(event: "finish"): boolean;
emit(event: "pipe", src: stream.Readable): boolean;
emit(event: "unpipe", src: stream.Readable): boolean;
emit(event: string | symbol, ...args: any[]): boolean;
on(event: "close", listener: () => void): this;
on(event: "drain", listener: () => void): this;
on(event: "error", listener: (error: Error) => void): this;
on(event: "finish", listener: () => void): this;
on(event: "pipe", listener: (src: stream.Readable) => void): this;
on(event: "unpipe", listener: (src: stream.Readable) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "drain", listener: () => void): this;
|
once(event: "error", listener: (error: Error) => void): this;
once(event: "finish", listener: () => void): this;
once(event: "pipe", listener: (src: stream.Readable) => void): this;
once(event: "unpipe", listener: (src: stream.Readable) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "drain", listener: () => void): this;
prependListener(event: "error", listener: (error: Error) => void): this;
prependListener(event: "finish", listener: () => void): this;
prependListener(event: "pipe", listener: (src: stream.Readable) => void): this;
prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "drain", listener: () => void): this;
prependOnceListener(event: "error", listener: (error: Error) => void): this;
prependOnceListener(event: "finish", listener: () => void): this;
prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this;
prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
export namespace constants {
const NGHTTP2_SESSION_SERVER: number;
const NGHTTP2_SESSION_CLIENT: number;
const NGHTTP2_STREAM_STATE_IDLE: number;
const NGHTTP2_STREAM_STATE_OPEN: number;
const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number;
const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number;
const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number;
const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number;
const NGHTTP2_STREAM_STATE_CLOSED: number;
const NGHTTP2_NO_ERROR: number;
const NGHTTP2_PROTOCOL_ERROR: number;
const NGHTTP2_INTERNAL_ERROR: number;
const NGHTTP2_FLOW_CONTROL_ERROR: number;
const NGHTTP2_SETTINGS_TIMEOUT: number;
const NGHTTP2_STREAM_CLOSED: number;
const NGHTTP2_FRAME_SIZE_ERROR: number;
const NGHTTP2_REFUSED_STREAM: number;
const NGHTTP2_CANCEL: number;
const NGHTTP2_COMPRESSION_ERROR: number;
const NGHTTP2_CONNECT_ERROR: number;
const NGHTTP2_ENHANCE_YOUR_CALM: number;
const NGHTTP2_INADEQUATE_SECURITY: number;
const NGHTTP2_HTTP_1_1_REQUIRED: number;
const NGHTTP2_ERR_FRAME_SIZE_ERROR: number;
const NGHTTP2_FLAG_NONE: number;
const NGHTTP2_FLAG_END_STREAM: number;
const NGHTTP2_FLAG_END_HEADERS: number;
const NGHTTP2_FLAG_ACK: number;
const NGHTTP2_FLAG_PADDED: number;
const NGHTTP2_FLAG_PRIORITY: number;
const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number;
const DEFAULT_SETTINGS_ENABLE_PUSH: number;
const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number;
const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number;
const MAX_MAX_FRAME_SIZE: number;
const MIN_MAX_FRAME_SIZE: number;
const MAX_INITIAL_WINDOW_SIZE: number;
const NGHTTP2_DEFAULT_WEIGHT: number;
const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number;
const NGHTTP2_SETTINGS_ENABLE_PUSH: number;
const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number;
const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number;
const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number;
const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number;
const PADDING_STRATEGY_NONE: number;
const PADDING_STRATEGY_MAX: number;
const PADDING_STRATEGY_CALLBACK: number;
const HTTP2_HEADER_STATUS: string;
const HTTP2_HEADER_METHOD: string;
const HTTP2_HEADER_A |
UTHORITY: string;
const HTTP2_HEADER_SCHEME: string;
const HTTP2_HEADER_PATH: string;
const HTTP2_HEADER_ACCEPT_CHARSET: string;
const HTTP2_HEADER_ACCEPT_ENCODING: string;
const HTTP2_HEADER_ACCEPT_LANGUAGE: string;
const HTTP2_HEADER_ACCEPT_RANGES: string;
const HTTP2_HEADER_ACCEPT: string;
const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string;
const HTTP2_HEADER_AGE: string;
const HTTP2_HEADER_ALLOW: string;
const HTTP2_HEADER_AUTHORIZATION: string;
const HTTP2_HEADER_CACHE_CONTROL: string;
const HTTP2_HEADER_CONNECTION: string;
const HTTP2_HEADER_CONTENT_DISPOSITION: string;
const HTTP2_HEADER_CONTENT_ENCODING: string;
const HTTP2_HEADER_CONTENT_LANGUAGE: string;
const HTTP2_HEADER_CONTENT_LENGTH: string;
const HTTP2_HEADER_CONTENT_LOCATION: string;
const HTTP2_HEADER_CONTENT_MD5: string;
const HTTP2_HEADER_CONTENT_RANGE: string;
const HTTP2_HEADER_CONTENT_TYPE: string;
const HTTP2_HEADER_COOKIE: string;
const HTTP2_HEADER_DATE: string;
const HTTP2_HEADER_ETAG: string;
const HTTP2_HEADER_EXPECT: string;
const HTTP2_HEADER_EXPIRES: string;
const HTTP2_HEADER_FROM: string;
const HTTP2_HEADER_HOST: string;
const HTTP2_HEADER_IF_MATCH: string;
const HTTP2_HEADER_IF_MODIFIED_SINCE: string;
const HTTP2_HEADER_IF_NONE_MATCH: string;
const HTTP2_HEADER_IF_RANGE: string;
const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string;
const HTTP2_HEADER_LAST_MODIFIED: string;
const HTTP2_HEADER_LINK: string;
const HTTP2_HEADER_LOCATION: string;
const HTTP2_HEADER_MAX_FORWARDS: string;
const HTTP2_HEADER_PREFER: string;
const HTTP2_HEADER_PROXY_AUTHENTICATE: string;
const HTTP2_HEADER_PROXY_AUTHORIZATION: string;
const HTTP2_HEADER_RANGE: string;
const HTTP2_HEADER_REFERER: string;
const HTTP2_HEADER_REFRESH: string;
const HTTP2_HEADER_RETRY_AFTER: string;
const HTTP2_HEADER_SERVER: string;
const HTTP2_HEADER_SET_COOKIE: string;
const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string;
const HTTP2_HEADER_TRANSFER_ENCODING: string;
const HTTP2_HEADER_TE: string;
const HTTP2_HEADER_UPGRADE: string;
const HTTP2_HEADER_USER_AGENT: string;
const HTTP2_HEADER_VARY: string;
const HTTP2_HEADER_VIA: string;
const HTTP2_HEADER_WWW_AUTHENTICATE: string;
const HTTP2_HEADER_HTTP2_SETTINGS: string;
const HTTP2_HEADER_KEEP_ALIVE: string;
const HTTP2_HEADER_PROXY_CONNECTION: string;
const HTTP2_METHOD_ACL: string;
const HTTP2_METHOD_BASELINE_CONTROL: string;
const HTTP2_METHOD_BIND: string;
const HTTP2_METHOD_CHECKIN: string;
const HTTP2_METHOD_CHECKOUT: string;
const HTTP2_METHOD_CONNECT: string;
const HTTP2_METHOD_COPY: string;
const HTTP2_METHOD_DELETE: string;
const HTTP2_METHOD_GET: string;
const HTTP2_METHOD_HEAD: string;
const HTTP2_METHOD_LABEL: string;
const HTTP2_METHOD_LINK: string;
const HTTP2_METHOD_LOCK: string;
const HTTP2_METHOD_MERGE: string;
const HTTP2_METHOD_MKACTIVITY: string;
const HTTP2_METHOD_MKCALENDAR: string;
const HTTP2_METHOD_MKCOL: string;
const HTTP2_METHOD_MKREDIRECTREF: string;
const HTTP2_METHOD_MKWORKSPACE: string;
const HTTP2_METHOD_MOVE: string;
const HTTP2_METHOD_OPTIONS: string;
const HTTP2_METHOD_ORDERPATCH: string;
const HTTP2_METHOD_PATCH: string;
const HTTP2_METHOD_POST: string;
const HTTP2_METHOD_PRI: string;
const HTTP2_METHOD_PROPFIND: string;
const HTTP2_METHOD_PROPPATCH: string;
const HTTP2_METHOD_PUT: string;
const HTTP2_METHOD_REBIND: string;
|
const HTTP2_METHOD_REPORT: string;
const HTTP2_METHOD_SEARCH: string;
const HTTP2_METHOD_TRACE: string;
const HTTP2_METHOD_UNBIND: string;
const HTTP2_METHOD_UNCHECKOUT: string;
const HTTP2_METHOD_UNLINK: string;
const HTTP2_METHOD_UNLOCK: string;
const HTTP2_METHOD_UPDATE: string;
const HTTP2_METHOD_UPDATEREDIRECTREF: string;
const HTTP2_METHOD_VERSION_CONTROL: string;
const HTTP_STATUS_CONTINUE: number;
const HTTP_STATUS_SWITCHING_PROTOCOLS: number;
const HTTP_STATUS_PROCESSING: number;
const HTTP_STATUS_OK: number;
const HTTP_STATUS_CREATED: number;
const HTTP_STATUS_ACCEPTED: number;
const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number;
const HTTP_STATUS_NO_CONTENT: number;
const HTTP_STATUS_RESET_CONTENT: number;
const HTTP_STATUS_PARTIAL_CONTENT: number;
const HTTP_STATUS_MULTI_STATUS: number;
const HTTP_STATUS_ALREADY_REPORTED: number;
const HTTP_STATUS_IM_USED: number;
const HTTP_STATUS_MULTIPLE_CHOICES: number;
const HTTP_STATUS_MOVED_PERMANENTLY: number;
const HTTP_STATUS_FOUND: number;
const HTTP_STATUS_SEE_OTHER: number;
const HTTP_STATUS_NOT_MODIFIED: number;
const HTTP_STATUS_USE_PROXY: number;
const HTTP_STATUS_TEMPORARY_REDIRECT: number;
const HTTP_STATUS_PERMANENT_REDIRECT: number;
const HTTP_STATUS_BAD_REQUEST: number;
const HTTP_STATUS_UNAUTHORIZED: number;
const HTTP_STATUS_PAYMENT_REQUIRED: number;
const HTTP_STATUS_FORBIDDEN: number;
const HTTP_STATUS_NOT_FOUND: number;
const HTTP_STATUS_METHOD_NOT_ALLOWED: number;
const HTTP_STATUS_NOT_ACCEPTABLE: number;
const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number;
const HTTP_STATUS_REQUEST_TIMEOUT: number;
const HTTP_STATUS_CONFLICT: number;
const HTTP_STATUS_GONE: number;
const HTTP_STATUS_LENGTH_REQUIRED: number;
const HTTP_STATUS_PRECONDITION_FAILED: number;
const HTTP_STATUS_PAYLOAD_TOO_LARGE: number;
const HTTP_STATUS_URI_TOO_LONG: number;
const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number;
const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number;
const HTTP_STATUS_EXPECTATION_FAILED: number;
const HTTP_STATUS_TEAPOT: number;
const HTTP_STATUS_MISDIRECTED_REQUEST: number;
const HTTP_STATUS_UNPROCESSABLE_ENTITY: number;
const HTTP_STATUS_LOCKED: number;
const HTTP_STATUS_FAILED_DEPENDENCY: number;
const HTTP_STATUS_UNORDERED_COLLECTION: number;
const HTTP_STATUS_UPGRADE_REQUIRED: number;
const HTTP_STATUS_PRECONDITION_REQUIRED: number;
const HTTP_STATUS_TOO_MANY_REQUESTS: number;
const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number;
const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number;
const HTTP_STATUS_INTERNAL_SERVER_ERROR: number;
const HTTP_STATUS_NOT_IMPLEMENTED: number;
const HTTP_STATUS_BAD_GATEWAY: number;
const HTTP_STATUS_SERVICE_UNAVAILABLE: number;
const HTTP_STATUS_GATEWAY_TIMEOUT: number;
const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number;
const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number;
const HTTP_STATUS_INSUFFICIENT_STORAGE: number;
const HTTP_STATUS_LOOP_DETECTED: number;
const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number;
const HTTP_STATUS_NOT_EXTENDED: number;
const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number;
}
/**
* This symbol can be set as a property on the HTTP/2 headers object with
* an array value in order to provide a list of headers considered sensitive.
*/
export const sensitiveHeaders: symbol;
/**
* Returns an object containing the default settings for an `Http2Session`instance. This method returns a new object i |
nstance every time it is called
* so instances returned may be safely modified for use.
* @since v8.4.0
*/
export function getDefaultSettings(): Settings;
/**
* Returns a `Buffer` instance containing serialized representation of the given
* HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended
* for use with the `HTTP2-Settings` header field.
*
* ```js
* const http2 = require('node:http2');
*
* const packed = http2.getPackedSettings({ enablePush: false });
*
* console.log(packed.toString('base64'));
* // Prints: AAIAAAAA
* ```
* @since v8.4.0
*/
export function getPackedSettings(settings: Settings): Buffer;
/**
* Returns a `HTTP/2 Settings Object` containing the deserialized settings from
* the given `Buffer` as generated by `http2.getPackedSettings()`.
* @since v8.4.0
* @param buf The packed settings.
*/
export function getUnpackedSettings(buf: Uint8Array): Settings;
/**
* Returns a `net.Server` instance that creates and manages `Http2Session`instances.
*
* Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when
* communicating
* with browser clients.
*
* ```js
* const http2 = require('node:http2');
*
* // Create an unencrypted HTTP/2 server.
* // Since there are no browsers known that support
* // unencrypted HTTP/2, the use of `http2.createSecureServer()`
* // is necessary when communicating with browser clients.
* const server = http2.createServer();
*
* server.on('stream', (stream, headers) => {
* stream.respond({
* 'content-type': 'text/html; charset=utf-8',
* ':status': 200,
* });
* stream.end('<h1>Hello World</h1>');
* });
*
* server.listen(8000);
* ```
* @since v8.4.0
* @param onRequestHandler See `Compatibility API`
*/
export function createServer(
onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): Http2Server;
export function createServer(
options: ServerOptions,
onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): Http2Server;
/**
* Returns a `tls.Server` instance that creates and manages `Http2Session`instances.
*
* ```js
* const http2 = require('node:http2');
* const fs = require('node:fs');
*
* const options = {
* key: fs.readFileSync('server-key.pem'),
* cert: fs.readFileSync('server-cert.pem'),
* };
*
* // Create a secure HTTP/2 server
* const server = http2.createSecureServer(options);
*
* server.on('stream', (stream, headers) => {
* stream.respond({
* 'content-type': 'text/html; charset=utf-8',
* ':status': 200,
* });
* stream.end('<h1>Hello World</h1>');
* });
*
* server.listen(8443);
* ```
* @since v8.4.0
* @param onRequestHandler See `Compatibility API`
*/
export function createSecureServer(
onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): Http2SecureServer;
export function createSecureServer(
options: SecureServerOptions,
onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void,
): Http2SecureServer;
/**
* Returns a `ClientHttp2Session` instance.
*
* ```js
* const http2 = require('node:http2');
* const client = http2.connect('https://localhost:1234');
*
* // Use the client
*
* client.close();
* ```
* @since v8.4.0
* @param authority The remote HTTP/2 server to connect to. This must be in th |