温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com/reference/globals
点击访问原文链接

globals module | API Reference | Bun

globals module | API Reference | BunBuildDocsReferenceGuidesBlogDiscord/GlobalsCAbortControllerCAbortSignalFaddEventListenerFalertCArrayBufferCBlobCBroadcastChannelCByteLengthQueuingStrategyFclearImmediateFclearIntervalFclearTimeoutCCloseEventCCompressionStreamFconfirmVconsoleCCountQueuingStrategyVcryptoCCryptoCCryptoKeyCCustomEventCDecompressionStreamCDOMExceptionCErrorEventCEventCEventTargetVexportsFfetchCFileCFormDataCHeadersVLoaderCMessageChannelCMessageEventCMessagePortVmoduleVnavigatorCNavigatorVperformanceCPerformanceCPerformanceEntryCPerformanceMarkCPerformanceMeasureCPerformanceObserverCPerformanceObserverEntryListCPerformanceResourceTimingFpostMessageFpromptFqueueMicrotaskCReadableByteStreamControllerCReadableStreamCReadableStreamBYOBReaderCReadableStreamBYOBRequestCReadableStreamDefaultControllerCReadableStreamDefaultReaderFremoveEventListenerFreportErrorCRequestVrequireCResponseFsetImmediateFsetIntervalFsetTimeoutCShadowRealmFstructuredCloneCSubtleCryptoCTextDecoderCTextDecoderStreamCTextEncoderCTextEncoderStreamCTransformStreamCTransformStreamDefaultControllerCUint8ArrayCURLCURLSearchParamsCWritableStreamCWritableStreamDefaultControllerCWritableStreamDefaultWriter

Search the reference...

/

BuildDocsReferenceGuidesBlogDiscord/GlobalsCAbortControllerCAbortSignalFaddEventListenerFalertCArrayBufferCBlobCBroadcastChannelCByteLengthQueuingStrategyFclearImmediateFclearIntervalFclearTimeoutCCloseEventCCompressionStreamFconfirmVconsoleCCountQueuingStrategyVcryptoCCryptoCCryptoKeyCCustomEventCDecompressionStreamCDOMExceptionCErrorEventCEventCEventTargetVexportsFfetchCFileCFormDataCHeadersVLoaderCMessageChannelCMessageEventCMessagePortVmoduleVnavigatorCNavigatorVperformanceCPerformanceCPerformanceEntryCPerformanceMarkCPerformanceMeasureCPerformanceObserverCPerformanceObserverEntryListCPerformanceResourceTimingFpostMessageFpromptFqueueMicrotaskCReadableByteStreamControllerCReadableStreamCReadableStreamBYOBReaderCReadableStreamBYOBRequestCReadableStreamDefaultControllerCReadableStreamDefaultReaderFremoveEventListenerFreportErrorCRequestVrequireCResponseFsetImmediateFsetIntervalFsetTimeoutCShadowRealmFstructuredCloneCSubtleCryptoCTextDecoderCTextDecoderStreamCTextEncoderCTextEncoderStreamCTransformStreamCTransformStreamDefaultControllerCUint8ArrayCURLCURLSearchParamsCWritableStreamCWritableStreamDefaultControllerCWritableStreamDefaultWriter

module

globalsfunction fetch(input: string | URL | Request,init?: BunFetchRequestInit): PromiseResponse>;

Send a HTTP(s) request

@param input

URL string or Request object

@param init

A structured value that contains settings for the fetch() request.

@returns

A promise that resolves to Response object.

namespace fetch

Bun's extensions of the fetch API

function preconnect(url: string | URL,options?: { dns: boolean; http: boolean; https: boolean; tcp: boolean }): void;

Preconnect to a URL. This can be used to improve performance by pre-resolving the DNS and establishing a TCP connection before the request is made.

This is a custom property that is not part of the Fetch API specification.

@param url

The URL to preconnect to

@param options

Options for the preconnect

function setImmediate(handler: TimerHandler,...arguments: any[]): Timer;

Run a function immediately after main event loop is vacant

@param handler

function to call

namespace setImmediatefunction setTimeout(handler: TimerHandler,timeout?: number,...arguments: any[]): number;namespace setTimeoutconst console: Consoleconst crypto: Cryptoconst Error: ErrorConstructorconst exports: any

Same as module.exports

const Loader: { dependencyKeysIfEvaluated: (specifier: string) => string[]; registry: Mapstring, { dependencies: typeof Loader['registry'] extends Mapany, infer V> ? V : any[]; evaluated: boolean; fetch: Promiseany>; instantiate: Promiseany>; isAsync: boolean; key: string; linkError: any; linkSucceeded: boolean; module: { dependenciesMap: typeof Loader['registry'] }; satisfy: Promiseany>; state: number; then: any }>; resolve: (specifier: string, referrer: string) => string }

Low-level JavaScriptCore API for accessing the native ES Module loader (not a Bun API)

Before using this, be aware of a few things:

Using this incorrectly will crash your application.

This API may change any time JavaScriptCore is updated.

Bun may rewrite ESM import specifiers to point to bundled code. This will be confusing when using this API, as it will return a string like "/node_modules.server.bun".

Bun may inject additional imports into your code. This usually has a bun: prefix.

const module: NodeModule

A reference to the current module.

const navigator: Navigatorconst performance: Performanceconst require: NodeJS.Require

NodeJS-style require function

