Send a HTTP(s) request
Search the reference...
/
module
globalsfunction fetch(input: string | URL | Request,init?: BunFetchRequestInit): PromiseResponse>;URL string or Request object
A structured value that contains settings for the fetch() request.
A promise that resolves to Response object.
Bun's extensions of the fetch API
Preconnect to a URL. This can be used to improve performance by pre-resolving the DNS and establishing a TCP connection before the request is made.
This is a custom property that is not part of the Fetch API specification.
The URL to preconnect to
Options for the preconnect
Run a function immediately after main event loop is vacant
function to call
Same as module.exports
Low-level JavaScriptCore API for accessing the native ES Module loader (not a Bun API)
Before using this, be aware of a few things:
Using this incorrectly will crash your application.
This API may change any time JavaScriptCore is updated.
Bun may rewrite ESM import specifiers to point to bundled code. This will be confusing when using this API, as it will return a string like "/node_modules.server.bun".
Bun may inject additional imports into your code. This usually has a bun: prefix.
A reference to the current module.
NodeJS-style require function
Cancel an immediate function call by its immediate ID.
immediate id
Send a HTTP(s) request
URL string or Request object
A structured value that contains settings for the fetch() request.
A promise that resolves to Response object.
Preconnect to a URL. This can be used to improve performance by pre-resolving the DNS and establishing a TCP connection before the request is made.
This is a custom property that is not part of the Fetch API specification.
The URL to preconnect to
Options for the preconnect
Post a message to the parent thread.
Only useful in a worker thread; calling this from the main thread does nothing.
Log an error using the default exception handler
Error or string
Run a function immediately after main event loop is vacant
function to call
The URL interface represents an object providing static methods used for creating object URLs.
A message received by a target object.
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.
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.
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.
Returns the object whose event listener's callback is currently being invoked.
Returns the data of the message.
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
Returns true if event was dispatched by the user agent, and false otherwise.
Returns the last event ID string, for server-sent events.
Returns the origin of the message, for server-sent events and cross-document messaging.
Returns the MessagePort array sent with the message, for cross-document messaging and channel messaging.
Returns the WindowProxy of the source window, for cross-document messaging, and the MessagePort being attached, in the connect event fired at SharedWorkerGlobalScope objects.
Returns the object to which event is dispatched (its target).
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the type of event, e.g. "click", "hashchange", or "submit".
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the defaultPrevented property 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.
A controller object that allows you to abort one or more DOM requests as and when desired.
Returns the AbortSignal object associated with this object.
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.
Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.
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.
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.
Removes the event listener in target's event listener list with the same type, callback, and options.
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.
Read-only. The length of the ArrayBuffer (in bytes).
Resizes the ArrayBuffer to the specified size (in bytes).
Resize an ArrayBuffer in-place.
Returns a section of an ArrayBuffer.
Creates a new ArrayBuffer with the same byte content as this buffer, then detaches this buffer.
Creates a new non-resizable ArrayBuffer with the same byte content as this buffer, then detaches this buffer.
A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
Returns a promise that resolves to the contents of the blob as an ArrayBuffer
Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes) its the same as new Uint8Array(await blob.arrayBuffer())
Read the data from the blob as a FormData object.
This first decodes the data from UTF-8, then parses it as a multipart/form-data body or 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.
Wrap this blob in a Bun.Image pipeline. Equivalent to new Bun.Image(this, options) — the constructor is synchronous (the underlying read happens lazily when an Image terminal is awaited), so this works on Bun.file(), Bun.s3(), fd-backed and in-memory blobs alike:
await Bun.file("photo.jpg").image().resize(400).webp().write("thumb.webp");
Read the data from the blob as a JSON object.
This first decodes the data from UTF-8, then parses it as JSON.
Returns a readable stream of the blob's contents
Returns a promise that resolves to the contents of the blob as a string
Returns the channel name (as passed to the constructor).
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.
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
Closes the BroadcastChannel object, opening it up to garbage collection.
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.
Sends the given message to other BroadcastChannel objects set up for this channel. Messages can be structured objects, e.g. nested objects and arrays.
Removes the event listener in target's event listener list with the same type, callback, and options.
Removes the event listener in target's event listener list with the same type, callback, and options.
This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.
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.
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.
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.
Returns the WebSocket connection close code provided by the server.
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.
Returns the object whose event listener's callback is currently being invoked.
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
Returns true if event was dispatched by the user agent, and false otherwise.
Returns the WebSocket connection close reason provided by the server.
Returns the object to which event is dispatched (its target).
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the type of event, e.g. "click", "hashchange", or "submit".
Returns true if the connection closed cleanly; false otherwise.
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the defaultPrevented property 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.
This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams.
Basic cryptography features available in the current context. It allows access to a cryptographically strong random number generator and to cryptographic primitives.
Available only in secure contexts.
The CryptoKey dictionary of the Web Crypto API represents a cryptographic key. Available only in secure contexts.
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.
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.
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.
Returns the object whose event listener's callback is currently being invoked.
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
Returns any custom data event was created with. Typically used for synthetic events.
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
Returns true if event was dispatched by the user agent, and false otherwise.
Returns the object to which event is dispatched (its target).
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the type of event, e.g. "click", "hashchange", or "submit".
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the defaultPrevented property 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.
An abnormal event (called an exception) which occurs as a result of calling a method or accessing a property of a web API.
The cause of the error.
Events providing information related to errors in scripts or in files.
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.
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.
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.
Returns the object whose event listener's callback is currently being invoked.
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
Returns true if event was dispatched by the user agent, and false otherwise.
Returns the object to which event is dispatched (its target).
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the type of event, e.g. "click", "hashchange", or "submit".
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the defaultPrevented property 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.
An event which takes place in the DOM.
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.
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.
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.
Returns the object whose event listener's callback is currently being invoked.
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
Returns true if event was dispatched by the user agent, and false otherwise.
Returns the object to which event is dispatched (its target).
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the type of event, e.g. "click", "hashchange", or "submit".
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the defaultPrevented property 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.
EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.
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.
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.
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.
Removes the event listener in target's event listener list with the same type, callback, and options.
Removes the event listener in target's event listener list with the same type, callback, and options.
Provides information about files and allows JavaScript in a web page to access their content.
Returns a promise that resolves to the contents of the blob as an ArrayBuffer
Returns a promise that resolves to the contents of the blob as a Uint8Array (array of bytes) its the same as new Uint8Array(await blob.arrayBuffer())
Read the data from the blob as a FormData object.
This first decodes the data from UTF-8, then parses it as a multipart/form-data body or 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.
Wrap this blob in a Bun.Image pipeline. Equivalent to new Bun.Image(this, options) — the constructor is synchronous (the underlying read happens lazily when an Image terminal is awaited), so this works on Bun.file(), Bun.s3(), fd-backed and in-memory blobs alike:
await Bun.file("photo.jpg").image().resize(400).webp().write("thumb.webp");
Read the data from the blob as a JSON object.
This first decodes the data from UTF-8, then parses it as JSON.
Returns a readable stream of the blob's contents
Returns a promise that resolves to the contents of the blob as a string
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".
Returns an array of key, value pairs for every entry in the list.
Returns a list of keys in the list.
Returns a list of values in the list.
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.
Get the total number of headers
Returns an iterator allowing to go through all key/value pairs contained in this object.
Get all headers matching the name
Only supports "Set-Cookie". All other headers are empty arrays.
The header name to get
An array of header values
const headers = new Headers();
headers.append("Set-Cookie", "foo=bar");
headers.append("Set-Cookie", "baz=qux");
headers.getAll("Set-Cookie"); // ["foo=bar", "baz=qux"]
Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.
Convert Headers to a plain JavaScript object.
About 10x faster than Object.fromEntries(headers.entries())
Called when you run JSON.stringify(headers)
Does not preserve insertion order. Well-known header names are lowercased. Other header names are left as-is.
Returns an iterator allowing to go through all values of the key/value pairs contained in this object.
This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties.
Returns the first MessagePort object.
Returns the second MessagePort object.
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.
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.
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
Disconnects the port, so that it is no longer active.
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.
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.
Removes the event listener in target's event listener list with the same type, callback, and options.
Removes the event listener in target's event listener list with the same type, callback, and options.
Begins dispatching messages received on the port.
The state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.
Available only in secure contexts.
Available only in secure contexts.
Available only in secure contexts.
Available only in secure contexts.
Available only in secure contexts.
Available only in secure contexts.
Available only in secure contexts.
Available only in secure contexts.
Available only in secure contexts.
Available only in secure contexts.
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.
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.
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.
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.
Removes the event listener in target's event listener list with the same type, callback, and options.
Removes the event listener in target's event listener list with the same type, callback, and options.
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).
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.
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.
Enables retrieval and analysis of detailed network timing data regarding the loading of an application's resources. An application can use the timing metrics to determine, for example, the length of time it takes to fetch a specific resource, such as an XMLHttpRequest, , image, or script.
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.
Only available in Bun. If there are multiple chunks in the queue, this will return all of them at the same time. Will only return a promise if the data is not immediately available.
This Fetch API interface represents a resource request.
Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching.
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.
Returns the kind of resource requested by request, e.g., "document" or "script".
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.
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]
Returns a boolean indicating whether or not request can outlive the global in which it was created.
Returns request's HTTP method, which is "GET" by default.
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.
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.
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.
Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer.
Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler.
Returns the URL of request as a string.
This Fetch API interface represents the response to a request.
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
Creates a new ShadowRealm
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
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.
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.
Returns encoding's name, lowercased.
Returns true if error mode is "fatal", otherwise false.
Returns the value of ignore BOM.
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.
Returns encoding's name, lowercased.
Returns true if error mode is "fatal", otherwise false.
Returns the value of ignore BOM.
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.
Returns "utf-8".
Returns the result of running UTF-8's encoder.
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.
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);
The text to encode.
The array to hold the encode result.
Returns "utf-8".
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.
The ArrayBuffer instance referenced by the array.
The length in bytes of the array.
The offset in bytes of the array.
The size in bytes of each element in the array.
The length of the array.
Returns the item located at the specified index.
The zero-based index of the desired code unit. A negative index will count back from the last item.
Returns the this object after copying a section of the array identified by start and end to the same array starting at position target
If target is negative, it is treated as length+target where length is the length of the array.
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
If not specified, length of the this object is used as its default value.
Returns an array of key, value pairs for every entry in the array
Determines whether all the members of an array satisfy the specified test.
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
Changes all array elements from start to end index to a static value and returns the modified array
value to fill array section with
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
index to stop filling the array at. If end is negative, it is treated as length+end.
Returns the elements of an array that meet the condition specified in a callback function.
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
Returns the index of the first element in the array where predicate is true, and -1 otherwise.
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
Returns the value of the last element in the array where predicate is true, and undefined otherwise.
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
Returns the index of the last element in the array where predicate is true, and -1 otherwise.
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
Performs the specified action for each element in an array.
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
Determines whether an array includes a certain element, returning true or false as appropriate.
The element to search for.
The position in this array at which to begin searching for searchElement.
Returns the index of the first occurrence of a value in an array.
The value to locate in the array.
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
Adds all the elements of an array separated by the specified separator string.
A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
Returns an list of keys in the array
Returns the index of the last occurrence of a value in an array.
The value to locate in the array.
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
Calls a defined callback function on each element of an array, and returns an array that contains the results.
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
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.
Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
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.
Reverses the elements in an Array.
Sets a value or an array of values.
A typed or untyped array of values to set.
The index in the current array at which the values are to be written.
Set the contents of the Uint8Array from a base64 encoded string
The base64 encoded string to decode into the array
Optional starting index to begin setting the decoded bytes (default: 0)
Set the contents of the Uint8Array from a hex encoded string
The hex encoded string to decode into the array. The string must have an even number of characters, be valid hexadecimal characters and contain no whitespace.
Returns a section of an array.
The beginning of the specified portion of the array.
The end of the specified portion of the array. This is exclusive of the element at the index 'end'.
Determines whether the specified callback function returns true for any element of an array.
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
Sorts an array.
Function used to determine the order of the elements. It is expected to return a negative value if first argument is less than second argument, zero if they're equal and a positive value otherwise. If omitted, the elements are sorted in ascending order.
[11,2,22,1].sort((a, b) => a - b)
Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements at begin, inclusive, up to end, exclusive.
The index of the beginning of the array.
The index of the end of the array.
Convert the Uint8Array to a base64 encoded string
The base64 encoded string representation of the Uint8Array
Convert the Uint8Array to a hex encoded string
The hex encoded string representation of the Uint8Array
Converts a number to a string by using the current locale.
Copies the array and returns the copy with the elements in reverse order.
Copies and sorts the array.
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending order.
const myNums = Uint8Array.from([11, 2, 22, 1]); myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22]
Returns a string representation of an array.
Returns the primitive value of the specified object.
Returns an list of values in the array
Copies the array and inserts the given number at the provided index.
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
The value to insert into the copied array.
A copy of the original array with the inserted value.
Appends a specified key/value pair as a new search parameter.
Deletes the given search parameter, and its associated value, from the list of all search parameters.
Returns an array of key, value pairs for every entry in the search params.
Returns the first value associated to the given search parameter.
Returns all the values association with a given search parameter.
Returns a Boolean indicating if such a search parameter exists.
Returns a list of keys in the search params.
Sets the value associated to a given search parameter to the given value. If there were several values, delete the others.
Returns a string containing a query string suitable for use in a URL. Does not include the question mark.
Returns a list of values in the search params.
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.
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.
This Streams API interface is the object returned by WritableStream.getWriter() and once created locks the
Creates an array from an array-like object.
An array-like object to convert to an array.
Creates an array from an iterable object.
An array-like object to convert to an array.
A mapping function to call on every element of the array.
Value of 'this' used to invoke the mapfn.
Creates an array from an iterable object.
An iterable object to convert to an array.
Creates an array from an iterable object.
An iterable object to convert to an array.
A mapping function to call on every element of the array.
Value of 'this' used to invoke the mapfn.
Creates an array from an async iterator or iterable object.
An async iterator or array-like object to convert to an array.
Creates an array from an async iterator or iterable object.
An async iterator or array-like object to convert to an array.
Value of 'this' used when executing mapfn.
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]
The iterable or async iterable to convert to an array.
A Promise whose fulfillment is a new Array instance containing the values from the iterator.
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]
The iterable or async iterable to convert to an array.
A mapper function that transforms each element of arrayLike after awaiting them.
The this to which mapFn is bound.
A Promise whose fulfillment is a new Array instance containing the values from the iterator.
Returns a new array from a set of elements.
A set of elements to include in the new array object.
Set a default "type". Not yet implemented.
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.
A BodyInit object or null to set request's body.
A string indicating how the request will interact with the browser's cache to set request's cache.
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.
Control automatic decompression of the response body. When set to false, the response body will not be automatically decompressed, and the Content-Encoding header will be preserved. This can improve performance when you need to handle compressed data manually or forward it as-is. This is a custom property that is not part of the Fetch API specification.
// Disable automatic decompression for a proxy server
const response = await fetch("https://example.com/api", {
decompress: false
});
// response.headers.get('content-encoding') might be 'gzip' or 'br'
A Headers object, an object literal, or an array of two-item arrays to set request's headers.
A cryptographic hash of the resource to be fetched by request. Sets request's integrity.
A boolean to set request's keepalive.
A string to set request's method.
A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode.
Force the underlying HTTP version. "http2" advertises only h2 in the TLS ALPN list and the request fails with HTTP2Unsupported if the server doesn't select it. "http1.1" pins the request to HTTP/1.1, overriding --experimental-http2-fetch / BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT if set. Omit to use the default (h2 is offered iff the flag is on).
Requires https. This is a custom property that is not part of the Fetch API specification.
Override http_proxy or HTTPS_PROXY This is a custom property that is not part of the Fetch API specification.
Can be a string URL or an object with url and optional headers.
// String format
const response = await fetch("http://example.com", {
proxy: "https://username:password@127.0.0.1:8080"
});
// Object format with custom headers sent to the proxy
const response = await fetch("http://example.com", {
proxy: {
url: "https://127.0.0.1:8080",
headers: {
"Proxy-Authorization": "Bearer token",
"X-Custom-Proxy-Header": "value"
}
}
});
If a Proxy-Authorization header is provided in proxy.headers, it takes precedence over credentials parsed from the proxy URL.
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.
A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer.
A referrer policy to set request's referrerPolicy.
Override the default S3 options
const response = await fetch("s3:http://bucket/key", {
s3: {
accessKeyId: "AKIAIOSFODNN7EXAMPLE",
secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
region: "us-east-1",
}
});
An AbortSignal to set request's signal.
Override the default TLS options
Make the request over a Unix socket
const response = await fetch("http://example.com", { unix: "/path/to/socket" });
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
Can only be null. Used to disassociate request from any Window.
Extends Bun.TLSOptions with extra properties that are only supported in fetch(url, {tls: ...})
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 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.
Custom function to check the server identity
File path to a .pem file custom Diffie Helman parameters
Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with options.passphrase. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form {pem: [, passphrase: ]}. The object form can only occur in an array. object.passphrase is optional. Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not.
This sets OPENSSL_RELEASE_BUFFERS to 1. It reduces overall performance but saves some memory.
Passphrase for the TLS key
If set to false, any certificate is accepted. Default is $NODE_TLS_REJECT_UNAUTHORIZED environment variable, or true if it is not set.
If set to true, the server will request a client certificate.
Default is false.
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
Explicitly set a server name
Asynchronously read lines from standard input (fd 0)
for await (const line of console) {
console.log(line);
}
Clear the console
Increment a count
label counter
Log to stderr in your terminal
Appears in red
something to display
Does nothing currently
Does nothing currently
Does nothing currently
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.
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.
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' │
// └────┴─────┘
Alternate properties for constructing the table.
Begin a timer to log with console.timeEnd
The label to use for the timer
console.time("how long????");
for (let i = 0; i 999999; i++) {
// do stuff
let x = i * i;
}
console.timeEnd("how long????");
End a timer to log with console.time
The label to use for the timer
console.time("how long????");
for (let i = 0; i 999999; i++) {
// do stuff
let x = i * i;
}
console.timeEnd("how long????");
Write text or bytes to stdout
Unlike console.log, this does no formatting and doesn't add a newline or spaces between arguments. You can pass it strings or bytes or any combination of the two.
console.write("hello world!", "\n"); // "hello world\n"
The data to write
The number of bytes written
This function is not available in the browser.
The cause of the error.
The cause of the error.
The Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will not capture any frames.
Create .stack property on a target object
Check if a value is an instance of Error
The value to check
True if the value is an instance of Error, false otherwise
The cause of the error.
Returns the state of this EventSource object's connection. It can have the values described below.
Returns the URL providing the event stream.
Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
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.
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.
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
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.
Removes the event listener in target's event listener list with the same type, callback, and options.
Removes the event listener in target's event listener list with the same type, callback, and options.
Removes the event listener in target's event listener list with the same type, callback, and options.
An event which takes place in the DOM.
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.
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.
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.
Returns the object whose event listener's callback is currently being invoked.
Returns true if preventDefault() was invoked successfully to indicate cancelation, and false otherwise.
Returns the event's phase, which is one of NONE, CAPTURING_PHASE, AT_TARGET, and BUBBLING_PHASE.
Returns true if event was dispatched by the user agent, and false otherwise.
Returns the object to which event is dispatched (its target).
Returns the event's timestamp as the number of milliseconds measured relative to the time origin.
Returns the type of event, e.g. "click", "hashchange", or "submit".
Returns the invocation target objects of event's path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root's mode is "closed" that are not reachable from event's currentTarget.
Sets the defaultPrevented property 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.
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.
Absolute path to the directory containing the source file.
Does not have a trailing slash
Alias of import.meta.dir. Exists for Node.js compatibility
The environment variables of the process
import.meta.env === process.env
Filename of the source file
Alias of import.meta.path. Exists for Node.js compatibility
Hot module replacement APIs. This value is undefined in production and can be used in an if statement to check if HMR APIs are available
if (import.meta.hot) {
// HMR APIs are available
}
However, this check is usually not needed as Bun will dead-code-eliminate calls to all of the HMR APIs in production builds.
https://bun.com/docs/bundler/hmr
Did the current file start the process?
if (import.meta.main) {
console.log("I started the process!");
}
Absolute path to the source file
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.
file:http:// url string for the current module.
console.log(import.meta.url); "file:http:///Users/me/projects/my-app/src/my-app.ts"
Represents the completion of an asynchronous operation
Creates a new Promise.
A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error.
A reference to the prototype.
Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected.
An iterable of Promises.
A new Promise.
Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected.
An array of Promises.
A new Promise.
Creates a Promise that is resolved with an array of results when all of the provided Promises resolve or reject.
An array of Promises.
A new Promise.
Creates a Promise that is resolved with an array of results when all of the provided Promises resolve or reject.
An array of Promises.
A new Promise.
The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.
An array or iterable of Promises.
A new Promise.
The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.
An array or iterable of Promises.
A new Promise.
Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected.
An iterable of Promises.
A new Promise.
Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected.
An array of Promises.
A new Promise.
Creates a new rejected promise for the provided reason.
The reason the promise was rejected.
A new rejected Promise.
Creates a new resolved promise.
A resolved promise.
Creates a new resolved promise for the provided value.
A promise.
A promise whose internal state matches the provided promise.
Creates a new resolved promise for the provided value.
A promise.
A promise whose internal state matches the provided promise.
Takes a callback of any kind (returns or throws, synchronously or asynchronously) and wraps its result in a Promise.
A function that is called synchronously. It can do anything: either return a value, throw an error, or return a promise.
Additional arguments, that will be passed to the callback.
A Promise that is:
Already fulfilled, if the callback synchronously returns a value.Already rejected, if the callback synchronously throws an error.Asynchronously fulfilled or rejected, if the callback returns a promise.Try to run a function and return the result. If the function throws, return the result of the catch function.
The function to run
The arguments to pass to the function. This is similar to setTimeout and avoids the extra closure.
The result of the function or the result of the catch function
Creates a new Promise and returns it in an object, along with its resolve and reject functions.
An object with the properties promise, resolve, and reject.
const { promise, resolve, reject } = Promise.withResolversT>();
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!"
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.
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.
Escapes any potential regex syntax characters in a string, and returns a new string that can be safely used as a literal pattern for the RegExp() constructor.
const re = new RegExp(RegExp.escape("foo.bar"));
re.test("foo.bar"); // true
re.test("foo!bar"); // false
A BodyInit object or null to set request's body.
A string indicating how the request will interact with the browser's cache to set request's cache.
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.
A Headers object, an object literal, or an array of two-item arrays to set request's headers.
A cryptographic hash of the resource to be fetched by request. Sets request's integrity.
A boolean to set request's keepalive.
A string to set request's method.
A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode.
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.
A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer.
A referrer policy to set request's referrerPolicy.
An AbortSignal to set request's signal.
Can only be null. Used to disassociate request from any Window.
Read-only. The length of the ArrayBuffer (in bytes).
Grows the SharedArrayBuffer to the specified size (in bytes).
Grow the SharedArrayBuffer in-place.
Returns a section of an SharedArrayBuffer.
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.
The size in bytes of each element in the array.
Creates an array from an array-like or iterable object.
An array-like object to convert to an array.
Creates an array from an array-like or iterable object.
An array-like object to convert to an array.
A mapping function to call on every element of the array.
Value of 'this' used to invoke the mapfn.
Creates an array from an array-like or iterable object.
An iterable object to convert to an array.
Creates an array from an array-like or iterable object.
An iterable object to convert to an array.
A mapping function to call on every element of the array.
Value of 'this' used to invoke the mapfn.
Create a new Uint8Array from a base64 encoded string
The base64 encoded string to convert to a Uint8Array
Optional options for decoding the base64 string
A new Uint8Array containing the decoded data
Create a new Uint8Array from a hex encoded string
The hex encoded string to convert to a Uint8Array
A new Uint8Array containing the decoded data
Returns a new array from a set of elements.
A set of elements to include in the new array object.
Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.
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".
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.)
Returns the extensions selected by the server, if any.
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.
Returns the state of the WebSocket object's connection. It can have the values described below.
Returns the URL that was used to establish the WebSocket connection.
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.
Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.
The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.
When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.
When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.
When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.
If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.
The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.
Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.
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.
Removes the event listener in target's event listener list with the same type, callback, and options.
Removes the event listener in target's event listener list with the same type, callback, and options.
Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.
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.
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.
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.
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.
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.
Removes the event listener in target's event listener list with the same type, callback, and options.
Removes the event listener in target's event listener list with the same type, callback, and options.
Aborts worker's associated global environment.
Bun's Web Worker constructor supports some extra options on top of the API browsers have.
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.
In Bun, this does nothing.
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.
A string specifying an identifying name for the DedicatedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes.
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.
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.
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.
In Bun, this does nothing.
Resources
ReferenceDocsGuidesDiscordMerch StoreGitHubBlogToolkit
RuntimePackage managerTest runnerBundlerPackage runnerProject
Bun 1.0Bun 1.1Bun 1.2Bun 1.3RoadmapContributingLicenseBaked with ❤️ in San Francisco
We're hiring →globals module | API Reference | Bun,AI智能索引,全网链接索引,智能导航,网页索引
- API documentation for module globals | Bun