Bun

Module

Globals

classAbortController

A controller object that allows you to abort one or more DOM requests as and when desired.

MDN Reference

signal: AbortSignal

Returns the AbortSignal object associated with this object.

MDN Reference

abort(reason?: any): void

Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted.

MDN Reference

classAbortSignalextendsEventTarget

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.

MDN Reference

staticabort(reason?: any): AbortSignal

statictimeout(milliseconds: number): AbortSignal

aborted: boolean

Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.

MDN Reference

onabort: null | (this: AbortSignal, ev: Event) => any

addEventListener<K extends 'abort'>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): 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.

MDN Reference

dispatchEvent(event: Event): 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.

MDN Reference

removeEventListener<K extends 'abort'>(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void

Removes the event listener in target's event listener list with the same type, callback, and options.

MDN Reference

functionaddEventListener<K extends keyof WindowEventMap>(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void

functionalert(message?: any): void

classArrayBuffer

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.

byteLength: number

Read-only. The length of the ArrayBuffer (in bytes).

getdetached: boolean

getmaxByteLength: number

getresizable: boolean

resize(newByteLength?: number): void

Resizes the ArrayBuffer to the specified size (in bytes).

MDN

slice(begin?: number, end?: number): ArrayBuffer

Returns a section of an ArrayBuffer.

transfer(newByteLength?: number): ArrayBuffer

Creates a new ArrayBuffer with the same byte content as this buffer, then detaches this buffer.

MDN

transferToFixedLength(newByteLength?: number): ArrayBuffer

Creates a new non-resizable ArrayBuffer with the same byte content as this buffer, then detaches this buffer.

MDN

classBlob

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.

MDN Reference

bytes(): Promise<Uint8Array<ArrayBufferLike>>

formData(): Promise<FormData>

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 a application/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 the BodyMixin API.

json(): Promise<any>

Read the data from the blob as a JSON object.

This first decodes the data from UTF-8, then parses it as JSON.

slice(start?: number, end?: number, contentType?: string): Blob

text(): Promise<string>

classBroadcastChannelextendsEventTarget

name: string

Returns the channel name (as passed to the constructor).

MDN Reference

addEventListener<K extends keyof BroadcastChannelEventMap>(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | AddEventListenerOptions): 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.

MDN Reference

close(): void

Closes the BroadcastChannel object, opening it up to garbage collection.

MDN Reference

dispatchEvent(event: Event): 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.

MDN Reference

postMessage(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.

MDN Reference

removeEventListener<K extends keyof BroadcastChannelEventMap>(type: K, listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any, options?: boolean | EventListenerOptions): void

Removes the event listener in target's event listener list with the same type, callback, and options.

MDN Reference

classByteLengthQueuingStrategyextendsQueuingStrategy<ArrayBufferView>

This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.

MDN Reference

size: QueuingStrategySize<ArrayBufferView<ArrayBufferLike>>

functionclearImmediate(id?: number | Timer): void

Cancel an immediate function call by its immediate ID.

id

immediate id

functionclearInterval(id: undefined | number): void

functionclearTimeout(id: undefined | number): void

classCloseEventextendsEvent

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.

MDN Reference

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.

MDN Reference

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.

MDN Reference

code: number

Returns the WebSocket connection close code provided by the server.

MDN Reference

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.

MDN Reference

currentTarget: null | EventTarget

Returns the object whose event listener's callback is currently being invoked.

MDN Reference

defaultPrevented: boolean

Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.

MDN Reference

eventPhase: number

Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.

MDN Reference

isTrusted: boolean

Returns true if event was dispatched by the user agent, and false otherwise.

MDN Reference

NONE: 0

reason: string

Returns the WebSocket connection close reason provided by the server.

MDN Reference

target: null | EventTarget

Returns the object to which event is dispatched (its target).

MDN Reference

timeStamp: number

Returns the event's timestamp as the number of milliseconds measured relative to the time origin.

MDN Reference

type: string

Returns the type of event, e.g. "click", "hashchange", or "submit".

MDN Reference

wasClean: boolean

Returns true if the connection closed cleanly; false otherwise.

MDN Reference

composedPath(): EventTarget[]

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.

MDN Reference

preventDefault(): void

If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.

MDN Reference

stopImmediatePropagation(): void

Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.

MDN Reference

stopPropagation(): void

When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.

MDN Reference

functionconfirm(message?: string): boolean

classCountQueuingStrategyextendsQueuingStrategy

This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.

MDN Reference

classCrypto

Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives.

MDN Reference

subtle: SubtleCrypto

timingSafeEqual: (a: ArrayBufferView, b: ArrayBufferView) => boolean

getRandomValues<T extends null | ArrayBufferView<ArrayBufferLike>>(array: T): T

randomUUID(): `${string}-${string}-${string}-${string}-${string}`

classCryptoKeyextendsNodeCryptoWebcryptoCryptoKey

The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. Available only in secure contexts.

MDN Reference

classCustomEvent<T=any>extendsEvent

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.

MDN Reference

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.

MDN Reference

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.

MDN Reference

currentTarget: null | EventTarget

Returns the object whose event listener's callback is currently being invoked.

MDN Reference

defaultPrevented: boolean

Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.

MDN Reference

detail: T

Returns any custom data event was created with. Typically used for synthetic events.

MDN Reference

eventPhase: number

Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.

MDN Reference

isTrusted: boolean

Returns true if event was dispatched by the user agent, and false otherwise.

MDN Reference

NONE: 0

target: null | EventTarget

Returns the object to which event is dispatched (its target).

MDN Reference

timeStamp: number

Returns the event's timestamp as the number of milliseconds measured relative to the time origin.

MDN Reference

type: string

Returns the type of event, e.g. "click", "hashchange", or "submit".

MDN Reference

composedPath(): EventTarget[]

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.

MDN Reference

preventDefault(): void

If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.

MDN Reference

stopImmediatePropagation(): void

Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.

MDN Reference

stopPropagation(): void

When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.

MDN Reference

classErrorEventextendsEvent

Events providing information related to errors in scripts or in files.

MDN Reference

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.

MDN Reference

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.

MDN Reference

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.

MDN Reference

currentTarget: null | EventTarget

Returns the object whose event listener's callback is currently being invoked.

MDN Reference

defaultPrevented: boolean

Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.

MDN Reference

eventPhase: number

Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.

MDN Reference

isTrusted: boolean

Returns true if event was dispatched by the user agent, and false otherwise.

MDN Reference

NONE: 0

target: null | EventTarget

Returns the object to which event is dispatched (its target).

MDN Reference

timeStamp: number

Returns the event's timestamp as the number of milliseconds measured relative to the time origin.

MDN Reference

type: string

Returns the type of event, e.g. "click", "hashchange", or "submit".

MDN Reference

composedPath(): EventTarget[]

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.

MDN Reference

preventDefault(): void

If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.

MDN Reference

stopImmediatePropagation(): void

Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.

MDN Reference

stopPropagation(): void

When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.

MDN Reference

classEvent

staticAT_TARGET: 2

staticNONE: 0

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.

MDN Reference

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.

MDN Reference

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.

MDN Reference

currentTarget: null | EventTarget

Returns the object whose event listener's callback is currently being invoked.

MDN Reference

defaultPrevented: boolean

Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.

MDN Reference

eventPhase: number

Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.

MDN Reference

isTrusted: boolean

Returns true if event was dispatched by the user agent, and false otherwise.

MDN Reference

NONE: 0

target: null | EventTarget

Returns the object to which event is dispatched (its target).

MDN Reference

timeStamp: number

Returns the event's timestamp as the number of milliseconds measured relative to the time origin.

MDN Reference

type: string

Returns the type of event, e.g. "click", "hashchange", or "submit".

MDN Reference

composedPath(): EventTarget[]

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.

MDN Reference

preventDefault(): void

If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.

MDN Reference

stopImmediatePropagation(): void

Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.

MDN Reference

stopPropagation(): void

When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.

MDN Reference

classEventTarget

EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.

MDN Reference

addEventListener(type: string, callback: null | EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): 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.

MDN Reference

dispatchEvent(event: Event): 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.

MDN Reference

removeEventListener(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.

MDN Reference

Vexports: any

Same as module.exports

functionfetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>

Bun's extensions of the fetch API

functionfetch.preconnect(url: string | URL, options?:
{

dns: boolean

Preconnect to the DNS of the URL

http: boolean

Preconnect to the HTTP connection of the URL

https: boolean

Preconnect to the HTTPS connection of the URL

tcp: boolean

Preconnect to the TCP connection of the URL

}
): 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.

url

The URL to preconnect to

options

Options for the preconnect

functionfetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>

functionfetch.preconnect(url: string | URL, options?:
{

dns: boolean

Preconnect to the DNS of the URL

http: boolean

Preconnect to the HTTP connection of the URL

https: boolean

Preconnect to the HTTPS connection of the URL

tcp: boolean

Preconnect to the TCP connection of the URL

}
): 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.

url

The URL to preconnect to

options

Options for the preconnect

classFileextendsBlob

Provides information about files and allows JavaScript in a web page to access their content.

MDN Reference

bytes(): Promise<Uint8Array<ArrayBufferLike>>

formData(): Promise<FormData>

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 a application/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 the BodyMixin API.

json(): Promise<any>

Read the data from the blob as a JSON object.

This first decodes the data from UTF-8, then parses it as JSON.

slice(start?: number, end?: number, contentType?: string): Blob

text(): Promise<string>

classFormData

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

MDN Reference

[Symbol.iterator](): FormDataIterator<[string, FormDataEntryValue]>

append(name: string, value: string | Blob): void

delete(name: string): void

entries(): FormDataIterator<[string, FormDataEntryValue]>

Returns an array of key, value pairs for every entry in the list.

forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void

get(name: string): null | FormDataEntryValue

getAll(name: string): FormDataEntryValue[]

has(name: string): boolean

keys(): FormDataIterator<string>

Returns a list of keys in the list.

set(name: string, value: string | Blob): void

values(): FormDataIterator<FormDataEntryValue>

Returns a list of values in the list.

classHeadersextendsBunHeadersOverride

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.

MDN Reference

count: number

Get the total number of headers

[Symbol.iterator](): HeadersIterator<[string, string]>

append(name: string, value: string): void

delete(name: string): void

entries(): HeadersIterator<[string, string]>

Returns an iterator allowing to go through all key/value pairs contained in this object.

forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void

get(name: string): null | string

getAll(name: 'set-cookie' | 'Set-Cookie'): string[]

Get all headers matching the name

Only supports "Set-Cookie". All other headers are empty arrays.

name

The header name to get

returns

An array of header values

has(name: string): boolean

keys(): HeadersIterator<string>

Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.

set(name: string, value: string): void

toJSON(): Record<string, string>

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.

values(): HeadersIterator<string>

Returns an iterator allowing to go through all values of the key/value pairs contained in this object.

VLoader:
{

dependencyKeysIfEvaluated: (specifier: string) => string[]

For an already-evaluated module, return the dependencies as module specifiers

This list is already sorted and uniqued.

registry: Map<string,
{

dependencies: typeof Loader['registry'] extends Map<any, V> ? V : any[]

evaluated: boolean

fetch: Promise<any>

instantiate: Promise<any>

isAsync: boolean

key: string

linkError: any

linkSucceeded: boolean

module:
{

dependenciesMap: typeof Loader['registry']

}

Your application will probably crash if you mess with this.

satisfy: Promise<any>

state: number

This refers to the state the ESM module is in

TODO: make an enum for this number

then: any

}
>

ESM module registry

This lets you implement live reload in Bun. If you delete a module specifier from this map, the next time it's imported, it will be re-transpiled and loaded again.

The keys are the module specifiers and the values are metadata about the module.

The keys are an implementation detail for Bun that will change between versions.

  • Userland modules are an absolute file path
  • Virtual modules have a bun: prefix or node: prefix
  • JS polyfills start with "/bun-vfs/". "buffer" is an example of a JS polyfill
  • If you have a node_modules.bun file, many modules will point to that file

Virtual modules and JS polyfills are embedded in bun's binary. They don't point to anywhere in your local filesystem.

resolve: (specifier: string, referrer: string) => string

The function JavaScriptCore internally calls when you use an import statement.

This may return a path to node_modules.server.bun, which will be confusing.

Consider Bun.resolve or ImportMeta.resolve instead.

}

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.

classMessageChannel

This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties.

MDN Reference

port1: MessagePort

port2: MessagePort

classMessageEvent<T=any>extendsEvent

constructor<T>(type: string, eventInitDict?: MessageEventInit<T>): MessageEvent<T>

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.

MDN Reference

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.

MDN Reference

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.

MDN Reference

currentTarget: null | EventTarget

Returns the object whose event listener's callback is currently being invoked.

MDN Reference

data: T

defaultPrevented: boolean

Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.

MDN Reference

eventPhase: number

Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.

MDN Reference

isTrusted: boolean

Returns true if event was dispatched by the user agent, and false otherwise.

MDN Reference

lastEventId: string

Returns the last event ID string, for server-sent events.

MDN Reference

NONE: 0

origin: string

Returns the origin of the message, for server-sent events and cross-document messaging.

MDN Reference

ports: readonly MessagePort[]

Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging.

MDN Reference

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.

MDN Reference

target: null | EventTarget

Returns the object to which event is dispatched (its target).

MDN Reference

timeStamp: number

Returns the event's timestamp as the number of milliseconds measured relative to the time origin.

MDN Reference

type: string

Returns the type of event, e.g. "click", "hashchange", or "submit".

MDN Reference

composedPath(): EventTarget[]

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.

MDN Reference

preventDefault(): void

If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.

MDN Reference

stopImmediatePropagation(): void

Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.

MDN Reference

stopPropagation(): void

When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.

MDN Reference

classMessagePortextendsEventTarget, MessageEventTarget<MessagePort>, LibEmptyOrNodeMessagePort

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.

MDN Reference

onmessage: null | (this: MessagePort, ev: MessageEvent) => any

addEventListener<K extends keyof MessagePortEventMap>(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | AddEventListenerOptions): 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.

MDN Reference

close(): void

Disconnects the port, so that it is no longer active.

MDN Reference

dispatchEvent(event: Event): 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.

MDN Reference

postMessage(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.

MDN Reference

removeEventListener<K extends keyof MessagePortEventMap>(type: K, listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any, options?: boolean | EventListenerOptions): void

Removes the event listener in target's event listener list with the same type, callback, and options.

MDN Reference

start(): void

Vmodule: NodeModule

A reference to the current module.

classNavigatorextendsNavigatorAutomationInformation, NavigatorBadge, NavigatorConcurrentHardware, NavigatorContentUtils, NavigatorCookies, NavigatorID, NavigatorLanguage, NavigatorLocks, NavigatorOnLine, NavigatorPlugins, NavigatorStorage

The state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.

MDN Reference

clipboard: Clipboard

credentials: CredentialsContainer

doNotTrack: null | string

languages: readonly string[]

locks: LockManager

mediaDevices: MediaDevices

platform: 'MacIntel' | 'Win32' | 'Linux x86_64'

serviceWorker: ServiceWorkerContainer

storage: StorageManager

userAgent: string

canShare(data?: ShareData): boolean

getGamepads(): null | Gamepad[]

registerProtocolHandler(scheme: string, url: string | URL): void

requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: MediaKeySystemConfiguration[]): Promise<MediaKeySystemAccess>

requestMIDIAccess(options?: MIDIOptions): Promise<MIDIAccess>

sendBeacon(url: string | URL, data?: null | BodyInit): boolean

setAppBadge(contents?: number): Promise<void>

share(data?: ShareData): Promise<void>

vibrate(pattern: VibratePattern): boolean

classPerformanceextendsEventTarget, LibPerformanceOrNodePerfHooksPerformance

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.

MDN Reference

addEventListener<K extends 'resourcetimingbufferfull'>(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): 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.

MDN Reference

clearMarks(markName?: string): void

clearMeasures(measureName?: string): void

dispatchEvent(event: Event): 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.

MDN Reference

getEntries(): PerformanceEntryList

getEntriesByName(name: string, type?: string): PerformanceEntryList

getEntriesByType(type: string): PerformanceEntryList

mark(markName: string, markOptions?: PerformanceMarkOptions): PerformanceMark

measure(measureName: string, startOrMeasureOptions?: string | PerformanceMeasureOptions, endMark?: string): PerformanceMeasure

removeEventListener<K extends 'resourcetimingbufferfull'>(type: K, listener: (this: Performance, ev: PerformanceEventMap[K]) => any, options?: boolean | EventListenerOptions): void

Removes the event listener in target's event listener list with the same type, callback, and options.

MDN Reference

classPerformanceEntry

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

MDN Reference

classPerformanceMarkextendsPerformanceEntry

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.

MDN Reference

classPerformanceMeasureextendsPerformanceEntry

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.

MDN Reference

classPerformanceObserver

staticsupportedEntryTypes: readonly string[]

observe(options?: PerformanceObserverInit): void

takeRecords(): PerformanceEntryList

classPerformanceObserverEntryList

getEntries(): PerformanceEntryList

getEntriesByName(name: string, type?: string): PerformanceEntryList

getEntriesByType(type: string): PerformanceEntryList

classPerformanceResourceTimingextendsPerformanceEntry

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.

MDN Reference

functionpostMessage(message: any, targetOrigin: string, transfer?: Transferable[]): void

Posts a message to the given window. Messages can be structured objects, e.g. nested objects and arrays, can contain JavaScript values (strings, numbers, Date objects, etc), and can contain certain data objects such as File Blob, FileList, and ArrayBuffer objects.

Objects listed in the transfer member of options are transferred, not just cloned, meaning that they are no longer usable on the sending side.

A target origin can be specified using the targetOrigin member of options. If not provided, it defaults to "/". This default restricts the message to same-origin targets only.

If the origin of the target window doesn't match the given target origin, the message is discarded, to avoid information leakage. To send the message to the target regardless of origin, set the target origin to "*".

Throws a "DataCloneError" DOMException if transfer array contains duplicate objects or if message could not be cloned.

MDN Reference

functionprompt(message?: string, _default?: string): null | string

functionqueueMicrotask(callback: VoidFunction): void

classReadableStream<R=any>extendsLibEmptyOrNodeReadableStream<R>

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.

MDN Reference

[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>

cancel(reason?: any): Promise<void>

pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>

values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>

classReadableStreamBYOBReaderextendsReadableStreamGenericReader

closed: Promise<void>

cancel(reason?: any): Promise<void>

read<T extends ArrayBufferView<ArrayBufferLike>>(view: T): Promise<ReadableStreamReadResult<T>>

classReadableStreamBYOBRequest

view: null | ArrayBufferView<ArrayBufferLike>

respond(bytesWritten: number): void

respondWithNewView(view: ArrayBufferView): void

classReadableStreamDefaultReader<R=any>extendsReadableStreamGenericReader

closed: Promise<void>

cancel(reason?: any): Promise<void>

read(): Promise<ReadableStreamReadResult<R>>

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.

functionremoveEventListener<K extends keyof WindowEventMap>(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | EventListenerOptions): void

functionreportError(e: any): void

classRequestextendsBody, BunRequestOverride

This Fetch API interface represents a resource request.

MDN Reference

body: null | ReadableStream<Uint8Array<ArrayBufferLike>>

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.

MDN Reference

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.

MDN Reference

destination: RequestDestination

Returns the kind of resource requested by request, e.g., "document" or "script".

MDN Reference

headers: Headers

Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header.

MDN Reference

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]

MDN Reference

keepalive: boolean

Returns a boolean indicating whether or not request can outlive the global in which it was created.

MDN Reference

method: string

Returns request's HTTP method, which is "GET" by default.

MDN Reference

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.

MDN Reference

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.

MDN Reference

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.

MDN Reference

referrerPolicy: ReferrerPolicy

Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer.

MDN Reference

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.

MDN Reference

url: string

bytes(): Promise<Uint8Array<ArrayBufferLike>>

json(): Promise<any>

text(): Promise<string>

Vrequire: NodeJS.Require

NodeJS-style require function

classResponseextendsBody, BunResponseOverride

This Fetch API interface represents the response to a request.

MDN Reference

functionsetImmediate(handler: TimerHandler, arguments: any[]): Timer

Run a function immediately after main event loop is vacant

handler

function to call

functionsetImmediate.__promisify__<T=void>(value?: T, options?: TimerOptions): Promise<T>

import {
  setImmediate,
} from 'node:timers/promises';

const res = await setImmediate('result');

console.log(res);  // Prints 'result'
value

A value with which the promise is fulfilled.

functionsetInterval(handler: TimerHandler, timeout?: number, arguments: any[]): number

functionsetTimeout(handler: TimerHandler, timeout?: number, arguments: any[]): number

functionsetTimeout.__promisify__<T=void>(delay?: number, value?: T, options?: TimerOptions): Promise<T>

import {
  setTimeout,
} from 'node:timers/promises';

const res = await setTimeout(100, 'result');

console.log(res);  // Prints 'result'
delay

The number of milliseconds to wait before fulfilling the promise. Default: 1.

value

A value with which the promise is fulfilled.

classShadowRealm

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

evaluate(sourceText: string): any

importValue(specifier: string, bindingName: string): Promise<any>

VSharedArrayBuffer: SharedArrayBufferConstructor

functionstructuredClone<T=any>(value: T, options?: StructuredSerializeOptions): T

classSubtleCryptoextendsNodeCryptoWebcryptoSubtleCrypto

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.

MDN Reference

decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>

deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length?: null | number): Promise<ArrayBuffer>

deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | HkdfParams | Pbkdf2Params | AesDerivedKeyParams | HmacImportParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>

digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise<ArrayBuffer>

encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>

exportKey(format: 'jwk', key: CryptoKey): Promise<JsonWebKey>

generateKey(algorithm: 'Ed25519' |
{

name: 'Ed25519'

}
, extractable: boolean, keyUsages: readonly 'sign' | 'verify'[]): Promise<CryptoKeyPair>

importKey(format: 'jwk', keyData: JsonWebKey, algorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: readonly KeyUsage[]): Promise<CryptoKey>

sign(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>

unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, unwrappedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>

verify(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams, key: CryptoKey, signature: BufferSource, data: BufferSource): Promise<boolean>

wrapKey(format: KeyFormat, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams): Promise<ArrayBuffer>

classTextDecoderextendsTextDecoderCommon, LibEmptyOrNodeUtilTextDecoder

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.

MDN Reference

encoding: string

fatal: boolean

Returns true if error mode is "fatal", otherwise false.

MDN Reference

ignoreBOM: boolean

decode(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.

MDN Reference

classTextDecoderStreamextendsGenericTransformStream, TextDecoderCommon

encoding: string

fatal: boolean

Returns true if error mode is "fatal", otherwise false.

MDN Reference

ignoreBOM: boolean

classTextEncoderextendsTextEncoderCommon, LibEmptyOrNodeUtilTextEncoder

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.

MDN Reference

encoding: string

encode(input?: string): Uint8Array

encodeInto(source: string, destination: Uint8Array): 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.

MDN Reference

classTextEncoderStreamextendsGenericTransformStream, TextEncoderCommon

classUint8Array<TArrayBuffer extends ArrayBufferLike=ArrayBufferLike>extendsRelativeIndexable<number>

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.

[Symbol.toStringTag]: 'Uint8Array'

buffer: TArrayBuffer

The ArrayBuffer instance referenced by the array.

byteLength: number

The length in bytes of the array.

byteOffset: number

The offset in bytes of the array.

BYTES_PER_ELEMENT: number

The size in bytes of each element in the array.

length: number

The length of the array.

[Symbol.iterator](): ArrayIterator<number>

at(index: number): undefined | number

Returns the item located at the specified index.

index

The zero-based index of the desired code unit. A negative index will count back from the last item.

copyWithin(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

target

If target is negative, it is treated as length+target where length is the length of the array.

start

If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.

end

If not specified, length of the this object is used as its default value.

entries(): ArrayIterator<[number, number]>

Returns an array of key, value pairs for every entry in the array

every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean

Determines whether all the members of an array satisfy the specified test.

predicate

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

thisArg

An 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 to end index to a static value and returns the modified array

value

value to fill array section with

start

index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.

end

index to stop filling the array at. If end is negative, it is treated as length+end.

filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Uint8Array<ArrayBuffer>

Returns the elements of an array that meet the condition specified in a callback function.

predicate

A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.

thisArg

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

predicate

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

thisArg

If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

findIndex(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.

predicate

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

thisArg

If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

findLast<S extends number>(predicate: (value: number, index: number, array: this) => asserts value is S, thisArg?: any): undefined | S

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate

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

thisArg

If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

findLastIndex(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.

predicate

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

thisArg

If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void

Performs the specified action for each element in an array.

callbackfn

A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.

thisArg

An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

includes(searchElement: number, fromIndex?: number): boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement

The element to search for.

fromIndex

The position in this array at which to begin searching for searchElement.

indexOf(searchElement: number, fromIndex?: number): number

Returns the index of the first occurrence of a value in an array.

searchElement

The value to locate in the array.

fromIndex

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

separator

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

keys(): ArrayIterator<number>

Returns an list of keys in the array

lastIndexOf(searchElement: number, fromIndex?: number): number

Returns the index of the last occurrence of a value in an array.

searchElement

The value to locate in the array.

fromIndex

The 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): Uint8Array<ArrayBuffer>

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn

A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

thisArg

An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

reduce(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.

callbackfn

A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.

reduceRight(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.

callbackfn

A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.

reverse(): this

Reverses the elements in an Array.

set(array: ArrayLike<number>, offset?: number): void

Sets a value or an array of values.

array

A typed or untyped array of values to set.

offset

The index in the current array at which the values are to be written.

setFromBase64(base64: string, offset?: number):
{

read: number

The number of bytes read from the base64 string

written: number

The number of bytes written to the Uint8Array Will never be greater than the .byteLength of this Uint8Array

}

Set the contents of the Uint8Array from a base64 encoded string

base64

The base64 encoded string to decode into the array

offset

Optional starting index to begin setting the decoded bytes (default: 0)

setFromHex(hex: string):
{

read: number

The number of bytes read from the hex string

written: number

The number of bytes written to the Uint8Array Will never be greater than the .byteLength of this Uint8Array

}

Set the contents of the Uint8Array from a hex encoded string

hex

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

slice(start?: number, end?: number): Uint8Array<ArrayBuffer>

Returns a section of an array.

start

The beginning of the specified portion of the array.

end

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

predicate

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

thisArg

An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

sort(compareFn?: (a: number, b: number) => number): this

Sorts an array.

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)

subarray(begin?: number, end?: number): Uint8Array<TArrayBuffer>

Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements at begin, inclusive, up to end, exclusive.

begin

The index of the beginning of the array.

end

The index of the end of the array.

toBase64(options?:
{

alphabet: 'base64' | 'base64url'

omitPadding: boolean

}
): string

Convert the Uint8Array to a base64 encoded string

returns

The base64 encoded string representation of the Uint8Array

toHex(): string

Convert the Uint8Array to a hex encoded string

returns

The hex encoded string representation of the Uint8Array

toLocaleString(): string

Converts a number to a string by using the current locale.

toReversed(): Uint8Array<ArrayBuffer>

Copies the array and returns the copy with the elements in reverse order.

toSorted(compareFn?: (a: number, b: number) => number): Uint8Array<ArrayBuffer>

Copies and sorts the array.

compareFn

Function 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]

toString(): string

Returns a string representation of an array.

valueOf(): this

Returns the primitive value of the specified object.

values(): ArrayIterator<number>

Returns an list of values in the array

with(index: number, value: number): Uint8Array<ArrayBuffer>

Copies the array and inserts the given number at the provided index.

index

The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.

value

The value to insert into the copied array.

returns

A copy of the original array with the inserted value.

classURL

The URL interface represents an object providing static methods used for creating object URLs.

MDN Reference

staticcanParse(url: string | URL, base?: string | URL): boolean

staticcreateObjectURL(obj: Blob | MediaSource): string

staticparse(url: string | URL, base?: string | URL): null | URL

staticrevokeObjectURL(url: string): void

toString(): string

classURLSearchParams

[Symbol.iterator](): URLSearchParamsIterator<[string, string]>

append(name: string, value: string): void

Appends a specified key/value pair as a new search parameter.

MDN Reference

delete(name: string, value?: string): void

Deletes the given search parameter, and its associated value, from the list of all search parameters.

MDN Reference

entries(): URLSearchParamsIterator<[string, string]>

Returns an array of key, value pairs for every entry in the search params.

forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void

get(name: string): null | string

Returns the first value associated to the given search parameter.

MDN Reference

getAll(name: string): string[]

Returns all the values association with a given search parameter.

MDN Reference

has(name: string, value?: string): boolean

Returns a Boolean indicating if such a search parameter exists.

MDN Reference

keys(): URLSearchParamsIterator<string>

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.

MDN Reference

toString(): string

Returns a string containing a query string suitable for use in a URL. Does not include the question mark.

values(): URLSearchParamsIterator<string>

Returns a list of values in the search params.

classWritableStream<W=any>extendsLibEmptyOrNodeWritableStream<W>

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.

MDN Reference

classWritableStreamDefaultController

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.

MDN Reference

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

MDN Reference

closed: Promise<void>

ready: Promise<void>

abort(reason?: any): Promise<void>

close(): Promise<void>

write(chunk?: W): Promise<void>

Type Definitions

interfaceAddEventListenerOptionsextendsEventListenerOptions, EventListenerOptions

capture: boolean

once: boolean

passive: boolean

interfaceArrayBufferConstructor

constructor(byteLength: number): ArrayBuffer

isView(arg: any): asserts arg is ArrayBufferView<ArrayBufferLike>

interfaceArrayConstructor

(arrayLength?: number) => any[];

interfaceBlobPropertyBag

endings: EndingType

type: string

Set a default "type". Not yet implemented.

interfaceBunFetchRequestInitextendsRequestInit

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 a RequestInit, because they won't work if passed to new Request(). This is why it's a separate type.

body: null | BodyInit

A BodyInit object or null to set request's body.

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.

keepalive: boolean

A boolean to set request's keepalive.

method: string

A string to set request's method.

mode: RequestMode

A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode.

priority: RequestPriority

proxy: string

Override http_proxy or HTTPS_PROXY This is a custom property that is not part of the Fetch API specification.

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.

referrerPolicy: ReferrerPolicy

A referrer policy to set request's referrerPolicy.

s3: S3Options

Override the default S3 options

signal: null | AbortSignal

An AbortSignal to set request's signal.

tls: BunFetchRequestInitTLS

Override the default TLS options

unix: string

Make the request over a Unix 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

window: null

Can only be null. Used to disassociate request from any Window.

interfaceBunFetchRequestInitTLSextendsTLSOptions

Extends Bun.TLSOptions with extra properties that are only supported in fetch(url, {tls: ...})

ca: string | Buffer<ArrayBufferLike> | BunFile | string | Buffer<ArrayBufferLike> | BunFile[]

Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option.

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

dhParamsFile: string

File path to a .pem file custom Diffie Helman parameters

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.

passphrase: string

Passphrase for the TLS key

rejectUnauthorized: boolean

If set to false, any certificate is accepted. Default is $NODE_TLS_REJECT_UNAUTHORIZED environment variable, or true if it is not set.

requestCert: boolean

If set to true, the server will request a client certificate.

Default is false.

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

serverName: string

Explicitly set a server name

namespaceconsole

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node: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

interfaceConsoleConstructor

constructor(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console

interfaceConsoleConstructorOptions

colorMode: boolean | 'auto'

Set color support for this Console instance. Setting to true enables coloring while inspecting values. Setting to false disables coloring while inspecting values. Setting to 'auto' makes color support depend on the value of the isTTY property and the value returned by getColorDepth() on the respective stream. This option can not be used, if inspectOptions.colors is set as well.

groupIndentation: number

Set group indentation.

ignoreErrors: boolean

Ignore errors when writing to the underlying streams.

inspectOptions: InspectOptions

stderr: WritableStream

stdout: WritableStream

interfaceConsole

Console: ConsoleConstructor

[Symbol.asyncIterator](): AsyncIterableIterator<string>

Asynchronously read lines from standard input (fd 0)

for await (const line of console) {
  console.log(line);
}

assert(condition?: boolean, data: any[]): void

count(label?: string): void

countReset(label?: string): void

debug(data: any[]): void

dir(item?: any, options?: any): void

dirxml(data: any[]): void

error(data: any[]): void

group(data: any[]): void

groupCollapsed(data: any[]): void

info(data: any[]): void

log(data: any[]): void

profile(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.

profileEnd(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.

table(tabularData?: any, properties?: string[]): void

time(label?: string): void

timeEnd(label?: string): void

timeLog(label?: string, data: any[]): void

timeStamp(label?: string): void

trace(data: any[]): void

warn(data: any[]): void

write(data: string | ArrayBuffer | ArrayBufferView<ArrayBufferLike>[]): 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"
data

The data to write

returns

The number of bytes written

This function is not available in the browser.

interfaceConsoleOptions

colorMode: boolean | 'auto'

ignoreErrors: boolean

inspectOptions: InspectOptions

stderr: Writable

stdout: Writable

interfaceDict<T>

interfaceErrnoExceptionextendsError

cause: unknown

The cause of the error.

code: string

errno: number

message: string

name: string

path: string

stack: string

syscall: string

interfaceError

cause: unknown

The cause of the error.

message: string

name: string

stack: string

interfaceErrorConstructor

(message?: string) => Error;

interfaceErrorOptions

cause: unknown

The cause of the error.

interfaceEventListener

(evt: Event) => void;

interfaceEventListenerObject

handleEvent(object: Event): void

interfaceEventSourceextendsEventTarget

onerror: null | (this: EventSource, ev: Event) => any

onmessage: null | (this: EventSource, ev: MessageEvent) => any

onopen: null | (this: EventSource, ev: Event) => any

OPEN: 1

readyState: number

Returns the state of this EventSource object's connection. It can have the values described below.

MDN Reference

url: string

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.

MDN Reference

addEventListener<K extends keyof EventSourceEventMap>(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | AddEventListenerOptions): 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.

MDN Reference

close(): void

Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.

MDN Reference

dispatchEvent(event: Event): 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.

MDN Reference

removeEventListener<K extends keyof EventSourceEventMap>(type: K, listener: (this: EventSource, ev: EventSourceEventMap[K]) => any, options?: boolean | EventListenerOptions): void

Removes the event listener in target's event listener list with the same type, callback, and options.

MDN Reference

interfaceFetchEventextendsEvent

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.

MDN Reference

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.

MDN Reference

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.

MDN Reference

currentTarget: null | EventTarget

Returns the object whose event listener's callback is currently being invoked.

MDN Reference

defaultPrevented: boolean

Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.

MDN Reference

eventPhase: number

Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.

MDN Reference

isTrusted: boolean

Returns true if event was dispatched by the user agent, and false otherwise.

MDN Reference

NONE: 0

target: null | EventTarget

Returns the object to which event is dispatched (its target).

MDN Reference

timeStamp: number

Returns the event's timestamp as the number of milliseconds measured relative to the time origin.

MDN Reference

type: string

Returns the type of event, e.g. "click", "hashchange", or "submit".

MDN Reference

url: string

composedPath(): EventTarget[]

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.

MDN Reference

preventDefault(): void

If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.

MDN Reference

respondWith(response: Response | Promise<Response>): void

stopImmediatePropagation(): void

Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.

MDN Reference

stopPropagation(): void

When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.

MDN Reference

waitUntil(promise: Promise<any>): void

interfaceImportMeta

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.

dir: string

Absolute path to the directory containing the source file.

Does not have a trailing slash

dirname: string

Alias of import.meta.dir. Exists for Node.js compatibility

env: Env & ProcessEnv & ImportMetaEnv

The environment variables of the process

import.meta.env === process.env

file: string

Filename of the source file

filename: string

Alias of import.meta.path. Exists for Node.js compatibility

hot:
{

data: any

import.meta.hot.data maintains state between module instances during hot replacement, enabling data transfer from previous to new versions. When import.meta.hot.data is written to, Bun will mark this module as capable of self-accepting (equivalent of calling accept()).

accept(): void

Indicate that this module can be replaced simply by re-evaluating the file. After a hot update, importers of this module will be automatically patched.

When import.meta.hot.accept is not used, the page will reload when the file updates, and a console message shows which files were checked.

decline

dispose(cb: (data: any) => void | Promise<void>): void

Attach an on-dispose callback. This is called:

  • Just before the module is replaced with another copy (before the next is loaded)
  • After the module is detached (removing all imports to this module)

This callback is not called on route navigation or when the browser tab closes.

Returning a promise will delay module replacement until the module is disposed. All dispose callbacks are called in parallel.

off(event: HMREvent, callback: () => void): void

Stop listening for an event from the dev server

For compatibility with Vite, event names are also available via vite:* prefix instead of bun:*.

https://bun.sh/docs/bundler/hmr#import-meta-hot-on-and-off

event

The event to stop listening to

callback

The callback to stop listening to

on(event: HMREvent, callback: () => void): void

Listen for an event from the dev server

For compatibility with Vite, event names are also available via vite:* prefix instead of bun:*.

https://bun.sh/docs/bundler/hmr#import-meta-hot-on-and-off

event

The event to listen to

callback

The callback to call when the event is emitted

}

Hot module replacement APIs. This value is undefined in production and can be used in an if statement to check if HMR APIs are available

if (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

main: boolean

Did the current file start the process?

path: string

Absolute path to the source file

require: Require

Load a CommonJS module within an ES Module. Bun's transpiler rewrites all calls to require with import.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.

resolve(specifier: string): string

interfaceImportMetaEnv

interfacePosition

column: number

file: string

length: number

line: number

lineText: string

namespace: string

offset: number

interfacePromiseConstructor

Represents the completion of an asynchronous operation

constructor<T>(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>

Creates a new Promise.

executor

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

prototype: Promise<any>

A reference to the prototype.

all<T>(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.

values

An iterable of Promises.

returns

A new Promise.

allSettled<T extends readonly unknown[] | []>(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.

values

An array of Promises.

returns

A new Promise.

any<T extends readonly unknown[] | []>(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.

values

An array or iterable of Promises.

returns

A new Promise.

race<T>(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.

values

An iterable of Promises.

returns

A new Promise.

reject<T=never>(reason?: any): Promise<T>

Creates a new rejected promise for the provided reason.

reason

The reason the promise was rejected.

returns

A new rejected Promise.

resolve(): Promise<void>

Creates a new resolved promise.

returns

A resolved promise.

try<T, U extends unknown[]>(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.

callbackFn

A function that is called synchronously. It can do anything: either return a value, throw an error, or return a promise.

args

Additional arguments, that will be passed to the callback.

returns

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

withResolvers<T>(): PromiseWithResolvers<T>

Creates a new Promise and returns it in an object, along with its resolve and reject functions.

returns

An object with the properties promise, resolve, and reject.

const { promise, resolve, reject } = Promise.withResolvers<T>();

interfaceQueuingStrategyInit

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.

interfaceQueuingStrategySize<T=any>

(chunk: T) => number;

interfaceReadableStreamDirectController

close(error?: Error): void

end(): number | Promise<number>

flush(): number | Promise<number>

start(): void

write(data: string | BufferSource): number | Promise<number>

interfaceReadableStreamGenericReader

closed: Promise<void>

cancel(reason?: any): Promise<void>

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

interfaceReadOnlyDict<T>

interfaceRequestInitextendsLibOrFallbackRequestInit

body: null | BodyInit

A BodyInit object or null to set request's body.

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.

keepalive: boolean

A boolean to set request's keepalive.

method: string

A string to set request's method.

mode: RequestMode

A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode.

priority: RequestPriority

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.

referrerPolicy: ReferrerPolicy

A referrer policy to set request's referrerPolicy.

signal: null | AbortSignal

An AbortSignal to set request's signal.

window: null

Can only be null. Used to disassociate request from any Window.

interfaceResponseInitextendsLibOrFallbackResponseInit

headers: HeadersInit

status: number

statusText: string

interfaceSharedArrayBuffer

[Symbol.toStringTag]: 'SharedArrayBuffer'

byteLength: number

Read-only. The length of the ArrayBuffer (in bytes).

getgrowable: boolean

getmaxByteLength: number

grow(newByteLength?: number): void

Grows the SharedArrayBuffer to the specified size (in bytes).

MDN

slice(begin?: number, end?: number): SharedArrayBuffer

Returns a section of an SharedArrayBuffer.

interfaceStreamPipeOptions

preventAbort: boolean

preventCancel: boolean

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.

interfaceTimer

interfaceTransformer<I=any, O=any>

flush: TransformerFlushCallback<O>

readableType: undefined

start: TransformerStartCallback<O>

transform: TransformerTransformCallback<I, O>

writableType: undefined

interfaceUint8ArrayConstructor

BYTES_PER_ELEMENT: number

The size in bytes of each element in the array.

prototype: Uint8Array<ArrayBufferLike>

from(arrayLike: ArrayLike<number>): Uint8Array<ArrayBuffer>

Creates an array from an array-like or iterable object.

arrayLike

An array-like object to convert to an array.

fromBase64(base64: string, options?:
{

alphabet: 'base64' | 'base64url'

lastChunkHandling: 'loose' | 'strict' | 'stop-before-partial'

}
): Uint8Array

Create a new Uint8Array from a base64 encoded string

base64

The base64 encoded string to convert to a Uint8Array

options

Optional options for decoding the base64 string

returns

A new Uint8Array containing the decoded data

fromHex(hex: string): Uint8Array

Create a new Uint8Array from a hex encoded string

hex

The hex encoded string to convert to a Uint8Array

returns

A new Uint8Array containing the decoded data

of(items: number[]): Uint8Array<ArrayBuffer>

Returns a new array from a set of elements.

items

A set of elements to include in the new array object.

interfaceWebSocketextendsEventTarget, LibEmptyOrBunWebSocket

Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.

MDN Reference

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

MDN Reference

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

MDN Reference

extensions: string

Returns the extensions selected by the server, if any.

MDN Reference

onclose: null | (this: WebSocket, ev: CloseEvent) => any

onerror: null | (this: WebSocket, ev: Event) => any

onmessage: null | (this: WebSocket, ev: MessageEvent) => any

onopen: null | (this: WebSocket, ev: Event) => any

OPEN: 1

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.

MDN Reference

readyState: number

Returns the state of the WebSocket object's connection. It can have the values described below.

MDN Reference

url: string

Returns the URL that was used to establish the WebSocket connection.

MDN Reference

addEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): 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.

MDN Reference

close(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.

MDN Reference

dispatchEvent(event: Event): 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.

MDN Reference

removeEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void

Removes the event listener in target's event listener list with the same type, callback, and options.

MDN Reference

send(data: string | ArrayBufferLike | ArrayBufferView<ArrayBufferLike> | Blob): void

Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.

MDN Reference

interfaceWorkerextendsEventTarget, AbstractWorker, MessageEventTarget<Worker>, LibWorkerOrBunWorker

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.

MDN Reference

constructor(scriptURL: string | URL, options?: WorkerOptions): Worker

onerror: null | (this: AbstractWorker, ev: ErrorEvent) => any

onmessage: null | (this: Worker, ev: MessageEvent) => any

onmessageerror: null | (this: Worker, ev: MessageEvent) => any

addEventListener<K extends keyof WorkerEventMap>(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): 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.

MDN Reference

dispatchEvent(event: Event): 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.

MDN Reference

postMessage(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.

MDN Reference

removeEventListener<K extends keyof WorkerEventMap>(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void

Removes the event listener in target's event listener list with the same type, callback, and options.

MDN Reference

terminate(): void

interfaceWorkerOptions

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 the data but the values will be available on the global Bun.argv as if they were passed as CLI options to the script.

credentials: RequestCredentials

In Bun, this does nothing.

env: Record<string, string> | typeof SHARE_ENV

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 or unref'd. When false, 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.

type: WorkerType

In Bun, this does nothing.