const SharedArrayBuffer: SharedArrayBufferConstructorfunction addEventListenerK extends keyof EventMap>(type: K,listener: (this: object, ev: EventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;function alert(message?: string): void;function clearImmediate(id?: number | Timer): void;

Cancel an immediate function call by its immediate ID.

@param id

immediate id

function clearInterval(id: undefined | number): void;function clearTimeout(id: undefined | number): void;function confirm(message?: string): boolean;function fetch(input: string | URL | Request,init?: BunFetchRequestInit): PromiseResponse>;

Send a HTTP(s) request

@param input

URL string or Request object

@param init

A structured value that contains settings for the fetch() request.

@returns

A promise that resolves to Response object.

function preconnect(url: string | URL,options?: { dns: boolean; http: boolean; https: boolean; tcp: boolean }): void;

Preconnect to a URL. This can be used to improve performance by pre-resolving the DNS and establishing a TCP connection before the request is made.

This is a custom property that is not part of the Fetch API specification.

@param url

The URL to preconnect to

@param options

Options for the preconnect

function postMessage(message: any,transfer?: Transferable[]): void;

Post a message to the parent thread.

Only useful in a worker thread; calling this from the main thread does nothing.

function prompt(message?: string,_default?: string): null | string;function queueMicrotask(callback: VoidFunction): void;function removeEventListenerK extends keyof EventMap>(type: K,listener: (this: object, ev: EventMap[K]) => any,options?: boolean | EventListenerOptions): void;function reportError(error: any): void;

Log an error using the default exception handler

@param error

Error or string

function setImmediate(handler: TimerHandler,...arguments: any[]): Timer;

Run a function immediately after main event loop is vacant

@param handler

function to call

function setInterval(handler: TimerHandler,timeout?: number,...arguments: any[]): number;function setTimeout(handler: TimerHandler,timeout?: number,...arguments: any[]): number;function structuredCloneT = any>(value: T,options?: StructuredSerializeOptions): T;class URL

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

MDN Reference

hash: stringhost: stringhostname: stringhref: stringreadonly origin: stringpassword: stringpathname: stringport: stringprotocol: stringsearch: stringreadonly searchParams: URLSearchParamsusername: stringtoJSON(): string;toString(): string;static canParse(url: string | URL,base?: string | URL): boolean;static createObjectURL(obj: Blob | MediaSource): string;static parse(url: string | URL,base?: string | URL): null | URL;static revokeObjectURL(url: string): void;class MessageEventT = any>readonly AT_TARGET: 2readonly bubbles: boolean

Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.

MDN Reference

readonly BUBBLING_PHASE: 3readonly cancelable: boolean

Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.

MDN Reference

readonly CAPTURING_PHASE: 1readonly composed: boolean

Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.

MDN Reference

readonly currentTarget: null | EventTarget

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

MDN Reference

readonly data: Treadonly defaultPrevented: boolean

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

MDN Reference

readonly eventPhase: number

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

MDN Reference

readonly isTrusted: boolean

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

MDN Reference

readonly lastEventId: string

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

MDN Reference

readonly NONE: 0readonly origin: string

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

MDN Reference

readonly ports: readonly MessagePort[]

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

MDN Reference

prototype: MessageEventreadonly source: null | MessageEventSource

Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects.

MDN Reference

readonly target: null | EventTarget

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

MDN Reference

readonly timeStamp: number

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

MDN Reference

readonly type: string

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

MDN Reference

composedPath(): EventTarget[];

Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.

MDN Reference

preventDefault(): void;

Sets the defaultPrevented property to true if cancelable is true.

stopImmediatePropagation(): void;

Stops the invocation of event listeners after the current one completes.

stopPropagation(): void;

This is not used in Node.js and is provided purely for completeness.

class AbortController

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

MDN Reference

readonly signal: AbortSignal

Returns the AbortSignal object associated with this object.

MDN Reference

abort(reason?: any): void;class AbortSignal

A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object.

MDN Reference

readonly aborted: boolean

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

MDN Reference

onabort: null | (this: AbortSignal, ev: Event) => anyreadonly reason: anyaddEventListenerK extends 'abort'>(type: K,listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

dispatchEvent(event: Event): boolean;

Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

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

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

MDN Reference

throwIfAborted(): void;static abort(reason?: any): AbortSignal;static any(signals: AbortSignal[]): AbortSignal;static timeout(milliseconds: number): AbortSignal;class ArrayBuffer

Represents a raw buffer of binary data, which is used to store data for the different typed arrays. ArrayBuffers cannot be read from or written to directly, but can be passed to a typed array or DataView Object to interpret the raw buffer as needed.

readonly [Symbol.toStringTag]: stringreadonly byteLength: number

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

resize(newByteLength?: number): void;

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

MDN

resize(byteLength: number): ArrayBuffer;

Resize an ArrayBuffer in-place.

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

Returns a section of an ArrayBuffer.

transfer(newByteLength?: number): ArrayBuffer;

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

MDN

transferToFixedLength(newByteLength?: number): ArrayBuffer;

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

MDN

class Blob

A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

MDN Reference

readonly size: numberreadonly type: stringarrayBuffer(): PromiseArrayBuffer>;

Returns a promise that resolves to the contents of the blob as an ArrayBuffer

bytes(): PromiseUint8ArrayArrayBufferLike>>;bytes(): PromiseUint8ArrayArrayBuffer>>;

Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes) its the same as new Uint8Array(await blob.arrayBuffer())

formData(): PromiseFormData>;

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.

image(options?: ConstructorOptions): Image;

Wrap this blob in a Bun.Image pipeline. Equivalent to new Bun.Image(this, options) — the constructor is synchronous (the underlying read happens lazily when an Image terminal is awaited), so this works on Bun.file(), Bun.s3(), fd-backed and in-memory blobs alike:

await Bun.file("photo.jpg").image().resize(400).webp().write("thumb.webp");
json(): Promiseany>;

Read the data from the blob as a JSON object.

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

slice(start?: number,end?: number,contentType?: string): Blob;stream(): ReadableStreamUint8ArrayArrayBufferLike>>;stream(): ReadableStreamUint8ArrayArrayBuffer>>;

Returns a readable stream of the blob's contents

text(): Promisestring>;

Returns a promise that resolves to the contents of the blob as a string

class BroadcastChannelreadonly name: string

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

MDN Reference

onmessage: null | (this: BroadcastChannel, ev: MessageEvent) => anyonmessageerror: null | (this: BroadcastChannel, ev: MessageEvent) => anyaddEventListenerK extends keyof BroadcastChannelEventMap>(type: K,listener: (this: BroadcastChannel, ev: BroadcastChannelEventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

addEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

close(): void;

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

MDN Reference

dispatchEvent(event: Event): boolean;

Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

postMessage(message: any): void;

Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays.

MDN Reference

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

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

MDN Reference

removeEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;

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

MDN Reference

class ByteLengthQueuingStrategy

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

MDN Reference

readonly highWaterMark: numberreadonly size: QueuingStrategySizeArrayBufferViewArrayBufferLike>>class CloseEvent

A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute.

MDN Reference

readonly AT_TARGET: 2readonly bubbles: boolean

Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.

MDN Reference

readonly BUBBLING_PHASE: 3readonly cancelable: boolean

Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.

MDN Reference

readonly CAPTURING_PHASE: 1readonly code: number

Returns the WebSocket connection close code provided by the server.

MDN Reference

readonly composed: boolean

Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.

MDN Reference

readonly currentTarget: null | EventTarget

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

MDN Reference

readonly defaultPrevented: boolean

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

MDN Reference

readonly eventPhase: number

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

MDN Reference

readonly isTrusted: boolean

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

MDN Reference

readonly NONE: 0readonly reason: string

Returns the WebSocket connection close reason provided by the server.

MDN Reference

readonly target: null | EventTarget

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

MDN Reference

readonly timeStamp: number

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

MDN Reference

readonly type: string

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

MDN Reference

readonly wasClean: boolean

Returns true if the connection closed cleanly; false otherwise.

MDN Reference

composedPath(): EventTarget[];

Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.

MDN Reference

preventDefault(): void;

Sets the defaultPrevented property to true if cancelable is true.

stopImmediatePropagation(): void;

Stops the invocation of event listeners after the current one completes.

stopPropagation(): void;

This is not used in Node.js and is provided purely for completeness.

class CompressionStreamreadonly readable: ReadableStreamUint8ArrayArrayBufferLike>>readonly writable: WritableStreamBufferSource>class CountQueuingStrategy

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

MDN Reference

readonly highWaterMark: numberreadonly size: QueuingStrategySizeclass Crypto

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

MDN Reference

readonly subtle: SubtleCryptotimingSafeEqual: (a: ArrayBufferView, b: ArrayBufferView) => booleangetRandomValuesT extends null | ArrayBufferViewArrayBufferLike>>(array: T): T;randomUUID(): `${string}-${string}-${string}-${string}-${string}`;class CryptoKey

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

MDN Reference

readonly algorithm: KeyAlgorithmreadonly extractable: booleanreadonly type: KeyTypereadonly usages: KeyUsage[]class CustomEventT = any>readonly AT_TARGET: 2readonly bubbles: boolean

Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.

MDN Reference

readonly BUBBLING_PHASE: 3readonly cancelable: boolean

Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.

MDN Reference

readonly CAPTURING_PHASE: 1readonly composed: boolean

Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.

MDN Reference

readonly currentTarget: null | EventTarget

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

MDN Reference

readonly defaultPrevented: boolean

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

MDN Reference

readonly detail: T

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

MDN Reference

readonly eventPhase: number

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

MDN Reference

readonly isTrusted: boolean

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

MDN Reference

readonly NONE: 0readonly target: null | EventTarget

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

MDN Reference

readonly timeStamp: number

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

MDN Reference

readonly type: string

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

MDN Reference

composedPath(): EventTarget[];

Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.

MDN Reference

preventDefault(): void;

Sets the defaultPrevented property to true if cancelable is true.

stopImmediatePropagation(): void;

Stops the invocation of event listeners after the current one completes.

stopPropagation(): void;

This is not used in Node.js and is provided purely for completeness.

class DecompressionStreamreadonly readable: ReadableStreamUint8ArrayArrayBufferLike>>readonly writable: WritableStreamBufferSource>class DOMException

An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API.

MDN Reference

readonly ABORT_ERR: 20cause?: unknown

The cause of the error.

readonly DATA_CLONE_ERR: 25readonly DOMSTRING_SIZE_ERR: 2readonly HIERARCHY_REQUEST_ERR: 3readonly INDEX_SIZE_ERR: 1readonly INUSE_ATTRIBUTE_ERR: 10readonly INVALID_ACCESS_ERR: 15readonly INVALID_CHARACTER_ERR: 5readonly INVALID_MODIFICATION_ERR: 13readonly INVALID_NODE_TYPE_ERR: 24readonly INVALID_STATE_ERR: 11readonly message: stringreadonly name: stringreadonly NAMESPACE_ERR: 14readonly NETWORK_ERR: 19readonly NO_DATA_ALLOWED_ERR: 6readonly NO_MODIFICATION_ALLOWED_ERR: 7readonly NOT_FOUND_ERR: 8readonly NOT_SUPPORTED_ERR: 9readonly QUOTA_EXCEEDED_ERR: 22readonly SECURITY_ERR: 18stack?: stringreadonly SYNTAX_ERR: 12readonly TIMEOUT_ERR: 23readonly TYPE_MISMATCH_ERR: 17readonly URL_MISMATCH_ERR: 21readonly VALIDATION_ERR: 16readonly WRONG_DOCUMENT_ERR: 4readonly static ABORT_ERR: 20readonly static DATA_CLONE_ERR: 25readonly static DOMSTRING_SIZE_ERR: 2readonly static HIERARCHY_REQUEST_ERR: 3readonly static INDEX_SIZE_ERR: 1readonly static INUSE_ATTRIBUTE_ERR: 10readonly static INVALID_ACCESS_ERR: 15readonly static INVALID_CHARACTER_ERR: 5readonly static INVALID_MODIFICATION_ERR: 13readonly static INVALID_NODE_TYPE_ERR: 24readonly static INVALID_STATE_ERR: 11readonly static NAMESPACE_ERR: 14readonly static NETWORK_ERR: 19readonly static NO_DATA_ALLOWED_ERR: 6readonly static NO_MODIFICATION_ALLOWED_ERR: 7readonly static NOT_FOUND_ERR: 8readonly static NOT_SUPPORTED_ERR: 9readonly static QUOTA_EXCEEDED_ERR: 22readonly static SECURITY_ERR: 18readonly static SYNTAX_ERR: 12readonly static TIMEOUT_ERR: 23readonly static TYPE_MISMATCH_ERR: 17readonly static URL_MISMATCH_ERR: 21readonly static VALIDATION_ERR: 16readonly static WRONG_DOCUMENT_ERR: 4class ErrorEvent

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

MDN Reference

readonly AT_TARGET: 2readonly bubbles: boolean

Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.

MDN Reference

readonly BUBBLING_PHASE: 3readonly cancelable: boolean

Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.

MDN Reference

readonly CAPTURING_PHASE: 1readonly colno: numberreadonly composed: boolean

Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.

MDN Reference

readonly currentTarget: null | EventTarget

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

MDN Reference

readonly defaultPrevented: boolean

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

MDN Reference

readonly error: anyreadonly eventPhase: number

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

MDN Reference

readonly filename: stringreadonly isTrusted: boolean

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

MDN Reference

readonly lineno: numberreadonly message: stringreadonly NONE: 0readonly target: null | EventTarget

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

MDN Reference

readonly timeStamp: number

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

MDN Reference

readonly type: string

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

MDN Reference

composedPath(): EventTarget[];

Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.

MDN Reference

preventDefault(): void;

Sets the defaultPrevented property to true if cancelable is true.

stopImmediatePropagation(): void;

Stops the invocation of event listeners after the current one completes.

stopPropagation(): void;

This is not used in Node.js and is provided purely for completeness.

class Eventreadonly AT_TARGET: 2readonly bubbles: boolean

Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.

MDN Reference

readonly BUBBLING_PHASE: 3readonly cancelable: boolean

Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.

MDN Reference

readonly CAPTURING_PHASE: 1readonly composed: boolean

Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.

MDN Reference

readonly currentTarget: null | EventTarget

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

MDN Reference

readonly defaultPrevented: boolean

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

MDN Reference

readonly eventPhase: number

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

MDN Reference

readonly isTrusted: boolean

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

MDN Reference

readonly NONE: 0readonly target: null | EventTarget

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

MDN Reference

readonly timeStamp: number

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

MDN Reference

readonly type: string

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

MDN Reference

readonly static AT_TARGET: 2readonly static BUBBLING_PHASE: 3readonly static CAPTURING_PHASE: 1readonly static NONE: 0composedPath(): EventTarget[];

Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.

MDN Reference

preventDefault(): void;

Sets the defaultPrevented property to true if cancelable is true.

stopImmediatePropagation(): void;

Stops the invocation of event listeners after the current one completes.

stopPropagation(): void;

This is not used in Node.js and is provided purely for completeness.

class EventTarget

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

MDN Reference

addEventListener(type: string,callback: null | EventListenerOrEventListenerObject,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

addEventListener(type: string,listener: EventListener | EventListenerObject,options?: boolean | AddEventListenerOptions): void;

Adds a new handler for the type event. Any given listener is added only once per type and per capture option value.

If the once option is true, the listener is removed after the next time a type event is dispatched.

The capture option is not used by Node.js in any functional way other than tracking registered event listeners per the EventTarget specification. Specifically, the capture option is used as part of the key when registering a listener. Any individual listener may be added once with capture = false, and once with capture = true.

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.

MDN Reference

removeEventListener(type: string,listener: EventListener | EventListenerObject,options?: boolean | EventListenerOptions): void;

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

class File

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

MDN Reference

readonly lastModified: numberreadonly name: stringreadonly size: numberreadonly type: stringreadonly webkitRelativePath: stringarrayBuffer(): PromiseArrayBuffer>;

Returns a promise that resolves to the contents of the blob as an ArrayBuffer

bytes(): PromiseUint8ArrayArrayBufferLike>>;bytes(): PromiseUint8ArrayArrayBuffer>>;

Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes) its the same as new Uint8Array(await blob.arrayBuffer())

formData(): PromiseFormData>;

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.

image(options?: ConstructorOptions): Image;

Wrap this blob in a Bun.Image pipeline. Equivalent to new Bun.Image(this, options) — the constructor is synchronous (the underlying read happens lazily when an Image terminal is awaited), so this works on Bun.file(), Bun.s3(), fd-backed and in-memory blobs alike:

await Bun.file("photo.jpg").image().resize(400).webp().write("thumb.webp");
json(): Promiseany>;

Read the data from the blob as a JSON object.

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

slice(start?: number,end?: number,contentType?: string): Blob;stream(): ReadableStreamUint8ArrayArrayBufferLike>>;stream(): ReadableStreamUint8ArrayArrayBuffer>>;

Returns a readable stream of the blob's contents

text(): Promisestring>;

Returns a promise that resolves to the contents of the blob as a string

class FormData

Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

MDN Reference

[Symbol.iterator](): FormDataIterator[string, FormDataEntryValue]>;append(name: string,value: string | Blob): void;append(name: string,value: string): void;append(name: string,blobValue: Blob,filename?: string): void;delete(name: string): void;entries(): FormDataIterator[string, FormDataEntryValue]>;

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

entries(): IterableIterator[string, string]>;forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void,thisArg?: any): void;get(name: string): null | FormDataEntryValue;getAll(name: string): FormDataEntryValue[];has(name: string): boolean;keys(): FormDataIteratorstring>;

Returns a list of keys in the list.

keys(): IterableIteratorstring>;set(name: string,value: string | Blob): void;set(name: string,value: string): void;set(name: string,blobValue: Blob,filename?: string): void;values(): FormDataIteratorFormDataEntryValue>;

Returns a list of values in the list.

values(): IterableIteratorstring>;class Headers

This Fetch API interface allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.  You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence.

MDN Reference

readonly count: number

Get the total number of headers

[Symbol.iterator](): HeadersIterator[string, string]>;append(name: string,value: string): void;delete(name: string): void;entries(): HeadersIterator[string, string]>;

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

forEach(callbackfn: (value: string, key: string, parent: Headers) => void,thisArg?: any): void;get(name: string): null | string;getAll(name: 'set-cookie' | 'Set-Cookie'): string[];

Get all headers matching the name

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

@param name

The header name to get

@returns

An array of header values

const headers = new Headers();
headers.append("Set-Cookie", "foo=bar");
headers.append("Set-Cookie", "baz=qux");
headers.getAll("Set-Cookie"); // ["foo=bar", "baz=qux"]
getSetCookie(): string[];has(name: string): boolean;keys(): HeadersIteratorstring>;

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

set(name: string,value: string): void;toJSON(): Recordstring, string> & { set-cookie: 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(): HeadersIteratorstring>;

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

class MessageChannel

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

MDN Reference

readonly port1: MessagePortreadonly port2: MessagePortclass MessagePort

This Channel Messaging API interface represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other.

MDN Reference

onmessage: null | (this: MessagePort, ev: MessageEvent) => anyonmessageerror: null | (this: MessagePort, ev: MessageEvent) => anyaddEventListenerK extends keyof MessagePortEventMap>(type: K,listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

addEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

close(): void;

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

MDN Reference

dispatchEvent(event: Event): boolean;

Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

postMessage(message: any,transfer: Transferable[]): void;

Posts a message through the channel. Objects listed in transfer are transferred, not just cloned, meaning that they are no longer usable on the sending side.

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

MDN Reference

postMessage(message: any,options?: StructuredSerializeOptions): void;removeEventListenerK extends keyof MessagePortEventMap>(type: K,listener: (this: MessagePort, ev: MessagePortEventMap[K]) => any,options?: boolean | EventListenerOptions): void;

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

MDN Reference

removeEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;

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

MDN Reference

start(): void;class Navigator

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

MDN Reference

readonly clipboard: Clipboardreadonly cookieEnabled: booleanreadonly credentials: CredentialsContainerreadonly doNotTrack: null | stringreadonly geolocation: Geolocationreadonly hardwareConcurrency: numberreadonly language: stringreadonly languages: readonly string[]readonly locks: LockManagerreadonly maxTouchPoints: numberreadonly mediaCapabilities: MediaCapabilitiesreadonly mediaDevices: MediaDevicesreadonly mediaSession: MediaSessionreadonly onLine: booleanreadonly pdfViewerEnabled: booleanreadonly permissions: Permissionsreadonly platform: 'MacIntel' | 'Win32' | 'Linux x86_64'readonly serviceWorker: ServiceWorkerContainerreadonly storage: StorageManagerreadonly userActivation: UserActivationreadonly userAgent: stringreadonly wakeLock: WakeLockreadonly webdriver: booleancanShare(data?: ShareData): boolean;clearAppBadge(): Promisevoid>;getGamepads(): null | Gamepad[];registerProtocolHandler(scheme: string,url: string | URL): void;requestMediaKeySystemAccess(keySystem: string,supportedConfigurations: MediaKeySystemConfiguration[]): PromiseMediaKeySystemAccess>;requestMediaKeySystemAccess(keySystem: string,supportedConfigurations: IterableMediaKeySystemConfiguration>): PromiseMediaKeySystemAccess>;requestMIDIAccess(options?: MIDIOptions): PromiseMIDIAccess>;sendBeacon(url: string | URL,data?: null | BodyInit): boolean;setAppBadge(contents?: number): Promisevoid>;share(data?: ShareData): Promisevoid>;vibrate(pattern: VibratePattern): boolean;vibrate(pattern: Iterablenumber>): boolean;class Performance

Provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API.

MDN Reference

readonly eventCounts: EventCountsonresourcetimingbufferfull: null | (this: Performance, ev: Event) => anyreadonly timeOrigin: numberaddEventListenerK extends 'resourcetimingbufferfull'>(type: K,listener: (this: Performance, ev: PerformanceEventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

addEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

clearMarks(markName?: string): void;clearMeasures(measureName?: string): void;clearResourceTimings(): void;dispatchEvent(event: Event): boolean;

Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

getEntries(): PerformanceEntryList;getEntriesByName(name: string,type?: string): PerformanceEntryList;getEntriesByType(type: string): PerformanceEntryList;mark(markName: string,markOptions?: PerformanceMarkOptions): PerformanceMark;measure(measureName: string,startOrMeasureOptions?: string | PerformanceMeasureOptions,endMark?: string): PerformanceMeasure;now(): number;removeEventListenerK extends 'resourcetimingbufferfull'>(type: K,listener: (this: Performance, ev: PerformanceEventMap[K]) => any,options?: boolean | EventListenerOptions): void;

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

MDN Reference

removeEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;

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

MDN Reference

setResourceTimingBufferSize(maxSize: number): void;toJSON(): any;class PerformanceEntry

Encapsulates a single performance metric that is part of the performance timeline. A performance entry can be directly created by making a performance mark or measure (for example by calling the mark() method) at an explicit point in an application. Performance entries are also created in indirect ways such as loading a resource (such as an image).

MDN Reference

readonly duration: numberreadonly entryType: stringreadonly name: stringreadonly startTime: numbertoJSON(): any;class PerformanceMark

PerformanceMark is an abstract interface for PerformanceEntry objects with an entryType of "mark". Entries of this type are created by calling performance.mark() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline.

MDN Reference

readonly detail: anyreadonly duration: numberreadonly entryType: stringreadonly name: stringreadonly startTime: numbertoJSON(): any;class PerformanceMeasure

PerformanceMeasure is an abstract interface for PerformanceEntry objects with an entryType of "measure". Entries of this type are created by calling performance.measure() to add a named DOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline.

MDN Reference

readonly detail: anyreadonly duration: numberreadonly entryType: stringreadonly name: stringreadonly startTime: numbertoJSON(): any;class PerformanceObserverreadonly static supportedEntryTypes: readonly string[]disconnect(): void;observe(options?: PerformanceObserverInit): void;takeRecords(): PerformanceEntryList;class PerformanceObserverEntryListgetEntries(): PerformanceEntryList;getEntriesByName(name: string,type?: string): PerformanceEntryList;getEntriesByType(type: string): PerformanceEntryList;, image, or script. [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming)" data-algolia-static="false" data-algolia-merged="false" data-type="Class">class PerformanceResourceTiming

Enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. An application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an XMLHttpRequest, , image, or script.

MDN Reference

readonly connectEnd: numberreadonly connectStart: numberreadonly decodedBodySize: numberreadonly domainLookupEnd: numberreadonly domainLookupStart: numberreadonly duration: numberreadonly encodedBodySize: numberreadonly entryType: stringreadonly fetchStart: numberreadonly initiatorType: stringreadonly name: stringreadonly nextHopProtocol: stringreadonly redirectEnd: numberreadonly redirectStart: numberreadonly requestStart: numberreadonly responseEnd: numberreadonly responseStart: numberreadonly responseStatus: numberreadonly secureConnectionStart: numberreadonly serverTiming: readonly PerformanceServerTiming[]readonly startTime: numberreadonly transferSize: numberreadonly workerStart: numbertoJSON(): any;class ReadableByteStreamControllerreadonly byobRequest: null | ReadableStreamBYOBRequestreadonly desiredSize: null | numberclose(): void;enqueue(chunk: ArrayBufferView): void;error(e?: any): void;class ReadableStreamR = any>

This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.

MDN Reference

readonly locked: boolean[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIteratorR>;cancel(reason?: any): Promisevoid>;getReader(options: { mode: 'byob' }): ReadableStreamBYOBReader;getReader(): ReadableStreamDefaultReaderR>;getReader(options?: ReadableStreamGetReaderOptions): ReadableStreamReaderR>;pipeThroughT>(transform: ReadableWritablePairT, R>,options?: StreamPipeOptions): ReadableStreamT>;pipeTo(destination: WritableStreamR>,options?: StreamPipeOptions): Promisevoid>;tee(): [ReadableStreamR>, ReadableStreamR>];values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIteratorR>;class ReadableStreamBYOBReaderreadonly closed: Promisevoid>cancel(reason?: any): Promisevoid>;readT extends ArrayBufferViewArrayBufferLike>>(view: T): PromiseReadableStreamReadResultT>>;releaseLock(): void;class ReadableStreamBYOBRequestreadonly view: null | ArrayBufferViewArrayBufferLike>respond(bytesWritten: number): void;respondWithNewView(view: ArrayBufferView): void;class ReadableStreamDefaultControllerR = any>readonly desiredSize: null | numberclose(): void;enqueue(chunk?: R): void;error(e?: any): void;class ReadableStreamDefaultReaderR = any>readonly closed: Promisevoid>cancel(reason?: any): Promisevoid>;read(): PromiseReadableStreamReadResultR>>;read(): PromiseReadableStreamDefaultReadResultR>>;readMany(): ReadableStreamDefaultReadManyResultR> | PromiseReadableStreamDefaultReadManyResultR>>;

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.

releaseLock(): void;class Request

This Fetch API interface represents a resource request.

MDN Reference

readonly body: null | ReadableStreamUint8ArrayArrayBufferLike>>readonly bodyUsed: booleanreadonly cache: RequestCache

Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching.

MDN Reference

readonly credentials: RequestCredentials

Returns the credentials mode associated with request, which is a string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL.

MDN Reference

readonly destination: RequestDestination

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

MDN Reference

readonly headers: Headers

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

MDN Reference

readonly integrity: string

Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI]

MDN Reference

readonly keepalive: boolean

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

MDN Reference

readonly method: string

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

MDN Reference

readonly mode: RequestMode

Returns the mode associated with request, which is a string indicating whether the request will use CORS, or will be restricted to same-origin URLs.

MDN Reference

readonly redirect: RequestRedirect

Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default.

MDN Reference

readonly referrer: string

Returns the referrer of request. Its value can be a same-origin URL if explicitly set in init, the empty string to indicate no referrer, and "about:client" when defaulting to the global's default. This is used during fetching to determine the value of the Referer header of the request being made.

MDN Reference

readonly referrerPolicy: ReferrerPolicy

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

MDN Reference

readonly signal: AbortSignal

Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler.

MDN Reference

readonly url: stringarrayBuffer(): PromiseArrayBuffer>;blob(): PromiseBlob>;bytes(): PromiseUint8ArrayArrayBufferLike>>;clone(): Request;formData(): PromiseFormData>;json(): Promiseany>;text(): Promisestring>;class Response

This Fetch API interface represents the response to a request.

MDN Reference

readonly body: null | ReadableStreamUint8ArrayArrayBufferLike>>readonly bodyUsed: booleanreadonly headers: Headersreadonly ok: booleanreadonly redirected: booleanreadonly status: numberreadonly statusText: stringreadonly type: ResponseTypereadonly url: stringarrayBuffer(): PromiseArrayBuffer>;blob(): PromiseBlob>;bytes(): PromiseUint8ArrayArrayBufferLike>>;clone(): Response;formData(): PromiseFormData>;json(): Promiseany>;text(): Promisestring>;static error(): Response;static json(data: any,init?: ResponseInit): Response;static redirect(url: string | URL,status?: number): Response;class ShadowRealm

ShadowRealms are a distinct global environment, with its own global object containing its own intrinsics and built-ins (standard objects that are not bound to global variables, like the initial value of Object.prototype).

const red = new ShadowRealm();

// realms can import modules that will execute within it's own environment.
// When the module is resolved, it captured the binding value, or creates a new
// wrapped function that is connected to the callable binding.
const redAdd = await red.importValue('./inside-code.js', 'add');

// redAdd is a wrapped function exotic object that chains it's call to the
// respective imported binding.
let result = redAdd(2, 3);

console.assert(result === 5); // yields true

// The evaluate method can provide quick code evaluation within the constructed
// shadowRealm without requiring any module loading, while it still requires CSP
// relaxing.
globalThis.someValue = 1;
red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global
console.assert(globalThis.someValue === 1);

// The wrapped functions can also wrap other functions the other way around.
const setUniqueValue =
await red.importValue('./inside-code.js', 'setUniqueValue');

// setUniqueValue = (cb) => (cb(globalThis.someValue) * 2);

result = setUniqueValue((x) => x ** 3);

console.assert(result === 16); // yields true
evaluate(sourceText: string): any;importValue(specifier: string,bindingName: string): Promiseany>;
const red = new ShadowRealm();

// realms can import modules that will execute within it's own environment.
// When the module is resolved, it captured the binding value, or creates a new
// wrapped function that is connected to the callable binding.
const redAdd = await red.importValue('./inside-code.js', 'add');

// redAdd is a wrapped function exotic object that chains it's call to the
// respective imported binding.
let result = redAdd(2, 3);

console.assert(result === 5); // yields true

// The evaluate method can provide quick code evaluation within the constructed
// shadowRealm without requiring any module loading, while it still requires CSP
// relaxing.
globalThis.someValue = 1;
red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global
console.assert(globalThis.someValue === 1);

// The wrapped functions can also wrap other functions the other way around.
const setUniqueValue =
await red.importValue('./inside-code.js', 'setUniqueValue');

// setUniqueValue = (cb) => (cb(globalThis.someValue) * 2);

result = setUniqueValue((x) => x ** 3);

console.assert(result === 16); // yields true
class SubtleCrypto

This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). Available only in secure contexts.

MDN Reference

decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,key: CryptoKey,data: BufferSource): PromiseArrayBuffer>;deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,baseKey: CryptoKey,length?: null | number): PromiseArrayBuffer>;deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,baseKey: CryptoKey,derivedKeyType: AlgorithmIdentifier | HkdfParams | Pbkdf2Params | AesDerivedKeyParams | HmacImportParams,extractable: boolean,keyUsages: KeyUsage[]): PromiseCryptoKey>;deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,baseKey: CryptoKey,derivedKeyType: AlgorithmIdentifier | HkdfParams | Pbkdf2Params | AesDerivedKeyParams | HmacImportParams,extractable: boolean,keyUsages: IterableKeyUsage>): PromiseCryptoKey>;digest(algorithm: AlgorithmIdentifier,data: BufferSource): PromiseArrayBuffer>;encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,key: CryptoKey,data: BufferSource): PromiseArrayBuffer>;exportKey(format: 'jwk',key: CryptoKey): PromiseJsonWebKey>;exportKey(format: 'spki' | 'pkcs8' | 'raw',key: CryptoKey): PromiseArrayBuffer>;exportKey(format: KeyFormat,key: CryptoKey): PromiseArrayBuffer | JsonWebKey>;generateKey(algorithm: 'Ed25519' | { name: 'Ed25519' },extractable: boolean,keyUsages: readonly 'sign' | 'verify'[]): PromiseCryptoKeyPair>;generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams,extractable: boolean,keyUsages: readonly KeyUsage[]): PromiseCryptoKeyPair>;generateKey(algorithm: Pbkdf2Params | AesKeyGenParams | HmacKeyGenParams,extractable: boolean,keyUsages: readonly KeyUsage[]): PromiseCryptoKey>;generateKey(algorithm: AlgorithmIdentifier,extractable: boolean,keyUsages: KeyUsage[]): PromiseCryptoKeyPair | CryptoKey>;generateKey(algorithm: AlgorithmIdentifier,extractable: boolean,keyUsages: IterableKeyUsage>): PromiseCryptoKeyPair | CryptoKey>;importKey(format: 'jwk',keyData: JsonWebKey,algorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,extractable: boolean,keyUsages: readonly KeyUsage[]): PromiseCryptoKey>;importKey(format: 'spki' | 'pkcs8' | 'raw',keyData: BufferSource,algorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,extractable: boolean,keyUsages: KeyUsage[]): PromiseCryptoKey>;importKey(format: 'spki' | 'pkcs8' | 'raw',keyData: BufferSource,algorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,extractable: boolean,keyUsages: IterableKeyUsage>): PromiseCryptoKey>;sign(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,key: CryptoKey,data: BufferSource): PromiseArrayBuffer>;unwrapKey(format: KeyFormat,wrappedKey: BufferSource,unwrappingKey: CryptoKey,unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,unwrappedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,extractable: boolean,keyUsages: KeyUsage[]): PromiseCryptoKey>;unwrapKey(format: KeyFormat,wrappedKey: BufferSource,unwrappingKey: CryptoKey,unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,unwrappedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,extractable: boolean,keyUsages: IterableKeyUsage>): PromiseCryptoKey>;verify(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,key: CryptoKey,signature: BufferSource,data: BufferSource): Promiseboolean>;wrapKey(format: KeyFormat,key: CryptoKey,wrappingKey: CryptoKey,wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams): PromiseArrayBuffer>;class TextDecoder

