Bun

module

globals

  • function fetch(
    input: string | URL | Request,
    ): Promise<Response>;

    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 setImmediate

  • function setTimeout(
    handler: TimerHandler,
    timeout?: number,
    ...arguments: any[]
    ): number;

    namespace setTimeout

  • const exports: any

    Same as module.exports

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

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

    Before using this, be aware of a few things:

    Using this incorrectly will crash your application.

    This API may change any time JavaScriptCore is updated.

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

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

  • const module: NodeModule

    A reference to the current module.

  • const require: NodeJS.Require

    NodeJS-style require function

  • const SharedArrayBuffer: SharedArrayBufferConstructor
  • function addEventListener<K 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,
    ): Promise<Response>;

    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 removeEventListener<K 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 structuredClone<T = any>(
    value: T,
    options?: StructuredSerializeOptions
    ): T;
  • class URL

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

    MDN Reference

  • class MessageEvent<T = any>

    • readonly AT_TARGET: 2
    • readonly bubbles: boolean

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

      MDN Reference

    • readonly BUBBLING_PHASE: 3
    • readonly cancelable: boolean

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

      MDN Reference

    • readonly CAPTURING_PHASE: 1
    • 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 data: T
    • 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 lastEventId: string

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

      MDN Reference

    • readonly NONE: 0
    • readonly 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

    • readonly source: null | MessageEventSource

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

      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

    • 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

    • Sets the defaultPrevented property to true if cancelable is true.

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

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

  • class AbortController

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

    MDN Reference

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

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

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

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

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

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

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

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

      MDN Reference

    • event: Event
      ): boolean;

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

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

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

      MDN Reference

    • static abort(
      reason?: any
    • static timeout(
      milliseconds: number
  • 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]: string
    • readonly byteLength: number

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

    • newByteLength?: number
      ): void;

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

      MDN

      byteLength: number

      Resize an ArrayBuffer in-place.

    • begin: number,
      end?: number

      Returns a section of an ArrayBuffer.

    • newByteLength?: number

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

      MDN

    • newByteLength?: number

      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: number
    • readonly type: string
    • Returns a promise that resolves to the contents of the blob as an ArrayBuffer

    • bytes(): Promise<Uint8Array<ArrayBufferLike>>;

      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(): Promise<FormData>;

      Read the data from the blob as a FormData object.

      This first decodes the data from UTF-8, then parses it as a multipart/form-data body or a application/x-www-form-urlencoded body.

      The type property of the blob is used to determine the format of the body.

      This is a non-standard addition to the Blob API, to make it conform more closely to the BodyMixin API.

    • json(): Promise<any>;

      Read the data from the blob as a JSON object.

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

    • start?: number,
      end?: number,
      contentType?: string
      ): Blob;
    • stream(): ReadableStream<Uint8Array<ArrayBufferLike>>;

      Returns a readable stream of the blob's contents

    • text(): Promise<string>;

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

    • readonly name: string

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

      MDN Reference

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

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

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

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

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

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

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

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

      MDN Reference

      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

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

    • message: any
      ): void;

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

      MDN Reference

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

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

      MDN Reference

      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

  • 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: 2
    • readonly bubbles: boolean

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

      MDN Reference

    • readonly BUBBLING_PHASE: 3
    • readonly cancelable: boolean

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

      MDN Reference

    • readonly CAPTURING_PHASE: 1
    • readonly 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: 0
    • readonly 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

    • 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

    • Sets the defaultPrevented property to true if cancelable is true.

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

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

  • class CountQueuingStrategy

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

    MDN Reference

  • class 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

  • class CryptoKey

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

    MDN Reference

    • readonly AT_TARGET: 2
    • readonly bubbles: boolean

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

      MDN Reference

    • readonly BUBBLING_PHASE: 3
    • readonly cancelable: boolean

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

      MDN Reference

    • readonly CAPTURING_PHASE: 1
    • 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 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: 0
    • 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

    • 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

    • Sets the defaultPrevented property to true if cancelable is true.

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

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

  • class DOMException

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

    MDN Reference

  • class ErrorEvent

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

    MDN Reference

    • readonly AT_TARGET: 2
    • readonly bubbles: boolean

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

      MDN Reference

    • readonly BUBBLING_PHASE: 3
    • readonly cancelable: boolean

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

      MDN Reference

    • readonly CAPTURING_PHASE: 1
    • readonly colno: number
    • 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 error: any
    • readonly eventPhase: number

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

      MDN Reference

    • readonly filename: string
    • readonly isTrusted: boolean

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

      MDN Reference

    • readonly lineno: number
    • readonly message: string
    • readonly NONE: 0
    • 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

    • 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

    • Sets the defaultPrevented property to true if cancelable is true.

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

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

  • class Event

    • readonly AT_TARGET: 2
    • readonly bubbles: boolean

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

      MDN Reference

    • readonly BUBBLING_PHASE: 3
    • readonly cancelable: boolean

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

      MDN Reference

    • readonly CAPTURING_PHASE: 1
    • 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: 0
    • 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 static AT_TARGET: 2
    • readonly static BUBBLING_PHASE: 3
    • readonly static CAPTURING_PHASE: 1
    • readonly static NONE: 0
    • 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

    • Sets the defaultPrevented property to true if cancelable is true.

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

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

  • class EventTarget

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

    MDN Reference

    • 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

      type: string,
      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.

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

    • 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

      type: string,
      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: number
    • readonly name: string
    • readonly size: number
    • readonly type: string
    • Returns a promise that resolves to the contents of the blob as an ArrayBuffer

    • bytes(): Promise<Uint8Array<ArrayBufferLike>>;

      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(): Promise<FormData>;

      Read the data from the blob as a FormData object.

      This first decodes the data from UTF-8, then parses it as a multipart/form-data body or a application/x-www-form-urlencoded body.

      The type property of the blob is used to determine the format of the body.

      This is a non-standard addition to the Blob API, to make it conform more closely to the BodyMixin API.

    • json(): Promise<any>;

      Read the data from the blob as a JSON object.

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

    • start?: number,
      end?: number,
      contentType?: string
      ): Blob;
    • stream(): ReadableStream<Uint8Array<ArrayBufferLike>>;

      Returns a readable stream of the blob's contents

    • text(): Promise<string>;

      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

  • 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]>;
    • name: string,
      value: string
      ): void;
    • name: string
      ): void;
    • entries(): HeadersIterator<[string, string]>;

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

    • callbackfn: (value: string, key: string, parent: Headers) => void,
      thisArg?: any
      ): void;
    • name: string
      ): null | string;
    • 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"]
      
    • name: string
      ): boolean;
    • keys(): HeadersIterator<string>;

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

    • name: string,
      value: string
      ): void;
    • toJSON(): Record<string, 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(): HeadersIterator<string>;

      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

  • class MessagePort

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

    MDN Reference

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

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

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

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

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

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

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

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

      MDN Reference

      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

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

    • 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

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

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

      MDN Reference

      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

  • 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: EventCounts
    • readonly timeOrigin: number
    • addEventListener<K extends 'resourcetimingbufferfull'>(
      type: K,
      listener: (this: Performance, ev: PerformanceEventMap[K]) => any,
      options?: boolean | AddEventListenerOptions
      ): void;

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

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

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

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

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

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

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

      MDN Reference

      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

    • markName?: string
      ): void;
    • measureName?: string
      ): void;
    • 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;
    • name: string,
      type?: string
      ): PerformanceEntryList;
    • type: string
      ): PerformanceEntryList;
    • markName: string,
      markOptions?: PerformanceMarkOptions
    • measureName: string,
      startOrMeasureOptions?: string | PerformanceMeasureOptions,
      endMark?: string
    • now(): number;
    • removeEventListener<K extends 'resourcetimingbufferfull'>(
      type: K,
      listener: (this: Performance, ev: PerformanceEventMap[K]) => any,
      options?: boolean | EventListenerOptions
      ): void;

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

      MDN Reference

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

  • 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

  • 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

  • class PerformanceResourceTiming

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

    MDN Reference

  • class ReadableStream<R = any>

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

    MDN Reference

  • class Request

    This Fetch API interface represents a resource request.

    MDN Reference

    • readonly body: null | ReadableStream<Uint8Array<ArrayBufferLike>>
    • readonly bodyUsed: boolean
    • readonly cache: RequestCache

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

      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: string
    • blob(): Promise<Blob>;
    • bytes(): Promise<Uint8Array<ArrayBufferLike>>;
    • json(): Promise<any>;
    • text(): Promise<string>;
  • class Response

    This Fetch API interface represents the response to a request.

    MDN Reference

  • 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
    
    • sourceText: string
      ): any;
    • specifier: string,
      bindingName: string
      ): Promise<any>;
      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

    • algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
      key: CryptoKey,
      data: BufferSource
      ): Promise<ArrayBuffer>;
    • algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,
      baseKey: CryptoKey,
      length?: null | number
      ): Promise<ArrayBuffer>;
    • algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,
      baseKey: CryptoKey,
      derivedKeyType: AlgorithmIdentifier | HkdfParams | Pbkdf2Params | AesDerivedKeyParams | HmacImportParams,
      extractable: boolean,
      keyUsages: KeyUsage[]
      ): Promise<CryptoKey>;
      algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,
      baseKey: CryptoKey,
      derivedKeyType: AlgorithmIdentifier | HkdfParams | Pbkdf2Params | AesDerivedKeyParams | HmacImportParams,
      extractable: boolean,
      keyUsages: Iterable<KeyUsage>
      ): Promise<CryptoKey>;
    • algorithm: AlgorithmIdentifier,
      data: BufferSource
      ): Promise<ArrayBuffer>;
    • algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
      key: CryptoKey,
      data: BufferSource
      ): Promise<ArrayBuffer>;
    • format: 'jwk',
      ): Promise<JsonWebKey>;
      format: 'spki' | 'pkcs8' | 'raw',
      ): Promise<ArrayBuffer>;
      format: KeyFormat,
      ): Promise<ArrayBuffer | JsonWebKey>;
    • algorithm: 'Ed25519' | { name: 'Ed25519' },
      extractable: boolean,
      keyUsages: readonly 'sign' | 'verify'[]
      ): Promise<CryptoKeyPair>;
      algorithm: RsaHashedKeyGenParams | EcKeyGenParams,
      extractable: boolean,
      keyUsages: readonly KeyUsage[]
      ): Promise<CryptoKeyPair>;
      algorithm: Pbkdf2Params | AesKeyGenParams | HmacKeyGenParams,
      extractable: boolean,
      keyUsages: readonly KeyUsage[]
      ): Promise<CryptoKey>;
      algorithm: AlgorithmIdentifier,
      extractable: boolean,
      keyUsages: KeyUsage[]
      ): Promise<CryptoKey | CryptoKeyPair>;
      algorithm: AlgorithmIdentifier,
      extractable: boolean,
      keyUsages: Iterable<KeyUsage>
      ): Promise<CryptoKey | CryptoKeyPair>;
    • format: 'jwk',
      keyData: JsonWebKey,
      algorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,
      extractable: boolean,
      keyUsages: readonly KeyUsage[]
      ): Promise<CryptoKey>;
      format: 'spki' | 'pkcs8' | 'raw',
      keyData: BufferSource,
      algorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,
      extractable: boolean,
      keyUsages: KeyUsage[]
      ): Promise<CryptoKey>;
      format: 'spki' | 'pkcs8' | 'raw',
      keyData: BufferSource,
      algorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,
      extractable: boolean,
      keyUsages: Iterable<KeyUsage>
      ): Promise<CryptoKey>;
    • algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,
      key: CryptoKey,
      data: BufferSource
      ): Promise<ArrayBuffer>;
    • format: KeyFormat,
      wrappedKey: BufferSource,
      unwrappingKey: CryptoKey,
      unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
      unwrappedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,
      extractable: boolean,
      keyUsages: KeyUsage[]
      ): Promise<CryptoKey>;
      format: KeyFormat,
      wrappedKey: BufferSource,
      unwrappingKey: CryptoKey,
      unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
      unwrappedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | RsaHashedImportParams | EcKeyImportParams | AesKeyAlgorithm,
      extractable: boolean,
      keyUsages: Iterable<KeyUsage>
      ): Promise<CryptoKey>;
    • algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,
      key: CryptoKey,
      signature: BufferSource,
      data: BufferSource
      ): Promise<boolean>;
    • format: KeyFormat,
      key: CryptoKey,
      wrappingKey: CryptoKey,
      wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams
      ): Promise<ArrayBuffer>;
  • 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: string
    • readonly fatal: boolean

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

      MDN Reference

    • readonly ignoreBOM: boolean
    • 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 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: string
    • input?: string
    • 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

      src?: string,

      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 Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike>

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

    • 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](): ArrayIterator<number>;
    • 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.

    • 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

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

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

    • predicate: (value: number, index: number, array: this) => any,
      thisArg?: any

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

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

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

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

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

      predicate: (value: number, index: number, array: this) => unknown,
      thisArg?: any
      ): undefined | number;
    • predicate: (value: number, index: number, array: this) => unknown,
      thisArg?: any
      ): number;

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

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

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

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

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

    • 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(): ArrayIterator<number>;

      Returns an list of keys in the array

    • searchElement: number,
      fromIndex?: number
      ): number;

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

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

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

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

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

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

      callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number,
      initialValue: number
      ): number;
      reduce<U>(
      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.

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

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

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

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

    • array: ArrayLike<number>,
      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.

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

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

    • start?: number,
      end?: number

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

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

    • 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)
      
    • begin?: number,
      end?: number
      ): Uint8Array<TArrayBuffer>;

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

      @param begin

      The index of the beginning of the array.

      @param end

      The index of the end of the array.

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

      locales: string | string[],
      options?: NumberFormatOptions
      ): string;
    • Copies the array and returns the copy with the elements in reverse order.

    • compareFn?: (a: number, b: number) => number

      Copies and sorts the array.

      @param compareFn

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

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

      Returns a string representation of an array.

    • valueOf(): this;

      Returns the primitive value of the specified object.

    • values(): ArrayIterator<number>;

      Returns an list of values in the array

    • index: number,
      value: number

      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.

    • readonly size: number
    • [Symbol.iterator](): URLSearchParamsIterator<[string, string]>;
    • name: string,
      value: string
      ): void;

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

      MDN Reference

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

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

      Iterates over each name-value pair in the query and invokes the given function.

      const myURL = new URL('https://example.org/?a=b&#x26;c=d');
      myURL.searchParams.forEach((value, name, searchParams) => {
        console.log(name, value, myURL.searchParams === searchParams);
      });
      // Prints:
      //   a b true
      //   c d true
      
      @param callbackfn

      Invoked for each name-value pair in the query

      @param thisArg

      To be used as this value for when fn is called

    • name: string
      ): null | string;

      Returns the first value associated to the given search parameter.

      MDN Reference

    • name: string
      ): string[];

      Returns all the values association with a given search parameter.

      MDN Reference

    • name: string,
      value?: string
      ): boolean;

      Returns a Boolean indicating if such a search parameter exists.

      MDN Reference

    • keys(): URLSearchParamsIterator<string>;

      Returns a list of keys in the search params.

    • name: string,
      value: string
      ): void;

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

      MDN Reference

    • toString(): string;

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

    • values(): URLSearchParamsIterator<string>;

      Returns a list of values in the search params.

  • class WritableStream<W = any>

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

    MDN Reference

  • 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

  • class WritableStreamDefaultWriter<W = any>

    This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the < writer to the WritableStream ensuring that no other streams can write to the underlying sink.

    MDN Reference

