Send a HTTP(s) request
module
globals
- @param input
URL string or Request object
@param initA structured value that contains settings for the fetch() request.
@returnsA promise that resolves to Response object.
namespace fetch
Bun's extensions of the
fetch
API- options?: { dns: boolean; http: boolean; https: boolean; tcp: boolean }): void;
Preconnect to a URL. This can be used to improve performance by pre-resolving the DNS and establishing a TCP connection before the request is made.
This is a custom property that is not part of the Fetch API specification.
@param urlThe URL to preconnect to
@param optionsOptions for the preconnect
- ...arguments: any[]
Run a function immediately after main event loop is vacant
@param handlerfunction to call
namespace setImmediate
- handler: TimerHandler,timeout?: number,...arguments: any[]): number;
namespace setTimeout
Same as module.exports
- const Loader: { dependencyKeysIfEvaluated: (specifier: string) => string[]; registry: Map<string, { dependencies: typeof Loader['registry'] extends Map<any, infer V> ? V : any[]; evaluated: boolean; fetch: Promise<any>; instantiate: Promise<any>; isAsync: boolean; key: string; linkError: any; linkSucceeded: boolean; module: { dependenciesMap: typeof Loader['registry'] }; satisfy: Promise<any>; state: number; then: any }>; resolve: (specifier: string, referrer: string) => string }
Low-level JavaScriptCore API for accessing the native ES Module loader (not a Bun API)
Before using this, be aware of a few things:
Using this incorrectly will crash your application.
This API may change any time JavaScriptCore is updated.
Bun may rewrite ESM import specifiers to point to bundled code. This will be confusing when using this API, as it will return a string like "/node_modules.server.bun".
Bun may inject additional imports into your code. This usually has a
bun:
prefix. A reference to the current module.
NodeJS-style
require
function- type: K,): void;
- ): void;
Cancel an immediate function call by its immediate ID.
@param idimmediate id
Send a HTTP(s) request
@param inputURL string or Request object
@param initA structured value that contains settings for the fetch() request.
@returnsA promise that resolves to Response object.
options?: { dns: boolean; http: boolean; https: boolean; tcp: boolean }): void;Preconnect to a URL. This can be used to improve performance by pre-resolving the DNS and establishing a TCP connection before the request is made.
This is a custom property that is not part of the Fetch API specification.
@param urlThe URL to preconnect to
@param optionsOptions for the preconnect
- message: any,): void;
Post a message to the parent thread.
Only useful in a worker thread; calling this from the main thread does nothing.
- type: K,): void;
- @param error
Error or string
- ...arguments: any[]
Run a function immediately after main event loop is vacant
@param handlerfunction to call
- handler: TimerHandler,timeout?: number,...arguments: any[]): number;
- handler: TimerHandler,timeout?: number,...arguments: any[]): number;
class URL
The URL interface represents an object providing static methods used for creating object URLs.
The
toString()
method on theURL
object returns the serialized URL. The value returned is equivalent to that of href and toJSON.
class MessageEvent<T = any>
A message received by a target object.
- readonly bubbles: boolean
Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.
- readonly cancelable: boolean
Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.
- readonly composed: boolean
Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.
- readonly currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
- readonly defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
- readonly eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
- readonly isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
- readonly origin: string
Returns the origin of the message, for server-sent events and cross-document messaging.
- readonly ports: readonly MessagePort[]
Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging.
- readonly source: null | MessageEventSource
Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects.
- readonly timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the
defaultPrevented
property totrue
ifcancelable
istrue
.Stops the invocation of event listeners after the current one completes.
This is not used in Node.js and is provided purely for completeness.
class AbortController
A controller object that allows you to abort one or more DOM requests as and when desired.
class AbortSignal
A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object.
- readonly aborted: boolean
Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.
- type: K,): void;
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
- ): boolean;
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.
- type: K,options?: boolean | EventListenerOptions): void;
Removes the event listener in target's event listener list with the same type, callback, and options.
class ArrayBuffer
Represents a raw buffer of binary data, which is used to store data for the different typed arrays. ArrayBuffers cannot be read from or written to directly, but can be passed to a typed array or DataView Object to interpret the raw buffer as needed.
class Blob
A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
Returns a promise that resolves to the contents of the blob as an ArrayBuffer
Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes) its the same as
new Uint8Array(await blob.arrayBuffer())
Read the data from the blob as a FormData object.
This first decodes the data from UTF-8, then parses it as a
multipart/form-data
body or aapplication/x-www-form-urlencoded
body.The
type
property of the blob is used to determine the format of the body.This is a non-standard addition to the
Blob
API, to make it conform more closely to theBodyMixin
API.Read the data from the blob as a JSON object.
This first decodes the data from UTF-8, then parses it as JSON.
Returns a readable stream of the blob's contents
Returns a promise that resolves to the contents of the blob as a string
- type: K,): void;
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
type: string,listener: EventListenerOrEventListenerObject,): void;Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
Closes the BroadcastChannel object, opening it up to garbage collection.
- ): boolean;
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.
- message: any): void;
Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays.
- type: K,options?: boolean | EventListenerOptions): void;
Removes the event listener in target's event listener list with the same type, callback, and options.
type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;Removes the event listener in target's event listener list with the same type, callback, and options.
class ByteLengthQueuingStrategy
This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.
class CloseEvent
A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute.
- readonly bubbles: boolean
Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.
- readonly cancelable: boolean
Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.
- readonly composed: boolean
Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.
- readonly currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
- readonly defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
- readonly eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
- readonly isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
- readonly timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the
defaultPrevented
property totrue
ifcancelable
istrue
.Stops the invocation of event listeners after the current one completes.
This is not used in Node.js and is provided purely for completeness.
class CountQueuingStrategy
This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.
class Crypto
Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives.
class CryptoKey
The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. Available only in secure contexts.
class CustomEvent<T = any>
- readonly bubbles: boolean
Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.
- readonly cancelable: boolean
Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.
- readonly composed: boolean
Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.
- readonly currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
- readonly defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
- readonly detail: T
Returns any custom data event was created with. Typically used for synthetic events.
- readonly eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
- readonly isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
- readonly timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the
defaultPrevented
property totrue
ifcancelable
istrue
.Stops the invocation of event listeners after the current one completes.
This is not used in Node.js and is provided purely for completeness.
class DOMException
An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API.
class ErrorEvent
Events providing information related to errors in scripts or in files.
- readonly bubbles: boolean
Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.
- readonly cancelable: boolean
Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.
- readonly composed: boolean
Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.
- readonly currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
- readonly defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
- readonly eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
- readonly isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
- readonly timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the
defaultPrevented
property totrue
ifcancelable
istrue
.Stops the invocation of event listeners after the current one completes.
This is not used in Node.js and is provided purely for completeness.
class Event
An event which takes place in the DOM.
- readonly bubbles: boolean
Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.
- readonly cancelable: boolean
Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.
- readonly composed: boolean
Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.
- readonly currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
- readonly defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
- readonly eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
- readonly isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
- readonly timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the
defaultPrevented
property totrue
ifcancelable
istrue
.Stops the invocation of event listeners after the current one completes.
This is not used in Node.js and is provided purely for completeness.
class EventTarget
EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.
- type: string,callback: null | EventListenerOrEventListenerObject,): void;
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
type: string,): void;Adds a new handler for the
type
event. Any givenlistener
is added only once pertype
and percapture
option value.If the
once
option is true, thelistener
is removed after the next time atype
event is dispatched.The
capture
option is not used by Node.js in any functional way other than tracking registered event listeners per theEventTarget
specification. Specifically, thecapture
option is used as part of the key when registering alistener
. Any individuallistener
may be added once withcapture = false
, and once withcapture = true
. - ): boolean;
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.
- type: string,callback: null | EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;
Removes the event listener in target's event listener list with the same type, callback, and options.
type: string,): void;Removes the event listener in target's event listener list with the same type, callback, and options.
class File
Provides information about files and allows JavaScript in a web page to access their content.
Returns a promise that resolves to the contents of the blob as an ArrayBuffer
Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes) its the same as
new Uint8Array(await blob.arrayBuffer())
Read the data from the blob as a FormData object.
This first decodes the data from UTF-8, then parses it as a
multipart/form-data
body or aapplication/x-www-form-urlencoded
body.The
type
property of the blob is used to determine the format of the body.This is a non-standard addition to the
Blob
API, to make it conform more closely to theBodyMixin
API.Read the data from the blob as a JSON object.
This first decodes the data from UTF-8, then parses it as JSON.
Returns a readable stream of the blob's contents
Returns a promise that resolves to the contents of the blob as a string
class FormData
Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".
- thisArg?: any): void;
class Headers
This Fetch API interface allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs. You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence.
Returns an iterator allowing to go through all key/value pairs contained in this object.
- name: 'set-cookie' | 'Set-Cookie'): string[];
Get all headers matching the name
Only supports
"Set-Cookie"
. All other headers are empty arrays.@param nameThe header name to get
@returnsAn array of header values
const headers = new Headers(); headers.append("Set-Cookie", "foo=bar"); headers.append("Set-Cookie", "baz=qux"); headers.getAll("Set-Cookie"); // ["foo=bar", "baz=qux"]
Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.
Convert Headers to a plain JavaScript object.
About 10x faster than
Object.fromEntries(headers.entries())
Called when you run
JSON.stringify(headers)
Does not preserve insertion order. Well-known header names are lowercased. Other header names are left as-is.
Returns an iterator allowing to go through all values of the key/value pairs contained in this object.
class MessageChannel
This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties.
class MessagePort
This Channel Messaging API interface represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.
- type: K,): void;
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
type: string,listener: EventListenerOrEventListenerObject,): void;Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
Disconnects the port, so that it is no longer active.
- ): boolean;
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.
- message: any,transfer: Transferable[]): void;
Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side.
Throws a "DataCloneError" DOMException if transfer contains duplicate objects or port, or if message could not be cloned.
- type: K,options?: boolean | EventListenerOptions): void;
Removes the event listener in target's event listener list with the same type, callback, and options.
type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;Removes the event listener in target's event listener list with the same type, callback, and options.
Begins dispatching messages received on the port.
class Performance
Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API.
- type: K,): void;
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
type: string,listener: EventListenerOrEventListenerObject,): void;Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
- ): boolean;
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.
- measureName: string,startOrMeasureOptions?: string | PerformanceMeasureOptions,endMark?: string
- type: K,options?: boolean | EventListenerOptions): void;
Removes the event listener in target's event listener list with the same type, callback, and options.
type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;Removes the event listener in target's event listener list with the same type, callback, and options.
class PerformanceEntry
Encapsulates a single performance metric that is part of the performance timeline. A performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. Performance entries are also created in indirect ways such as loading a resource (such as an image).
class PerformanceMark
PerformanceMark is an abstract interface for PerformanceEntry objects with an entryType of "mark". Entries of this type are created by calling performance.mark() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline.
class PerformanceMeasure
PerformanceMeasure is an abstract interface for PerformanceEntry objects with an entryType of "measure". Entries of this type are created by calling performance.measure() to add a named DOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline.
class PerformanceResourceTiming
Enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. An application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an XMLHttpRequest, <SVG>, image, or script.
class ReadableStream<R = any>
This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.
- view: T): Promise<ReadableStreamReadResult<T>>;
class ReadableStreamDefaultController<R = any>
class ReadableStreamDefaultReader<R = any>
- readMany(): ReadableStreamDefaultReadManyResult<R> | Promise<ReadableStreamDefaultReadManyResult<R>>;
Only available in Bun. If there are multiple chunks in the queue, this will return all of them at the same time. Will only return a promise if the data is not immediately available.
class Request
This Fetch API interface represents a resource request.
- readonly cache: RequestCache
Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching.
- readonly credentials: RequestCredentials
Returns the credentials mode associated with request, which is a string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL.
- readonly destination: RequestDestination
Returns the kind of resource requested by request, e.g., "document" or "script".
- readonly integrity: string
Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI]
- readonly keepalive: boolean
Returns a boolean indicating whether or not request can outlive the global in which it was created.
- readonly mode: RequestMode
Returns the mode associated with request, which is a string indicating whether the request will use CORS, or will be restricted to same-origin URLs.
- readonly redirect: RequestRedirect
Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default.
- readonly referrer: string
Returns the referrer of request. Its value can be a same-origin URL if explicitly set in init, the empty string to indicate no referrer, and "about:client" when defaulting to the global's default. This is used during fetching to determine the value of the
Referer
header of the request being made. - readonly referrerPolicy: ReferrerPolicy
Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer.
- readonly signal: AbortSignal
Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler.
class Response
This Fetch API interface represents the response to a request.
class ShadowRealm
ShadowRealms are a distinct global environment, with its own global object containing its own intrinsics and built-ins (standard objects that are not bound to global variables, like the initial value of Object.prototype).
const red = new ShadowRealm(); // realms can import modules that will execute within it's own environment. // When the module is resolved, it captured the binding value, or creates a new // wrapped function that is connected to the callable binding. const redAdd = await red.importValue('./inside-code.js', 'add'); // redAdd is a wrapped function exotic object that chains it's call to the // respective imported binding. let result = redAdd(2, 3); console.assert(result === 5); // yields true // The evaluate method can provide quick code evaluation within the constructed // shadowRealm without requiring any module loading, while it still requires CSP // relaxing. globalThis.someValue = 1; red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global console.assert(globalThis.someValue === 1); // The wrapped functions can also wrap other functions the other way around. const setUniqueValue = await red.importValue('./inside-code.js', 'setUniqueValue'); // setUniqueValue = (cb) => (cb(globalThis.someValue) * 2); result = setUniqueValue((x) => x ** 3); console.assert(result === 16); // yields true
const red = new ShadowRealm(); // realms can import modules that will execute within it's own environment. // When the module is resolved, it captured the binding value, or creates a new // wrapped function that is connected to the callable binding. const redAdd = await red.importValue('./inside-code.js', 'add'); // redAdd is a wrapped function exotic object that chains it's call to the // respective imported binding. let result = redAdd(2, 3); console.assert(result === 5); // yields true // The evaluate method can provide quick code evaluation within the constructed // shadowRealm without requiring any module loading, while it still requires CSP // relaxing. globalThis.someValue = 1; red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global console.assert(globalThis.someValue === 1); // The wrapped functions can also wrap other functions the other way around. const setUniqueValue = await red.importValue('./inside-code.js', 'setUniqueValue'); // setUniqueValue = (cb) => (cb(globalThis.someValue) * 2); result = setUniqueValue((x) => x ** 3); console.assert(result === 16); // yields true
class SubtleCrypto
This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). Available only in secure contexts.
- algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,data: BufferSource
- algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,length?: null | number
- algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,derivedKeyType: AlgorithmIdentifier | HkdfParams | Pbkdf2Params | AesDerivedKeyParams | HmacImportParams,extractable: boolean,keyUsages: KeyUsage[]algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,derivedKeyType: AlgorithmIdentifier | HkdfParams | Pbkdf2Params | AesDerivedKeyParams | HmacImportParams,extractable: boolean,keyUsages: Iterable<KeyUsage>
- algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,data: BufferSource
- algorithm: 'Ed25519' | { name: 'Ed25519' },extractable: boolean,keyUsages: readonly 'sign' | 'verify'[]): Promise<CryptoKeyPair>;algorithm: RsaHashedKeyGenParams | EcKeyGenParams,extractable: boolean,keyUsages: readonly KeyUsage[]): Promise<CryptoKeyPair>;algorithm: Pbkdf2Params | AesKeyGenParams | HmacKeyGenParams,extractable: boolean,keyUsages: readonly KeyUsage[]algorithm: AlgorithmIdentifier,extractable: boolean,keyUsages: KeyUsage[]algorithm: AlgorithmIdentifier,extractable: boolean,keyUsages: Iterable<KeyUsage>
- format: 'jwk',keyData: JsonWebKey,algorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,extractable: boolean,keyUsages: readonly KeyUsage[]
- format: KeyFormat,wrappedKey: BufferSource,unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,unwrappedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,extractable: boolean,keyUsages: KeyUsage[]format: KeyFormat,wrappedKey: BufferSource,unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,unwrappedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,extractable: boolean,keyUsages: Iterable<KeyUsage>
- algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,signature: BufferSource,data: BufferSource): Promise<boolean>;
- format: KeyFormat,wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams
class TextDecoder
A decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays.
- input?: AllowSharedBufferSource,options?: TextDecodeOptions): string;
Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments.
var string = "", decoder = new TextDecoder(encoding), buffer; while(buffer = next_chunk()) { string += decoder.decode(buffer, {stream:true}); } string += decoder.decode(); // end-of-queue
If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError.
class TextEncoder
TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays.
- source: string,): TextEncoderEncodeIntoResult;
Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination.
src?: string,UTF-8 encodes the
src
string to thedest
Uint8Array and returns an object containing the read Unicode code units and written UTF-8 bytes.const encoder = new TextEncoder(); const src = 'this is some data'; const dest = new Uint8Array(10); const { read, written } = encoder.encodeInto(src, dest);
@param srcThe text to encode.
@param destThe array to hold the encode result.
class TransformStream<I = any, O = any>
class TransformStreamDefaultController<O = any>
class Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike>
A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.
- @param index
The zero-based index of the desired code unit. A negative index will count back from the last item.
- target: number,start: number,end?: number): this;
Returns the this object after copying a section of the array identified by start and end to the same array starting at position target
@param targetIf target is negative, it is treated as length+target where length is the length of the array.
@param startIf start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
@param endIf not specified, length of the this object is used as its default value.
Returns an array of key, value pairs for every entry in the array
- predicate: (value: number, index: number, array: this) => unknown,thisArg?: any): boolean;
Determines whether all the members of an array satisfy the specified test.
@param predicateA function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
@param thisArgAn object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
- fill(value: number,start?: number,end?: number): this;
Changes all array elements from
start
toend
index to a staticvalue
and returns the modified array@param valuevalue to fill array section with
@param startindex to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
@param endindex to stop filling the array at. If end is negative, it is treated as length+end.
- predicate: (value: number, index: number, array: this) => any,thisArg?: any
Returns the elements of an array that meet the condition specified in a callback function.
@param predicateA function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
@param thisArgAn object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
- find(predicate: (value: number, index: number, obj: this) => boolean,thisArg?: any): undefined | number;
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
@param predicatefind calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
@param thisArgIf provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
- predicate: (value: number, index: number, obj: this) => boolean,thisArg?: any): number;
Returns the index of the first element in the array where predicate is true, and -1 otherwise.
@param predicatefind calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
@param thisArgIf provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
- predicate: (value: number, index: number, array: this) => value is S,thisArg?: any): undefined | S;
Returns the value of the last element in the array where predicate is true, and undefined otherwise.
@param predicatefindLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
@param thisArgIf provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
predicate: (value: number, index: number, array: this) => unknown,thisArg?: any): undefined | number; - predicate: (value: number, index: number, array: this) => unknown,thisArg?: any): number;
Returns the index of the last element in the array where predicate is true, and -1 otherwise.
@param predicatefindLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
@param thisArgIf provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
- callbackfn: (value: number, index: number, array: this) => void,thisArg?: any): void;
Performs the specified action for each element in an array.
@param callbackfnA function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
@param thisArgAn object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
- searchElement: number,fromIndex?: number): boolean;
Determines whether an array includes a certain element, returning true or false as appropriate.
@param searchElementThe element to search for.
@param fromIndexThe position in this array at which to begin searching for searchElement.
- searchElement: number,fromIndex?: number): number;
Returns the index of the first occurrence of a value in an array.
@param searchElementThe value to locate in the array.
@param fromIndexThe array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
- join(separator?: string): string;
Adds all the elements of an array separated by the specified separator string.
@param separatorA string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
Returns an list of keys in the array
- searchElement: number,fromIndex?: number): number;
Returns the index of the last occurrence of a value in an array.
@param searchElementThe value to locate in the array.
@param fromIndexThe array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
- map(callbackfn: (value: number, index: number, array: this) => number,thisArg?: any
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@param callbackfnA function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param thisArgAn object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
- callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number;
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@param callbackfnA function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,initialValue: number): number;callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U,initialValue: U): U;Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@param callbackfnA function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
@param initialValueIf initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
- callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number;
Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@param callbackfnA function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,initialValue: number): number;callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U,initialValue: U): U;Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@param callbackfnA function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
@param initialValueIf initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
Reverses the elements in an Array.
- @param array
A typed or untyped array of values to set.
@param offsetThe index in the current array at which the values are to be written.
- base64: string,offset?: number): { read: number; written: number };
Set the contents of the Uint8Array from a base64 encoded string
@param base64The base64 encoded string to decode into the array
@param offsetOptional starting index to begin setting the decoded bytes (default: 0)
- hex: string): { read: number; written: number };
Set the contents of the Uint8Array from a hex encoded string
@param hexThe hex encoded string to decode into the array. The string must have an even number of characters, be valid hexadecimal characters and contain no whitespace.
- @param start
The beginning of the specified portion of the array.
@param endThe end of the specified portion of the array. This is exclusive of the element at the index 'end'.
- some(predicate: (value: number, index: number, array: this) => unknown,thisArg?: any): boolean;
Determines whether the specified callback function returns true for any element of an array.
@param predicateA function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
@param thisArgAn object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
- @param compareFn
Function used to determine the order of the elements. It is expected to return a negative value if first argument is less than second argument, zero if they're equal and a positive value otherwise. If omitted, the elements are sorted in ascending order.
[11,2,22,1].sort((a, b) => a - b)
- begin?: number,end?: number
Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements at begin, inclusive, up to end, exclusive.
@param beginThe index of the beginning of the array.
@param endThe index of the end of the array.
- options?: { alphabet: 'base64' | 'base64url'; omitPadding: boolean }): string;
Convert the Uint8Array to a base64 encoded string
@returnsThe base64 encoded string representation of the Uint8Array
Convert the Uint8Array to a hex encoded string
@returnsThe hex encoded string representation of the Uint8Array
Converts a number to a string by using the current locale.
Copies the array and returns the copy with the elements in reverse order.
- compareFn?: (a: number, b: number) => number
Copies and sorts the array.
@param compareFnFunction used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending order.
const myNums = Uint8Array.from([11, 2, 22, 1]); myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22]
Returns a string representation of an array.
Returns the primitive value of the specified object.
Returns an list of values in the array
- with(index: number,value: number
Copies the array and inserts the given number at the provided index.
@param indexThe index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
@param valueThe value to insert into the copied array.
@returnsA copy of the original array with the inserted value.
- name: string,value: string): void;
Appends a specified key/value pair as a new search parameter.
- name: string,value?: string): void;
Deletes the given search parameter, and its associated value, from the list of all search parameters.
Returns an array of key, value pairs for every entry in the search params.
- thisArg?: any): void;
Iterates over each name-value pair in the query and invokes the given function.
const myURL = new URL('https://example.org/?a=b&c=d'); myURL.searchParams.forEach((value, name, searchParams) => { console.log(name, value, myURL.searchParams === searchParams); }); // Prints: // a b true // c d true
@param callbackfnInvoked for each name-value pair in the query
@param thisArgTo be used as
this
value for whenfn
is called - name: string): string[];
Returns all the values association with a given search parameter.
- has(name: string,value?: string): boolean;
Returns a Boolean indicating if such a search parameter exists.
Returns a list of keys in the search params.
- set(name: string,value: string): void;
Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.
Returns a string containing a query string suitable for use in a URL. Does not include the question mark.
Returns a list of values in the search params.
class WritableStream<W = any>
This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.
class WritableStreamDefaultController
This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.
class WritableStreamDefaultWriter<W = any>
This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink.
Type definitions
namespace console
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 asconsole.log()
,console.error()
andconsole.warn()
that can be used to write to any Node.js stream. - A global
console
instance configured to write toprocess.stdout
andprocess.stderr
. The globalconsole
can be used without importing thenode:console
module.
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
: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: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
interface ConsoleConstructor
- constructor ConsoleConstructor(stdout: WritableStream,stderr?: WritableStream,ignoreErrors?: boolean
interface ConsoleConstructorOptions
- colorMode?: boolean | 'auto'
Set color support for this
Console
instance. Setting to true enables coloring while inspecting values. Setting tofalse
disables coloring while inspecting values. Setting to'auto'
makes color support depend on the value of theisTTY
property and the value returned bygetColorDepth()
on the respective stream. This option can not be used, ifinspectOptions.colors
is set as well.
- A
interface AddEventListenerOptions
interface ArrayBufferConstructor
- constructor ArrayBufferConstructor(byteLength: number,options: { maxByteLength: number }
interface ArrayConstructor
- constructor ArrayConstructor(arrayLength?: number): any[];constructor ArrayConstructor<T>(arrayLength: number): T[];constructor ArrayConstructor<T>(...items: T[]): T[];
- @param arrayLike
An array-like object to convert to an array.
arrayLike: ArrayLike<T>,mapfn: (v: T, k: number) => U,thisArg?: any): U[];Creates an array from an iterable object.
@param arrayLikeAn array-like object to convert to an array.
@param mapfnA mapping function to call on every element of the array.
@param thisArgValue of 'this' used to invoke the mapfn.
iterable: Iterable<T, any, any> | ArrayLike<T>): T[];Creates an array from an iterable object.
@param iterableAn iterable object to convert to an array.
iterable: Iterable<T, any, any> | ArrayLike<T>,mapfn: (v: T, k: number) => U,thisArg?: any): U[];Creates an array from an iterable object.
@param iterableAn iterable object to convert to an array.
@param mapfnA mapping function to call on every element of the array.
@param thisArgValue of 'this' used to invoke the mapfn.
- iterableOrArrayLike: AsyncIterable<T, any, any> | Iterable<T | PromiseLike<T>, any, any> | ArrayLike<T | PromiseLike<T>>): Promise<T[]>;
Creates an array from an async iterator or iterable object.
@param iterableOrArrayLikeAn async iterator or array-like object to convert to an array.
iterableOrArrayLike: AsyncIterable<T, any, any> | Iterable<T, any, any> | ArrayLike<T>,mapFn: (value: Awaited<T>, index: number) => U,thisArg?: any): Promise<Awaited<U>[]>;Creates an array from an async iterator or iterable object.
@param iterableOrArrayLikeAn async iterator or array-like object to convert to an array.
@param thisArgValue of 'this' used when executing mapfn.
arrayLike: AsyncIterable<T, any, any> | Iterable<T, any, any> | ArrayLike<T>): Promise<Awaited<T>[]>;Create an array from an iterable or async iterable object. Values from the iterable are awaited.
await Array.fromAsync([1]); // [1] await Array.fromAsync([Promise.resolve(1)]); // [1] await Array.fromAsync((async function*() { yield 1 })()); // [1]
@param arrayLikeThe iterable or async iterable to convert to an array.
@returnsA Promise whose fulfillment is a new Array instance containing the values from the iterator.
arrayLike: AsyncIterable<T, any, any> | Iterable<T, any, any> | ArrayLike<T>,mapFn?: (value: T, index: number) => U,thisArg?: any): Promise<Awaited<U>[]>;Create an array from an iterable or async iterable object. Values from the iterable are awaited. Results of the map function are also awaited.
await Array.fromAsync([1]); // [1] await Array.fromAsync([Promise.resolve(1)]); // [1] await Array.fromAsync((async function*() { yield 1 })()); // [1] await Array.fromAsync([1], (n) => n + 1); // [2] await Array.fromAsync([1], (n) => Promise.resolve(n + 1)); // [2]
@param arrayLikeThe iterable or async iterable to convert to an array.
@param mapFnA mapper function that transforms each element of
arrayLike
after awaiting them.@param thisArgThe
this
to whichmapFn
is bound.@returnsA Promise whose fulfillment is a new Array instance containing the values from the iterator.
- @param items
A set of elements to include in the new array object.
interface BlobPropertyBag
interface BunFetchRequestInit
BunFetchRequestInit represents additional options that Bun supports in
fetch()
only.Bun extends the
fetch
API with some additional options, except this interface is not quite aRequestInit
, because they won't work if passed tonew Request()
. This is why it's a separate type.- cache?: RequestCache
A string indicating how the request will interact with the browser's cache to set request's cache.
- credentials?: RequestCredentials
A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials.
- headers?: HeadersInit
A Headers object, an object literal, or an array of two-item arrays to set request's headers.
- integrity?: string
A cryptographic hash of the resource to be fetched by request. Sets request's integrity.
- mode?: RequestMode
A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode.
- proxy?: string
Override http_proxy or HTTPS_PROXY This is a custom property that is not part of the Fetch API specification.
const response = await fetch("http://example.com", { proxy: "https://username:password@127.0.0.1:8080" });
- redirect?: RequestRedirect
A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect.
- referrer?: string
A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer.
- unix?: string
Make the request over a Unix socket
const response = await fetch("http://example.com", { unix: "/path/to/socket" });
- verbose?: boolean
Log the raw HTTP request & response to stdout. This API may be removed in a future version of Bun without notice. This is a custom property that is not part of the Fetch API specification. It exists mostly as a debugging tool
interface BunFetchRequestInitTLS
Extends Bun.TLSOptions with extra properties that are only supported in
fetch(url, {tls: ...})
- cert?: string | Buffer<ArrayBufferLike> | BunFile | string | Buffer<ArrayBufferLike> | BunFile[]
Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private key, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see ca). When providing multiple cert chains, they do not have to be in the same order as their private keys in key. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.
- checkServerIdentity?: (hostname: string, cert: PeerCertificate) => undefined | Error
Custom function to check the server identity
- key?: string | Buffer<ArrayBufferLike> | BunFile | string | Buffer<ArrayBufferLike> | BunFile[]
Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with options.passphrase. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form {pem: <string|buffer>[, passphrase: <string>]}. The object form can only occur in an array. object.passphrase is optional. Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
- lowMemoryMode?: boolean
This sets
OPENSSL_RELEASE_BUFFERS
to 1. It reduces overall performance but saves some memory. - secureOptions?: number
Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the SSL_OP_* options from OpenSSL Options
interface Console
Asynchronously read lines from standard input (fd 0)
for await (const line of console) { console.log(line); }
- value: any,message?: string,...optionalParams: any[]): void;
console.assert()
writes a message ifvalue
is 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 usingutil.format()
.If
value
is truthy, nothing happens.console.assert(true, 'does nothing'); console.assert(false, 'Whoops %s work', 'didn\'t'); // Assertion failed: Whoops didn't work console.assert(); // Assertion failed
@param valueThe value tested for being truthy.
@param messageAll arguments besides
value
are used as error message. When
stdout
is a TTY, callingconsole.clear()
will attempt to clear the TTY. Whenstdout
is not a TTY, this method does nothing.The specific operation of
console.clear()
can vary across operating systems and terminal types. For most Linux operating systems,console.clear()
operates similarly to theclear
shell command. On Windows,console.clear()
will clear only the output in the current terminal viewport for the Node.js binary.- label?: string): void;
Maintains an internal counter specific to
label
and outputs tostdout
the number of timesconsole.count()
has been called with the givenlabel
.> 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 >
@param labelThe display label for the counter.
- label?: string): void;
Resets the internal counter specific to
label
.> console.count('abc'); abc: 1 undefined > console.countReset('abc'); undefined > console.count('abc'); abc: 1 undefined >
@param labelThe display label for the counter.
- dir(obj: any,): void;
Uses
util.inspect()
onobj
and prints the resulting string tostdout
. This function bypasses any custominspect()
function defined onobj
. - ...data: any[]): void;
This method calls
console.log()
passing it the arguments received. This method does not produce any XML formatting. - @param data
something to display
message?: any,...optionalParams: 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 toprintf(3)
(the arguments are all passed toutil.format()
).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 thenutil.inspect()
is called on each argument and the resulting string values are concatenated. Seeutil.format()
for more information. - ...label: 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. Decreases indentation of subsequent lines by spaces for
groupIndentation
length.- log(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 toprintf(3)
(the arguments are all passed toutil.format()
).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. - label?: string): void;
This method does not display anything unless used in the inspector. The
console.profile()
method starts a JavaScript CPU profile with an optional label until profileEnd is called. The profile is then added to the Profile panel of the inspector.console.profile('MyLabel'); // Some code console.profileEnd('MyLabel'); // Adds the profile 'MyLabel' to the Profiles panel of the inspector.
- 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. See profile for an example.
If this method is called without a label, the most recently started profile is stopped.
- tabularData?: any,properties?: string[]): void;
Try to construct a table with the columns of the properties of
tabularData
(or useproperties
) and rows oftabularData
and log it. Falls back to just logging the argument if it can't be parsed as tabular.// 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 }]); // ┌────┬─────┬─────┐ // │ │ a │ b │ // ├────┼─────┼─────┤ // │ 0 │ 1 │ 'Y' │ // │ 1 │ 'Z' │ 2 │ // └────┴─────┴─────┘ console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); // ┌────┬─────┐ // │ │ a │ // ├────┼─────┤ // │ 0 │ 1 │ // │ 1 │ 'Z' │ // └────┴─────┘
@param propertiesAlternate properties for constructing the table.
tabularData: any,properties?: readonly string[]): void;Try to construct a table with the columns of the properties of
tabularData
(or useproperties
) and rows oftabularData
and log it. Falls back to just logging the argument if it can't be parsed as tabular.// 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' │ // └─────────┴─────┘
@param propertiesAlternate properties for constructing the table.
- time(label?: 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 samelabel
when calling timeEnd to stop the timer and output the elapsed time in suitable time units tostdout
. For example, if the elapsed time is 3869ms,console.timeEnd()
displays "3.869s". - label?: string): void;
Stops a timer that was previously started by calling time and prints the result to
stdout
:console.time('bunch-of-stuff'); // Do a bunch of stuff. console.timeEnd('bunch-of-stuff'); // Prints: bunch-of-stuff: 225.438ms
- label?: string,...data: any[]): void;
For a timer that was previously started by calling time, prints the elapsed time and other
data
arguments tostdout
:console.time('process'); const value = expensiveProcess1(); // Returns 42 console.timeLog('process', value); // Prints "process: 365.227ms 42". doExpensiveProcess2(value); console.timeEnd('process');
- label?: string): void;
This method does not display anything unless used in the inspector. The
console.timeStamp()
method adds an event with the label'label'
to the Timeline panel of the inspector. - message?: any,...optionalParams: any[]): void;
Prints to
stderr
the string'Trace: '
, followed by theutil.format()
formatted message and stack trace to the current position in the code.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)
- ): number;
Write text or bytes to stdout
Unlike console.log, this does no formatting and doesn't add a newline or spaces between arguments. You can pass it strings or bytes or any combination of the two.
console.write("hello world!", "\n"); // "hello world\n"
@param dataThe data to write
@returnsThe number of bytes written
This function is not available in the browser.
interface ConsoleOptions
interface Dict<T>
interface ErrorConstructor
- prepareStackTrace?: (err: Error, stackTraces: CallSite[]) => any
Optional override for formatting stack traces
- targetObject: object,constructorOpt?: Function): void;
Creates a
.stack
property ontargetObject
, which when accessed returns a string representing the location in the code at whichError.captureStackTrace()
was called.const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack`
The first line of the trace will be prefixed with
${myObject.name}: ${myObject.message}
.The optional
constructorOpt
argument accepts a function. If given, all frames aboveconstructorOpt
, includingconstructorOpt
, will be omitted from the generated stack trace.The
constructorOpt
argument is useful for hiding implementation details of error generation from the user. For instance:function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a();
interface ErrorOptions
interface EventListener
interface EventListenerObject
interface EventSource
- readonly readyState: number
Returns the state of this EventSource object's connection. It can have the values described below.
- readonly withCredentials: boolean
Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
- type: K,): void;
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
type: string,): void;Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
type: string,listener: EventListenerOrEventListenerObject,): void;Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
- ): boolean;
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.
- type: K,options?: boolean | EventListenerOptions): void;
Removes the event listener in target's event listener list with the same type, callback, and options.
type: string,options?: boolean | EventListenerOptions): void;Removes the event listener in target's event listener list with the same type, callback, and options.
type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;Removes the event listener in target's event listener list with the same type, callback, and options.
interface EventSourceInit
interface FetchEvent
An event which takes place in the DOM.
- readonly bubbles: boolean
Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.
- readonly cancelable: boolean
Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.
- readonly composed: boolean
Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.
- readonly currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
- readonly defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
- readonly eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
- readonly isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
- readonly timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the
defaultPrevented
property totrue
ifcancelable
istrue
.Stops the invocation of event listeners after the current one completes.
This is not used in Node.js and is provided purely for completeness.
interface ImportMeta
The type of
import.meta
.If you need to declare that a given property exists on
import.meta
, this type may be augmented via interface merging.- readonly dir: string
Absolute path to the directory containing the source file.
Does not have a trailing slash
- readonly env: Env & ProcessEnv & ImportMetaEnv
The environment variables of the process
import.meta.env === process.env
- hot: { data: any; accept(): void; decline; dispose(cb: (data: any) => void | Promise<void>): void; off(event: HMREvent, callback: () => void): void; on(event: HMREvent, callback: () => void): void }
Hot module replacement APIs. This value is
undefined
in production and can be used in anif
statement to check if HMR APIs are availableif (import.meta.hot) { // HMR APIs are available }
However, this check is usually not needed as Bun will dead-code-eliminate calls to all of the HMR APIs in production builds.
https://bun.sh/docs/bundler/hmr
- readonly main: boolean
Did the current file start the process?
if (import.meta.main) { console.log("I started the process!"); }
- require: Require
Load a CommonJS module within an ES Module. Bun's transpiler rewrites all calls to
require
withimport.meta.require
when transpiling ES Modules for the runtime.Warning: This API is not stable and may change or be removed in the future. Use at your own risk.
- url: string
file://
url string for the current module.console.log(import.meta.url); "file:///Users/me/projects/my-app/src/my-app.ts"
- specifier: string,): string;
Provides a module-relative resolution function scoped to each module, returning the URL string.
Second
parent
parameter is only used when the--experimental-import-meta-resolve
command flag enabled.@param specifierThe module specifier to resolve relative to
parent
.@param parentThe absolute parent module URL to resolve from.
@returnsThe absolute (
file:
) URL string for the resolved module.
interface ImportMetaEnv
interface PromiseConstructor
Represents the completion of an asynchronous operation
- constructor PromiseConstructor<T>(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
Creates a new Promise.
@param executorA callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.
- values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]>;
Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected.
@param valuesAn iterable of Promises.
@returnsA new Promise.
values: T): Promise<{ [K in string | number | symbol]: Awaited<T[P<P>]> }>;Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected.
@param valuesAn array of Promises.
@returnsA new Promise.
- values: T): Promise<{ [K in string | number | symbol]: PromiseSettledResult<Awaited<T[P<P>]>> }>;
Creates a Promise that is resolved with an array of results when all of the provided Promises resolve or reject.
@param valuesAn array of Promises.
@returnsA new Promise.
values: Iterable<T | PromiseLike<T>>): Promise<PromiseSettledResult<Awaited<T>>[]>;Creates a Promise that is resolved with an array of results when all of the provided Promises resolve or reject.
@param valuesAn array of Promises.
@returnsA new Promise.
- values: T): Promise<Awaited<T[number]>>;
The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.
@param valuesAn array or iterable of Promises.
@returnsA new Promise.
values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.
@param valuesAn array or iterable of Promises.
@returnsA new Promise.
- values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;
Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected.
@param valuesAn iterable of Promises.
@returnsA new Promise.
values: T): Promise<Awaited<T[number]>>;Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected.
@param valuesAn array of Promises.
@returnsA new Promise.
- @param reason
The reason the promise was rejected.
@returnsA new rejected Promise.
Creates a new resolved promise.
@returnsA resolved promise.
@param valueA promise.
@returnsA promise whose internal state matches the provided promise.
value: T | PromiseLike<T>): Promise<Awaited<T>>;Creates a new resolved promise for the provided value.
@param valueA promise.
@returnsA promise whose internal state matches the provided promise.
- callbackFn: (...args: U) => T | PromiseLike<T>,...args: U): Promise<Awaited<T>>;
Takes a callback of any kind (returns or throws, synchronously or asynchronously) and wraps its result in a Promise.
@param callbackFnA function that is called synchronously. It can do anything: either return a value, throw an error, or return a promise.
@param argsAdditional arguments, that will be passed to the callback.
@returnsA Promise that is:
- Already fulfilled, if the callback synchronously returns a value.
- Already rejected, if the callback synchronously throws an error.
- Asynchronously fulfilled or rejected, if the callback returns a promise.
fn: (...args: A) => T | PromiseLike<T>,...args: A): Promise<T>;Try to run a function and return the result. If the function throws, return the result of the
catch
function.@param fnThe function to run
@param argsThe arguments to pass to the function. This is similar to
setTimeout
and avoids the extra closure.@returnsThe result of the function or the result of the
catch
function Creates a new Promise and returns it in an object, along with its resolve and reject functions.
@returnsAn object with the properties
promise
,resolve
, andreject
.const { promise, resolve, reject } = Promise.withResolvers<T>();
withResolvers<T>(): { promise: Promise<T>; reject: (reason?: any) => void; resolve: (value?: T | PromiseLike<T>) => void };Create a deferred promise, with exposed
resolve
andreject
methods which can be called separately.This is useful when you want to return a Promise and have code outside the Promise resolve or reject it.
const { promise, resolve, reject } = Promise.withResolvers(); setTimeout(() => { resolve("Hello world!"); }, 1000); await promise; // "Hello world!"
interface QueuingStrategy<T = any>
interface QueuingStrategyInit
- highWaterMark: number
Creates a new ByteLengthQueuingStrategy with the provided high water mark.
Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw.
interface QueuingStrategySize<T = any>
interface ReadableStreamDefaultReadDoneResult
interface ReadableStreamDefaultReadValueResult<T>
interface ReadableStreamDirectController
interface ReadableStreamGenericReader
interface ReadableWritablePair<R = any, W = any>
- writable: WritableStream<W>
Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use.
Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
interface ReadOnlyDict<T>
interface RequestInit
- cache?: RequestCache
A string indicating how the request will interact with the browser's cache to set request's cache.
- credentials?: RequestCredentials
A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials.
- headers?: HeadersInit
A Headers object, an object literal, or an array of two-item arrays to set request's headers.
- integrity?: string
A cryptographic hash of the resource to be fetched by request. Sets request's integrity.
- mode?: RequestMode
A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode.
- redirect?: RequestRedirect
A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect.
- referrer?: string
A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer.
interface ResponseInit
interface StreamPipeOptions
- preventClose?: boolean
Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.
Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
Errors and closures of the source and destination streams propagate as follows:
An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination.
An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source.
When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error.
If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.
The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set.
interface Transformer<I = any, O = any>
interface Uint8ArrayConstructor
- buffer: TArrayBuffer,byteOffset?: number,length?: numberconstructor Uint8ArrayConstructor(byteOffset?: number,length?: number
- @param arrayLike
An array-like object to convert to an array.
arrayLike: ArrayLike<T>,mapfn: (v: T, k: number) => number,thisArg?: anyCreates an array from an array-like or iterable object.
@param arrayLikeAn array-like object to convert to an array.
@param mapfnA mapping function to call on every element of the array.
@param thisArgValue of 'this' used to invoke the mapfn.
@param elementsAn iterable object to convert to an array.
elements: Iterable<T>,mapfn?: (v: T, k: number) => number,thisArg?: anyCreates an array from an array-like or iterable object.
@param elementsAn iterable object to convert to an array.
@param mapfnA mapping function to call on every element of the array.
@param thisArgValue of 'this' used to invoke the mapfn.
- base64: string,options?: { alphabet: 'base64' | 'base64url'; lastChunkHandling: 'strict' | 'loose' | 'stop-before-partial' }
Create a new Uint8Array from a base64 encoded string
@param base64The base64 encoded string to convert to a Uint8Array
@param optionsOptional options for decoding the base64 string
@returnsA new Uint8Array containing the decoded data
- @param hex
The hex encoded string to convert to a Uint8Array
@returnsA new Uint8Array containing the decoded data
- @param items
A set of elements to include in the new array object.
interface WebSocket
Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
- binaryType: BinaryType
Returns a string that indicates how binary data from the WebSocket object is exposed to scripts:
Can be set, to change how binary data is returned. The default is "blob".
- readonly bufferedAmount: number
Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network.
If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.)
- readonly protocol: string
Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.
- readonly readyState: number
Returns the state of the WebSocket object's connection. It can have the values described below.
- type: K,): void;
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
type: string,listener: EventListenerOrEventListenerObject,): void;Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
- code?: number,reason?: string): void;
Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.
- ): boolean;
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.
- type: K,options?: boolean | EventListenerOptions): void;
Removes the event listener in target's event listener list with the same type, callback, and options.
type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;Removes the event listener in target's event listener list with the same type, callback, and options.
- send(): void;
Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.
interface Worker
This Web Workers API interface represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread.
- type: K,): void;
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
type: string,listener: EventListenerOrEventListenerObject,): void;Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
- ): boolean;
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.
- message: any,transfer: Transferable[]): void;
Clones message and transmits it to worker's global environment. transfer can be passed as a list of objects that are to be transferred rather than cloned.
- type: K,options?: boolean | EventListenerOptions): void;
Removes the event listener in target's event listener list with the same type, callback, and options.
type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;Removes the event listener in target's event listener list with the same type, callback, and options.
Aborts worker's associated global environment.
interface WorkerOptions
Bun's Web Worker constructor supports some extra options on top of the API browsers have.
- argv?: any[]
List of arguments which would be stringified and appended to
Bun.argv
/process.argv
in the worker. This is mostly similar to thedata
but the values will be available on the globalBun.argv
as if they were passed as CLI options to the script. - env?: typeof SHARE_ENV | Record<string, string>
If set, specifies the initial value of process.env inside the Worker thread. As a special value, worker.SHARE_ENV may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread's process.env object affect the other thread as well. Default: process.env.
- name?: string
A string specifying an identifying name for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes.
- preload?: string | string[]
An array of module specifiers to preload in the worker.
These modules load before the worker's entry point is executed.
Equivalent to passing the
--preload
CLI argument, but only for this Worker. - ref?: boolean
When
true
, the worker will keep the parent thread alive until the worker is terminated orunref
'd. Whenfalse
, the worker will not keep the parent thread alive.By default, this is
false
. - smol?: boolean
Use less memory, but make the worker slower.
Internally, this sets the heap size configuration in JavaScriptCore to be the small heap instead of the large heap.