A decoder for a specific method, that is a specific character encoding, like utf-8, iso-8859-2, koi8, cp1261, gbk, etc. A decoder takes a stream of bytes as input and emits a stream of code points. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays.

MDN Reference

readonly encoding: stringreadonly fatal: boolean

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

MDN Reference

readonly ignoreBOM: booleandecode(input?: AllowSharedBufferSource,options?: TextDecodeOptions): string;

Returns the result of running encoding's decoder. The method can be invoked zero or more times with options's stream set to true, and then once without options's stream (or set to false), to process a fragmented input. If the invocation without options's stream (or set to false) has no input, it's clearest to omit both arguments.

var string = "", decoder = new TextDecoder(encoding), buffer;
while(buffer = next_chunk()) {
string += decoder.decode(buffer, {stream:true});
}
string += decoder.decode(); // end-of-queue

If the error mode is "fatal" and encoding's decoder returns error, throws a TypeError.

MDN Reference

class TextDecoderStreamreadonly encoding: stringreadonly fatal: boolean

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

MDN Reference

readonly ignoreBOM: booleanreadonly readable: ReadableStreamstring>readonly writable: WritableStreamBufferSource>class TextEncoder

TextEncoder takes a stream of code points as input and emits a stream of bytes. For a more scalable, non-native library, see StringView – a C-like representation of strings based on typed arrays.