Type definitions

  • namespace console

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

    The module exports two specific components:

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

    Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

    Example using the global console:

    console.log('hello world');
    // Prints: hello world, to stdout
    console.log('hello %s', 'world');
    // Prints: hello world, to stdout
    console.error(new Error('Whoops, something bad happened'));
    // Prints error message and stack trace to stderr:
    //   Error: Whoops, something bad happened
    //     at [eval]:5:15
    //     at Script.runInThisContext (node:vm:132:18)
    //     at Object.runInThisContext (node:vm:309:38)
    //     at node:internal/process/execution:77:19
    //     at [eval]-wrapper:6:22
    //     at evalScript (node:internal/process/execution:76:60)
    //     at node:internal/main/eval_string:23:3
    
    const name = 'Will Robinson';
    console.warn(`Danger ${name}! Danger!`);
    // Prints: Danger Will Robinson! Danger!, to stderr
    

    Example using the Console class:

    const out = getStreamSomehow();
    const err = getStreamSomehow();
    const myConsole = new console.Console(out, err);
    
    myConsole.log('hello world');
    // Prints: hello world, to out
    myConsole.log('hello %s', 'world');
    // Prints: hello world, to out
    myConsole.error(new Error('Whoops, something bad happened'));
    // Prints: [Error: Whoops, something bad happened], to err
    
    const name = 'Will Robinson';
    myConsole.warn(`Danger ${name}! Danger!`);
    // Prints: Danger Will Robinson! Danger!, to err
    
  • interface AddEventListenerOptions

  • interface ArrayBufferConstructor

  • interface ArrayConstructor

    • constructor ArrayConstructor(
      arrayLength?: number
      ): any[];
      constructor ArrayConstructor<T>(
      arrayLength: number
      ): T[];
      constructor ArrayConstructor<T>(
      ...items: T[]
      ): T[];
    • readonly prototype: any[]
    • from<T>(
      arrayLike: ArrayLike<T>
      ): T[];

      Creates an array from an array-like object.

      @param arrayLike

      An array-like object to convert to an array.

      from<T, U>(
      arrayLike: ArrayLike<T>,
      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.

      from<T>(
      iterable: Iterable<T, any, any> | ArrayLike<T>
      ): T[];

      Creates an array from an iterable object.

      @param iterable

      An iterable object to convert to an array.

      from<T, U>(
      iterable: Iterable<T, any, any> | ArrayLike<T>,
      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.

    • iterableOrArrayLike: AsyncIterable<T, any, any> | Iterable<T | PromiseLike<T>, any, any> | ArrayLike<T | PromiseLike<T>>
      ): Promise<T[]>;

      Creates an array from an async iterator or iterable object.

      @param iterableOrArrayLike

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

      fromAsync<T, U>(
      iterableOrArrayLike: AsyncIterable<T, any, any> | Iterable<T, any, any> | ArrayLike<T>,
      mapFn: (value: Awaited<T>, index: number) => U,
      thisArg?: any
      ): Promise<Awaited<U>[]>;

      Creates an array from an async iterator or iterable object.

      @param iterableOrArrayLike

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

      @param thisArg

      Value of 'this' used when executing mapfn.

      arrayLike: AsyncIterable<T, any, any> | Iterable<T, any, any> | ArrayLike<T>
      ): Promise<Awaited<T>[]>;

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

      await Array.fromAsync([1]); // [1]
      await Array.fromAsync([Promise.resolve(1)]); // [1]
      await Array.fromAsync((async function*() { yield 1 })()); // [1]
      
      @param 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.

      fromAsync<T, U>(
      arrayLike: AsyncIterable<T, any, any> | Iterable<T, any, any> | ArrayLike<T>,
      mapFn?: (value: T, index: number) => U,
      thisArg?: any
      ): Promise<Awaited<U>[]>;

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

      await Array.fromAsync([1]); // [1]
      await Array.fromAsync([Promise.resolve(1)]); // [1]
      await Array.fromAsync((async function*() { yield 1 })()); // [1]
      await Array.fromAsync([1], (n) => n + 1); // [2]
      await Array.fromAsync([1], (n) => Promise.resolve(n + 1)); // [2]
      
      @param 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.

    • arg: any
      ): arg is any[];
    • of<T>(
      ...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 BlobPropertyBag

    • endings?: EndingType
    • type?: 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.

    • headers?: HeadersInit

      A Headers object, an object literal, or an array of two-item arrays to set request's headers.

    • integrity?: string

      A cryptographic hash of the resource to be fetched by request. Sets request's integrity.

    • keepalive?: boolean

      A boolean to set request's keepalive.

    • method?: string

      A string to set request's method.

    • mode?: RequestMode

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

    • priority?: RequestPriority
    • proxy?: string

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

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

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

    • referrer?: string

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

    • referrerPolicy?: ReferrerPolicy

      A referrer policy to set request's referrerPolicy.

    • s3?: S3Options

      Override the default S3 options

      const response = await fetch("s3://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: ...})

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

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

    • cert?: string | Buffer<ArrayBufferLike> | BunFile | string | Buffer<ArrayBufferLike> | BunFile[]

      Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private key, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see ca). When providing multiple cert chains, they do not have to be in the same order as their private keys in key. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.

    • checkServerIdentity?: (hostname: string, cert: PeerCertificate) => undefined | Error

      Custom function to check the server identity

    • dhParamsFile?: string

      File path to a .pem file custom Diffie Helman parameters

    • key?: string | Buffer<ArrayBufferLike> | BunFile | string | Buffer<ArrayBufferLike> | BunFile[]

      Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with options.passphrase. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form {pem: <string|buffer>[, passphrase: <string>]}. The object form can only occur in an array. object.passphrase is optional. Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.

    • lowMemoryMode?: boolean

      This sets OPENSSL_RELEASE_BUFFERS to 1. It reduces overall performance but saves some memory.

    • passphrase?: string

      Passphrase for the TLS key

    • rejectUnauthorized?: boolean

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

    • requestCert?: boolean

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

      Default is false.

    • secureOptions?: number

      Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the SSL_OP_* options from OpenSSL Options

    • serverName?: string

      Explicitly set a server name

  • interface Console

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

      Asynchronously read lines from standard input (fd 0)

      for await (const line of console) {
        console.log(line);
      }
      
    • condition?: boolean,
      ...data: any[]
      ): void;
      value: any,
      message?: string,
      ...optionalParams: any[]
      ): void;

      console.assert() writes a message if value is falsy or omitted. It only writes a message and does not otherwise affect execution. The output always starts with "Assertion failed". If provided, message is formatted using util.format().

      If value is truthy, nothing happens.

      console.assert(true, 'does nothing');
      
      console.assert(false, 'Whoops %s work', 'didn\'t');
      // Assertion failed: Whoops didn't work
      
      console.assert();
      // Assertion failed
      
      @param value

      The value tested for being truthy.

      @param message

      All arguments besides value are used as error message.

    • clear(): void;

      When stdout is a TTY, calling console.clear() will attempt to clear the TTY. When stdout is not a TTY, this method does nothing.

      The specific operation of console.clear() can vary across operating systems and terminal types. For most Linux operating systems, console.clear() operates similarly to the clear shell command. On Windows, console.clear() will clear only the output in the current terminal viewport for the Node.js binary.

    • label?: string
      ): void;

      Maintains an internal counter specific to label and outputs to stdout the number of times console.count() has been called with the given label.

      > console.count()
      default: 1
      undefined
      > console.count('default')
      default: 2
      undefined
      > console.count('abc')
      abc: 1
      undefined
      > console.count('xyz')
      xyz: 1
      undefined
      > console.count('abc')
      abc: 2
      undefined
      > console.count()
      default: 3
      undefined
      >
      
      @param label

      The display label for the counter.

    • label?: string
      ): void;

      Resets the internal counter specific to label.

      > console.count('abc');
      abc: 1
      undefined
      > console.countReset('abc');
      undefined
      > console.count('abc');
      abc: 1
      undefined
      >
      
      @param label

      The display label for the counter.

    • ...data: any[]
      ): void;
      message?: any,
      ...optionalParams: any[]
      ): void;

      The console.debug() function is an alias for log.

    • item?: any,
      options?: any
      ): void;
      obj: any,
      options?: InspectOptions
      ): void;

      Uses util.inspect() on obj and prints the resulting string to stdout. This function bypasses any custom inspect() function defined on obj.

    • ...data: any[]
      ): void;

      This method calls console.log() passing it the arguments received. This method does not produce any XML formatting.

    • ...data: any[]
      ): void;

      Log to stderr in your terminal

      Appears in red

      @param data

      something to display

      message?: any,
      ...optionalParams: any[]
      ): void;

      Prints to stderr with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

      const code = 5;
      console.error('error #%d', code);
      // Prints: error #5, to stderr
      console.error('error', code);
      // Prints: error 5, to stderr
      

      If formatting elements (e.g. %d) are not found in the first string then util.inspect() is called on each argument and the resulting string values are concatenated. See util.format() for more information.

    • ...label: any[]
      ): void;

      Increases indentation of subsequent lines by spaces for groupIndentation length.

      If one or more labels are provided, those are printed first without the additional indentation.

    • ...label: any[]
      ): void;

      An alias for group.

    • groupEnd(): void;

      Decreases indentation of subsequent lines by spaces for groupIndentation length.

    • ...data: any[]
      ): void;
      message?: any,
      ...optionalParams: any[]
      ): void;

      The console.info() function is an alias for log.

    • ...data: any[]
      ): void;
      message?: any,
      ...optionalParams: any[]
      ): void;

      Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

      const count = 5;
      console.log('count: %d', count);
      // Prints: count: 5, to stdout
      console.log('count:', count);
      // Prints: count: 5, to stdout
      

      See util.format() for more information.

    • label?: string
      ): void;

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

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

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

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

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

      Try to construct a table with the columns of the properties of tabularData (or 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.

      tabularData: any,
      properties?: readonly 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 }]);
      // ┌─────────┬─────┬─────┐
      // │ (index) │  a  │  b  │
      // ├─────────┼─────┼─────┤
      // │    0    │  1  │ 'Y' │
      // │    1    │ 'Z' │  2  │
      // └─────────┴─────┴─────┘
      
      console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
      // ┌─────────┬─────┐
      // │ (index) │  a  │
      // ├─────────┼─────┤
      // │    0    │  1  │
      // │    1    │ 'Z' │
      // └─────────┴─────┘
      
      @param properties

      Alternate properties for constructing the table.

    • label?: string
      ): void;

      Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique label. Use the same label when calling timeEnd to stop the timer and output the elapsed time in suitable time units to stdout. For example, if the elapsed time is 3869ms, console.timeEnd() displays "3.869s".

    • label?: string
      ): void;

      Stops a timer that was previously started by calling time and prints the result to stdout:

      console.time('bunch-of-stuff');
      // Do a bunch of stuff.
      console.timeEnd('bunch-of-stuff');
      // Prints: bunch-of-stuff: 225.438ms
      
    • label?: string,
      ...data: any[]
      ): void;

      For a timer that was previously started by calling time, prints the elapsed time and other data arguments to stdout:

      console.time('process');
      const value = expensiveProcess1(); // Returns 42
      console.timeLog('process', value);
      // Prints "process: 365.227ms 42".
      doExpensiveProcess2(value);
      console.timeEnd('process');
      
    • label?: string
      ): void;

      This method does not display anything unless used in the inspector. The console.timeStamp() method adds an event with the label 'label' to the Timeline panel of the inspector.

    • ...data: any[]
      ): void;
      message?: any,
      ...optionalParams: any[]
      ): void;

      Prints to stderr the string 'Trace: ', followed by the util.format() formatted message and stack trace to the current position in the code.

      console.trace('Show me');
      // Prints: (stack trace will vary based on where trace is called)
      //  Trace: Show me
      //    at repl:2:9
      //    at REPLServer.defaultEval (repl.js:248:27)
      //    at bound (domain.js:287:14)
      //    at REPLServer.runBound [as eval] (domain.js:300:12)
      //    at REPLServer.<anonymous> (repl.js:412:12)
      //    at emitOne (events.js:82:20)
      //    at REPLServer.emit (events.js:169:7)
      //    at REPLServer.Interface._onLine (readline.js:210:10)
      //    at REPLServer.Interface._line (readline.js:549:8)
      //    at REPLServer.Interface._ttyWrite (readline.js:826:14)
      
    • ...data: any[]
      ): void;
      message?: any,
      ...optionalParams: any[]
      ): void;

      The console.warn() function is an alias for error.

    • ...data: string | ArrayBuffer | ArrayBufferView<ArrayBufferLike>[]
      ): number;

      Write text or bytes to stdout

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

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

      The data to write

      @returns

      The number of bytes written

      This function is not available in the browser.

  • interface Dict<T>

  • interface ErrnoException

  • interface Error

  • interface ErrorConstructor

    • constructor ErrorConstructor(
      message?: string
      ): Error;
      constructor ErrorConstructor(
      message?: string,
      options?: ErrorOptions
      ): Error;
    • prepareStackTrace?: (err: Error, stackTraces: CallSite[]) => any

      Optional override for formatting stack traces

    • readonly prototype: Error
    • stackTraceLimit: number

      The maximum number of stack frames to capture.

    • targetObject: object,
      constructorOpt?: Function
      ): void;

      Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

      const myObject = {};
      Error.captureStackTrace(myObject);
      myObject.stack;  // Similar to `new Error().stack`
      

      The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

      The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

      The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

      function a() {
        b();
      }
      
      function b() {
        c();
      }
      
      function c() {
        // Create an error without stack trace to avoid calculating the stack trace twice.
        const { stackTraceLimit } = Error;
        Error.stackTraceLimit = 0;
        const error = new Error();
        Error.stackTraceLimit = stackTraceLimit;
      
        // Capture the stack trace above function b
        Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
        throw error;
      }
      
      a();
      
    • 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

  • interface ErrorOptions

    • cause?: unknown

      The cause of the error.

  • interface EventListener

  • interface EventListenerObject

  • interface EventSource

    • readonly CLOSED: 2
    • readonly CONNECTING: 0
    • onerror: null | (this: EventSource, ev: Event) => any
    • onmessage: null | (this: EventSource, ev: MessageEvent) => any
    • onopen: null | (this: EventSource, ev: Event) => any
    • readonly OPEN: 1
    • readonly readyState: number

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

      MDN Reference

    • readonly url: string
    • readonly withCredentials: boolean

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

      MDN Reference

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

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

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

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

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

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

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

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

      MDN Reference

      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

      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

    • event: Event
      ): boolean;

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

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

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

      MDN Reference

      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

      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 EventSourceInit

  • interface FetchEvent

    • readonly AT_TARGET: 2
    • readonly bubbles: boolean

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

      MDN Reference

    • readonly BUBBLING_PHASE: 3
    • readonly cancelable: boolean

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

      MDN Reference

    • readonly CAPTURING_PHASE: 1
    • 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: 0
    • readonly request: Request
    • 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 url: string
    • 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

    • Sets the defaultPrevented property to true if cancelable is true.

    • response: Response | Promise<Response>
      ): void;
    • Stops the invocation of event listeners after the current one completes.

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

    • promise: Promise<any>
      ): 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 | Promise<void>): void; off(event: HMREvent, callback: () => void): void; on(event: HMREvent, callback: () => void): void }

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

      if (import.meta.hot) {
        // HMR APIs are available
      }
      

      However, this check is usually not needed as Bun will dead-code-eliminate calls to all of the HMR APIs in production builds.

      https://bun.sh/docs/bundler/hmr

    • readonly 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:// url string for the current module.

      console.log(import.meta.url);
      "file:///Users/me/projects/my-app/src/my-app.ts"
      
    • specifier: string
      ): string;
      specifier: string,
      parent?: string | URL
      ): string;

      Provides a module-relative resolution function scoped to each module, returning the URL string.

      Second parent parameter is only used when the --experimental-import-meta-resolve command flag enabled.

      @param specifier

      The module specifier to resolve relative to parent.

      @param parent

      The absolute parent module URL to resolve from.

      @returns

      The absolute (file:) URL string for the resolved module.

  • interface ImportMetaEnv

  • interface Position

  • interface PromiseConstructor

    Represents the completion of an asynchronous operation

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

      Creates a new Promise.

      @param 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 prototype: Promise<any>

      A reference to the prototype.

    • all<T>(
      values: Iterable<T | PromiseLike<T>>
      ): Promise<Awaited<T>[]>;

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

      @param values

      An iterable of Promises.

      @returns

      A new Promise.

      all<T extends [] | readonly unknown[]>(
      values: T
      ): Promise<{ [K in string | number | symbol]: Awaited<T[P<P>]> }>;

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

      @param values

      An array of Promises.

      @returns

      A new Promise.

    • allSettled<T extends [] | readonly unknown[]>(
      values: T
      ): Promise<{ [K in string | number | symbol]: PromiseSettledResult<Awaited<T[P<P>]>> }>;

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

      @param values

      An array of Promises.

      @returns

      A new Promise.

      values: Iterable<T | PromiseLike<T>>
      ): Promise<PromiseSettledResult<Awaited<T>>[]>;

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

      @param values

      An array of Promises.

      @returns

      A new Promise.

    • any<T extends [] | readonly unknown[]>(
      values: T
      ): Promise<Awaited<T[number]>>;

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

      @param values

      An array or iterable of Promises.

      @returns

      A new Promise.

      any<T>(
      values: Iterable<T | PromiseLike<T>>
      ): Promise<Awaited<T>>;

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

      @param values

      An array or iterable of Promises.

      @returns

      A new Promise.

    • race<T>(
      values: Iterable<T | PromiseLike<T>>
      ): Promise<Awaited<T>>;

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

      @param values

      An iterable of Promises.

      @returns

      A new Promise.

      race<T extends [] | readonly unknown[]>(
      values: T
      ): Promise<Awaited<T[number]>>;

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

      @param values

      An array of Promises.

      @returns

      A new Promise.

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

      Creates a new rejected promise for the provided reason.

      @param reason

      The reason the promise was rejected.

      @returns

      A new rejected Promise.

    • resolve(): Promise<void>;

      Creates a new resolved promise.

      @returns

      A resolved promise.

      value: T
      ): Promise<Awaited<T>>;

      Creates a new resolved promise for the provided value.

      @param value

      A promise.

      @returns

      A promise whose internal state matches the provided promise.

      value: T | PromiseLike<T>
      ): Promise<Awaited<T>>;

      Creates a new resolved promise for the provided value.

      @param value

      A promise.

      @returns

      A promise whose internal state matches the provided promise.

    • try<T, U extends unknown[]>(
      callbackFn: (...args: U) => T | PromiseLike<T>,
      ...args: U
      ): Promise<Awaited<T>>;

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

      @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.
      try<T, A extends any[] = []>(
      fn: (...args: A) => T | PromiseLike<T>,
      ...args: A
      ): Promise<T>;

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

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

    • withResolvers<T>(): PromiseWithResolvers<T>;

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

      @returns

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

      const { promise, resolve, reject } = Promise.withResolvers<T>();
      
      withResolvers<T>(): { promise: Promise<T>; reject: (reason?: any) => void; resolve: (value?: T | PromiseLike<T>) => 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 QueuingStrategy<T = any>

  • interface QueuingStrategyInit

    • highWaterMark: number

      Creates a new ByteLengthQueuingStrategy with the provided high water mark.

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

  • interface QueuingStrategySize<T = any>

  • interface ReadableStreamDirectController

  • interface ReadableStreamGenericReader

  • interface ReadableWritablePair<R = any, W = any>

    • writable: WritableStream<W>

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

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

  • interface ReadOnlyDict<T>

  • interface RequestInit

    • body?: null | BodyInit

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

    • cache?: RequestCache

      A string indicating how the request will interact with the browser's cache to set request's cache.

    • credentials?: RequestCredentials

      A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials.

    • headers?: HeadersInit

      A Headers object, an object literal, or an array of two-item arrays to set request's headers.

    • integrity?: string

      A cryptographic hash of the resource to be fetched by request. Sets request's integrity.

    • keepalive?: boolean

      A boolean to set request's keepalive.

    • method?: string

      A string to set request's method.

    • mode?: RequestMode

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

    • priority?: RequestPriority
    • redirect?: RequestRedirect

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

    • referrer?: string

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

    • referrerPolicy?: ReferrerPolicy

      A referrer policy to set request's referrerPolicy.

    • signal?: null | AbortSignal

      An AbortSignal to set request's signal.

    • window?: null

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

  • interface ResponseInit

  • interface SharedArrayBuffer

  • interface StreamPipeOptions

    • preventAbort?: boolean
    • preventCancel?: boolean
    • preventClose?: boolean

      Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.

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

      Errors and closures of the source and destination streams propagate as follows:

      An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination.

      An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source.

      When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error.

      If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source.

      The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set.

  • interface Timer

  • interface Transformer<I = any, O = any>

  • interface Uint8ArrayConstructor

    • constructor Uint8ArrayConstructor(
      length: number
      constructor Uint8ArrayConstructor(
      array: ArrayLike<number>
      constructor Uint8ArrayConstructor<TArrayBuffer extends ArrayBufferLike = ArrayBuffer>(
      buffer: TArrayBuffer,
      byteOffset?: number,
      length?: number
      ): Uint8Array<TArrayBuffer>;
      constructor Uint8ArrayConstructor(
      buffer: ArrayBuffer,
      byteOffset?: number,
      length?: number
      constructor Uint8ArrayConstructor(
      array: ArrayBuffer | ArrayLike<number>
      constructor Uint8ArrayConstructor(
      elements: Iterable<number>
      constructor (): Uint8Array<ArrayBuffer>;
    • readonly BYTES_PER_ELEMENT: number

      The size in bytes of each element in the array.

    • readonly prototype: Uint8Array<ArrayBufferLike>
    • arrayLike: ArrayLike<number>

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

      @param arrayLike

      An array-like object to convert to an array.

      from<T>(
      arrayLike: ArrayLike<T>,
      mapfn: (v: T, k: number) => number,
      thisArg?: any

      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.

      elements: Iterable<number>

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

      @param elements

      An iterable object to convert to an array.

      from<T>(
      elements: Iterable<T>,
      mapfn?: (v: T, k: number) => number,
      thisArg?: any

      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.

    • base64: string,
      options?: { alphabet: 'base64' | 'base64url'; lastChunkHandling: 'strict' | 'loose' | 'stop-before-partial' }

      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

    • hex: string

      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

    • ...items: number[]

      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: 3
    • readonly CLOSING: 2
    • readonly CONNECTING: 0
    • readonly extensions: string

      Returns the extensions selected by the server, if any.

      MDN Reference

    • onclose: null | (this: WebSocket, ev: CloseEvent) => any
    • onerror: null | (this: WebSocket, ev: Event) => any
    • onmessage: null | (this: WebSocket, ev: MessageEvent) => any
    • onopen: null | (this: WebSocket, ev: Event) => any
    • readonly OPEN: 1
    • readonly protocol: string

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

      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

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

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

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

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

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

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

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

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

      MDN Reference

      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

    • 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

    • event: Event
      ): boolean;

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

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

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

      MDN Reference

      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

    • data: string | ArrayBufferLike | Blob | ArrayBufferView<ArrayBufferLike>
      ): 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

    • constructor Worker(
      scriptURL: string | URL,
      options?: WorkerOptions
      ): Worker;
    • onerror: null | (this: AbstractWorker, ev: ErrorEvent) => any
    • onmessage: null | (this: Worker, ev: MessageEvent) => any
    • onmessageerror: null | (this: Worker, ev: MessageEvent) => any
    • addEventListener<K extends keyof WorkerEventMap>(
      type: K,
      listener: (this: Worker, ev: WorkerEventMap[K]) => any,
      options?: boolean | AddEventListenerOptions
      ): void;

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

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

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

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

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

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

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

      MDN Reference

      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

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

    • 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

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

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

      MDN Reference

      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?: typeof SHARE_ENV | Record<string, string>

      If set, specifies the initial value of process.env inside the Worker thread. As a special value, worker.SHARE_ENV may be used to specify that the parent thread and the child thread should share their environment variables; in that case, changes to one thread's process.env object affect the other thread as well. Default: process.env.

    • name?: string

      A string specifying an identifying name for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes.

    • preload?: string | string[]

      An array of module specifiers to preload in the worker.

      These modules load before the worker's entry point is executed.

      Equivalent to passing the --preload CLI argument, but only for this Worker.

    • ref?: boolean

      When true, the worker will keep the parent thread alive until the worker is terminated 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.