text
stringlengths
2
4k
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"; }
export {}; // Don't export anything! //// DOM-like Events // NB: The Event / EventTarget / EventListener implementations below were copied // from lib.dom.d.ts, then edited to reflect Node's documentation at // https://nodejs.org/api/events.html#class-eventtarget. // Please read that link to understand important implementation differences. // This conditional type will be the existing global Event in a browser, or // the copy below in a Node environment. type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {} : { /** This is not used in Node.js and is provided purely for completeness. */ readonly bubbles: boolean; /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ cancelBubble: () => void; /** True if the event was created with the cancelable option */ readonly cancelable: boolean; /** This is not used in Node.js and is provided purely for completeness. */ readonly composed: boolean; /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ composedPath(): [EventTarget?]; /** Alias for event.target. */ readonly currentTarget: EventTarget | null; /** Is true if cancelable is true and event.preventDefault() has been called. */ readonly defaultPrevented: boolean; /** This is not used in Node.js and is provided purely for completeness. */ readonly eventPhase: 0 | 2; /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ readonly isTrusted: boolean; /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ preventDefault(): void; /** This is not used in Node.js and is provided purely for completeness. */ returnValue: boolean; /** Alias for event.target. */ readonly srcElement: EventTarget | null; /** Stops the invocation of event listeners after the current one completes. */ stopImmediatePropagation(): void; /** This is not used in Node.js and is provided purely for completeness. */ stopPropagation(): void; /** The `EventTarget` dispatching the event */ readonly target: EventTarget | null; /** The millisecond timestamp when the Event object was created. */ readonly timeStamp: number; /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ readonly type: string; }; // See comment above explaining conditional type type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {} : { /** * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. * * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. * * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. * Specifically, the `capture` option is used as part of the key when registering a `listener`. * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. */ addEventListener( type: string, listener: EventListener | EventListenerObject, options?: AddEventListenerOptions | boolean, ): void; /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ dispatchEvent(event: Event): boolean; /** Removes the event listener in ta
rget's event listener list with the same type, callback, and options. */ removeEventListener( type: string, listener: EventListener | EventListenerObject, options?: EventListenerOptions | boolean, ): void; }; interface EventInit { bubbles?: boolean; cancelable?: boolean; composed?: boolean; } interface EventListenerOptions { /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ capture?: boolean; } interface AddEventListenerOptions extends EventListenerOptions { /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ once?: boolean; /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ passive?: boolean; } interface EventListener { (evt: Event): void; } interface EventListenerObject { handleEvent(object: Event): void; } import {} from "events"; // Make this an ambient declaration declare global { /** An event which takes place in the DOM. */ interface Event extends __Event {} var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T : { prototype: __Event; new(type: string, eventInitDict?: EventInit): __Event; }; /** * EventTarget is a DOM interface implemented by objects that can * receive events and may have listeners for them. */ interface EventTarget extends __EventTarget {} var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T : { prototype: __EventTarget; new(): __EventTarget; }; }
/** * The `node:console` module provides a simple debugging console that is similar to * the JavaScript console mechanism provided by web browsers. * * The module exports two specific components: * * * A `Console` class with methods such as `console.log()`, `console.error()`, and`console.warn()` that can be used to write to any Node.js stream. * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('node:console')`. * * _**Warning**_: The global console object's methods are neither consistently * synchronous like the browser APIs they resemble, nor are they consistently * asynchronous like all other Node.js streams. See the `note on process I/O` for * more information. * * Example using the global `console`: * * ```js * console.log('hello world'); * // Prints: hello world, to stdout * console.log('hello %s', 'world'); * // Prints: hello world, to stdout * console.error(new Error('Whoops, something bad happened')); * // Prints error message and stack trace to stderr: * // Error: Whoops, something bad happened * // at [eval]:5:15 * // at Script.runInThisContext (node:vm:132:18) * // at Object.runInThisContext (node:vm:309:38) * // at node:internal/process/execution:77:19 * // at [eval]-wrapper:6:22 * // at evalScript (node:internal/process/execution:76:60) * // at node:internal/main/eval_string:23:3 * * const name = 'Will Robinson'; * console.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to stderr * ``` * * Example using the `Console` class: * * ```js * const out = getStreamSomehow(); * const err = getStreamSomehow(); * const myConsole = new console.Console(out, err); * * myConsole.log('hello world'); * // Prints: hello world, to out * myConsole.log('hello %s', 'world'); * // Prints: hello world, to out * myConsole.error(new Error('Whoops, something bad happened')); * // Prints: [Error: Whoops, something bad happened], to err * * const name = 'Will Robinson'; * myConsole.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to err * ``` * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/console.js) */ declare module "console" { import console = require("node:console"); export = console; } declare module "node:console" { import { InspectOptions } from "node:util"; global { // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build interface Console { Console: console.ConsoleConstructor; /** * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only * writes a message and does not otherwise affect execution. The output always * starts with `"Assertion failed"`. If provided, `message` is formatted using `util.format()`. * * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. * * ```js * console.assert(true, 'does nothing'); * * console.assert(false, 'Whoops %s work', 'didn\'t'); * // Assertion failed: Whoops didn't work * * console.assert(); * // Assertion failed * ``` * @since v0.1.101 * @param value The value tested for being truthy. * @param message All arguments besides `value` are used as error message. */ assert(value: any, message?: string, ...optionalParams: any[]): void; /** * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the * TTY. When `stdout` is not a TTY, this method does nothing. * * The specific operation of `console.cl
ear()` can vary across operating systems * and terminal types. For most Linux operating systems, `console.clear()`operates similarly to the `clear` shell command. On Windows, `console.clear()`will clear only the output in the * current terminal viewport for the Node.js * binary. * @since v8.3.0 */ clear(): void; /** * Maintains an internal counter specific to `label` and outputs to `stdout` the * number of times `console.count()` has been called with the given `label`. * * ```js * > console.count() * default: 1 * undefined * > console.count('default') * default: 2 * undefined * > console.count('abc') * abc: 1 * undefined * > console.count('xyz') * xyz: 1 * undefined * > console.count('abc') * abc: 2 * undefined * > console.count() * default: 3 * undefined * > * ``` * @since v8.3.0 * @param [label='default'] The display label for the counter. */ count(label?: string): void; /** * Resets the internal counter specific to `label`. * * ```js * > console.count('abc'); * abc: 1 * undefined * > console.countReset('abc'); * undefined * > console.count('abc'); * abc: 1 * undefined * > * ``` * @since v8.3.0 * @param [label='default'] The display label for the counter. */ countReset(label?: string): void; /** * The `console.debug()` function is an alias for {@link log}. * @since v8.0.0 */ debug(message?: any, ...optionalParams: any[]): void; /** * Uses `util.inspect()` on `obj` and prints the resulting string to `stdout`. * This function bypasses any custom `inspect()` function defined on `obj`. * @since v0.1.101 */ dir(obj: any, options?: InspectOptions): void; /** * This method calls `console.log()` passing it the arguments received. * This method does not produce any XML formatting. * @since v8.0.0 */ dirxml(...data: any[]): void; /** * Prints to `stderr` with newline. Multiple arguments can be passed, with the * first used as the primary message and all additional used as substitution * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). * * ```js * const code = 5; * console.error('error #%d', code); * // Prints: error #5, to stderr * console.error('error', code); * // Prints: error 5, to stderr * ``` * * If formatting elements (e.g. `%d`) are not found in the first string then `util.inspect()` is called on each argument and the resulting string * values are concatenated. See `util.format()` for more information. * @since v0.1.100 */ error(message?: any, ...optionalParams: any[]): void; /** * Increases indentation of subsequent lines by spaces for `groupIndentation`length. * * If one or more `label`s are provided, those are printed first without the * additional indentation. * @since v8.5.0 */ group(...label: any[]): void; /**
* An alias for {@link group}. * @since v8.5.0 */ groupCollapsed(...label: any[]): void; /** * Decreases indentation of subsequent lines by spaces for `groupIndentation`length. * @since v8.5.0 */ groupEnd(): void; /** * The `console.info()` function is an alias for {@link log}. * @since v0.1.100 */ info(message?: any, ...optionalParams: any[]): void; /** * Prints to `stdout` with newline. Multiple arguments can be passed, with the * first used as the primary message and all additional used as substitution * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to `util.format()`). * * ```js * const count = 5; * console.log('count: %d', count); * // Prints: count: 5, to stdout * console.log('count:', count); * // Prints: count: 5, to stdout * ``` * * See `util.format()` for more information. * @since v0.1.100 */ log(message?: any, ...optionalParams: any[]): void; /** * Try to construct a table with the columns of the properties of `tabularData`(or use `properties`) and rows of `tabularData` and log it. Falls back to just * logging the argument if it can't be parsed as tabular. * * ```js * // These can't be parsed as tabular data * console.table(Symbol()); * // Symbol() * * console.table(undefined); * // undefined * * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); * // β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” * // β”‚ (index) β”‚ a β”‚ b β”‚ * // β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ * // β”‚ 0 β”‚ 1 β”‚ 'Y' β”‚ * // β”‚ 1 β”‚ 'Z' β”‚ 2 β”‚ * // β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜ * * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); * // β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” * // β”‚ (index) β”‚ a β”‚ * // β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ * // β”‚ 0 β”‚ 1 β”‚ * // β”‚ 1 β”‚ 'Z' β”‚ * // β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜ * ``` * @since v10.0.0 * @param properties Alternate properties for constructing the table. */ table(tabularData: any, properties?: readonly string[]): void; /** * Starts a timer that can be used to compute the duration of an operation. Timers * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in * suitable time units to `stdout`. For example, if the elapsed * time is 3869ms, `console.timeEnd()` displays "3.869s". * @since v0.1.104 * @param [label='default'] */ time(label?: string): void; /** * Stops a timer that was previously started by calling {@link time} and * prints the result to `stdout`: * * ```js * console.time('bunch-of-stuff'); * // Do a bunch of stuff. * console.timeEnd('bunch-of-stuff'); * // Prints: bunch-of-stuff: 225.438ms * ``` * @since v0.1.104 * @param [label='default'] */ timeEnd(label?: string): void; /** * For a timer that was previously started by calling {@link time}, prints * the elapsed time and other `data` arguments to `stdout`: * * ```js * console.time('process');
* const value = expensiveProcess1(); // Returns 42 * console.timeLog('process', value); * // Prints "process: 365.227ms 42". * doExpensiveProcess2(value); * console.timeEnd('process'); * ``` * @since v10.7.0 * @param [label='default'] */ timeLog(label?: string, ...data: any[]): void; /** * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` formatted message and stack trace to the current position in the code. * * ```js * console.trace('Show me'); * // Prints: (stack trace will vary based on where trace is called) * // Trace: Show me * // at repl:2:9 * // at REPLServer.defaultEval (repl.js:248:27) * // at bound (domain.js:287:14) * // at REPLServer.runBound [as eval] (domain.js:300:12) * // at REPLServer.<anonymous> (repl.js:412:12) * // at emitOne (events.js:82:20) * // at REPLServer.emit (events.js:169:7) * // at REPLServer.Interface._onLine (readline.js:210:10) * // at REPLServer.Interface._line (readline.js:549:8) * // at REPLServer.Interface._ttyWrite (readline.js:826:14) * ``` * @since v0.1.104 */ trace(message?: any, ...optionalParams: any[]): void; /** * The `console.warn()` function is an alias for {@link error}. * @since v0.1.100 */ warn(message?: any, ...optionalParams: any[]): void; // --- Inspector mode only --- /** * This method does not display anything unless used in the inspector. * Starts a JavaScript CPU profile with an optional label. */ profile(label?: string): void; /** * This method does not display anything unless used in the inspector. * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. */ profileEnd(label?: string): void; /** * This method does not display anything unless used in the inspector. * Adds an event with the label `label` to the Timeline panel of the inspector. */ timeStamp(label?: string): void; } /** * The `console` module provides a simple debugging console that is similar to the * JavaScript console mechanism provided by web browsers. * * The module exports two specific components: * * * A `Console` class with methods such as `console.log()`, `console.error()` and`console.warn()` that can be used to write to any Node.js stream. * * A global `console` instance configured to write to `process.stdout` and `process.stderr`. The global `console` can be used without calling`require('console')`. * * _**Warning**_: The global console object's methods are neither consistently * synchronous like the browser APIs they resemble, nor are they consistently * asynchronous like all other Node.js streams. See the `note on process I/O` for * more information. * * Example using the global `console`: * * ```js * console.log('hello world'); * // Prints: hello world, to stdout * console.log('hello %s', 'world'); * // Prints: hello world, to stdout * console.error(new Error('Whoops, something bad happened')); * // Prints error message and stack trace to stderr: * // Error: Whoops, something bad happened * // at [eval]:5:15 * // at Script.runInThisContext (node:vm:132:18)
* // at Object.runInThisContext (node:vm:309:38) * // at node:internal/process/execution:77:19 * // at [eval]-wrapper:6:22 * // at evalScript (node:internal/process/execution:76:60) * // at node:internal/main/eval_string:23:3 * * const name = 'Will Robinson'; * console.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to stderr * ``` * * Example using the `Console` class: * * ```js * const out = getStreamSomehow(); * const err = getStreamSomehow(); * const myConsole = new console.Console(out, err); * * myConsole.log('hello world'); * // Prints: hello world, to out * myConsole.log('hello %s', 'world'); * // Prints: hello world, to out * myConsole.error(new Error('Whoops, something bad happened')); * // Prints: [Error: Whoops, something bad happened], to err * * const name = 'Will Robinson'; * myConsole.warn(`Danger ${name}! Danger!`); * // Prints: Danger Will Robinson! Danger!, to err * ``` * @see [source](https://github.com/nodejs/node/blob/v16.4.2/lib/console.js) */ namespace console { interface ConsoleConstructorOptions { stdout: NodeJS.WritableStream; stderr?: NodeJS.WritableStream | undefined; ignoreErrors?: boolean | undefined; colorMode?: boolean | "auto" | undefined; inspectOptions?: InspectOptions | undefined; /** * Set group indentation * @default 2 */ groupIndentation?: number | undefined; } interface ConsoleConstructor { prototype: Console; new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; new(options: ConsoleConstructorOptions): Console; } } var console: Console; } export = globalThis.console; }
/** * 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 `timer` module exposes a global API for scheduling functions to * be called at some future period of time. Because the timer functions are * globals, there is no need to call `require('node:timers')` to use the API. * * The timer functions within Node.js implement a similar API as the timers API * provided by Web Browsers but use a different internal implementation that is * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/timers.js) */ declare module "timers" { import { Abortable } from "node:events"; import { setImmediate as setImmediatePromise, setInterval as setIntervalPromise, setTimeout as setTimeoutPromise, } from "node:timers/promises"; interface TimerOptions extends Abortable { /** * Set to `false` to indicate that the scheduled `Timeout` * should not require the Node.js event loop to remain active. * @default true */ ref?: boolean | undefined; } let setTimeout: typeof global.setTimeout; let clearTimeout: typeof global.clearTimeout; let setInterval: typeof global.setInterval; let clearInterval: typeof global.clearInterval; let setImmediate: typeof global.setImmediate; let clearImmediate: typeof global.clearImmediate; global { namespace NodeJS { // compatibility with older typings interface Timer extends RefCounted { hasRef(): boolean; refresh(): this; [Symbol.toPrimitive](): number; } /** * This object is created internally and is returned from `setImmediate()`. It * can be passed to `clearImmediate()` in order to cancel the scheduled * actions. * * By default, when an immediate is scheduled, the Node.js event loop will continue * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()`functions that can be used to * control this default behavior. */ class Immediate implements RefCounted { /** * When called, requests that the Node.js event loop _not_ exit so long as the`Immediate` is active. Calling `immediate.ref()` multiple times will have no * effect. * * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary * to call `immediate.ref()` unless `immediate.unref()` had been called previously. * @since v9.7.0 * @return a reference to `immediate` */ ref(): this; /** * When called, the active `Immediate` object will not require the Node.js event * loop to remain active. If there is no other activity keeping the event loop * running, the process may exit before the `Immediate` object's callback is * invoked. Calling `immediate.unref()` multiple times will have no effect. * @since v9.7.0 * @return a reference to `immediate` */ unref(): this; /** * If true, the `Immediate` object will keep the Node.js event loop active. * @since v11.0.0 */ hasRef(): boolean; _onImmediate: Function; // to distinguish it from the Timeout class /** * Cancels the immediate. This is similar to calling `clearImmediate()`. * @since v20.5.0 */ [Symbol.dispose](): void; } /** * This object is created i
nternally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the * scheduled actions. * * By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the * timer is active. Each of the `Timeout` objects returned by these functions * export both `timeout.ref()` and `timeout.unref()` functions that can be used to * control this default behavior. */ class Timeout implements Timer { /** * When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. * * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary * to call `timeout.ref()` unless `timeout.unref()` had been called previously. * @since v0.9.1 * @return a reference to `timeout` */ ref(): this; /** * When called, the active `Timeout` object will not require the Node.js event loop * to remain active. If there is no other activity keeping the event loop running, * the process may exit before the `Timeout` object's callback is invoked. Calling`timeout.unref()` multiple times will have no effect. * @since v0.9.1 * @return a reference to `timeout` */ unref(): this; /** * If true, the `Timeout` object will keep the Node.js event loop active. * @since v11.0.0 */ hasRef(): boolean; /** * Sets the timer's start time to the current time, and reschedules the timer to * call its callback at the previously specified duration adjusted to the current * time. This is useful for refreshing a timer without allocating a new * JavaScript object. * * Using this on a timer that has already called its callback will reactivate the * timer. * @since v10.2.0 * @return a reference to `timeout` */ refresh(): this; [Symbol.toPrimitive](): number; /** * Cancels the timeout. * @since v20.5.0 */ [Symbol.dispose](): void; } } /** * Schedules execution of a one-time `callback` after `delay` milliseconds. * * The `callback` will likely not be invoked in precisely `delay` milliseconds. * Node.js makes no guarantees about the exact timing of when callbacks will fire, * nor of their ordering. The callback will be called as close as possible to the * time specified. * * When `delay` is larger than `2147483647` or less than `1`, the `delay`will be set to `1`. Non-integer delays are truncated to an integer. * * If `callback` is not a function, a `TypeError` will be thrown. * * This method has a custom variant for promises that is available using `timersPromises.setTimeout()`. * @since v0.0.1 * @param callback The function to call when the timer elapses. * @param [delay=1] The number of milliseconds to wait before calling the `callback`. * @param args Optional arguments to pass when the `callback` is called. * @return for use with {@link clearTimeout} */ function setTimeout<TArgs extends any[]>( callback: (...args: TArgs) => void, ms?: number, .
..args: TArgs ): NodeJS.Timeout; // util.promisify no rest args compability // eslint-disable-next-line @typescript-eslint/no-invalid-void-type function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; namespace setTimeout { const __promisify__: typeof setTimeoutPromise; } /** * Cancels a `Timeout` object created by `setTimeout()`. * @since v0.0.1 * @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number. */ function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; /** * Schedules repeated execution of `callback` every `delay` milliseconds. * * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be * set to `1`. Non-integer delays are truncated to an integer. * * If `callback` is not a function, a `TypeError` will be thrown. * * This method has a custom variant for promises that is available using `timersPromises.setInterval()`. * @since v0.0.1 * @param callback The function to call when the timer elapses. * @param [delay=1] The number of milliseconds to wait before calling the `callback`. * @param args Optional arguments to pass when the `callback` is called. * @return for use with {@link clearInterval} */ function setInterval<TArgs extends any[]>( callback: (...args: TArgs) => void, ms?: number, ...args: TArgs ): NodeJS.Timeout; // util.promisify no rest args compability // eslint-disable-next-line @typescript-eslint/no-invalid-void-type function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout; namespace setInterval { const __promisify__: typeof setIntervalPromise; } /** * Cancels a `Timeout` object created by `setInterval()`. * @since v0.0.1 * @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number. */ function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; /** * Schedules the "immediate" execution of the `callback` after I/O events' * callbacks. * * When multiple calls to `setImmediate()` are made, the `callback` functions are * queued for execution in the order in which they are created. The entire callback * queue is processed every event loop iteration. If an immediate timer is queued * from inside an executing callback, that timer will not be triggered until the * next event loop iteration. * * If `callback` is not a function, a `TypeError` will be thrown. * * This method has a custom variant for promises that is available using `timersPromises.setImmediate()`. * @since v0.9.1 * @param callback The function to call at the end of this turn of the Node.js `Event Loop` * @param args Optional arguments to pass when the `callback` is called. * @return for use with {@link clearImmediate} */ function setImmediate<TArgs extends any[]>( callback: (...args: TArgs) => void, ...args: TArgs ): NodeJS.Immediate; // util.promisify no rest args compability // eslint-disable-next-line @typescript-eslint/no-invalid-void-type function setImmediate(callback: (args: void) => void): NodeJS.Immediate; namespace setImmediate { const __promisify__: typeof setImmediatePromise; } /** * Cancels an `Immediate` object created by `setImmediate()`. * @since v0.9.1 * @param immediate An `
Immediate` object as returned by {@link setImmediate}. */ function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; function queueMicrotask(callback: () => void): void; } } declare module "node:timers" { export * from "timers"; }
/** * 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 }; }
/** * To use the HTTP server and client one must `require('node:http')`. * * The HTTP interfaces in Node.js are designed to support many features * of the protocol which have been traditionally difficult to use. * In particular, large, possibly chunk-encoded, messages. The interface is * careful to never buffer entire requests or responses, so the * user is able to stream data. * * HTTP message headers are represented by an object like this: * * ```json * { "content-length": "123", * "content-type": "text/plain", * "connection": "keep-alive", * "host": "example.com", * "accept": "*" } * ``` * * Keys are lowercased. Values are not modified. * * In order to support the full spectrum of possible HTTP applications, the Node.js * HTTP API is very low-level. It deals with stream handling and message * parsing only. It parses a message into headers and body but it does not * parse the actual headers or the body. * * See `message.headers` for details on how duplicate headers are handled. * * The raw headers as they were received are retained in the `rawHeaders`property, which is an array of `[key, value, key2, value2, ...]`. For * example, the previous message header object might have a `rawHeaders`list like the following: * * ```js * [ 'ConTent-Length', '123456', * 'content-LENGTH', '123', * 'content-type', 'text/plain', * 'CONNECTION', 'keep-alive', * 'Host', 'example.com', * 'accepT', '*' ] * ``` * @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/http.js) */ declare module "http" { import * as stream from "node:stream"; import { URL } from "node:url"; import { LookupOptions } from "node:dns"; import { EventEmitter } from "node:events"; import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; // incoming headers will never contain number interface IncomingHttpHeaders extends NodeJS.Dict<string | string[]> { accept?: string | undefined; "accept-language"?: string | undefined; "accept-patch"?: string | undefined; "accept-ranges"?: string | undefined; "access-control-allow-credentials"?: string | undefined; "access-control-allow-headers"?: string | undefined; "access-control-allow-methods"?: string | undefined; "access-control-allow-origin"?: string | undefined; "access-control-expose-headers"?: string | undefined; "access-control-max-age"?: string | undefined; "access-control-request-headers"?: string | undefined; "access-control-request-method"?: string | undefined; age?: string | undefined; allow?: string | undefined; "alt-svc"?: string | undefined; authorization?: string | undefined; "cache-control"?: string | undefined; connection?: string | undefined; "content-disposition"?: string | undefined; "content-encoding"?: string | undefined; "content-language"?: string | undefined; "content-length"?: string | undefined; "content-location"?: string | undefined; "content-range"?: string | undefined; "content-type"?: string | undefined; cookie?: string | undefined; date?: string | undefined; etag?: string | undefined; expect?: string | undefined; expires?: string | undefined; forwarded?: string | undefined; from?: string | undefined; host?: string | undefined; "if-match"?: string | undefined; "if-modified-since"?: string | undefined; "if-none-match"?: string | undefined; "if-unmodified-since"?: string | undefined; "last-modified"?: string | undefined; location?: string | undefined; origin?: string | undefined; pragma?: string | undefined; "proxy-authenticate"?: string | undefined; "proxy-authorization"?: string | undefined; "public-key-pins"?: string | undefine
d; range?: string | undefined; referer?: string | undefined; "retry-after"?: string | undefined; "sec-websocket-accept"?: string | undefined; "sec-websocket-extensions"?: string | undefined; "sec-websocket-key"?: string | undefined; "sec-websocket-protocol"?: string | undefined; "sec-websocket-version"?: string | undefined; "set-cookie"?: string[] | undefined; "strict-transport-security"?: string | undefined; tk?: string | undefined; trailer?: string | undefined; "transfer-encoding"?: string | undefined; upgrade?: string | undefined; "user-agent"?: string | undefined; vary?: string | undefined; via?: string | undefined; warning?: string | undefined; "www-authenticate"?: string | undefined; } // outgoing headers allows numbers (as they are converted internally to strings) type OutgoingHttpHeader = number | string | string[]; interface OutgoingHttpHeaders extends NodeJS.Dict<OutgoingHttpHeader> { accept?: string | string[] | undefined; "accept-charset"?: string | string[] | undefined; "accept-encoding"?: string | string[] | undefined; "accept-language"?: string | string[] | undefined; "accept-ranges"?: string | undefined; "access-control-allow-credentials"?: string | undefined; "access-control-allow-headers"?: string | undefined; "access-control-allow-methods"?: string | undefined; "access-control-allow-origin"?: string | undefined; "access-control-expose-headers"?: string | undefined; "access-control-max-age"?: string | undefined; "access-control-request-headers"?: string | undefined; "access-control-request-method"?: string | undefined; age?: string | undefined; allow?: string | undefined; authorization?: string | undefined; "cache-control"?: string | undefined; "cdn-cache-control"?: string | undefined; connection?: string | string[] | undefined; "content-disposition"?: string | undefined; "content-encoding"?: string | undefined; "content-language"?: string | undefined; "content-length"?: string | number | undefined; "content-location"?: string | undefined; "content-range"?: string | undefined; "content-security-policy"?: string | undefined; "content-security-policy-report-only"?: string | undefined; cookie?: string | string[] | undefined; dav?: string | string[] | undefined; dnt?: string | undefined; date?: string | undefined; etag?: string | undefined; expect?: string | undefined; expires?: string | undefined; forwarded?: string | undefined; from?: string | undefined; host?: string | undefined; "if-match"?: string | undefined; "if-modified-since"?: string | undefined; "if-none-match"?: string | undefined; "if-range"?: string | undefined; "if-unmodified-since"?: string | undefined; "last-modified"?: string | undefined; link?: string | string[] | undefined; location?: string | undefined; "max-forwards"?: string | undefined; origin?: string | undefined; prgama?: string | string[] | undefined; "proxy-authenticate"?: string | string[] | undefined; "proxy-authorization"?: string | undefined; "public-key-pins"?: string | undefined; "public-key-pins-report-only"?: string | undefined; range?: string | undefined; referer?: string | undefined; "referrer-policy"?: string | undefined; refresh?: string | undefined; "retry-after"?: string | undefined; "sec-websocket-accept"?: string | undefined; "sec-websocket-extensions"?: string | string[] | undefined; "sec-websocket-key"?: string | undefined;
"sec-websocket-protocol"?: string | string[] | undefined; "sec-websocket-version"?: string | undefined; server?: string | undefined; "set-cookie"?: string | string[] | undefined; "strict-transport-security"?: string | undefined; te?: string | undefined; trailer?: string | undefined; "transfer-encoding"?: string | undefined; "user-agent"?: string | undefined; upgrade?: string | undefined; "upgrade-insecure-requests"?: string | undefined; vary?: string | undefined; via?: string | string[] | undefined; warning?: string | undefined; "www-authenticate"?: string | string[] | undefined; "x-content-type-options"?: string | undefined; "x-dns-prefetch-control"?: string | undefined; "x-frame-options"?: string | undefined; "x-xss-protection"?: string | undefined; } interface ClientRequestArgs { _defaultAgent?: Agent | undefined; agent?: Agent | boolean | undefined; auth?: string | null | undefined; // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 createConnection?: | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) | undefined; defaultPort?: number | string | undefined; family?: number | undefined; headers?: OutgoingHttpHeaders | undefined; hints?: LookupOptions["hints"]; host?: string | null | undefined; hostname?: string | null | undefined; insecureHTTPParser?: boolean | undefined; localAddress?: string | undefined; localPort?: number | undefined; lookup?: LookupFunction | undefined; /** * @default 16384 */ maxHeaderSize?: number | undefined; method?: string | undefined; path?: string | null | undefined; port?: number | string | null | undefined; protocol?: string | null | undefined; setHost?: boolean | undefined; signal?: AbortSignal | undefined; socketPath?: string | undefined; timeout?: number | undefined; uniqueHeaders?: Array<string | string[]> | undefined; joinDuplicateHeaders?: boolean; } interface ServerOptions< Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse = typeof ServerResponse, > { /** * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. */ IncomingMessage?: Request | undefined; /** * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. */ ServerResponse?: Response | undefined; /** * Sets the timeout value in milliseconds for receiving the entire request from the client. * @see Server.requestTimeout for more information. * @default 300000 * @since v18.0.0 */ requestTimeout?: number | undefined; /** * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. * @default false * @since v18.14.0 */ joinDuplicateHeaders?: boolean; /** * The number of milliseconds of inactivity a server needs to wait for additional incoming data, * after it has finished writing the last response, before a socket will be destroyed. * @see Server.keepAliveTimeout for more information. * @default 5000 * @since v18.0.0 */ keepAliveTimeout?: number | undefined; /** * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. * @default 30000 */ connectionsCheckingInterval?: number | undefined; /** * Opti
onally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. * Default: @see stream.getDefaultHighWaterMark(). * @since v20.1.0 */ highWaterMark?: number | undefined; /** * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. * Using the insecure parser should be avoided. * See --insecure-http-parser for more information. * @default false */ insecureHTTPParser?: boolean | undefined; /** * Optionally overrides the value of * `--max-http-header-size` for requests received by this server, i.e. * the maximum length of request headers in bytes. * @default 16384 * @since v13.3.0 */ maxHeaderSize?: number | undefined; /** * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. * @default true * @since v16.5.0 */ noDelay?: boolean | undefined; /** * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. * @default false * @since v16.5.0 */ keepAlive?: boolean | undefined; /** * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. * @default 0 * @since v16.5.0 */ keepAliveInitialDelay?: number | undefined; /** * A list of response headers that should be sent only once. * If the header's value is an array, the items will be joined using `; `. */ uniqueHeaders?: Array<string | string[]> | undefined; } type RequestListener< Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse = typeof ServerResponse, > = (req: InstanceType<Request>, res: InstanceType<Response> & { req: InstanceType<Request> }) => void; /** * @since v0.1.17 */ class Server< Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse = typeof ServerResponse, > extends NetServer { constructor(requestListener?: RequestListener<Request, Response>); constructor(options: ServerOptions<Request, Response>, requestListener?: RequestListener<Request, Response>); /** * Sets the timeout value for sockets, and emits a `'timeout'` event on * the Server object, passing the socket as an argument, if a timeout * occurs. * * If there is a `'timeout'` event listener on the Server object, then it * will be called with the timed-out socket as an argument. * * By default, the Server does not timeout sockets. However, if a callback * is assigned to the Server's `'timeout'` event, timeouts must be handled * explicitly. * @since v0.9.12 * @param [msecs=0 (no timeout)] */ setTimeout(msecs?: number, callback?: () => void): this; setTimeout(callback: () => void): this; /** * Limits maximum incoming headers count. If set to 0, no limit will be applied. * @since v0.7.0 */ maxHeadersCount: number | null; /** * The maximum number of requests socket can handle * before closing keep alive connection. * * A value of `0` will disable the limit. * * When the limit is reached it will set the `Connection` header value to `close`, * but will not actually close the connection, subsequent requests sent * a
fter the limit is reached will get `503 Service Unavailable` as a response. * @since v16.10.0 */ maxRequestsPerSocket: number | null; /** * The number of milliseconds of inactivity before a socket is presumed * to have timed out. * * A value of `0` will disable the timeout behavior on incoming connections. * * The socket timeout logic is set up on connection, so changing this * value only affects new connections to the server, not any existing connections. * @since v0.9.12 */ timeout: number; /** * Limit the amount of time the parser will wait to receive the complete HTTP * headers. * * If the timeout expires, the server responds with status 408 without * forwarding the request to the request listener and then closes the connection. * * It must be set to a non-zero value (e.g. 120 seconds) to protect against * potential Denial-of-Service attacks in case the server is deployed without a * reverse proxy in front. * @since v11.3.0, v10.14.0 */ headersTimeout: number; /** * The number of milliseconds of inactivity a server needs to wait for additional * incoming data, after it has finished writing the last response, before a socket * will be destroyed. If the server receives new data before the keep-alive * timeout has fired, it will reset the regular inactivity timeout, i.e.,`server.timeout`. * * A value of `0` will disable the keep-alive timeout behavior on incoming * connections. * A value of `0` makes the http server behave similarly to Node.js versions prior * to 8.0.0, which did not have a keep-alive timeout. * * The socket timeout logic is set up on connection, so changing this value only * affects new connections to the server, not any existing connections. * @since v8.0.0 */ keepAliveTimeout: number; /** * Sets the timeout value in milliseconds for receiving the entire request from * the client. * * If the timeout expires, the server responds with status 408 without * forwarding the request to the request listener and then closes the connection. * * It must be set to a non-zero value (e.g. 120 seconds) to protect against * potential Denial-of-Service attacks in case the server is deployed without a * reverse proxy in front. * @since v14.11.0 */ requestTimeout: number; /** * Closes all connections connected to this server. * @since v18.2.0 */ closeAllConnections(): void; /** * Closes all connections connected to this server which are not sending a request * or waiting for a response. * @since v18.2.0 */ closeIdleConnections(): void; addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "connection", listener: (socket: Socket) => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "listening", listener: () => void): this; addListener(event: "checkContinue", listener: RequestListener<Request, Response>): this; addListener(event: "checkExpectation", listener: RequestListener<Request, Response>): this; addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; addListener( event: "connect", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, ): this; addListener(event: "dropRequest", listener: (req: InstanceType<Request>, socket: str
eam.Duplex) => void): this; addListener(event: "request", listener: RequestListener<Request, Response>): this; addListener( event: "upgrade", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, ): this; emit(event: string, ...args: any[]): boolean; emit(event: "close"): boolean; emit(event: "connection", socket: Socket): boolean; emit(event: "error", err: Error): boolean; emit(event: "listening"): boolean; emit( event: "checkContinue", req: InstanceType<Request>, res: InstanceType<Response> & { req: InstanceType<Request> }, ): boolean; emit( event: "checkExpectation", req: InstanceType<Request>, res: InstanceType<Response> & { req: InstanceType<Request> }, ): boolean; emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; emit(event: "connect", req: InstanceType<Request>, socket: stream.Duplex, head: Buffer): boolean; emit(event: "dropRequest", req: InstanceType<Request>, socket: stream.Duplex): boolean; emit( event: "request", req: InstanceType<Request>, res: InstanceType<Response> & { req: InstanceType<Request> }, ): boolean; emit(event: "upgrade", req: InstanceType<Request>, socket: stream.Duplex, head: Buffer): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "connection", listener: (socket: Socket) => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "listening", listener: () => void): this; on(event: "checkContinue", listener: RequestListener<Request, Response>): this; on(event: "checkExpectation", listener: RequestListener<Request, Response>): this; on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; on(event: "connect", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void): this; on(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this; on(event: "request", listener: RequestListener<Request, Response>): this; on(event: "upgrade", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "connection", listener: (socket: Socket) => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "listening", listener: () => void): this; once(event: "checkContinue", listener: RequestListener<Request, Response>): this; once(event: "checkExpectation", listener: RequestListener<Request, Response>): this; once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; once( event: "connect", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, ): this; once(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this; once(event: "request", listener: RequestListener<Request, Response>): this; once( event: "upgrade", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, ): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "connection", listener: (socket: Socket) => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "listening", listen
er: () => void): this; prependListener(event: "checkContinue", listener: RequestListener<Request, Response>): this; prependListener(event: "checkExpectation", listener: RequestListener<Request, Response>): this; prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; prependListener( event: "connect", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, ): this; prependListener( event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void, ): this; prependListener(event: "request", listener: RequestListener<Request, Response>): this; prependListener( event: "upgrade", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, ): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "listening", listener: () => void): this; prependOnceListener(event: "checkContinue", listener: RequestListener<Request, Response>): this; prependOnceListener(event: "checkExpectation", listener: RequestListener<Request, Response>): this; prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; prependOnceListener( event: "connect", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, ): this; prependOnceListener( event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void, ): this; prependOnceListener(event: "request", listener: RequestListener<Request, Response>): this; prependOnceListener( event: "upgrade", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, ): this; } /** * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from * the perspective of the participants of an HTTP transaction. * @since v0.1.17 */ class OutgoingMessage<Request extends IncomingMessage = IncomingMessage> extends stream.Writable { readonly req: Request; chunkedEncoding: boolean; shouldKeepAlive: boolean; useChunkedEncodingByDefault: boolean; sendDate: boolean; /** * @deprecated Use `writableEnded` instead. */ finished: boolean; /** * Read-only. `true` if the headers were sent, otherwise `false`. * @since v0.9.3 */ readonly headersSent: boolean; /** * Alias of `outgoingMessage.socket`. * @since v0.3.0 * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. */ readonly connection: Socket | null; /** * Reference to the underlying socket. Usually, users will not want to access * this property. * * After calling `outgoingMessage.end()`, this property will be nulled. * @since v0.3.0 */ readonly socket: Socket | null; constructor(); /** * Once a socket is associated with the message and is connected,`socket.setTimeout()` will be called with `msecs` as the first parameter. * @since v0.9.12 * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. */ setTimeout(msecs: number, callback?: () => void): this; /** * Sets a si
ngle header value. If the header already exists in the to-be-sent * headers, its value will be replaced. Use an array of strings to send multiple * headers with the same name. * @since v0.4.0 * @param name Header name * @param value Header value */ setHeader(name: string, value: number | string | readonly string[]): this; /** * Append a single header value for the header object. * * If the value is an array, this is equivalent of calling this method multiple * times. * * If there were no previous value for the header, this is equivalent of calling `outgoingMessage.setHeader(name, value)`. * * Depending of the value of `options.uniqueHeaders` when the client request or the * server were created, this will end up in the header being sent multiple times or * a single time with values joined using `; `. * @since v18.3.0, v16.17.0 * @param name Header name * @param value Header value */ appendHeader(name: string, value: string | readonly string[]): this; /** * Gets the value of the HTTP header with the given name. If that header is not * set, the returned value will be `undefined`. * @since v0.4.0 * @param name Name of header */ getHeader(name: string): number | string | string[] | undefined; /** * 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 `outgoingMessage.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 * outgoingMessage.setHeader('Foo', 'bar'); * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); * * const headers = outgoingMessage.getHeaders(); * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } * ``` * @since v7.7.0 */ getHeaders(): OutgoingHttpHeaders; /** * Returns an array containing the unique names of the current outgoing headers. * All names are lowercase. * @since v7.7.0 */ getHeaderNames(): string[]; /** * Returns `true` if the header identified by `name` is currently set in the * outgoing headers. The header name is case-insensitive. * * ```js * const hasContentType = outgoingMessage.hasHeader('content-type'); * ``` * @since v7.7.0 */ hasHeader(name: string): boolean; /** * Removes a header that is queued for implicit sending. * * ```js * outgoingMessage.removeHeader('Content-Encoding'); * ``` * @since v0.4.0 * @param name Header name */ removeHeader(name: string): void; /** * Adds HTTP trailers (headers but at the end of the message) to the message. * * Trailers will **only** be emitted if the message is chunked encoded. If not, * the trailers will be silently discarded. * * HTTP requires the `Trailer` header to be sent to emit trailers, * with a list of header field names in its value, e.g. * * ```js * message.writeHead(200, { 'Content-Type': 'text/plain', * 'Trailer': 'Content-MD5' });
* message.write(fileData); * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); * message.end(); * ``` * * Attempting to set a header field name or value that contains invalid characters * will result in a `TypeError` being thrown. * @since v0.3.0 */ addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; /** * Flushes the message headers. * * For efficiency reason, Node.js normally buffers the message headers * until `outgoingMessage.end()` is called or the first chunk of message data * is written. It then tries to pack the headers and data into a single TCP * packet. * * It is usually desired (it saves a TCP round-trip), but not when the first * data is not sent until possibly much later. `outgoingMessage.flushHeaders()`bypasses the optimization and kickstarts the message. * @since v1.6.0 */ flushHeaders(): void; } /** * 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 v0.1.17 */ class ServerResponse<Request extends IncomingMessage = IncomingMessage> extends OutgoingMessage<Request> { /** * 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 v0.4.0 */ statusCode: number; /** * When using implicit headers (not calling `response.writeHead()` explicitly), * this property controls the status message that will be sent to the client when * the headers get flushed. If this is left as `undefined` then the standard * message for the status code will be used. * * ```js * response.statusMessage = 'Not found'; * ``` * * After response header was sent to the client, this property indicates the * status message which was sent out. * @since v0.11.8 */ statusMessage: string; /** * If set to `true`, Node.js will check whether the `Content-Length`header value and the size of the body, in bytes, are equal. * Mismatching the `Content-Length` header value will result * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. * @since v18.10.0, v16.18.0 */ strictContentLength: boolean; constructor(req: Request); assignSocket(socket: Socket): void; detachSocket(socket: Socket): void; /** * Sends an HTTP/1.1 100 Continue message to the client, indicating that * the request body should be sent. See the `'checkContinue'` event on`Server`. * @since v0.3.0 */ writeContinue(callback?: () => void): void; /** * Sends an HTTP/1.1 103 Early Hints message 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. The optional `callback` argument will be called when * the response message has been written. * * **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, * 'x-trace-id': 'id for diagnostics', * }); * * const earlyHintsCallback = () => console.log('early hints message sent'); * response.writeEarlyHints({ * 'link': earlyHintsLinks, * }, earlyHintsCallback); * ``` * @since v18.11.0 * @param hints An object containing the values of headers * @param callback Will be called when the response message has been written */ writeEarlyHints(hints: Record<string, string | string[]>, callback?: () => void): 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. * Optionally one can give a human-readable `statusMessage` as the second * argument. * * `headers` may be an `Array` where 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. The array is in the same * format as `request.rawHeaders`. * * Returns a reference to the `ServerResponse`, so that calls can be chained. * * ```js * const body = 'hello world'; * response * .writeHead(200, { * 'Content-Length': Buffer.byteLength(body), * 'Content-Type': 'text/plain', * }) * .end(body); * ``` * * This method must only be called once on a message and it must * be called 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. * * If this method is called and `response.setHeader()` has not been called, * it will directly write the supplied header values onto the network channel * without caching internally, and the `response.getHeader()` on the header * will not yield the expected result. If progressive population of headers is * desired with potential future retrieval and modification, use `response.setHeader()` instead. * * ```js * // Returns content-type = text/plain * const server = http.createServer((req, res) => { * res.setHeader('Content-Type', 'text/html'); * res.setHeader('X-Foo', 'bar'); * res.writeHead(200, { 'Content-Type': 'text/plain' }); * res.end('ok'); * }); * ``` * * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js * will check whether `Content-Length` and the length of the body which has * been transmitted are equal or not. * * Attempting to set a header field name or value that contains invalid characters * will result in a \[`Error`\]\[\] being thrown. * @since v0.1.30 */ writeHead( statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], ): this; writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; /** * Sends a HTTP/1.1 102 Processing message to the client, indicating that * the request
body should be sent. * @since v10.0.0 */ writeProcessing(): void; } interface InformationEvent { statusCode: number; statusMessage: string; httpVersion: string; httpVersionMajor: number; httpVersionMinor: number; headers: IncomingHttpHeaders; rawHeaders: string[]; } /** * This object is created internally and returned from {@link request}. It * represents an _in-progress_ request whose header has already been queued. The * header is still mutable using the `setHeader(name, value)`,`getHeader(name)`, `removeHeader(name)` API. The actual header will * be sent along with the first data chunk or when calling `request.end()`. * * To get the response, add a listener for `'response'` to the request object.`'response'` will be emitted from the request object when the response * headers have been received. The `'response'` event is executed with one * argument which is an instance of {@link IncomingMessage}. * * During the `'response'` event, one can add listeners to the * response object; particularly to listen for the `'data'` event. * * If no `'response'` handler is added, then the response will be * entirely discarded. However, if a `'response'` event handler is added, * then the data from the response object **must** be consumed, either by * calling `response.read()` whenever there is a `'readable'` event, or * by adding a `'data'` handler, or by calling the `.resume()` method. * Until the data is consumed, the `'end'` event will not fire. Also, until * the data is read it will consume memory that can eventually lead to a * 'process out of memory' error. * * For backward compatibility, `res` will only emit `'error'` if there is an`'error'` listener registered. * * Set `Content-Length` header to limit the response body size. * If `response.strictContentLength` is set to `true`, mismatching the`Content-Length` header value will result in an `Error` being thrown, * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. * * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. * @since v0.1.17 */ class ClientRequest extends OutgoingMessage { /** * The `request.aborted` property will be `true` if the request has * been aborted. * @since v0.11.14 * @deprecated Since v17.0.0,v16.12.0 - Check `destroyed` instead. */ aborted: boolean; /** * The request host. * @since v14.5.0, v12.19.0 */ host: string; /** * The request protocol. * @since v14.5.0, v12.19.0 */ protocol: string; /** * When sending request through a keep-alive enabled agent, the underlying socket * might be reused. But if server closes connection at unfortunate time, client * may run into a 'ECONNRESET' error. * * ```js * import http from 'node:http'; * * // Server has a 5 seconds keep-alive timeout by default * http * .createServer((req, res) => { * res.write('hello\n'); * res.end(); * }) * .listen(3000); * * setInterval(() => { * // Adapting a keep-alive agent * http.get('http://localhost:3000', { agent }, (res) => { * res.on('data', (data) => { * // Do nothing * }); * }); * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout * ``` * * By marking a request whether it reused socket or not, we can do * automatic error retry base on it. * * ```js * import http from 'node:http'
; * const agent = new http.Agent({ keepAlive: true }); * * function retriableRequest() { * const req = http * .get('http://localhost:3000', { agent }, (res) => { * // ... * }) * .on('error', (err) => { * // Check if retry is needed * if (req.reusedSocket &#x26;&#x26; err.code === 'ECONNRESET') { * retriableRequest(); * } * }); * } * * retriableRequest(); * ``` * @since v13.0.0, v12.16.0 */ reusedSocket: boolean; /** * Limits maximum response headers count. If set to 0, no limit will be applied. */ maxHeadersCount: number; constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); /** * The request method. * @since v0.1.97 */ method: string; /** * The request path. * @since v0.4.0 */ path: string; /** * Marks the request as aborting. Calling this will cause remaining data * in the response to be dropped and the socket to be destroyed. * @since v0.3.8 * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. */ abort(): void; onSocket(socket: Socket): void; /** * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. * @since v0.5.9 * @param timeout Milliseconds before a request times out. * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. */ setTimeout(timeout: number, callback?: () => void): this; /** * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. * @since v0.5.9 */ setNoDelay(noDelay?: boolean): void; /** * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. * @since v0.5.9 */ setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; /** * Returns an array containing the unique names of the current outgoing raw * headers. Header names are returned with their exact casing being set. * * ```js * request.setHeader('Foo', 'bar'); * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); * * const headerNames = request.getRawHeaderNames(); * // headerNames === ['Foo', 'Set-Cookie'] * ``` * @since v15.13.0, v14.17.0 */ getRawHeaderNames(): string[]; /** * @deprecated */ addListener(event: "abort", listener: () => void): this; addListener( event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, ): this; addListener(event: "continue", listener: () => void): this; addListener(event: "information", listener: (info: InformationEvent) => void): this; addListener(event: "response", listener: (response: IncomingMessage) => void): this; addListener(event: "socket", listener: (socket: Socket) => void): this; addListener(event: "timeout", listener: () => void): this; addListener( event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, ): this; addListener(event: "close", listener: () => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "finish", listener: () => void): this; addListener(event: "pipe", listener: (src: stream.Readable) => void): th
is; addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; /** * @deprecated */ on(event: "abort", listener: () => void): this; on(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; on(event: "continue", listener: () => void): this; on(event: "information", listener: (info: InformationEvent) => void): this; on(event: "response", listener: (response: IncomingMessage) => void): this; on(event: "socket", listener: (socket: Socket) => void): this; on(event: "timeout", listener: () => void): this; on(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; on(event: "close", listener: () => void): this; on(event: "drain", listener: () => void): this; on(event: "error", listener: (err: 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; /** * @deprecated */ once(event: "abort", listener: () => void): this; once(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; once(event: "continue", listener: () => void): this; once(event: "information", listener: (info: InformationEvent) => void): this; once(event: "response", listener: (response: IncomingMessage) => void): this; once(event: "socket", listener: (socket: Socket) => void): this; once(event: "timeout", listener: () => void): this; once(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; once(event: "close", listener: () => void): this; once(event: "drain", listener: () => void): this; once(event: "error", listener: (err: 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; /** * @deprecated */ prependListener(event: "abort", listener: () => void): this; prependListener( event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, ): this; prependListener(event: "continue", listener: () => void): this; prependListener(event: "information", listener: (info: InformationEvent) => void): this; prependListener(event: "response", listener: (response: IncomingMessage) => void): this; prependListener(event: "socket", listener: (socket: Socket) => void): this; prependListener(event: "timeout", listener: () => void): this; prependListener( event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, ): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "drain", listener: () => void): this; prependListener(event: "error", listener: (err: 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; /** * @deprecated */ prependOnceListener(eve
nt: "abort", listener: () => void): this; prependOnceListener( event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, ): this; prependOnceListener(event: "continue", listener: () => void): this; prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; prependOnceListener( event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, ): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "error", listener: (err: 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; } /** * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to * access response * status, headers, and data. * * Different from its `socket` value which is a subclass of `stream.Duplex`, the`IncomingMessage` itself extends `stream.Readable` and is created separately to * parse and emit the incoming HTTP headers and payload, as the underlying socket * may be reused multiple times in case of keep-alive. * @since v0.1.17 */ class IncomingMessage extends stream.Readable { constructor(socket: Socket); /** * The `message.aborted` property will be `true` if the request has * been aborted. * @since v10.1.0 * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from <a href="stream.html#class-streamreadable" class="type">stream.Readable</a>. */ aborted: boolean; /** * 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. * Probably either `'1.1'` or `'1.0'`. * * Also `message.httpVersionMajor` is the first integer and`message.httpVersionMinor` is the second. * @since v0.1.1 */ httpVersion: string; httpVersionMajor: number; httpVersionMinor: number; /** * The `message.complete` property will be `true` if a complete HTTP message has * been received and successfully parsed. * * This property is particularly useful as a means of determining if a client or * server fully transmitted a message before a connection was terminated: * * ```js * const req = http.request({ * host: '127.0.0.1', * port: 8080, * method: 'POST', * }, (res) => { * res.resume(); * res.on('end', () => { * if (!res.complete) * console.error( * 'The connection was terminated while the message was still being sent'); * }); * }); * ``` * @since v0.3.0 */ complete: boolean; /** * Alias for `message.socket`. * @since v0.1.90 * @deprecated Since v16.0.0 - Use `socket`. */ connection: Socket; /** * The `net.Socket` object associated with the connection.
* * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the * client's authentication details. * * This property is guaranteed to be an instance of the `net.Socket` class, * a subclass of `stream.Duplex`, unless the user specified a socket * type other than `net.Socket` or internally nulled. * @since v0.3.0 */ socket: Socket; /** * 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); * ``` * * Duplicates in raw headers are handled in the following ways, depending on the * header name: * * * Duplicates of `age`, `authorization`, `content-length`, `content-type`,`etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,`last-modified`, `location`, * `max-forwards`, `proxy-authorization`, `referer`,`retry-after`, `server`, or `user-agent` are discarded. * To allow duplicate values of the headers listed above to be joined, * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more * information. * * `set-cookie` is always an array. Duplicates are added to the array. * * For duplicate `cookie` headers, the values are joined together with `; `. * * For all other headers, the values are joined together with `, `. * @since v0.1.5 */ headers: IncomingHttpHeaders; /** * Similar to `message.headers`, but there is no join logic and the values are * always arrays of strings, even for headers received just once. * * ```js * // Prints something like: * // * // { 'user-agent': ['curl/7.22.0'], * // host: ['127.0.0.1:8000'], * // accept: ['*'] } * console.log(request.headersDistinct); * ``` * @since v18.3.0, v16.17.0 */ headersDistinct: NodeJS.Dict<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 v0.11.6 */ rawHeaders: string[]; /** * The request/response trailers object. Only populated at the `'end'` event. * @since v0.3.0 */ trailers: NodeJS.Dict<string>; /** * Similar to `message.trailers`, but there is no join logic and the values are * always arrays of strings, even for headers received just once. * Only populated at the `'end'` event. * @since v18.3.0, v16.17.0 */ trailersDistinct: NodeJS.Dict<string[]>; /** * The raw request/response trailer keys and values exactly as they were * received. Only populated at the `'end'` event. * @since v0.11.6 */ rawTrailers: string[]; /** * Calls `message.socket.setTimeout
(msecs, callback)`. * @since v0.5.9 */ setTimeout(msecs: number, callback?: () => void): this; /** * **Only valid for request obtained from {@link Server}.** * * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. * @since v0.1.1 */ method?: string | undefined; /** * **Only valid for request obtained from {@link Server}.** * * Request URL string. This contains only the URL that is present in the actual * HTTP request. Take the following request: * * ```http * GET /status?name=ryan HTTP/1.1 * Accept: text/plain * ``` * * To parse the URL into its parts: * * ```js * new URL(request.url, `http://${request.headers.host}`); * ``` * * When `request.url` is `'/status?name=ryan'` and `request.headers.host` is`'localhost:3000'`: * * ```console * $ node * > new URL(request.url, `http://${request.headers.host}`) * URL { * href: 'http://localhost:3000/status?name=ryan', * origin: 'http://localhost:3000', * protocol: 'http:', * username: '', * password: '', * host: 'localhost:3000', * hostname: 'localhost', * port: '3000', * pathname: '/status', * search: '?name=ryan', * searchParams: URLSearchParams { 'name' => 'ryan' }, * hash: '' * } * ``` * @since v0.1.90 */ url?: string | undefined; /** * **Only valid for response obtained from {@link ClientRequest}.** * * The 3-digit HTTP response status code. E.G. `404`. * @since v0.1.1 */ statusCode?: number | undefined; /** * **Only valid for response obtained from {@link ClientRequest}.** * * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. * @since v0.11.10 */ statusMessage?: string | undefined; /** * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`is provided, an `'error'` event is emitted on the socket and `error` is passed * as an argument to any listeners on the event. * @since v0.3.0 */ destroy(error?: Error): this; } interface AgentOptions extends Partial<TcpSocketConnectOpts> { /** * Keep sockets around in a pool to be used by other requests in the future. Default = false */ keepAlive?: boolean | undefined; /** * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. * Only relevant if keepAlive is set to true. */ keepAliveMsecs?: number | undefined; /** * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity */ maxSockets?: number | undefined; /** * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. */ maxTotalSockets?: number | undefined; /** * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. */ maxFreeSockets?: number | undefined; /** * Socket timeout in milliseconds. This will set the timeout after the socket is connected. */ timeout?: number | undefined; /** * Scheduling strategy to apply when picking the next free socket to use. * @default `lifo` */ scheduling?: "fifo" | "lifo" | undefined; } /** * An `Agent` is responsible fo
r managing connection persistence * and reuse for HTTP clients. It maintains a queue of pending requests * for a given host and port, reusing a single socket connection for each * until the queue is empty, at which time the socket is either destroyed * or put into a pool where it is kept to be used again for requests to the * same host and port. Whether it is destroyed or pooled depends on the`keepAlive` `option`. * * Pooled connections have TCP Keep-Alive enabled for them, but servers may * still close idle connections, in which case they will be removed from the * pool and a new connection will be made when a new HTTP request is made for * that host and port. Servers may also refuse to allow multiple requests * over the same connection, in which case the connection will have to be * remade for every request and cannot be pooled. The `Agent` will still make * the requests to that server, but each one will occur over a new connection. * * When a connection is closed by the client or the server, it is removed * from the pool. Any unused sockets in the pool will be unrefed so as not * to keep the Node.js process running when there are no outstanding requests. * (see `socket.unref()`). * * It is good practice, to `destroy()` an `Agent` instance when it is no * longer in use, because unused sockets consume OS resources. * * Sockets are removed from an agent when the socket emits either * a `'close'` event or an `'agentRemove'` event. When intending to keep one * HTTP request open for a long time without keeping it in the agent, something * like the following may be done: * * ```js * http.get(options, (res) => { * // Do stuff * }).on('socket', (socket) => { * socket.emit('agentRemove'); * }); * ``` * * An agent may also be used for an individual request. By providing`{agent: false}` as an option to the `http.get()` or `http.request()`functions, a one-time use `Agent` with default options * will be used * for the client connection. * * `agent:false`: * * ```js * http.get({ * hostname: 'localhost', * port: 80, * path: '/', * agent: false, // Create a new agent just for this one request * }, (res) => { * // Do stuff with response * }); * ``` * @since v0.3.4 */ class Agent extends EventEmitter { /** * By default set to 256. For agents with `keepAlive` enabled, this * sets the maximum number of sockets that will be left open in the free * state. * @since v0.11.7 */ maxFreeSockets: number; /** * By default set to `Infinity`. Determines how many concurrent sockets the agent * can have open per origin. Origin is the returned value of `agent.getName()`. * @since v0.3.6 */ maxSockets: number; /** * By default set to `Infinity`. Determines how many concurrent sockets the agent * can have open. Unlike `maxSockets`, this parameter applies across all origins. * @since v14.5.0, v12.19.0 */ maxTotalSockets: number; /** * An object which contains arrays of sockets currently awaiting use by * the agent when `keepAlive` is enabled. Do not modify. * * Sockets in the `freeSockets` list will be automatically destroyed and * removed from the array on `'timeout'`. * @since v0.11.4 */ readonly freeSockets: NodeJS.ReadOnlyDict<Socket[]>; /** * An object which contains arrays of sockets currently in use by the * agent. Do not modify. * @since v0.3.6 */ readonly sockets: NodeJS.ReadOnlyDict<Socket[]>; /** * An object which contains queues of requests that have not yet been
assigned to * sockets. Do not modify. * @since v0.5.9 */ readonly requests: NodeJS.ReadOnlyDict<IncomingMessage[]>; constructor(opts?: AgentOptions); /** * Destroy any sockets that are currently in use by the agent. * * It is usually not necessary to do this. However, if using an * agent with `keepAlive` enabled, then it is best to explicitly shut down * the agent when it is no longer needed. Otherwise, * sockets might stay open for quite a long time before the server * terminates them. * @since v0.11.4 */ destroy(): void; } const METHODS: string[]; const STATUS_CODES: { [errorCode: number]: string | undefined; [errorCode: string]: string | undefined; }; /** * Returns a new instance of {@link Server}. * * The `requestListener` is a function which is automatically * added to the `'request'` event. * * ```js * import http from 'node:http'; * * // Create a local server to receive data from * const server = http.createServer((req, res) => { * res.writeHead(200, { 'Content-Type': 'application/json' }); * res.end(JSON.stringify({ * data: 'Hello World!', * })); * }); * * server.listen(8000); * ``` * * ```js * import http from 'node:http'; * * // Create a local server to receive data from * const server = http.createServer(); * * // Listen to the request event * server.on('request', (request, res) => { * res.writeHead(200, { 'Content-Type': 'application/json' }); * res.end(JSON.stringify({ * data: 'Hello World!', * })); * }); * * server.listen(8000); * ``` * @since v0.1.13 */ function createServer< Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse = typeof ServerResponse, >(requestListener?: RequestListener<Request, Response>): Server<Request, Response>; function createServer< Request extends typeof IncomingMessage = typeof IncomingMessage, Response extends typeof ServerResponse = typeof ServerResponse, >( options: ServerOptions<Request, Response>, requestListener?: RequestListener<Request, Response>, ): Server<Request, Response>; // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, // create interface RequestOptions would make the naming more clear to developers interface RequestOptions extends ClientRequestArgs {} /** * `options` in `socket.connect()` are also supported. * * Node.js maintains several connections per server to make HTTP requests. * This function allows one to transparently issue requests. * * `url` can be a string or a `URL` object. If `url` is a * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. * * If both `url` and `options` are specified, the objects are merged, with the`options` properties taking precedence. * * The optional `callback` parameter will be added as a one-time listener for * the `'response'` event. * * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to * upload a file with a POST request, then write to the `ClientRequest` object. * * ```js * import http from 'node:http'; * import { Buffer } from 'node:buffer'; * * const postData = JSON.stringify({ * 'msg': 'Hello World!', * }); * * const options = { * hostname: 'www.google.com', * port: 80, * path: '/upload', * method: 'POST', * headers: { * 'Content-Type':
'application/json', * 'Content-Length': Buffer.byteLength(postData), * }, * }; * * const req = http.request(options, (res) => { * console.log(`STATUS: ${res.statusCode}`); * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); * res.setEncoding('utf8'); * res.on('data', (chunk) => { * console.log(`BODY: ${chunk}`); * }); * res.on('end', () => { * console.log('No more data in response.'); * }); * }); * * req.on('error', (e) => { * console.error(`problem with request: ${e.message}`); * }); * * // Write data to request body * req.write(postData); * req.end(); * ``` * * In the example `req.end()` was called. With `http.request()` one * must always call `req.end()` to signify the end of the request - * even if there is no data being written to the request body. * * If any error is encountered during the request (be that with DNS resolution, * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted * on the returned request object. As with all `'error'` events, if no listeners * are registered the error will be thrown. * * There are a few special headers that should be noted. * * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to * the server should be persisted until the next request. * * Sending a 'Content-Length' header will disable the default chunked encoding. * * Sending an 'Expect' header will immediately send the request headers. * Usually, when sending 'Expect: 100-continue', both a timeout and a listener * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more * information. * * Sending an Authorization header will override using the `auth` option * to compute basic authentication. * * Example using a `URL` as `options`: * * ```js * const options = new URL('http://abc:xyz@example.com'); * * const req = http.request(options, (res) => { * // ... * }); * ``` * * In a successful request, the following events will be emitted in the following * order: * * * `'socket'` * * `'response'` * * `'data'` any number of times, on the `res` object * (`'data'` will not be emitted at all if the response body is empty, for * instance, in most redirects) * * `'end'` on the `res` object * * `'close'` * * In the case of a connection error, the following events will be emitted: * * * `'socket'` * * `'error'` * * `'close'` * * In the case of a premature connection close before the response is received, * the following events will be emitted in the following order: * * * `'socket'` * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` * * `'close'` * * In the case of a premature connection close after the response is received, * the following events will be emitted in the following order: * * * `'socket'` * * `'response'` * * `'data'` any number of times, on the `res` object * * (connection closed here) * * `'aborted'` on the `res` object * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'` * * `'close'` * * `'close'` on the `res` object * * If `req.destroy()` is called before a socket is assigned, the following * events will be emitted in the following order: * * * (`req.destroy()` called here) * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * If `req.destroy()` is called before the connection succeeds, the following * events will be emit
ted in the following order: * * * `'socket'` * * (`req.destroy()` called here) * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * If `req.destroy()` is called after the response is received, the following * events will be emitted in the following order: * * * `'socket'` * * `'response'` * * `'data'` any number of times, on the `res` object * * (`req.destroy()` called here) * * `'aborted'` on the `res` object * * `'error'` on the `res` object with an error with message `'Error: aborted'`and code `'ECONNRESET'`, or the error with which `req.destroy()` was called * * `'close'` * * `'close'` on the `res` object * * If `req.abort()` is called before a socket is assigned, the following * events will be emitted in the following order: * * * (`req.abort()` called here) * * `'abort'` * * `'close'` * * If `req.abort()` is called before the connection succeeds, the following * events will be emitted in the following order: * * * `'socket'` * * (`req.abort()` called here) * * `'abort'` * * `'error'` with an error with message `'Error: socket hang up'` and code`'ECONNRESET'` * * `'close'` * * If `req.abort()` is called after the response is received, the following * events will be emitted in the following order: * * * `'socket'` * * `'response'` * * `'data'` any number of times, on the `res` object * * (`req.abort()` called here) * * `'abort'` * * `'aborted'` on the `res` object * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. * * `'close'` * * `'close'` on the `res` object * * Setting the `timeout` option or using the `setTimeout()` function will * not abort the request or do anything besides add a `'timeout'` event. * * Passing an `AbortSignal` and then calling `abort()` on the corresponding`AbortController` will behave the same way as calling `.destroy()` on the * request. Specifically, the `'error'` event will be emitted with an error with * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'`and the `cause`, if one was provided. * @since v0.3.6 */ function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; function request( url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void, ): ClientRequest; /** * Since most requests are GET requests without bodies, Node.js provides this * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()`automatically. The callback must take care to * consume the response * data for reasons stated in {@link ClientRequest} section. * * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. * * JSON fetching example: * * ```js * http.get('http://localhost:8000/', (res) => { * const { statusCode } = res; * const contentType = res.headers['content-type']; * * let error; * // Any 2xx status code signals a successful response but * // here we're only checking for 200. * if (statusCode !== 200) { * error = new Error('Request Failed.\n' + * `Status Code: ${statusCode}`); * } else if (!/^application\/json/.test(contentType)) { * error = new Error('Invalid content-type.\n' + * `Expected application/json but received ${contentType}`); * } * if (error) { * console.error(error.message); * // Con
sume response data to free up memory * res.resume(); * return; * } * * res.setEncoding('utf8'); * let rawData = ''; * res.on('data', (chunk) => { rawData += chunk; }); * res.on('end', () => { * try { * const parsedData = JSON.parse(rawData); * console.log(parsedData); * } catch (e) { * console.error(e.message); * } * }); * }).on('error', (e) => { * console.error(`Got error: ${e.message}`); * }); * * // Create a local server to receive data from * const server = http.createServer((req, res) => { * res.writeHead(200, { 'Content-Type': 'application/json' }); * res.end(JSON.stringify({ * data: 'Hello World!', * })); * }); * * server.listen(8000); * ``` * @since v0.3.6 * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. */ function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; /** * Performs the low-level validations on the provided `name` that are done when`res.setHeader(name, value)` is called. * * Passing illegal value as `name` will result in a `TypeError` being thrown, * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. * * It is not necessary to use this method before passing headers to an HTTP request * or response. The HTTP module will automatically validate such headers. * * Example: * * ```js * import { validateHeaderName } from 'node:http'; * * try { * validateHeaderName(''); * } catch (err) { * console.error(err instanceof TypeError); // --> true * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' * } * ``` * @since v14.3.0 * @param [label='Header name'] Label for error message. */ function validateHeaderName(name: string): void; /** * Performs the low-level validations on the provided `value` that are done when`res.setHeader(name, value)` is called. * * Passing illegal value as `value` will result in a `TypeError` being thrown. * * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. * * It is not necessary to use this method before passing headers to an HTTP request * or response. The HTTP module will automatically validate such headers. * * Examples: * * ```js * import { validateHeaderValue } from 'node:http'; * * try { * validateHeaderValue('x-my-header', undefined); * } catch (err) { * console.error(err instanceof TypeError); // --> true * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' * } * * try { * validateHeaderValue('x-my-header', 'oʊmΙͺΙ‘Ι™'); * } catch (err) { * console.error(err instanceof TypeError); // --> true * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' * } * ``` * @since v14.3.0 * @param name Header name * @param value Header value */ function validateHeaderValue(name: string, value: string): void; /** * Set the maximum number of idle HTTP parsers. * @since v18.8.0, v16.18.0 * @param [max=1000] */ function setMaxIdleHTTPParsers(max: number): void; let globalAgent: Agent; /** * Re
ad-only property specifying the maximum allowed size of HTTP headers in bytes. * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. */ const maxHeaderSize: number; } declare module "node:http" { export * from "http"; }
/** * 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