MDN Reference

readonly encoding: stringencode(input?: string): Uint8Array;encodeInto(source: string,destination: Uint8Array): TextEncoderEncodeIntoResult;

Runs the UTF-8 encoder on source, stores the result of that operation into destination, and returns the progress made as an object wherein read is the number of converted code units of source and written is the number of bytes modified in destination.

MDN Reference

encodeInto(src?: string,dest?: BufferSource): TextEncoderEncodeIntoResult;

UTF-8 encodes the src string to the dest Uint8Array and returns an object containing the read Unicode code units and written UTF-8 bytes.

const encoder = new TextEncoder();
const src = 'this is some data';
const dest = new Uint8Array(10);
const { read, written } = encoder.encodeInto(src, dest);
@param src

The text to encode.

@param dest

The array to hold the encode result.

class TextEncoderStreamreadonly encoding: stringreadonly readable: ReadableStreamUint8ArrayArrayBufferLike>>readonly writable: WritableStreamstring>class TransformStreamI = any, O = any>readonly readable: ReadableStreamO>readonly writable: WritableStreamI>class TransformStreamDefaultControllerO = any>readonly desiredSize: null | numberenqueue(chunk?: O): void;error(reason?: any): void;terminate(): void;class Uint8ArrayTArrayBuffer extends ArrayBufferLike = ArrayBufferLike>

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

