A controller object that allows you to abort one or more DOM requests as and when desired.
Module
Globals
classAbortController
signal: AbortSignal
Returns the AbortSignal object associated with this object.
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.
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.
aborted: boolean
Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.
onabort: null | (this: AbortSignal, ev: Event) => any
reason: 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.
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.
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.
functionaddEventListener<K extends keyof WindowEventMap>(type: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions): 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.
[Symbol.toStringTag]: string
byteLength: number
Read-only. The length of the ArrayBuffer (in bytes).
getdetached: boolean
getmaxByteLength: number
getresizable: boolean
transfer(newByteLength?: number): ArrayBuffer
Creates a new ArrayBuffer with the same byte content as this buffer, then detaches this buffer.
transferToFixedLength(newByteLength?: number): ArrayBuffer
Creates a new non-resizable ArrayBuffer with the same byte content as this buffer, then detaches this buffer.
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.
size: number
type: string
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.
classBroadcastChannelextendsEventTarget
name: string
Returns the channel name (as passed to the constructor).
onmessage: null | (this: BroadcastChannel, ev: MessageEvent) => any
onmessageerror: null | (this: BroadcastChannel, ev: MessageEvent) => any
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.
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.
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.
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.
classByteLengthQueuingStrategyextendsQueuingStrategy<ArrayBufferView>
This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.
highWaterMark: number
size: QueuingStrategySize<ArrayBufferView<ArrayBufferLike>>
functionclearImmediate(id?: number | Timer): void
Cancel an immediate function call by its immediate ID.
immediate id
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.
AT_TARGET: 2
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.
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.
code: number
Returns the WebSocket connection close code provided by the server.
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.
currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
NONE: 0
reason: string
Returns the WebSocket connection close reason provided by the server.
target: null | EventTarget
Returns the object to which event is dispatched (its target).
timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
type: string
Returns the type of event, e.g. "click", "hashchange", or "submit".
wasClean: boolean
Returns true if the connection closed cleanly; false otherwise.
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.
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.
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.
stopPropagation(): void
When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.
classCountQueuingStrategyextendsQueuingStrategy
This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.
classCrypto
Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives.
subtle: SubtleCrypto
Available only in secure contexts.
timingSafeEqual: (a: ArrayBufferView, b: ArrayBufferView) => boolean
classCryptoKeyextendsNodeCryptoWebcryptoCryptoKey
The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. Available only in secure contexts.
classCustomEvent<T=any>extendsEvent
AT_TARGET: 2
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.
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.
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.
currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
NONE: 0
target: null | EventTarget
Returns the object to which event is dispatched (its target).
timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
type: string
Returns the type of event, e.g. "click", "hashchange", or "submit".
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.
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.
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.
stopPropagation(): void
When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.
classDOMExceptionextendsError
An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API.
staticABORT_ERR: 20
staticDATA_CLONE_ERR: 25
staticDOMSTRING_SIZE_ERR: 2
staticHIERARCHY_REQUEST_ERR: 3
staticINDEX_SIZE_ERR: 1
staticINUSE_ATTRIBUTE_ERR: 10
staticINVALID_ACCESS_ERR: 15
staticINVALID_CHARACTER_ERR: 5
staticINVALID_MODIFICATION_ERR: 13
staticINVALID_NODE_TYPE_ERR: 24
staticINVALID_STATE_ERR: 11
staticNAMESPACE_ERR: 14
staticNETWORK_ERR: 19
staticNO_DATA_ALLOWED_ERR: 6
staticNO_MODIFICATION_ALLOWED_ERR: 7
staticNOT_FOUND_ERR: 8
staticNOT_SUPPORTED_ERR: 9
staticQUOTA_EXCEEDED_ERR: 22
staticSECURITY_ERR: 18
staticSYNTAX_ERR: 12
staticTIMEOUT_ERR: 23
staticTYPE_MISMATCH_ERR: 17
staticURL_MISMATCH_ERR: 21
staticVALIDATION_ERR: 16
staticWRONG_DOCUMENT_ERR: 4
ABORT_ERR: 20
cause: unknown
The cause of the error.
DATA_CLONE_ERR: 25
message: string
name: string
NAMESPACE_ERR: 14
NETWORK_ERR: 19
SECURITY_ERR: 18
stack: string
SYNTAX_ERR: 12
TIMEOUT_ERR: 23
URL_MISMATCH_ERR: 21
VALIDATION_ERR: 16
classErrorEventextendsEvent
Events providing information related to errors in scripts or in files.
AT_TARGET: 2
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.
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.
colno: number
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.
currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
error: any
eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
filename: string
isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
lineno: number
message: string
NONE: 0
target: null | EventTarget
Returns the object to which event is dispatched (its target).
timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
type: string
Returns the type of event, e.g. "click", "hashchange", or "submit".
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.
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.
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.
stopPropagation(): void
When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.
classEvent
An event which takes place in the DOM.
staticAT_TARGET: 2
staticBUBBLING_PHASE: 3
staticCAPTURING_PHASE: 1
staticNONE: 0
AT_TARGET: 2
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.
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.
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.
currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
NONE: 0
target: null | EventTarget
Returns the object to which event is dispatched (its target).
timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
type: string
Returns the type of event, e.g. "click", "hashchange", or "submit".
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.
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.
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.
stopPropagation(): void
When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.
classEventTarget
EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.
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.
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.
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.
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
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
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.
The URL to preconnect to
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
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
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.
The URL to preconnect to
Options for the preconnect
classFileextendsBlob
Provides information about files and allows JavaScript in a web page to access their content.
lastModified: number
name: string
size: number
type: string
webkitRelativePath: string
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.
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".
[Symbol.iterator](): FormDataIterator<[string, FormDataEntryValue]>
entries(): FormDataIterator<[string, FormDataEntryValue]>
Returns an array of key, value pairs for every entry 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.
count: number
Get the total number of headers
[Symbol.iterator](): HeadersIterator<[string, string]>
entries(): HeadersIterator<[string, string]>
Returns an iterator allowing to go through all key/value pairs contained in this object.
getAll(name: 'set-cookie' | 'Set-Cookie'): string[]
Get all headers matching the name
Only supports "Set-Cookie"
. All other headers are empty arrays.
The header name to get
An array of header values
keys(): HeadersIterator<string>
Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.
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:
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.
}
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:
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
}>
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:
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 ornode:
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.
port1: MessagePort
Returns the first MessagePort object.
port2: MessagePort
Returns the second MessagePort object.
classMessageEvent<T=any>extendsEvent
A message received by a target object.
constructor<T>(type: string, eventInitDict?: MessageEventInit<T>): MessageEvent<T>
AT_TARGET: 2
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.
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.
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.
currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
lastEventId: string
Returns the last event ID string, for server-sent events.
NONE: 0
origin: string
Returns the origin of the message, for server-sent events and cross-document messaging.
ports: readonly MessagePort[]
Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging.
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.
target: null | EventTarget
Returns the object to which event is dispatched (its target).
timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
type: string
Returns the type of event, e.g. "click", "hashchange", or "submit".
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.
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.
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.
stopPropagation(): void
When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.
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.
onmessage: null | (this: MessagePort, ev: MessageEvent) => any
onmessageerror: 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.
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.
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.
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.
Vmodule: NodeModule
A reference to the current module.
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.
eventCounts: EventCounts
onresourcetimingbufferfull: null | (this: Performance, ev: Event) => any
timeOrigin: number
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.
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.
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.
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).
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.
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.
classPerformanceObserver
staticsupportedEntryTypes: readonly string[]
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.
connectEnd: number
connectStart: number
decodedBodySize: number
domainLookupEnd: number
domainLookupStart: number
duration: number
encodedBodySize: number
entryType: string
fetchStart: number
initiatorType: string
name: string
nextHopProtocol: string
redirectEnd: number
redirectStart: number
requestStart: number
responseEnd: number
responseStart: number
responseStatus: number
serverTiming: readonly PerformanceServerTiming[]
startTime: number
transferSize: number
workerStart: number
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.
classReadableByteStreamController
desiredSize: null | number
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.
locked: boolean
[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>
pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>
values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>
classReadableStreamBYOBReaderextendsReadableStreamGenericReader
classReadableStreamBYOBRequest
view: null | ArrayBufferView<ArrayBufferLike>
classReadableStreamDefaultController<R=any>
desiredSize: null | number
classReadableStreamDefaultReader<R=any>extendsReadableStreamGenericReader
closed: Promise<void>
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
classRequestextendsBody, BunRequestOverride
This Fetch API interface represents a resource request.
body: null | ReadableStream<Uint8Array<ArrayBufferLike>>
bodyUsed: boolean
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.
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.
destination: RequestDestination
Returns the kind of resource requested by request, e.g., "document" or "script".
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.
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]
keepalive: boolean
Returns a boolean indicating whether or not request can outlive the global in which it was created.
method: string
Returns request's HTTP method, which is "GET" by default.
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.
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.
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.
referrerPolicy: ReferrerPolicy
Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer.
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.
url: string
Returns the URL of request as a string.
Vrequire: NodeJS.Require
NodeJS-style require
function
classResponseextendsBody, BunResponseOverride
This Fetch API interface represents the response to a request.
body: null | ReadableStream<Uint8Array<ArrayBufferLike>>
bodyUsed: boolean
ok: boolean
redirected: boolean
status: number
statusText: string
type: ResponseType
url: string
functionsetImmediate(handler: TimerHandler, arguments: any[]): Timer
Run a function immediately after main event loop is vacant
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'
A value with which the promise is fulfilled.
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'
The number of milliseconds to wait before fulfilling the promise. Default: 1
.
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
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.
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>
encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>
generateKey(algorithm: 'Ed25519' | {name: 'Ed25519'
}, extractable: boolean, keyUsages: readonly 'sign' | 'verify'[]): Promise<CryptoKeyPair>
name: 'Ed25519'
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.
encoding: string
Returns encoding's name, lowercased.
fatal: boolean
Returns true if error mode is "fatal", otherwise false.
ignoreBOM: boolean
Returns the value of ignore BOM.
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.
classTextDecoderStreamextendsGenericTransformStream, TextDecoderCommon
encoding: string
Returns encoding's name, lowercased.
fatal: boolean
Returns true if error mode is "fatal", otherwise false.
ignoreBOM: boolean
Returns the value of ignore BOM.
readable: ReadableStream<string>
writable: WritableStream<BufferSource>
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.
encoding: string
Returns "utf-8".
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.
classTextEncoderStreamextendsGenericTransformStream, TextEncoderCommon
encoding: string
Returns "utf-8".
readable: ReadableStream<Uint8Array<ArrayBufferLike>>
writable: WritableStream<string>
classTransformStream<I=any, O=any>
classTransformStreamDefaultController<O=any>
desiredSize: null | number
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.
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
If target is negative, it is treated as length+target where length is the length of the array.
If start is negative, it is treated as length+start. If end is negative, it is treated as length+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.
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.
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 to fill array section with
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.
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.
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
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.
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.
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.
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.
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.
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.
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.
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.
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.
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
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.
The element to search for.
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.
The value to locate in the array.
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.
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.
lastIndexOf(searchElement: number, fromIndex?: number): number
Returns the index of the last occurrence of a value in an array.
The value to locate in the array.
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.
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
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.
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.
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
set(array: ArrayLike<number>, offset?: number): void
Sets a value or an array of values.
A typed or untyped array of values to set.
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
}
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
The base64 encoded string to decode into the array
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
}
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
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.
The beginning of the specified portion of the array.
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.
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.
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.
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.
The index of the beginning of the array.
The index of the end of the array.
toBase64(options?: {alphabet: 'base64' | 'base64url'
omitPadding: boolean
}): string
alphabet: 'base64' | 'base64url'
omitPadding: boolean
Convert the Uint8Array to a base64 encoded string
The base64 encoded string representation of the Uint8Array
toHex(): string
Convert the Uint8Array to a hex encoded string
The hex encoded string representation of the Uint8Array
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.
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]
with(index: number, value: number): Uint8Array<ArrayBuffer>
Copies the array and inserts the given number at the provided index.
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
The value to insert into the copied array.
A copy of the original array with the inserted value.
classURLSearchParams
size: number
[Symbol.iterator](): URLSearchParamsIterator<[string, string]>
append(name: string, value: string): void
Appends a specified key/value pair as a new search parameter.
delete(name: string, value?: string): void
Deletes the given search parameter, and its associated value, from the list of all search parameters.
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
has(name: string, value?: string): boolean
Returns a Boolean indicating if such a search parameter exists.
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.
toString(): string
Returns a string containing a query string suitable for use in a URL. Does not include the question mark.
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.
locked: boolean
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.
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.
Type Definitions
interfaceAddEventListenerOptionsextendsEventListenerOptions, EventListenerOptions
interfaceArrayBufferConstructor
constructor(byteLength: number): ArrayBuffer
isView(arg: any): asserts arg is ArrayBufferView<ArrayBufferLike>
interfaceArrayConstructor
interfaceBlobPropertyBag
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.
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 asconsole.log()
,console.error()
andconsole.warn()
that can be used to write to any Node.js stream. - A global
console
instance configured to write toprocess.stdout
andprocess.stderr
. The globalconsole
can be used without importing thenode:console
module.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O
for more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
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
Specifies options that are passed along to util.inspect()
.
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);
}
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.
timeStamp(label?: string): 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"
The data to write
The number of bytes written
This function is not available in the browser.
interfaceConsoleOptions
colorMode: boolean | 'auto'
groupIndentation: number
ignoreErrors: boolean
inspectOptions: InspectOptions
stderr: Writable
stdout: Writable
interfaceDict<T>
interfaceErrorConstructor
interfaceErrorOptions
cause: unknown
The cause of the error.
interfaceEventListener
interfaceEventListenerObject
handleEvent(object: Event): void
interfaceEventSourceextendsEventTarget
CLOSED: 2
CONNECTING: 0
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.
url: string
Returns the URL providing the event stream.
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.
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.
close(): void
Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
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.
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.
interfaceEventSourceInit
withCredentials: boolean
interfaceFetchEventextendsEvent
An event which takes place in the DOM.
AT_TARGET: 2
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.
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.
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.
currentTarget: null | EventTarget
Returns the object whose event listener's callback is currently being invoked.
defaultPrevented: boolean
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
eventPhase: number
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
isTrusted: boolean
Returns true if event was dispatched by the user agent, and false otherwise.
NONE: 0
target: null | EventTarget
Returns the object to which event is dispatched (its target).
timeStamp: number
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
type: string
Returns the type of event, e.g. "click", "hashchange", or "submit".
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.
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.
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.
stopPropagation(): void
When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.
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
}
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
The event to stop listening to
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
The event to listen to
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
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.
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.
An iterable of Promises.
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.
An array of Promises.
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.
An array or iterable of Promises.
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.
An iterable of Promises.
A new Promise.
reject<T=never>(reason?: any): Promise<T>
Creates a new rejected promise for the provided reason.
The reason the promise was rejected.
A new rejected 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.
A function that is called synchronously. It can do anything: either return a value, throw an error, or return a promise.
Additional arguments, that will be passed to the callback.
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.
An object with the properties promise
, resolve
, and reject
.
const { promise, resolve, reject } = Promise.withResolvers<T>();
interfaceQueuingStrategy<T=any>
highWaterMark: number
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>
interfaceReadableStreamDefaultReadDoneResult
interfaceReadableStreamDefaultReadValueResult<T>
interfaceReadableStreamDirectController
interfaceReadableStreamGenericReader
closed: 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
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.
interfaceTransformer<I=any, O=any>
readableType: undefined
writableType: undefined
interfaceUint8ArrayConstructor
constructor(length: number): Uint8Array<ArrayBuffer>
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.
An array-like object to convert to an array.
fromBase64(base64: string, options?: {alphabet: 'base64' | 'base64url'
lastChunkHandling: 'loose' | 'strict' | 'stop-before-partial'
}): Uint8Array
alphabet: 'base64' | 'base64url'
lastChunkHandling: 'loose' | 'strict' | 'stop-before-partial'
Create a new Uint8Array from a base64 encoded string
The base64 encoded string to convert to a Uint8Array
Optional options for decoding the base64 string
A new Uint8Array containing the decoded data
fromHex(hex: string): Uint8Array
Create a new Uint8Array from a hex encoded string
The hex encoded string to convert to a Uint8Array
A new Uint8Array containing the decoded data
of(items: number[]): Uint8Array<ArrayBuffer>
Returns a new array from a set of elements.
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.
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".
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.)
CLOSED: 3
CLOSING: 2
CONNECTING: 0
extensions: string
Returns the extensions selected by the server, if any.
onclose: null | (this: WebSocket, ev: CloseEvent) => any
onmessage: null | (this: WebSocket, ev: MessageEvent) => 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.
readyState: number
Returns the state of the WebSocket object's connection. It can have the values described below.
url: string
Returns the URL that was used to establish the WebSocket connection.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.