readonly [Symbol.toStringTag]: 'Uint8Array'readonly buffer: TArrayBuffer

The ArrayBuffer instance referenced by the array.

readonly byteLength: number

The length in bytes of the array.

readonly byteOffset: number

The offset in bytes of the array.

readonly BYTES_PER_ELEMENT: number

The size in bytes of each element in the array.

readonly length: number

The length of the array.

[Symbol.iterator](): ArrayIteratornumber>;at(index: number): undefined | number;

Returns the item located at the specified index.

@param 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

@param target

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

@param start

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

@param 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.

@param predicate

A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.

@param thisArg

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

fill(value: number,start?: number,end?: number): this;

Changes all array elements from start to end index to a static value and returns the modified array

@param value

value to fill array section with

@param start

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

@param end

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

filter(predicate: (value: number, index: number, array: this) => any,thisArg?: any): Uint8ArrayArrayBuffer>;

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

@param predicate

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

@param thisArg

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

find(predicate: (value: number, index: number, obj: this) => boolean,thisArg?: any): undefined | number;

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

@param predicate

find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.

@param thisArg

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

findIndex(predicate: (value: number, index: number, obj: this) => boolean,thisArg?: any): number;

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

@param predicate

find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.

@param thisArg

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

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

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

@param predicate

findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.

@param thisArg

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

findLast(predicate: (value: number, index: number, array: this) => unknown,thisArg?: any): undefined | number;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.

@param predicate

findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.

@param thisArg

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

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

Performs the specified action for each element in an array.

@param callbackfn

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

@param thisArg

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

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

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

@param searchElement

The element to search for.

@param fromIndex

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

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

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

@param searchElement

The value to locate in the array.

@param fromIndex

The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

join(separator?: string): string;

Adds all the elements of an array separated by the specified separator string.

@param separator

A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.

keys(): ArrayIteratornumber>;

Returns an list of keys in the array

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

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

@param searchElement

The value to locate in the array.

@param fromIndex

The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

map(callbackfn: (value: number, index: number, array: this) => number,thisArg?: any): Uint8ArrayArrayBuffer>;

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

@param callbackfn

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

@param thisArg

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

reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number;

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

@param callbackfn

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

reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,initialValue: number): number;reduceU>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U,initialValue: U): U;

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

@param callbackfn

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

@param initialValue

If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

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.

@param callbackfn

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

reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,initialValue: number): number;reduceRightU>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U,initialValue: U): U;

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

@param callbackfn

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

@param initialValue

If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

reverse(): this;

Reverses the elements in an Array.

set(array: ArrayLikenumber>,offset?: number): void;

Sets a value or an array of values.

@param array

A typed or untyped array of values to set.

@param offset

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

setFromBase64(base64: string,offset?: number): { read: number; written: number };

Set the contents of the Uint8Array from a base64 encoded string

@param base64

The base64 encoded string to decode into the array

@param offset

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

setFromHex(hex: string): { read: number; written: number };

Set the contents of the Uint8Array from a hex encoded string

@param hex

The hex encoded string to decode into the array. The string must have an even number of characters, be valid hexadecimal characters and contain no whitespace.

slice(start?: number,end?: number): Uint8ArrayArrayBuffer>;

Returns a section of an array.

@param start

The beginning of the specified portion of the array.

@param end

The end of the specified portion of the array. This is exclusive of the element at the index 'end'.

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

Determines whether the specified callback function returns true for any element of an array.

@param predicate

A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.

@param thisArg

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

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

Sorts an array.

@param compareFn

Function used to determine the order of the elements. It is expected to return a negative value if first argument is less than second argument, zero if they're equal and a positive value otherwise. If omitted, the elements are sorted in ascending order.

[11,2,22,1].sort((a, b) => a - b)
subarray(begin?: number,end?: number): Uint8ArrayTArrayBuffer>;

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

@param begin

The index of the beginning of the array.

@param end

The index of the end of the array.

toBase64(options?: { alphabet: 'base64' | 'base64url'; omitPadding: boolean }): string;

Convert the Uint8Array to a base64 encoded string

@returns

The base64 encoded string representation of the Uint8Array

toHex(): string;

Convert the Uint8Array to a hex encoded string

@returns

The hex encoded string representation of the Uint8Array

toLocaleString(): string;

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

toLocaleString(locales: string | string[],options?: NumberFormatOptions): string;toReversed(): Uint8ArrayArrayBuffer>;

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

toSorted(compareFn?: (a: number, b: number) => number): Uint8ArrayArrayBuffer>;

Copies and sorts the array.

@param compareFn

Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending order.

const myNums = Uint8Array.from([11, 2, 22, 1]);
myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22]
toString(): string;

Returns a string representation of an array.

valueOf(): this;

Returns the primitive value of the specified object.

values(): ArrayIteratornumber>;

Returns an list of values in the array

with(index: number,value: number): Uint8ArrayArrayBuffer>;

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

@param index

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

@param value

The value to insert into the copied array.

@returns

A copy of the original array with the inserted value.

class URLSearchParamsreadonly size: number[Symbol.iterator](): URLSearchParamsIterator[string, string]>;append(name: string,value: string): void;

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

MDN Reference

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

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

MDN Reference

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

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

forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void,thisArg?: any): void;get(name: string): null | string;

Returns the first value associated to the given search parameter.

MDN Reference

getAll(name: string): string[];

Returns all the values association with a given search parameter.

MDN Reference

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

Returns a Boolean indicating if such a search parameter exists.

MDN Reference

keys(): URLSearchParamsIteratorstring>;

Returns a list of keys in the search params.

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

Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.

MDN Reference

sort(): void;toJSON(): Recordstring, string>;toString(): string;

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

values(): URLSearchParamsIteratorstring>;

Returns a list of values in the search params.

class WritableStreamW = any>

This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.

MDN Reference

readonly locked: booleanabort(reason?: any): Promisevoid>;close(): Promisevoid>;getWriter(): WritableStreamDefaultWriterW>;class WritableStreamDefaultController

This Streams API interface represents a controller allowing control of a WritableStream's state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.

MDN Reference

readonly signal: AbortSignalerror(e?: any): void;class WritableStreamDefaultWriterW = any>

This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the

MDN Reference

readonly closed: Promisevoid>readonly desiredSize: null | numberreadonly ready: Promisevoid>abort(reason?: any): Promisevoid>;close(): Promisevoid>;releaseLock(): void;write(chunk?: W): Promisevoid>;Type definitionsinterface AddEventListenerOptionscapture?: booleanonce?: booleanpassive?: booleansignal?: AbortSignalinterface ArrayBufferConstructorconstructor ArrayBufferConstructor(byteLength: number): ArrayBuffer;constructor (): ArrayBuffer;constructor ArrayBufferConstructor(byteLength: number,options: { maxByteLength: number }): ArrayBuffer;readonly [Symbol.species]: ArrayBufferConstructorreadonly prototype: ArrayBufferisView(arg: any): arg is ArrayBufferViewArrayBufferLike>;interface ArrayConstructorconstructor ArrayConstructor(arrayLength?: number): any[];constructor ArrayConstructorT>(arrayLength: number): T[];constructor ArrayConstructorT>(...items: T[]): T[];readonly [Symbol.species]: ArrayConstructorreadonly prototype: any[]fromT>(arrayLike: ArrayLikeT>): T[];

Creates an array from an array-like object.

@param arrayLike

An array-like object to convert to an array.

fromT, U>(arrayLike: ArrayLikeT>,mapfn: (v: T, k: number) => U,thisArg?: any): U[];

Creates an array from an iterable object.

@param arrayLike

An array-like object to convert to an array.

@param mapfn

A mapping function to call on every element of the array.

@param thisArg

Value of 'this' used to invoke the mapfn.

fromT>(iterable: IterableT, any, any> | ArrayLikeT>): T[];

Creates an array from an iterable object.

@param iterable

An iterable object to convert to an array.

fromT, U>(iterable: IterableT, any, any> | ArrayLikeT>,mapfn: (v: T, k: number) => U,thisArg?: any): U[];

Creates an array from an iterable object.

@param iterable

An iterable object to convert to an array.

@param mapfn

A mapping function to call on every element of the array.

@param thisArg

Value of 'this' used to invoke the mapfn.

fromAsyncT>(iterableOrArrayLike: AsyncIterableT, any, any> | IterableT | PromiseLikeT>, any, any> | ArrayLikeT | PromiseLikeT>>): PromiseT[]>;

Creates an array from an async iterator or iterable object.

@param iterableOrArrayLike

An async iterator or array-like object to convert to an array.

fromAsyncT, U>(iterableOrArrayLike: AsyncIterableT, any, any> | IterableT, any, any> | ArrayLikeT>,mapFn: (value: AwaitedT>, index: number) => U,thisArg?: any): PromiseAwaitedU>[]>;

Creates an array from an async iterator or iterable object.

@param iterableOrArrayLike

An async iterator or array-like object to convert to an array.

@param thisArg

Value of 'this' used when executing mapfn.

fromAsyncT>(arrayLike: AsyncIterableT, any, any> | IterableT, any, any> | ArrayLikeT>): PromiseAwaitedT>[]>;

Create an array from an iterable or async iterable object. Values from the iterable are awaited.

await Array.fromAsync([1]); // [1]
await Array.fromAsync([Promise.resolve(1)]); // [1]
await Array.fromAsync((async function*() { yield 1 })()); // [1]
@param arrayLike

The iterable or async iterable to convert to an array.

@returns

A Promise whose fulfillment is a new Array instance containing the values from the iterator.

fromAsyncT, U>(arrayLike: AsyncIterableT, any, any> | IterableT, any, any> | ArrayLikeT>,mapFn?: (value: T, index: number) => U,thisArg?: any): PromiseAwaitedU>[]>;

Create an array from an iterable or async iterable object. Values from the iterable are awaited. Results of the map function are also awaited.

await Array.fromAsync([1]); // [1]
await Array.fromAsync([Promise.resolve(1)]); // [1]
await Array.fromAsync((async function*() { yield 1 })()); // [1]
await Array.fromAsync([1], (n) => n + 1); // [2]
await Array.fromAsync([1], (n) => Promise.resolve(n + 1)); // [2]
@param arrayLike

The iterable or async iterable to convert to an array.

@param mapFn

A mapper function that transforms each element of arrayLike after awaiting them.

@param thisArg

The this to which mapFn is bound.

@returns

A Promise whose fulfillment is a new Array instance containing the values from the iterator.

isArray(arg: any): arg is any[];ofT>(...items: T[]): T[];

Returns a new array from a set of elements.

@param items

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

interface BlobPropertyBagendings?: EndingTypetype?: string

Set a default "type". Not yet implemented.

interface BunFetchRequestInit

BunFetchRequestInit represents additional options that Bun supports in fetch() only.

Bun extends the fetch API with some additional options, except this interface is not quite 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.

decompress?: boolean

Control automatic decompression of the response body. When set to false, the response body will not be automatically decompressed, and the Content-Encoding header will be preserved. This can improve performance when you need to handle compressed data manually or forward it as-is. This is a custom property that is not part of the Fetch API specification.

// Disable automatic decompression for a proxy server
const response = await fetch("https://example.com/api", {
decompress: false
});
// response.headers.get('content-encoding') might be 'gzip' or 'br'
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?: RequestPriorityprotocol?: 'http2' | 'http1.1' | 'h2' | 'h1'

Force the underlying HTTP version. "http2" advertises only h2 in the TLS ALPN list and the request fails with HTTP2Unsupported if the server doesn't select it. "http1.1" pins the request to HTTP/1.1, overriding --experimental-http2-fetch / BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT if set. Omit to use the default (h2 is offered iff the flag is on).

Requires https. This is a custom property that is not part of the Fetch API specification.

proxy?: string | { headers: HeadersInit; url: string }

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

Can be a string URL or an object with url and optional headers.

// String format
const response = await fetch("http://example.com", {
proxy: "https://username:password@127.0.0.1:8080"
});

// Object format with custom headers sent to the proxy
const response = await fetch("http://example.com", {
proxy: {
url: "https://127.0.0.1:8080",
headers: {
"Proxy-Authorization": "Bearer token",
"X-Custom-Proxy-Header": "value"
}
}
});

If a Proxy-Authorization header is provided in proxy.headers, it takes precedence over credentials parsed from the proxy URL.

redirect?: RequestRedirect

A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect.

referrer?: string

A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer.

referrerPolicy?: ReferrerPolicy

A referrer policy to set request's referrerPolicy.

s3?: S3Options

Override the default S3 options

const response = await fetch("s3:http://bucket/key", {
s3: {
accessKeyId: "AKIAIOSFODNN7EXAMPLE",
secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
region: "us-east-1",
}
});
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

const response = await fetch("http://example.com", { unix: "/path/to/socket" });
verbose?: boolean

Log the raw HTTP request & response to stdout. This API may be removed in a future version of Bun without notice. This is a custom property that is not part of the Fetch API specification. It exists mostly as a debugging tool

window?: null

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

interface BunFetchRequestInitTLS

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

ALPNProtocols?: string | BufferSourceca?: string | BunFile | BufferSource | unknown[]

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 | BunFile | BufferSource | unknown[]

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

ciphers?: stringclientRenegotiationLimit?: numberclientRenegotiationWindow?: numberdhParamsFile?: string

File path to a .pem file custom Diffie Helman parameters

[, passphrase: ]}. 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." data-algolia-static="false" data-algolia-merged="false" data-type="Property">key?: string | BunFile | BufferSource | unknown[]

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: [, passphrase: ]}. 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

interface Consolereadonly Console: {new (stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean) => Console; new (options: ConsoleOptions) => Console}[Symbol.asyncIterator](): AsyncIterableIteratorstring>;

Asynchronously read lines from standard input (fd 0)

for await (const line of console) {
console.log(line);
}
assert(condition?: boolean,...data: any[]): void;clear(): void;

Clear the console

count(label?: string): void;@param label

label counter

countReset(label?: string): void;debug(...data: any[]): void;dir(item?: any,options?: any): void;dirxml(...data: any[]): void;error(...data: any[]): void;

Log to stderr in your terminal

Appears in red

@param data

something to display

group(...data: any[]): void;

Does nothing currently

groupCollapsed(...data: any[]): void;

Does nothing currently

groupEnd(): void;

Does nothing currently

info(...data: any[]): void;log(...data: any[]): void;profile(label?: string): void;

This method does not display anything unless used in the inspector. The console.profile() method starts a JavaScript CPU profile with an optional label until profileEnd is called. The profile is then added to the Profile panel of the inspector.

console.profile('MyLabel');
// Some code
console.profileEnd('MyLabel');
// Adds the profile 'MyLabel' to the Profiles panel of the inspector.
profileEnd(label?: string): void;

This method does not display anything unless used in the inspector. Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. See profile for an example.

If this method is called without a label, the most recently started profile is stopped.

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

Try to construct a table with the columns of the properties of tabularData (or use properties) and rows of tabularData and log it. Falls back to just logging the argument if it can't be parsed as tabular.

// These can't be parsed as tabular data
console.table(Symbol());
// Symbol()

console.table(undefined);
// undefined

console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
// ┌────┬─────┬─────┐
// │ │ a │ b │
// ├────┼─────┼─────┤
// │ 0 │ 1 │ 'Y' │
// │ 1 │ 'Z' │ 2 │
// └────┴─────┴─────┘

console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
// ┌────┬─────┐
// │ │ a │
// ├────┼─────┤
// │ 0 │ 1 │
// │ 1 │ 'Z' │
// └────┴─────┘
@param properties

Alternate properties for constructing the table.

time(label?: string): void;

Begin a timer to log with console.timeEnd

@param label

The label to use for the timer

 console.time("how long????");
for (let i = 0; i 999999; i++) {
// do stuff
let x = i * i;
}
console.timeEnd("how long????");
timeEnd(label?: string): void;

End a timer to log with console.time

@param label

The label to use for the timer

 console.time("how long????");
for (let i = 0; i 999999; i++) {
// do stuff
let x = i * i;
}
console.timeEnd("how long????");
timeLog(label?: string,...data: any[]): void;timeStamp(label?: string): void;trace(...data: any[]): void;warn(...data: any[]): void;write(...data: string | ArrayBuffer | ArrayBufferViewArrayBufferLike>[]): number;

Write text or bytes to stdout

Unlike console.log, this does no formatting and doesn't add a newline or spaces between arguments. You can pass it strings or bytes or any combination of the two.

console.write("hello world!", "\n"); // "hello world\n"
@param data

The data to write

@returns

The number of bytes written

This function is not available in the browser.

interface ConsoleOptionscolorMode?: boolean | 'auto'groupIndentation?: numberignoreErrors?: booleaninspectOptions?: InspectOptionsstderr?: Writablestdout: Writableinterface CryptoKeyPairprivateKey: CryptoKeypublicKey: CryptoKeyinterface DictT>interface ErrnoExceptioncause?: unknown

The cause of the error.

code?: stringerrno?: numbermessage: stringname: stringpath?: stringstack?: stringsyscall?: stringinterface Errorcause?: unknown

The cause of the error.

message: stringname: stringstack?: stringinterface ErrorConstructorconstructor ErrorConstructor(message?: string): Error;constructor ErrorConstructor(message?: string,options?: ErrorOptions): Error;readonly prototype: ErrorstackTraceLimit: number

The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).

The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.

If set to a non-number value, or set to a negative number, stack traces will not capture any frames.

captureStackTrace(targetObject: object,constructorOpt?: Function): void;

Create .stack property on a target object

isError(value: unknown): value is Error;

Check if a value is an instance of Error

@param value

The value to check

@returns

True if the value is an instance of Error, false otherwise

prepareStackTrace(err: Error,stackTraces: CallSite[]): any;
interface ErrorOptionscause?: unknown

The cause of the error.

interface EventListenerinterface EventListenerObjecthandleEvent(object: Event): void;interface EventMapfetch: FetchEventmessage: MessageEventmessageerror: MessageEventinterface EventSourcereadonly CLOSED: 2readonly CONNECTING: 0onerror: null | (this: EventSource, ev: Event) => anyonmessage: null | (this: EventSource, ev: MessageEvent) => anyonopen: null | (this: EventSource, ev: Event) => anyreadonly OPEN: 1readonly readyState: number

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

MDN Reference

readonly url: stringreadonly withCredentials: boolean

Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.

MDN Reference

addEventListenerK extends keyof EventSourceEventMap>(type: K,listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

addEventListener(type: string,listener: (this: EventSource, event: MessageEvent) => any,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

addEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

close(): void;

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

MDN Reference

dispatchEvent(event: Event): boolean;

Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

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

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

MDN Reference

removeEventListener(type: string,listener: (this: EventSource, event: MessageEvent) => any,options?: boolean | EventListenerOptions): void;

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

MDN Reference

removeEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;

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

MDN Reference

interface EventSourceInitwithCredentials?: booleaninterface FetchEventreadonly AT_TARGET: 2readonly bubbles: boolean

Returns true or false depending on how event was initialized. True if event goes through its target's ancestors in reverse tree order, and false otherwise.

MDN Reference

readonly BUBBLING_PHASE: 3readonly cancelable: boolean

Returns true or false depending on how event was initialized. Its return value does not always carry meaning, but true can indicate that part of the operation during which event was dispatched, can be canceled by invoking the preventDefault() method.

MDN Reference

readonly CAPTURING_PHASE: 1readonly composed: boolean

Returns true or false depending on how event was initialized. True if event invokes listeners past a ShadowRoot node that is the root of its target, and false otherwise.

MDN Reference

readonly currentTarget: null | EventTarget

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

MDN Reference

readonly defaultPrevented: boolean

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

MDN Reference

readonly eventPhase: number

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

MDN Reference

readonly isTrusted: boolean

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

MDN Reference

readonly NONE: 0readonly request: Requestreadonly target: null | EventTarget

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

MDN Reference

readonly timeStamp: number

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

MDN Reference

readonly type: string

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

MDN Reference

readonly url: stringcomposedPath(): EventTarget[];

Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.

MDN Reference

preventDefault(): void;

Sets the defaultPrevented property to true if cancelable is true.

respondWith(response: Response | PromiseResponse>): void;stopImmediatePropagation(): void;

Stops the invocation of event listeners after the current one completes.

stopPropagation(): void;

This is not used in Node.js and is provided purely for completeness.

waitUntil(promise: Promiseany>): void;interface ImportMeta

The type of import.meta.

If you need to declare that a given property exists on import.meta, this type may be augmented via interface merging.

readonly dir: string

Absolute path to the directory containing the source file.

Does not have a trailing slash

dirname: string

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

readonly env: Env & ProcessEnv & ImportMetaEnv

The environment variables of the process

import.meta.env === process.env
readonly file: string

Filename of the source file

filename: string

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

hot: { data: any; accept(): void; decline; dispose(cb: (data: any) => void | Promisevoid>): void; off(event: HMREvent, callback: () => void): void; on(event: HMREvent, callback: () => void): void }

Hot module replacement APIs. This value is undefined in production and can be used in 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.com/docs/bundler/hmr

main: boolean

Did the current file start the process?

if (import.meta.main) {
console.log("I started the process!");
}
readonly 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:http:// url string for the current module.

console.log(import.meta.url);
"file:http:///Users/me/projects/my-app/src/my-app.ts"
resolve(specifier: string): string;resolve(specifier: string,parent?: string | URL): string;interface ImportMetaEnvinterface Positioncolumn: numberfile: stringlength: numberline: numberlineText: stringnamespace: stringoffset: numberinterface PromiseConstructor

Represents the completion of an asynchronous operation

constructor PromiseConstructorT>(executor: (resolve: (value: T | PromiseLikeT>) => void, reject: (reason?: any) => void) => void): PromiseT>;

Creates a new Promise.

@param executor

A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.

readonly [Symbol.species]: PromiseConstructorreadonly prototype: Promiseany>

A reference to the prototype.

allT>(values: IterableT | PromiseLikeT>>): PromiseAwaitedT>[]>;

Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected.

@param values

An iterable of Promises.

@returns

A new Promise.

allT extends [] | readonly unknown[]>(values: T): Promise{ [K in string | number | symbol]: AwaitedT[PP>]> }>;

Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected.

@param values

An array of Promises.

@returns

A new Promise.

allSettledT extends [] | readonly unknown[]>(values: T): Promise{ [K in string | number | symbol]: PromiseSettledResultAwaitedT[PP>]>> }>;

Creates a Promise that is resolved with an array of results when all of the provided Promises resolve or reject.

@param values

An array of Promises.

@returns

A new Promise.

allSettledT>(values: IterableT | PromiseLikeT>>): PromisePromiseSettledResultAwaitedT>>[]>;

Creates a Promise that is resolved with an array of results when all of the provided Promises resolve or reject.

@param values

An array of Promises.

@returns

A new Promise.

anyT extends [] | readonly unknown[]>(values: T): PromiseAwaitedT[number]>>;

The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.

@param values

An array or iterable of Promises.

@returns

A new Promise.

anyT>(values: IterableT | PromiseLikeT>>): PromiseAwaitedT>>;

The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.

@param values

An array or iterable of Promises.

@returns

A new Promise.

raceT>(values: IterableT | PromiseLikeT>>): PromiseAwaitedT>>;

Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected.

@param values

An iterable of Promises.

@returns

A new Promise.

raceT extends [] | readonly unknown[]>(values: T): PromiseAwaitedT[number]>>;

Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected.

@param values

An array of Promises.

@returns

A new Promise.

rejectT = never>(reason?: any): PromiseT>;

Creates a new rejected promise for the provided reason.

@param reason

The reason the promise was rejected.

@returns

A new rejected Promise.

resolve(): Promisevoid>;

Creates a new resolved promise.

@returns

A resolved promise.

resolveT>(value: T): PromiseAwaitedT>>;

Creates a new resolved promise for the provided value.

@param value

A promise.

@returns

A promise whose internal state matches the provided promise.

resolveT>(value: T | PromiseLikeT>): PromiseAwaitedT>>;

Creates a new resolved promise for the provided value.

@param value

A promise.

@returns

A promise whose internal state matches the provided promise.

tryT, U extends unknown[]>(callbackFn: (...args: U) => T | PromiseLikeT>,...args: U): PromiseAwaitedT>>;

Takes a callback of any kind (returns or throws, synchronously or asynchronously) and wraps its result in a Promise.

@param callbackFn

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

@param args

Additional arguments, that will be passed to the callback.

@returns

A Promise that is:

Already fulfilled, if the callback synchronously returns a value.Already rejected, if the callback synchronously throws an error.Asynchronously fulfilled or rejected, if the callback returns a promise.
tryT, A extends any[] = []>(fn: (...args: A) => T | PromiseLikeT>,...args: A): PromiseT>;

Try to run a function and return the result. If the function throws, return the result of the catch function.

@param fn

The function to run

@param args

The arguments to pass to the function. This is similar to setTimeout and avoids the extra closure.

@returns

The result of the function or the result of the catch function

withResolversT>(): PromiseWithResolversT>;

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

@returns

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

const { promise, resolve, reject } = Promise.withResolversT>();
withResolversT>(): { promise: PromiseT>; reject: (reason?: any) => void; resolve: (value?: T | PromiseLikeT>) => void };

Create a deferred promise, with exposed resolve and reject methods which can be called separately.

This is useful when you want to return a Promise and have code outside the Promise resolve or reject it.

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

setTimeout(() => {
resolve("Hello world!");
}, 1000);

await promise; // "Hello world!"
interface QueuingStrategyT = any>highWaterMark?: numbersize?: QueuingStrategySizeT>interface QueuingStrategyInithighWaterMark: number

Creates a new ByteLengthQueuingStrategy with the provided high water mark.

Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw.

interface QueuingStrategySizeT = any>interface ReadableStreamDefaultReadDoneResultdone: truevalue?: undefinedinterface ReadableStreamDefaultReadValueResultT>done: falsevalue: Tinterface ReadableStreamDirectControllerclose(error?: Error): void;end(): number | Promisenumber>;flush(): number | Promisenumber>;start(): void;write(data: string | BufferSource): number | Promisenumber>;interface ReadableStreamGenericReaderreadonly closed: Promisevoid>cancel(reason?: any): Promisevoid>;interface ReadableWritablePairR = any, W = any>readable: ReadableStreamR>writable: WritableStreamW>

Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use.

Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.

interface ReadOnlyDictT>interface RegExpConstructorconstructor RegExpConstructor(pattern: string | RegExp): RegExp;constructor RegExpConstructor(pattern: string,flags?: string): RegExp;constructor RegExpConstructor(pattern: string | RegExp,flags?: string): RegExp;readonly [Symbol.species]: RegExpConstructorreadonly prototype: RegExpescape(string: string): string;

Escapes any potential regex syntax characters in a string, and returns a new string that can be safely used as a literal pattern for the RegExp() constructor.

MDN Reference

const re = new RegExp(RegExp.escape("foo.bar"));
re.test("foo.bar"); // true
re.test("foo!bar"); // false
interface RequestInitbody?: 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?: RequestPriorityredirect?: 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.

interface ResponseInitheaders?: HeadersInitstatus?: numberstatusText?: stringinterface SharedArrayBufferreadonly [Symbol.species]: SharedArrayBufferreadonly [Symbol.toStringTag]: 'SharedArrayBuffer'readonly byteLength: number

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

get growableget maxByteLengthgrow(newByteLength?: number): void;

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

MDN

grow(size: number): SharedArrayBuffer;

Grow the SharedArrayBuffer in-place.

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

Returns a section of an SharedArrayBuffer.

interface StreamPipeOptionspreventAbort?: booleanpreventCancel?: booleanpreventClose?: 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.

signal?: AbortSignalinterface Timer[Symbol.toPrimitive](): number;hasRef(): boolean;ref(): Timer;refresh(): Timer;unref(): Timer;interface TransformerI = any, O = any>flush?: TransformerFlushCallbackO>readableType?: undefinedstart?: TransformerStartCallbackO>transform?: TransformerTransformCallbackI, O>writableType?: undefinedinterface Uint8ArrayConstructorconstructor Uint8ArrayConstructor(length: number): Uint8ArrayArrayBuffer>;constructor Uint8ArrayConstructor(array: ArrayLikenumber>): Uint8ArrayArrayBuffer>;constructor Uint8ArrayConstructorTArrayBuffer extends ArrayBufferLike = ArrayBuffer>(buffer: TArrayBuffer,byteOffset?: number,length?: number): Uint8ArrayTArrayBuffer>;constructor Uint8ArrayConstructor(buffer: ArrayBuffer,byteOffset?: number,length?: number): Uint8ArrayArrayBuffer>;constructor Uint8ArrayConstructor(array: ArrayBuffer | ArrayLikenumber>): Uint8ArrayArrayBuffer>;constructor Uint8ArrayConstructor(elements: Iterablenumber>): Uint8ArrayArrayBuffer>;constructor (): Uint8ArrayArrayBuffer>;readonly BYTES_PER_ELEMENT: number

The size in bytes of each element in the array.

readonly prototype: Uint8ArrayArrayBufferLike>from(arrayLike: ArrayLikenumber>): Uint8ArrayArrayBuffer>;

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

@param arrayLike

An array-like object to convert to an array.

fromT>(arrayLike: ArrayLikeT>,mapfn: (v: T, k: number) => number,thisArg?: any): Uint8ArrayArrayBuffer>;

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

@param arrayLike

An array-like object to convert to an array.

@param mapfn

A mapping function to call on every element of the array.

@param thisArg

Value of 'this' used to invoke the mapfn.

from(elements: Iterablenumber>): Uint8ArrayArrayBuffer>;

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

@param elements

An iterable object to convert to an array.

fromT>(elements: IterableT>,mapfn?: (v: T, k: number) => number,thisArg?: any): Uint8ArrayArrayBuffer>;

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

@param elements

An iterable object to convert to an array.

@param mapfn

A mapping function to call on every element of the array.

@param thisArg

Value of 'this' used to invoke the mapfn.

fromBase64(base64: string,options?: { alphabet: 'base64' | 'base64url'; lastChunkHandling: 'strict' | 'loose' | 'stop-before-partial' }): Uint8ArrayArrayBuffer>;

Create a new Uint8Array from a base64 encoded string

@param base64

The base64 encoded string to convert to a Uint8Array

@param options

Optional options for decoding the base64 string

@returns

A new Uint8Array containing the decoded data

fromHex(hex: string): Uint8ArrayArrayBuffer>;

Create a new Uint8Array from a hex encoded string

@param hex

The hex encoded string to convert to a Uint8Array

@returns

A new Uint8Array containing the decoded data

of(...items: number[]): Uint8ArrayArrayBuffer>;

Returns a new array from a set of elements.

@param items

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

interface WebSocket

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

MDN Reference

binaryType: BinaryType

Returns a string that indicates how binary data from the WebSocket object is exposed to scripts:

Can be set, to change how binary data is returned. The default is "blob".

MDN Reference

readonly bufferedAmount: number

Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network.

If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.)

MDN Reference

readonly CLOSED: 3readonly CLOSING: 2readonly CONNECTING: 0readonly extensions: string

Returns the extensions selected by the server, if any.

MDN Reference

onclose: null | (this: WebSocket, ev: CloseEvent) => anyonerror: null | (this: WebSocket, ev: Event) => anyonmessage: null | (this: WebSocket, ev: MessageEvent) => anyonopen: null | (this: WebSocket, ev: Event) => anyreadonly OPEN: 1readonly protocol: string

Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.

MDN Reference

readonly readyState: number

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

MDN Reference

readonly url: string

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

MDN Reference

addEventListenerK extends keyof WebSocketEventMap>(type: K,listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

addEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

close(code?: number,reason?: string): void;

Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.

MDN Reference

dispatchEvent(event: Event): boolean;

Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

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

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

MDN Reference

removeEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;

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

MDN Reference

send(data: string | ArrayBufferLike | Blob | ArrayBufferViewArrayBufferLike>): void;

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

MDN Reference

interface Worker

This Web Workers API interface represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread.

MDN Reference

onerror: null | (this: AbstractWorker, ev: ErrorEvent) => anyonmessage: null | (this: Worker, ev: MessageEvent) => anyonmessageerror: null | (this: Worker, ev: MessageEvent) => anyaddEventListenerK extends keyof WorkerEventMap>(type: K,listener: (this: Worker, ev: WorkerEventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

addEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | AddEventListenerOptions): void;

Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

MDN Reference

dispatchEvent(event: Event): boolean;

Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

postMessage(message: any,transfer: Transferable[]): void;

Clones message and transmits it to worker's global environment. transfer can be passed as a list of objects that are to be transferred rather than cloned.

MDN Reference

postMessage(message: any,options?: StructuredSerializeOptions): void;removeEventListenerK extends keyof WorkerEventMap>(type: K,listener: (this: Worker, ev: WorkerEventMap[K]) => any,options?: boolean | EventListenerOptions): void;

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

MDN Reference

removeEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;

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

MDN Reference

terminate(): void;interface WorkerOptions

Bun's Web Worker constructor supports some extra options on top of the API browsers have.

argv?: any[]

List of arguments which would be stringified and appended to Bun.argv / process.argv in the worker. This is mostly similar to 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?: Recordstring, 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.

Resources

ReferenceDocsGuidesDiscordMerch StoreGitHubBlog 

Toolkit

RuntimePackage managerTest runnerBundlerPackage runner

Project

Bun 1.0Bun 1.1Bun 1.2Bun 1.3RoadmapContributingLicense

Baked with ❤️ in San Francisco

We're hiring →

globals module | API Reference | Bun,AI智能索引,全网链接索引,智能导航,网页索引

    API documentation for module globals | Bun