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

Bun module | API Reference | Bun

Bun module | API Reference | BunBuildDocsReferenceGuidesBlogDiscord/BunF$FallocUnsafeCArchiveVargvCArrayBufferSinkFbuildIBunFileFcolorFconcatArrayBuffersFconnectCCookieCCookieMapVcronCCryptoHasherCCryptoHashInterfaceNCSRFFdeepEqualsFdeepMatchFdeflateSyncNdnsVembeddedFilesVenableANSIColorsVenvFescapeHTMLCEventSourceVfetchFfileCFileSystemRouterFfileURLToPathFgcFgenerateHeapSnapshotCGlobFgunzipSyncFgzipSyncVhashFindexOfLineFinflateSyncFinspectVisMainThreadNJSON5NJSONCNJSONLFlistenVmainNmarkdownCMD4CMD5FmmapFnanosecondsFopenInEditorVpasswordFpathToFileURLFpeekVpluginFrandomUUIDv5FrandomUUIDv7FreadableStreamToArrayFreadableStreamToArrayBufferFreadableStreamToBlobFreadableStreamToBytesFreadableStreamToFormDataFreadableStreamToJSONFreadableStreamToTextVredisFresolveFresolveSyncVrevisionVs3CS3ClientIS3FileVsecretsNsemverFserveIServerFshaCSHA1CSHA224CSHA256CSHA384CSHA512CSHA512_256FshrinkFsleepFsleepSyncFsliceAnsiFspawnFspawnSyncNSQLVsqlVstderrVstdinVstdoutFstringWidthFstripANSICTerminalNTOMLCTranspilerFudpSocketNunsafeVversionVversion_with_shaCWebSocketFwhichCWorkerFwrapAnsiFwriteNYAMLFzstdCompressFzstdCompressSyncFzstdDecompressFzstdDecompressSync

Search the reference...

/

BuildDocsReferenceGuidesBlogDiscord/BunF$FallocUnsafeCArchiveVargvCArrayBufferSinkFbuildIBunFileFcolorFconcatArrayBuffersFconnectCCookieCCookieMapVcronCCryptoHasherCCryptoHashInterfaceNCSRFFdeepEqualsFdeepMatchFdeflateSyncNdnsVembeddedFilesVenableANSIColorsVenvFescapeHTMLCEventSourceVfetchFfileCFileSystemRouterFfileURLToPathFgcFgenerateHeapSnapshotCGlobFgunzipSyncFgzipSyncVhashFindexOfLineFinflateSyncFinspectVisMainThreadNJSON5NJSONCNJSONLFlistenVmainNmarkdownCMD4CMD5FmmapFnanosecondsFopenInEditorVpasswordFpathToFileURLFpeekVpluginFrandomUUIDv5FrandomUUIDv7FreadableStreamToArrayFreadableStreamToArrayBufferFreadableStreamToBlobFreadableStreamToBytesFreadableStreamToFormDataFreadableStreamToJSONFreadableStreamToTextVredisFresolveFresolveSyncVrevisionVs3CS3ClientIS3FileVsecretsNsemverFserveIServerFshaCSHA1CSHA224CSHA256CSHA384CSHA512CSHA512_256FshrinkFsleepFsleepSyncFsliceAnsiFspawnFspawnSyncNSQLVsqlVstderrVstdinVstdoutFstringWidthFstripANSICTerminalNTOMLCTranspilerFudpSocketNunsafeVversionVversion_with_shaCWebSocketFwhichCWorkerFwrapAnsiFwriteNYAMLFzstdCompressFzstdCompressSyncFzstdDecompressFzstdDecompressSync

module

bun

The 'bun' module is where most of Bun's APIs are located. You can import all of the values and types in this module with an import statement, or by referencing the Bun global namespace.

function $(strings: TemplateStringsArray,...expressions: ShellExpression[]): ShellPromise;

The Bun shell is a powerful tool for running shell commands.

const result = await $`echo "Hello, world!"`.text();
console.log(result); // "Hello, world!"
namespace $class ShellError

ShellError represents an error that occurred while executing a shell command with the Bun Shell.

try {
const result = await $`exit 1`;
} catch (error) {
if (error instanceof $.ShellError) {
console.log(error.exitCode); // 1
}
}
cause?: unknown

The cause of the error.

readonly exitCode: numbermessage: stringname: stringstack?: stringreadonly stderr: Bufferreadonly stdout: Bufferstatic stackTraceLimit: number

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

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

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

arrayBuffer(): ArrayBuffer;

Read from stdout as an ArrayBuffer

@returns

Stdout as an ArrayBuffer

const output = await $`echo hello`;
console.log(output.arrayBuffer()); // ArrayBuffer { byteLength: 6 }
blob(): Blob;

Read from stdout as a Blob

@returns

Stdout as a blob

const output = await $`echo hello`;
console.log(output.blob()); // Blob { size: 6, type: "" }
bytes(): Uint8ArrayArrayBuffer>;

Read from stdout as an Uint8Array

@returns

Stdout as an Uint8Array

const output = await $`echo hello`;
console.log(output.bytes()); // Uint8Array { byteLength: 6 }
json(): any;

Read from stdout as a JSON object

@returns

Stdout as a JSON object

const output = await $`echo '{"hello": 123}'`;
console.log(output.json()); // { hello: 123 }
text(encoding?: BufferEncoding): string;

Read from stdout as a string

@param encoding

The encoding to use when decoding the output

@returns

Stdout as a string with the given encoding

Read as UTF-8 string

const output = await $`echo hello`;
console.log(output.text()); // "hello\n"

Read as base64 string

const output = await $`echo ${atob("hello")}`;
console.log(output.text("base64")); // "hello\n"
static captureStackTrace(targetObject: object,constructorOpt?: Function): void;

Create .stack property on a target object

static isError(value: unknown): value is Error;

Check if a value is an instance of Error

@param value

The value to check

@returns

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

static prepareStackTrace(err: Error,stackTraces: CallSite[]): any;
class ShellPromise

The Bun.$.ShellPromise class represents a shell command that gets executed once awaited, or called with .text(), .json(), etc.

const myShellPromise = $`echo "Hello, world!"`;
const result = await myShellPromise.text();
console.log(result); // "Hello, world!"
readonly [Symbol.toStringTag]: stringreadonly static [Symbol.species]: PromiseConstructorarrayBuffer(): PromiseArrayBuffer>;

Read from stdout as an ArrayBuffer

Automatically calls quiet

@returns

A promise that resolves with stdout as an ArrayBuffer

const output = await $`echo hello`.arrayBuffer();
console.log(output); // ArrayBuffer { byteLength: 6 }
blob(): PromiseBlob>;

Read from stdout as a Blob

Automatically calls quiet

@returns

A promise that resolves with stdout as a Blob

const output = await $`echo hello`.blob();
console.log(output); // Blob { size: 6, type: "" }
catchTResult = never>(onrejected?: null | (reason: any) => TResult | PromiseLikeTResult>): PromiseShellOutput | TResult>;

Attaches a callback for only the rejection of the Promise.

@param onrejected

The callback to execute when the Promise is rejected.

@returns

A Promise for the completion of the callback.

cwd(newCwd: string): this;

Change the current working directory of the shell.

@param newCwd

The new working directory

env(newEnv: undefined | Dictstring> | Recordstring, undefined | string>): this;

Set environment variables for the shell.

@param newEnv

The new environment variables

await $`echo $FOO`.env({ ...process.env, FOO: "LOL!" })
expect(stdout.toString()).toBe("LOL!");
finally(onfinally?: null | () => void): PromiseShellOutput>;

Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The resolved value cannot be modified from the callback.

@param onfinally

The callback to execute when the Promise is settled (fulfilled or rejected).

@returns

A Promise for the completion of the callback.

json(): Promiseany>;

Read from stdout as a JSON object

Automatically calls quiet

@returns

A promise that resolves with stdout as a JSON object

const output = await $`echo '{"hello": 123}'`.json();
console.log(output); // { hello: 123 }
lines(): AsyncIterablestring>;

Read from stdout as a string, line by line

Automatically calls quiet to disable echoing to stdout.

nothrow(): this;

Configure the shell to not throw an exception on non-zero exit codes. Throwing can be re-enabled with .throws(true).

By default, the shell with throw an exception on commands which return non-zero exit codes.

quiet(isQuiet?: boolean): this;

By default, the shell will write to the current process's stdout and stderr, as well as buffering that output.

This configures the shell to only buffer the output.

@param isQuiet

Whether to suppress output. Defaults to true.

text(encoding?: BufferEncoding): Promisestring>;

Read from stdout as a string.

Automatically calls quiet to disable echoing to stdout.

@param encoding

The encoding to use when decoding the output

@returns

A promise that resolves with stdout as a string

Read as UTF-8 string

const output = await $`echo hello`.text();
console.log(output); // "hello\n"

Read as base64 string

const output = await $`echo ${atob("hello")}`.text("base64");
console.log(output); // "hello\n"
thenTResult1 = ShellOutput, TResult2 = never>(onfulfilled?: null | (value: ShellOutput) => TResult1 | PromiseLikeTResult1>,onrejected?: null | (reason: any) => TResult2 | PromiseLikeTResult2>): PromiseTResult1 | TResult2>;

Attaches callbacks for the resolution and/or rejection of the Promise.

@param onfulfilled

The callback to execute when the Promise is resolved.

@param onrejected

The callback to execute when the Promise is rejected.

@returns

A Promise for the completion of which ever callback is executed.

throws(shouldThrow: boolean): this;

Configure whether or not the shell should throw an exception on non-zero exit codes.

By default, this is configured to true.

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

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

@param values

An array of Promises.

@returns

A new Promise.

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

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

@param values

An array of Promises.

@returns

A new Promise.

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

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

@param values

An array or iterable of Promises.

@returns

A new Promise.

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

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

@param values

An array of Promises.

@returns

A new Promise.

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

Creates a new rejected promise for the provided reason.

@param reason

The reason the promise was rejected.

@returns

A new rejected Promise.

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

Creates a new resolved promise for the provided value.

@param value

A promise.

@returns

A promise whose internal state matches the provided promise.

static tryT, A extends any[] = []>(fn: (...args: A) => T | PromiseLikeT>,...args: A): PromiseT>;

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

@param fn

The function to run

@param args

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

@returns

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

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

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

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

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

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

await promise; // "Hello world!"
interface ShellOutputreadonly exitCode: numberreadonly stderr: Bufferreadonly stdout: BufferarrayBuffer(): ArrayBuffer;

Read from stdout as an ArrayBuffer

@returns

Stdout as an ArrayBuffer

const output = await $`echo hello`;
console.log(output.arrayBuffer()); // ArrayBuffer { byteLength: 6 }
blob(): Blob;

Read from stdout as a Blob

@returns

Stdout as a blob

const output = await $`echo hello`;
console.log(output.blob()); // Blob { size: 6, type: "" }
bytes(): Uint8ArrayArrayBuffer>;

Read from stdout as an Uint8Array

@returns

Stdout as an Uint8Array

const output = await $`echo hello`;
console.log(output.bytes()); // Uint8Array { byteLength: 6 }
json(): any;

Read from stdout as a JSON object

@returns

Stdout as a JSON object

const output = await $`echo '{"hello": 123}'`;
console.log(output.json()); // { hello: 123 }
text(encoding?: BufferEncoding): string;

Read from stdout as a string

@param encoding

The encoding to use when decoding the output

@returns

Stdout as a string with the given encoding

Read as UTF-8 string

const output = await $`echo hello`;
console.log(output.text()); // "hello\n"

Read as base64 string

const output = await $`echo ${atob("hello")}`;
console.log(output.text("base64")); // "hello\n"
const Shell: new () => $function braces(pattern: string): string[];

Perform bash-like brace expansion on the given pattern.

@param pattern

Brace pattern to expand

const result = braces('index.{js,jsx,ts,tsx}');
console.log(result) // ['index.js', 'index.jsx', 'index.ts', 'index.tsx']
function cwd(newCwd?: string): typeof $;@param newCwd

Default working directory to use for shells created by this instance.

function env(newEnv?: Dictstring> | Recordstring, undefined | string>): typeof $;

Change the default environment variables for shells created by this instance.

@param newEnv

Default environment variables to use for shells created by this instance.

import {$} from 'bun';
$.env({ BUN: "bun" });
await $`echo $BUN`;
// "bun"
function escape(input: string): string;

Escape strings for input into shell commands.

function nothrow(): typeof $;

Configure the shell to not throw an exception on non-zero exit codes.

function throws(shouldThrow: boolean): typeof $;

Configure whether or not the shell should throw an exception on non-zero exit codes.

namespace CSRF

Generate and verify CSRF tokens

function generate(secret?: string,options?: CSRFGenerateOptions): string;

Generate a CSRF token.

@param secret

The secret to use for the token. If not provided, a random default secret will be generated in memory and used.

@param options

The options for the token.

@returns

The generated token.

function verify(token: string,options?: CSRFVerifyOptions): boolean;

Verify a CSRF token.

@param token

The token to verify.

@param options

The options for the token.

@returns

True if the token is valid, false otherwise.

namespace dns

DNS Related APIs

const ADDRCONFIG: numberconst ALL: numberconst V4MAPPED: numberfunction getCacheStats(): { cacheHitsCompleted: number; cacheHitsInflight: number; cacheMisses: number; errors: number; size: number; totalCount: number };

Experimental API

function lookup(hostname: string,options?: { backend: 'system' | 'libc' | 'c-ares' | 'getaddrinfo'; family: 0 | 'IPv4' | 'IPv6' | 4 | 6 | 'any'; flags: number; port: number; socketType: 'udp' | 'tcp' }): PromiseDNSLookup[]>;

Lookup the IP address for a hostname

Uses non-blocking APIs by default

@param hostname

The hostname to lookup

@param options

Options for the lookup

Basic usage
const [{ address }] = await Bun.dns.lookup('example.com');
Filter results to IPv4
import { dns } from 'bun';
const [{ address }] = await dns.lookup('example.com', {family: 4});
console.log(address); // "123.122.22.126"
Filter results to IPv6
import { dns } from 'bun';
const [{ address }] = await dns.lookup('example.com', {family: 6});
console.log(address); // "2001:db8::1"
DNS resolver client

Bun supports three DNS resolvers:

c-ares - Uses the c-ares library to perform DNS resolution. This is the default on Linux.system - Uses the system's non-blocking DNS resolver API if available, falls back to getaddrinfo. This is the default on macOS and the same as getaddrinfo on Linux.getaddrinfo - Uses the posix standard getaddrinfo function. Will cause performance issues under concurrent loads.

To customize the DNS resolver, pass a backend option to dns.lookup:

import { dns } from 'bun';
const [{ address }] = await dns.lookup('example.com', {backend: 'getaddrinfo'});
console.log(address); // "19.42.52.62"
function prefetch(hostname: string,port?: number): void;

Experimental API

Prefetch a hostname.

This will be used by fetch() and Bun.connect() to avoid DNS lookups.

@param hostname

The hostname to prefetch

@param port

The port to prefetch. Default is 443. Port helps distinguish between IPv6 vs IPv4-only connections.

import { dns } from 'bun';
dns.prefetch('example.com');
// ... something expensive
await fetch('https://example.com');
function inspect(arg: any,options?: BunInspectOptions): string;

Pretty-print an object the same as console.log to a string

Supports JSX

@param arg

The value to inspect

@param options

Options for the inspection

namespace inspectconst custom: inspect.custom

That can be used to declare custom inspect functions.

function table(tabularData: object | unknown[],properties?: string[],options?: { colors: boolean }): string;

Pretty-print an object or array as a table

Like console.table, except it returns a string

function table(tabularData: object | unknown[],options?: { colors: boolean }): string;

Pretty-print an object or array as a table

Like console.table, except it returns a string

namespace JSON5

JSON5 related APIs

function parse(input: string): unknown;

Parse a JSON5 string into a JavaScript value.

JSON5 is a superset of JSON based on ECMAScript 5.1 that supports comments, trailing commas, unquoted keys, single-quoted strings, hex numbers, Infinity, NaN, and more.

@param input

The JSON5 string to parse

@returns

A JavaScript value

import { JSON5 } from "bun";

const result = JSON5.parse(`{
// This is a comment
name: 'my-app',
version: '1.0.0', // trailing comma is allowed
hex: 0xDEADbeef,
half: .5,
infinity: Infinity,
}`);
function stringify(input: unknown,replacer?: null,space?: string | number): undefined | string;

Convert a JavaScript value into a JSON5 string. Object keys that are valid identifiers are unquoted, strings use double quotes, Infinity and NaN are represented as literals, and indented output includes trailing commas.

@param input

The JavaScript value to stringify.

@param replacer

Currently not supported.

@param space

A number for how many spaces each level of indentation gets, or a string used as indentation. The number is clamped between 0 and 10, and the first 10 characters of the string are used.

@returns

A JSON5 string, or undefined if the input is undefined, a function, or a symbol.

import { JSON5 } from "bun";

console.log(JSON5.stringify({ a: 1, b: "two" }));
// {a:1,b:"two"}

console.log(JSON5.stringify({ a: 1, b: 2 }, null, 2));
// {
// a: 1,
// b: 2,
// }
namespace JSONC

JSONC related APIs

function parse(input: string): unknown;

Parse a JSONC (JSON with Comments) string into a JavaScript value.

Supports both single-line (http://) and block comments (/* ... */), as well as trailing commas in objects and arrays.

@param input

The JSONC string to parse

@returns

A JavaScript value

const result = Bun.JSONC.parse(`{
// This is a comment
"name": "my-app",
"version": "1.0.0", // trailing comma is allowed
}`);
namespace JSONL

JSONL (JSON Lines) related APIs.

Each line in the input is expected to be a valid JSON value separated by newlines.

interface ParseChunkResult

The result of Bun.JSONL.parseChunk.

done: boolean

true if all input was consumed successfully. false if the input ends with an incomplete value or a parse error occurred.

error: null | SyntaxError

A SyntaxError if a parse error occurred, otherwise null. Values parsed before the error are still available in values.

read: number

How far into the input was consumed. When the input is a string, this is a character offset. When the input is a TypedArray, this is a byte offset. Use input.slice(read) or input.subarray(read) to get the unconsumed remainder.

values: unknown[]

The successfully parsed JSON values.

function parse(input: string | ArrayBufferLike | TypedArrayArrayBufferLike> | DataViewArrayBuffer>): unknown[];

Parse a JSONL (JSON Lines) string into an array of JavaScript values.

If a parse error occurs and no values were successfully parsed, throws a SyntaxError. If values were parsed before the error, returns the successfully parsed values without throwing.

Incomplete trailing values (e.g. from a partial chunk) are silently ignored and not included in the result.

When a TypedArray is passed, the bytes are parsed directly without copying if the content is ASCII.

@param input

The JSONL string or typed array to parse

@returns

An array of parsed values

const items = Bun.JSONL.parse('{"a":1}\n{"b":2}\n');
// [{ a: 1 }, { b: 2 }]

// From a Uint8Array (zero-copy for ASCII):
const buf = new TextEncoder().encode('{"a":1}\n{"b":2}\n');
const items = Bun.JSONL.parse(buf);
// [{ a: 1 }, { b: 2 }]

// Partial results on error after valid values:
const partial = Bun.JSONL.parse('{"a":1}\n{bad}\n');
// [{ a: 1 }]

// Throws when no valid values precede the error:
Bun.JSONL.parse('{bad}\n'); // throws SyntaxError
function parseChunk(input: string | ArrayBufferLike | TypedArrayArrayBufferLike> | DataViewArrayBuffer>,start?: number,end?: number): ParseChunkResult;

Parse a JSONL chunk, designed for streaming use.

Never throws on parse errors. Instead, returns whatever values were successfully parsed along with an error property containing the SyntaxError (or null on success). Use read to determine how much input was consumed and done to check if all input was parsed.

When a TypedArray is passed, the bytes are parsed directly without copying if the content is ASCII. Optional start and end parameters select a window of the input without copying. For typed arrays these are byte offsets and read will be a byte offset into the original typed array. For strings these are character offsets and read will be a character offset into the original string.

@param input

The JSONL string or typed array to parse

@param start

Offset to start parsing from (bytes for typed arrays, characters for strings, default: 0)

@param end

Offset to stop parsing at (bytes for typed arrays, characters for strings, default: input length)

@returns

An object with values, read, done, and error properties

let buffer = new Uint8Array(0);
for await (const chunk of stream) {
buffer = Buffer.concat([buffer, chunk]);
const { values, read, error } = Bun.JSONL.parseChunk(buffer);
if (error) throw error;
for (const value of values) handle(value);
buffer = buffer.subarray(read);
}
namespace markdown

Markdown related APIs.

Provides fast markdown parsing and rendering with three output modes:

html() — render to an HTML stringrender() — render with custom callbacks for each elementreact() — parse to React-compatible JSX elements

Supports GFM extensions (tables, strikethrough, task lists, autolinks) and component overrides to replace default HTML tags with custom components.

// Render markdown to HTML
const html = Bun.markdown.html("# Hello **world**");
// "Hello world\n"

// Render with custom callbacks
const ansi = Bun.markdown.render("# Hello **world**", {
heading: (children, { level }) => `\x1b[1m${children}\x1b[0m\n`,
strong: (children) => `\x1b[1m${children}\x1b[22m`,
paragraph: (children) => children + "\n",
});

// Render as a React component
function Markdown({ text }: { text: string }) {
return Bun.markdown.react(text);
}

// With component overrides
const element = Bun.markdown.react("# Hello", { h1: MyHeadingComponent });
interface AnsiTheme

Theme for ANSI terminal rendering.

colors?: boolean

Emit ANSI color + styling escape sequences. When false, the renderer falls back to plain ASCII chrome (no box drawing, no emoji, no escape codes).

columns?: number

Line width used for word-wrapping paragraphs and headings and for the horizontal rule. Pass 0 to disable wrapping.

hyperlinks?: boolean

Emit OSC 8 hyperlinks (clickable links in modern terminals). When false, links render as text (url).

kittyGraphics?: boolean

Inline images using the Kitty Graphics Protocol when the src resolves to a local file on disk. Falls through to the text alt for remote URLs. Supported by Kitty, WezTerm, and Ghostty.

light?: boolean

True when the terminal background is light. Affects the color palette chosen for inline code backgrounds. Defaults to detecting from the COLORFGBG environment variable.

interface CellMeta

Meta passed to th and td callbacks.

align?: 'left' | 'center' | 'right'

Column alignment.

interface CellPropsalign?: 'left' | 'center' | 'right'

Column alignment.

children: unknown[]interface ChildrenPropschildren: unknown[]interface CodeBlockMeta

Meta passed to the code callback.

language?: string

The info-string language (e.g. "js").

interface CodeBlockPropschildren: unknown[]language?: string

The info-string language (e.g. "js").

interface ComponentOverrides

Component overrides for react().

Replace default HTML tags with custom React components. Each override receives the same props the default element would get.

function Code({ language, children }: { language?: string; children: React.ReactNode }) {
return pre data-language={language}>code>{children}code>pre>;
}
Bun.markdown.react(text, { pre: Code });
a?: ComponentLinkProps>blockquote?: ComponentChildrenProps>br?: Component{}>code?: ComponentChildrenProps>del?: ComponentChildrenProps>em?: ComponentChildrenProps>h1?: ComponentHeadingProps>h2?: ComponentHeadingProps>h3?: ComponentHeadingProps>h4?: ComponentHeadingProps>h5?: ComponentHeadingProps>h6?: ComponentHeadingProps>hr?: Component{}>html?: ComponentChildrenProps>img?: ComponentImageProps>li?: ComponentListItemProps>math?: ComponentChildrenProps>ol?: ComponentOrderedListProps>p?: ComponentChildrenProps>pre?: ComponentCodeBlockProps>strong?: ComponentChildrenProps>table?: ComponentChildrenProps>tbody?: ComponentChildrenProps>td?: ComponentCellProps>th?: ComponentCellProps>thead?: ComponentChildrenProps>tr?: ComponentChildrenProps>u?: ComponentChildrenProps>ul?: ComponentChildrenProps>interface HeadingMeta

Meta passed to the heading callback.

id?: string

Heading ID slug. Set when headings: { ids: true } is enabled.

level: number

Heading level (1–6).

interface HeadingPropschildren: unknown[]id?: string

Heading ID slug. Set when headings: { ids: true } is enabled.

interface ImageMeta

Meta passed to the image callback.

src: string

Image URL.

title?: string

Image title attribute.

interface ImagePropsalt?: string

Alt text.

src: string

Image URL.

title?: string

Image title attribute.

interface LinkMeta

Meta passed to the link callback.

href: string

Link URL.

title?: string

Link title attribute.

interface LinkPropschildren: unknown[]href: string

Link URL.

title?: string

Link title attribute.

interface ListItemMeta

Meta passed to the listItem callback.

checked?: boolean

Task list checked state. Set for - [x] / - [ ] items.

depth: number

Nesting depth of the parent list. 0 for items in a top-level list.

index: number

0-based index of this item within its parent list.

ordered: boolean

Whether the parent list is ordered.

start?: number

The start number of the parent list (only set when ordered is true).

interface ListItemPropschecked?: boolean

Task list checked state. Set for - [x] / - [ ] items.

children: unknown[]interface ListMeta

Meta passed to the list callback.

depth: number

Nesting depth. 0 for a top-level list, 1 for a list inside a list item, etc.

ordered: boolean

Whether this is an ordered list.

start?: number

The start number for ordered lists.

interface Options

Options for configuring the markdown parser.

By default, GFM extensions (tables, strikethrough, task lists) are enabled.

autolinks?: boolean | { email: boolean; url: boolean; www: boolean }

Enable autolinks. Pass true to enable all autolink types (URL, WWW, email), or an object to enable individually.

// Enable all autolinks
{ autolinks: true }
// Enable only URL and email autolinks
{ autolinks: { url: true, email: true } }
collapseWhitespace?: boolean

Collapse whitespace in text content. Default: false.

hardSoftBreaks?: boolean

Treat soft line breaks as hard line breaks. Default: false.

headings?: boolean | { autolink: boolean; ids: boolean }

Configure heading IDs and autolink headings. Pass true to enable both heading IDs and autolink headings, or an object to configure individually.

// Enable both heading IDs and autolink headings
{ headings: true }
// Enable only heading IDs
{ headings: { ids: true } }
latexMath?: boolean

Enable LaTeX math ($inline$ and $$display$$). Default: false.

noHtmlBlocks?: boolean

Disable HTML blocks. Default: false.

noHtmlSpans?: boolean

Disable inline HTML spans. Default: false.

noIndentedCodeBlocks?: boolean

Disable indented code blocks. Default: false.

permissiveAtxHeaders?: boolean

Allow ATX headers without a space after #. Default: false.

strikethrough?: boolean

Enable GFM strikethrough (~~text~~). Default: true.

tables?: boolean

Enable GFM tables. Default: true.

collapseWhitespace?: boolean

Collapse whitespace in text content. Default: false.

hardSoftBreaks?: boolean

Treat soft line breaks as hard line breaks. Default: false.

headings?: boolean | { autolink: boolean; ids: boolean }

Configure heading IDs and autolink headings. Pass true to enable both heading IDs and autolink headings, or an object to configure individually.

// Enable both heading IDs and autolink headings
{ headings: true }
// Enable only heading IDs
{ headings: { ids: true } }
latexMath?: boolean

Enable LaTeX math ($inline$ and $$display$$). Default: false.

noHtmlBlocks?: boolean

Disable HTML blocks. Default: false.

noHtmlSpans?: boolean

Disable inline HTML spans. Default: false.

noIndentedCodeBlocks?: boolean

Disable indented code blocks. Default: false.

permissiveAtxHeaders?: boolean

Allow ATX headers without a space after #. Default: false.

reactVersion?: 18 | 19

Which $$typeof symbol to use on the generated elements.

19 (default): Symbol.for('react.transitional.element')18: Symbol.for('react.element') — use this for React 18 and older
strikethrough?: boolean

Enable GFM strikethrough (~~text~~). Default: true.

tables?: boolean

Enable GFM tables. Default: true.

function html(input: string | ArrayBufferLike | TypedArrayArrayBufferLike> | DataViewArrayBuffer>,options?: Options): string;

Render markdown to an HTML string.

@param input

The markdown string or buffer to render

@param options

Parser options

@returns

An HTML string

const html = Bun.markdown.html("# Hello **world**");
// "Hello world\n"

// With options
const html = Bun.markdown.html("## Hello", { headings: { ids: true } });
// 'Hello\n'
function react(input: string | ArrayBufferLike | TypedArrayArrayBufferLike> | DataViewArrayBuffer>,components?: ComponentOverrides,options?: ReactOptions): unknown;

Render markdown to React JSX elements.

Returns a React Fragment containing the parsed markdown as children. Can be returned directly from a component or passed to renderToString().

Override any HTML element with a custom component by passing it in the second argument, keyed by tag name. Custom components receive the same props the default elements would (e.g. href for links, language for code blocks).

Parser options (including reactVersion) are passed as a separate third argument. Uses Symbol.for('react.transitional.element') by default (React 19). Pass reactVersion: 18 for React 18 and older.

@param input

The markdown string or buffer to parse

@param components

Component overrides keyed by HTML tag name

@param options

Parser options and element symbol configuration

@returns

A React Fragment element containing the parsed markdown

// Use directly as a component return value
function Markdown({ text }: { text: string }) {
return Bun.markdown.react(text);
}

// Server-side rendering
import { renderToString } from "react-dom/server";
const html = renderToString(Bun.markdown.react("# Hello **world**"));

// Custom components receive element props
function Code({ language, children }: { language?: string; children: React.ReactNode }) {
return pre data-language={language}>code>{children}code>pre>;
}
function Link({ href, children }: { href: string; children: React.ReactNode }) {
return a href={href} target="_blank">{children}a>;
}
const el = Bun.markdown.react(text, { pre: Code, a: Link });

// For React 18 and older
const el18 = Bun.markdown.react(text, undefined, { reactVersion: 18 });
function render(input: string | ArrayBufferLike | TypedArrayArrayBufferLike> | DataViewArrayBuffer>,callbacks?: RenderCallbacks,options?: Options): string;

Render markdown with custom JavaScript callbacks for each element.

Each callback receives the accumulated children as a string and optional metadata, and returns a string. Return null or undefined to omit an element. If no callback is registered, children pass through unchanged.

Parser options are passed as a separate third argument.

@param input

The markdown string to render

@param callbacks

Callbacks for each element type

@param options

Parser options

@returns

The accumulated string output

// Custom HTML with classes
const html = Bun.markdown.render("# Title\n\nHello **world**", {
heading: (children, { level }) => `${level} class="title">${children}${level}>`,
paragraph: (children) => `

${children}

`, strong: (children) => `${children}`, }); // ANSI terminal output const ansi = Bun.markdown.render("# Hello\n\n**bold**", { heading: (children) => `\x1b[1;4m${children}\x1b[0m\n`, paragraph: (children) => children + "\n", strong: (children) => `\x1b[1m${children}\x1b[22m`, }); // With parser options as third argument const text = Bun.markdown.render("Visit www.example.com", { link: (children, { href }) => `[${children}](${href})`, paragraph: (children) => children, }, { autolinks: true });
function peekT = undefined>(promise: T | PromiseT>): T | PromiseT>;

Extract the value from the Promise in the same tick of the event loop

namespace peekfunction statusT = undefined>(promise: T | PromiseT>): 'pending' | 'fulfilled' | 'rejected';namespace semver

Bun.semver provides a fast way to parse and compare version numbers.

function order(v1: StringLike,v2: StringLike): -1 | 0 | 1;

Returns 0 if the versions are equal, 1 if v1 is greater, or -1 if v2 is greater. Throws an error if either version is invalid.

function satisfies(version: StringLike,range: StringLike): boolean;

Test if the version satisfies the range. Stringifies both arguments. Returns true or false.

namespace SQLclass MySQLErrorcause?: unknown

The cause of the error.

readonly code: stringreadonly errno?: numbermessage: stringname: stringreadonly sqlState?: stringstack?: stringstatic stackTraceLimit: number

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

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

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

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

Create .stack property on a target object

static isError(value: unknown): value is Error;

Check if a value is an instance of Error

@param value

The value to check

@returns

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

static prepareStackTrace(err: Error,stackTraces: CallSite[]): any;
class PostgresErrorcause?: unknown

The cause of the error.

readonly code: stringreadonly column?: stringreadonly constraint?: stringreadonly dataType?: stringreadonly detail?: stringreadonly errno?: stringreadonly file?: stringreadonly hint?: stringreadonly internalPosition?: stringreadonly internalQuery?: stringreadonly line?: stringmessage: stringname: stringreadonly position?: stringreadonly routine?: stringreadonly schema?: stringreadonly severity?: stringstack?: stringreadonly table?: stringreadonly where?: stringstatic stackTraceLimit: number

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

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

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

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

Create .stack property on a target object

static isError(value: unknown): value is Error;

Check if a value is an instance of Error

@param value

The value to check

@returns

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

static prepareStackTrace(err: Error,stackTraces: CallSite[]): any;
class SQLErrorcause?: unknown

The cause of the error.

message: stringname: stringstack?: stringstatic stackTraceLimit: number

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

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

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

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

Create .stack property on a target object

static isError(value: unknown): value is Error;

Check if a value is an instance of Error

@param value

The value to check

@returns

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

static prepareStackTrace(err: Error,stackTraces: CallSite[]): any;
class SQLiteErrorreadonly byteOffset?: numbercause?: unknown

The cause of the error.

readonly code: stringreadonly errno: numbermessage: stringname: stringstack?: stringstatic stackTraceLimit: number

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

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

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

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

Create .stack property on a target object

static isError(value: unknown): value is Error;

Check if a value is an instance of Error

@param value

The value to check

@returns

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

static prepareStackTrace(err: Error,stackTraces: CallSite[]): any;
interface HelperT>

SQL.Helper represents a parameter or serializable value inside of a query.

const helper = sql(users, 'id');
await sql`insert into users ${helper}`;
readonly columns: keyof T[]readonly value: T[]interface PostgresOrMySQLOptionsadapter?: 'postgres' | 'mysql' | 'mariadb'

Database adapter/driver to use

bigint?: boolean

By default values outside i32 range are returned as strings. If this is true, values outside i32 range are returned as BigInts.

connection?: Recordstring, string | number | boolean>

Postgres client runtime configuration options

connectionTimeout?: number

Maximum time in seconds to wait when establishing a connection

database?: string

Name of the database to connect to

hostname?: string

Database server hostname

idleTimeout?: number

Maximum time in seconds to wait for connection to become available

max?: number

Maximum number of connections in the pool

maxLifetime?: number

Maximum lifetime in seconds of a connection

onclose?: (err: null | Error) => void

Callback executed when a connection is closed Receives the closing Error or null.

onconnect?: (err: null | Error) => void

Callback executed when a connection attempt completes Receives an Error on failure, or null on success.

password?: string | () => MaybePromisestring>

Database password for authentication

path?: string

Unix domain socket path for connection

port?: string | number

Database server port number

prepare?: boolean

Automatic creation of prepared statements

tls?: boolean | BunFile | TLSOptions

Whether to use TLS/SSL for the connection

url?: string | URL

Connection URL (can be string or URL object)

username?: string

Database user for authentication

interface QueryT>

Represents a SQL query that can be executed, with additional control methods Extends Promise to allow for async/await usage

readonly [Symbol.toStringTag]: stringactive: boolean

Indicates if the query is currently executing

cancelled: boolean

Indicates if the query has been cancelled

cancel(): QueryT>;

Cancels the executing query

catchTResult = never>(onrejected?: null | (reason: any) => TResult | PromiseLikeTResult>): PromiseT | TResult>;

Attaches a callback for only the rejection of the Promise.

@param onrejected

The callback to execute when the Promise is rejected.

@returns

A Promise for the completion of the callback.

execute(): QueryT>;

Executes the query

finally(onfinally?: null | () => void): PromiseT>;

Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The resolved value cannot be modified from the callback.

@param onfinally

The callback to execute when the Promise is settled (fulfilled or rejected).

@returns

A Promise for the completion of the callback.

raw(): QueryT>;

Returns the raw query result

simple(): QueryT>;

Executes the query as a simple query, no parameters are allowed but can execute multiple commands separated by semicolons

thenTResult1 = T, TResult2 = never>(onfulfilled?: null | (value: T) => TResult1 | PromiseLikeTResult1>,onrejected?: null | (reason: any) => TResult2 | PromiseLikeTResult2>): PromiseTResult1 | TResult2>;

Attaches callbacks for the resolution and/or rejection of the Promise.

@param onfulfilled

The callback to execute when the Promise is resolved.

@param onrejected

The callback to execute when the Promise is rejected.

@returns

A Promise for the completion of which ever callback is executed.

values(): QueryT>;

Returns only the values from the query result

interface SQLiteOptions

Options for Database

adapter?: 'sqlite'create?: boolean

Allow creating a new database

Equivalent to constants.SQLITE_OPEN_CREATE

filename?: URL | string & {} | ':memory:'

Specify the path to the database file

Examples:

sqlite:http://:memory:sqlite:http://./path/to/database.dbsqlite:http:///Users/bun/projects/my-app/database.db./dev.db:memory:
onclose?: (err: null | Error) => void

Callback executed when a connection is closed (SQLite) Receives the closing Error or null.

onconnect?: (err: null | Error) => void

Callback executed when a connection attempt completes (SQLite) Receives an Error on failure, or null on success.

readonly?: boolean

Open the database as read-only (no write operations, no create).

Equivalent to constants.SQLITE_OPEN_READONLY

readwrite?: boolean

Open the database as read-write

Equivalent to constants.SQLITE_OPEN_READWRITE

safeIntegers?: boolean

When set to true, integers are returned as bigint types.

When set to false, integers are returned as number types and truncated to 52 bits.

strict?: boolean

When set to false or undefined:

Queries missing bound parameters will NOT throw an errorBound named parameters in JavaScript need to exactly match the SQL query.
const db = new Database(":memory:", { strict: false });
db.run("INSERT INTO foo (name) VALUES ($name)", { $name: "foo" });

When set to true:

Queries missing bound parameters will throw an errorBound named parameters in JavaScript no longer need to be $, :, or @. The SQL query will remain prefixed.
type AwaitPromisesArrayT extends PromiseLikeany>[]> = { [K in keyof T]: AwaitedT[K]> }type ContextCallbackT, SQL> = (sql: SQL) => Bun.MaybePromiseT>type ContextCallbackResultT> = T extends PromiseLikeany>[] ? AwaitPromisesArrayT> : AwaitedT>type Options = SQLiteOptions | PostgresOrMySQLOptions

Configuration options for SQL client connection and behavior

const config: Bun.SQL.Options = {
host: 'localhost',
port: 5432,
user: 'dbuser',
password: 'secretpass',
database: 'myapp',
idleTimeout: 30,
max: 20,
onconnect: (client) => {
console.log('Connected to database');
}
};
type SavepointContextCallbackT> = ContextCallbackT, SavepointSQL>

Callback function type for savepoint contexts

type TransactionContextCallbackT> = ContextCallbackT, TransactionSQL>

Callback function type for transaction contexts

namespace TOML

TOML related APIs

function parse(input: string): object;

Parse a TOML string into a JavaScript object.

@param input

The TOML string to parse

@returns

A JavaScript object

namespace unsafefunction arrayBufferToString(buffer: ArrayBufferLike | Uint8ArrayArrayBuffer>): string;

Cast bytes to a String without copying. This is the fastest way to get a String from a Uint8Array or ArrayBuffer.

Only use this for ASCII strings. If there are non-ascii characters, your application may crash and/or very confusing bugs will happen such as "foo" !== "foo".

The input buffer must not be garbage collected. That means you will need to hold on to it for the duration of the string's lifetime.

function arrayBufferToString(buffer: Uint16Array): string;

Cast bytes to a String without copying. This is the fastest way to get a String from a Uint16Array

The input must be a UTF-16 encoded string. This API does no validation whatsoever.

The input buffer must not be garbage collected. That means you will need to hold on to it for the duration of the string's lifetime.

function gcAggressionLevel(level?: 0 | 2 | 1): 0 | 1 | 2;

Force the garbage collector to run extremely often, especially inside bun:test.

0: default, disable1: asynchronously call the garbage collector more often2: synchronously call the garbage collector more often.

This is a global setting. It's useful for debugging seemingly random crashes.

BUN_GARBAGE_COLLECTOR_LEVEL environment variable is also supported.

@returns

The previous level

function memoryFootprint(): undefined | number;

Accurate per-process memory footprint in bytes.

Unlike process.memoryUsage.rss(), this excludes pages already returned to the OS that the kernel keeps mapped lazily (Darwin's MADV_FREE_REUSABLE), so leak tests are platform-comparable.

Backed by task_info(TASK_VM_INFO).phys_footprint on Darwin, Pss: from /proc/self/smaps_rollup on Linux, and PrivateUsage on Windows. Returns undefined on platforms with no accurate accessor; callers should fall back: Bun.unsafe.memoryFootprint() ?? process.memoryUsage.rss().

function mimallocDump(): void;

Dump the mimalloc heap to the console

namespace YAML

YAML related APIs

function parse(input: string): unknown;

Parse a YAML string into a JavaScript value

@param input

The YAML string to parse

@returns

A JavaScript value

import { YAML } from "bun";

console.log(YAML.parse("123")) // 123
console.log(YAML.parse("null")) // null
console.log(YAML.parse("false")) // false
console.log(YAML.parse("abc")) // "abc"
console.log(YAML.parse("- abc")) // [ "abc" ]
console.log(YAML.parse("abc: def")) // { "abc": "def" }
function stringify(input: unknown,replacer?: null,space?: string | number): string;

Convert a JavaScript value into a YAML string. Strings are double quoted if they contain keywords, non-printable or escaped characters, or if a YAML parser would parse them as numbers. Anchors and aliases are inferred from objects, allowing cycles.

@param input

The JavaScript value to stringify.

@param replacer

Currently not supported.

@param space

A number for how many spaces each level of indentation gets, or a string used as indentation. Without this parameter, outputs flow-style (single-line) YAML. With this parameter, outputs block-style (multi-line) YAML. The number is clamped between 0 and 10, and the first 10 characters of the string are used.

@returns

A string containing the YAML document.

import { YAML } from "bun";

const input = {
abc: "def",
num: 123
};

// Without space - flow style (single-line)
console.log(YAML.stringify(input));
// {abc: def,num: 123}

// With space - block style (multi-line)
console.log(YAML.stringify(input, null, 2));
// abc: def
// num: 123

const cycle = {};
cycle.obj = cycle;
console.log(YAML.stringify(cycle, null, 2));
// &1
// obj: *1
class Archive

A class for creating and extracting tar archives with optional gzip compression.

Bun.Archive provides a fast, native implementation for working with tar archives. It supports creating archives from in-memory data or extracting existing archives to disk or memory.

Create an archive from an object:

const archive = new Bun.Archive({
"hello.txt": "Hello, World!",
"data.json": JSON.stringify({ foo: "bar" }),
"binary.bin": new Uint8Array([1, 2, 3, 4]),
});
blob(): PromiseBlob>;

Get the archive contents as a Blob.

Uses the compression settings specified when the Archive was created.

@returns

A promise that resolves with the archive data as a Blob

Get tarball as Blob:

const archive = new Bun.Archive(data);
const blob = await archive.blob();
bytes(): PromiseUint8ArrayArrayBuffer>>;

Get the archive contents as a Uint8Array.

Uses the compression settings specified when the Archive was created.

@returns

A promise that resolves with the archive data as a Uint8Array

Get tarball bytes:

const archive = new Bun.Archive(data);
const bytes = await archive.bytes();
extract(path: string,options?: ArchiveExtractOptions): Promisenumber>;

Extract the archive contents to a directory on disk.

Creates the target directory and any necessary parent directories if they don't exist. Existing files will be overwritten.

@param path

The directory path to extract to

@param options

Optional extraction options

@returns

A promise that resolves with the number of entries extracted (files, directories, and symlinks)

Extract all entries:

const archive = new Bun.Archive(tarballBytes);
const count = await archive.extract("./extracted");
console.log(`Extracted ${count} entries`);
files(glob?: string | readonly string[]): PromiseMapstring, File>>;

Get the archive contents as a Map of File objects.

Each file in the archive is returned as a File object with:

name: The file path within the archivelastModified: The file's modification time from the archiveStandard Blob methods (text(), arrayBuffer(), stream(), etc.)

Only regular files are included; directories are not returned. File contents are loaded into memory, so for large archives consider using extract() instead.

@param glob

Optional glob pattern(s) to filter files. Supports the same syntax as Bun.Glob, including negation patterns (prefixed with !). Patterns are matched against paths normalized to use forward slashes (/).

@returns

A promise that resolves with a Map where keys are file paths (always using forward slashes / as separators) and values are File objects

Get all files:

const entries = await archive.files();
for (const [path, file] of entries) {
console.log(`${path}: ${file.size} bytes`);
}
static write(path: string,data: Archive | ArchiveInput,options?: ArchiveOptions): Promisevoid>;

Create and write an archive directly to disk in one operation.

This is more efficient than creating an archive and then writing it separately, as it streams the data directly to disk.

@param path

The file path to write the archive to

@param data

The input data for the archive (same as new Archive())

@param options

Optional archive options including compression settings

@returns

A promise that resolves when the write is complete

Write uncompressed tarball:

await Bun.Archive.write("output.tar", {
"file1.txt": "content1",
"file2.txt": "content2",
});
class ArrayBufferSink

Fast incremental writer that becomes an ArrayBuffer on end().

end(): ArrayBuffer | Uint8ArrayArrayBuffer>;flush(): number | ArrayBuffer | Uint8ArrayArrayBuffer>;

Flush the internal buffer

If ArrayBufferSink.start was passed a stream option, this will return a ArrayBuffer If ArrayBufferSink.start was passed a stream option and asUint8Array, this will return a Uint8Array Otherwise, this will return the number of bytes written since the last flush

This API might change later to separate Uint8ArraySink and ArrayBufferSink

start(options?: { asUint8Array: boolean; highWaterMark: number; stream: boolean }): void;write(chunk: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>): number;class Cookie

A class for working with a single cookie

const cookie = new Bun.Cookie("name", "value");
console.log(cookie.toString()); // "name=value; Path=/; SameSite=Lax"
domain?: string

The domain of the cookie

expires?: Date

The expiration date of the cookie

httpOnly: boolean

Whether the cookie is HTTP-only

maxAge?: number

The maximum age of the cookie in seconds

readonly name: string

The name of the cookie

partitioned: boolean

Whether the cookie is partitioned

path: string

The path of the cookie

sameSite: CookieSameSite

The same-site attribute of the cookie

secure: boolean

Whether the cookie is secure

value: string

The value of the cookie

isExpired(): boolean;

Whether the cookie is expired

serialize(): string;

Serialize the cookie to a string

const cookie = Bun.Cookie.from("session", "abc123", {
domain: "example.com",
path: "/",
secure: true,
httpOnly: true
}).serialize(); // "session=abc123; Domain=example.com; Path=/; Secure; HttpOnly; SameSite=Lax"
toJSON(): CookieInit;

Serialize the cookie to a JSON object

toString(): string;

Serialize the cookie to a string

Alias of Cookie.serialize

static from(name: string,value: string,options?: CookieInit): Cookie;

Create a new cookie from a name and value and optional options

static parse(cookieString: string): Cookie;

Parse a cookie string into a Cookie object

@param cookieString

The cookie string

class CookieMap

A Map-like interface for working with collections of cookies.

Implements the Iterable interface, allowing use with for...of loops.

readonly size: number

The number of cookies in the map.

[Symbol.iterator](): IterableIterator[string, string]>;

Returns the default iterator for the CookieMap. Used by for...of loops to iterate over all entries.

@returns

An iterator for the entries in the map

delete(name: string): void;

Removes a cookie from the map.

@param name

The name of the cookie to delete

delete(options: CookieStoreDeleteOptions): void;

Removes a cookie from the map.

@param options

The options for the cookie to delete

delete(name: string,options: OmitCookieStoreDeleteOptions, 'name'>): void;

Removes a cookie from the map.

@param name

The name of the cookie to delete

@param options

The options for the cookie to delete

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

Returns an iterator of [name, value] pairs for every cookie in the map.

@returns

An iterator for the entries in the map

forEach(callback: (value: string, key: string, map: CookieMap) => void): void;

Executes a provided function once for each cookie in the map.

@param callback

Function to execute for each entry

get(name: string): null | string;

Gets the value of a cookie with the specified name.

@param name

The name of the cookie to retrieve

@returns

The cookie value as a string, or null if the cookie doesn't exist

has(name: string): boolean;

Checks if a cookie with the given name exists.

@param name

The name of the cookie to check

@returns

true if the cookie exists, false otherwise

keys(): IterableIteratorstring>;

Returns an iterator of all cookie names in the map.

@returns

An iterator for the cookie names

set(name: string,value: string,options?: CookieInit): void;

Adds or updates a cookie in the map.

@param name

The name of the cookie

@param value

The value of the cookie

@param options

Optional cookie attributes

set(options: CookieInit): void;

Adds or updates a cookie in the map using a cookie options object.

@param options

Cookie options including name and value

toJSON(): Recordstring, string>;

Converts the cookie map to a serializable format.

@returns

An array of name/value pairs

toSetCookieHeaders(): string[];

Gets an array of values for Set-Cookie headers in order to apply all changes to cookies.

@returns

An array of values for Set-Cookie headers

values(): IterableIteratorstring>;

Returns an iterator of all cookie values in the map.

@returns

An iterator for the cookie values

class CryptoHasher

Hardware-accelerated cryptographic hash functions

Used for crypto.createHash()

readonly algorithm: SupportedCryptoAlgorithms

The algorithm chosen to hash the data

readonly byteLength: number

The length of the output hash in bytes

readonly static algorithms: SupportedCryptoAlgorithms[]

List of supported hash algorithms

These are hardware accelerated with BoringSSL

copy(): CryptoHasher;

Perform a deep copy of the hasher

digest(encoding: DigestEncoding): string;

Finalize the hash. Resets the CryptoHasher so it can be reused.

@param encoding

DigestEncoding to return the hash in. If none is provided, it will return a Uint8Array.

digest(): Buffer;

Finalize the hash and return a Buffer

digest(hashInto: TypedArray): TypedArray;

Finalize the hash

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

update(input: BlobOrStringOrBuffer,inputEncoding?: Encoding): CryptoHasher;

Update the hash with data

static hash(algorithm: SupportedCryptoAlgorithms,input: BlobOrStringOrBuffer): Buffer;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

static hash(algorithm: SupportedCryptoAlgorithms,input: BlobOrStringOrBuffer,hashInto: TypedArray): TypedArray;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

static hash(algorithm: SupportedCryptoAlgorithms,input: BlobOrStringOrBuffer,encoding: DigestEncoding): string;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param encoding

DigestEncoding to return the hash in

class CryptoHashInterfaceT>

This class only exists in types

digest(encoding: DigestEncoding): string;

Finalize the hash

@param encoding

DigestEncoding to return the hash in. If none is provided, it will return a Uint8Array.

digest(hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Finalize the hash

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

update(data: BlobOrStringOrBuffer): T;

Update the hash with data

static hash(input: BlobOrStringOrBuffer,hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

static hash(input: BlobOrStringOrBuffer,encoding: DigestEncoding): string;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param encoding

DigestEncoding to return the hash in

class FileSystemRouterreadonly assetPrefix: stringreadonly origin: stringreadonly routes: Recordstring, string>readonly style: stringmatch(input: string | Request | Response): null | MatchedRoute;reload(): void;class Glob

Match files using glob patterns.

The supported pattern syntax for is:

? Matches any single character.* Matches zero or more characters, except for path separators ('/' or '').** Matches zero or more characters, including path separators. Must match a complete path segment, i.e. followed by a path separator or at the end of the pattern.[ab] Matches one of the characters contained in the brackets. Character ranges (e.g. "[a-z]") are also supported. Use "[!ab]" or "[^ab]" to match any character except those contained in the brackets.{a,b} Match one of the patterns contained in the braces. Any of the wildcards listed above can be used in the sub patterns. Braces may be nested up to 10 levels deep.! Negates the result when at the start of the pattern. Multiple "!" characters negate the pattern multiple times.`` Used to escape any of the special characters above.
const glob = new Glob("*.{ts,tsx}");
const scannedFiles = await Array.fromAsync(glob.scan({ cwd: './src' }))
match(str: string): boolean;

Match the glob against a string

const glob = new Glob("*.{ts,tsx}");
expect(glob.match('foo.ts')).toBeTrue();
scan(optionsOrCwd?: string | GlobScanOptions): AsyncIterableIteratorstring>;

Scan a root directory recursively for files that match this glob pattern. Returns an async iterator.

const glob = new Glob("*.{ts,tsx}");
const scannedFiles = await Array.fromAsync(glob.scan({ cwd: './src' }))
scanSync(optionsOrCwd?: string | GlobScanOptions): IterableIteratorstring>;

Synchronously scan a root directory recursively for files that match this glob pattern. Returns an iterator.

const glob = new Glob("*.{ts,tsx}");
const scannedFiles = Array.from(glob.scan({ cwd: './src' }))
class Image

Decode, transform and re-encode images. Ships JPEG, PNG and WebP via statically-linked libjpeg-turbo / libspng / libwebp; resize and rotate are SIMD kernels — no native module install, no sharp.

The constructor and every chainable method only record settings; the decode → transform → encode pipeline runs on a worker thread when a terminal (bytes, buffer, blob, toBase64, metadata) is awaited.

Chainables overwrite (calling .resize() twice keeps the second). Order of execution is fixed regardless of call order: autoOrient → rotate → flip/flop → resize → modulate.

The source ICC colour profile (Display P3, Adobe RGB, Jpegli XYB, etc.) is preserved through re-encode to JPEG, PNG, and WebP so non-sRGB images don't shift colour.

const thumb = await new Bun.Image("photo.jpg")
.resize(400, 400, { fit: "inside", withoutEnlargement: true })
.webp({ quality: 80 })
.bytes();
readonly height: numberreadonly width: number

Populated after the first awaited terminal; -1 before.

static backend: 'system' | 'bun'

Process-global pipeline backend.

"system" (default on macOS/Windows) — static codecs for JPEG/PNG/WebP (same bytes as Linux), Accelerate/vImage for lanczos3 resize · rotate · flip on macOS, and ImageIO/WIC for HEIC/AVIF."bun" — static codecs + Highway geometry only. Byte-identical to a Linux build; HEIC/AVIF reject with ERR_IMAGE_FORMAT_UNSUPPORTED.

Set before awaiting a pipeline; in-flight tasks read the value as of when they were scheduled.

avif(options?: { quality: number }): this;

Set output format to AVIF. Requires an OS AV1 encoder (macOS on Apple Silicon M3+, or Windows with the AV1 Video Extension) — the terminal rejects with error.code === "ERR_IMAGE_FORMAT_UNSUPPORTED" elsewhere.

blob(): PromiseBlob>;

Run the pipeline and return a Blob with the matching type.

buffer(): PromiseBufferArrayBufferLike>>;

Like bytes but as a Node Buffer.

bytes(): PromiseUint8ArrayArrayBufferLike>>;

Run the pipeline and return the encoded bytes. If no format setter was called, re-encodes in the source format.

`." data-algolia-static="false" data-algolia-merged="false" data-type="Method">dataurl(): Promisestring>;

Like toBase64 with a data:image/{format};base64, prefix. Drops straight into .

flip(): this;

Mirror about the x-axis (vertical).

flop(): this;

Mirror about the y-axis (horizontal).

heic(options?: { quality: number }): this;

Set output format to HEIC. macOS / Windows-with-HEIF-Extension only — the terminal rejects with error.code === "ERR_IMAGE_FORMAT_UNSUPPORTED" elsewhere.

jpeg(options?: { progressive: boolean; quality: number }): this;

Set output format to JPEG.

metadata(): PromiseMetadata>;

Decode just enough to read width/height/format.

modulate(options: ModulateOptions): this;

Adjust brightness/saturation.

` or Next's `blurDataURL`; no client-side decoder needed. ```ts const lqip = await Bun.file("hero.jpg").image().placeholder(); // "data:image/png;base64,iVBORw0KGgoAAAANSUhE…" ```" data-algolia-static="false" data-algolia-merged="false" data-type="Method">placeholder(as?: 'dataurl'): Promisestring>;

A ThumbHash-rendered low-quality placeholder of the source image as a data:image/png;base64,… URL — a ≤32px blur with the right average colour, aspect ratio and rough structure, ~400–700 bytes. Ready for or Next's blurDataURL; no client-side decoder needed.

const lqip = await Bun.file("hero.jpg").image().placeholder();
// "data:image/png;base64,iVBORw0KGgoAAAANSUhE…"
png(options?: { colors: number; compressionLevel: number; dither: boolean; palette: boolean }): this;

Set output format to PNG.

resize(width: number,height?: number,options?: ResizeOptions): this;

Set target dimensions. Omit height to keep the source aspect ratio.

rotate(degrees: number): this;

Rotate by a multiple of 90°.

toBase64(): Promisestring>;

Run the pipeline and return base64-encoded output.

toBuffer(): PromiseBufferArrayBufferLike>>;

Sharp-compatible alias for buffer.

webp(options?: { lossless: boolean; quality: number }): this;

Set output format to WebP.

write(dest: number | BunFile | PathLike | S3File): Promisenumber>;

Run the pipeline and write the encoded result via Bun.write — dest may be a path string, BunFile, S3File, or fd. Resolves to the number of bytes written.

If no format method was chained and dest is a path string, the format is inferred from its extension when it's one Bun can encode (.jpg/.png/.webp/.heic/.avif); otherwise the source format is reused.

static clipboardChangeCount(): number;

Monotone counter that increments on every system-wide clipboard write. Poll this and only call hasClipboardImage when it moves. -1 on Linux.

static fromClipboard(): null | Image;

Read an image from the system clipboard.

Returns a Bun.Image wrapping whatever container the clipboard holds (PNG, TIFF, HEIC, JPEG, BMP, …); call metadata, resize, etc. as usual. null if no image is present.

macOS: NSPasteboardWindows: registered "PNG" / CF_DIBV5 / CF_DIBLinux: always null (use wl-paste/xclip and pass the bytes to new Bun.Image(...))
static hasClipboardImage(): boolean;

Cheap probe — true if fromClipboard would return non-null.

class MD4

This class only exists in types

readonly static byteLength: 16

The number of bytes the hash will produce

digest(encoding: DigestEncoding): string;

Finalize the hash

@param encoding

DigestEncoding to return the hash in. If none is provided, it will return a Uint8Array.

digest(hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Finalize the hash

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

update(data: BlobOrStringOrBuffer): MD4;

Update the hash with data

static hash(input: BlobOrStringOrBuffer,hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

static hash(input: BlobOrStringOrBuffer,encoding: DigestEncoding): string;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param encoding

DigestEncoding to return the hash in

class MD5

This class only exists in types

readonly static byteLength: 16

The number of bytes the hash will produce

digest(encoding: DigestEncoding): string;

Finalize the hash

@param encoding

DigestEncoding to return the hash in. If none is provided, it will return a Uint8Array.

digest(hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Finalize the hash

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

update(data: BlobOrStringOrBuffer): MD5;

Update the hash with data

static hash(input: BlobOrStringOrBuffer,hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

static hash(input: BlobOrStringOrBuffer,encoding: DigestEncoding): string;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param encoding

DigestEncoding to return the hash in

class RedisClientreadonly bufferedAmount: number

Amount of data buffered in bytes

readonly connected: boolean

Whether the client is connected to the Redis server

onclose: null | (this: RedisClient, error: Error) => void

Callback fired when the client disconnects from the Redis server

onconnect: null | (this: RedisClient) => void

Callback fired when the client connects to the Redis server

append(key: KeyLike,value: KeyLike): Promisenumber>;

Append a value to a key

@param key

The key to append to

@param value

The value to append

@returns

Promise that resolves with the length of the string after the append operation

bitcount(key: KeyLike): Promisenumber>;

Count the number of set bits (population counting) in a string

@param key

The key to count bits in

@returns

Promise that resolves with the number of bits set to 1

blmove(source: KeyLike,destination: KeyLike,from: 'LEFT' | 'RIGHT',to: 'LEFT' | 'RIGHT',timeout: number): Promisenull | string>;

Blocking move from one list to another

Atomically moves an element from source to destination list, blocking until an element is available or the timeout expires. Allows specifying which end to pop from (LEFT/RIGHT) and which end to push to (LEFT/RIGHT).

@param source

Source list key

@param destination

Destination list key

@param from

Direction to pop from source: "LEFT" or "RIGHT"

@param to

Direction to push to destination: "LEFT" or "RIGHT"

@param timeout

Timeout in seconds (can be fractional, 0 = block indefinitely)

@returns

Promise that resolves with the moved element or null on timeout

// Move from right of source to left of destination (like BRPOPLPUSH)
const element = await redis.blmove("mylist", "otherlist", "RIGHT", "LEFT", 1.0);
if (element) {
console.log(`Moved element: ${element}`);
}

// Move from left to left
await redis.blmove("list1", "list2", "LEFT", "LEFT", 0.5);
blmpop(timeout: number,numkeys: number,...args: string | number[]): Promisenull | [string, string[]]>;

Blocking pop multiple elements from lists

Blocks until an element is available from one of the specified lists or the timeout expires. Can pop from the LEFT or RIGHT end and optionally pop multiple elements at once using COUNT.

@param timeout

Timeout in seconds (can be fractional, 0 = block indefinitely)

@param numkeys

Number of keys that follow

@param args

Keys, direction ("LEFT" or "RIGHT"), and optional COUNT modifier

@returns

Promise that resolves with [key, [elements]] or null on timeout

// Pop from left end of first available list, wait 1 second
const result = await redis.blmpop(1.0, 2, "list1", "list2", "LEFT");
if (result) {
const [key, elements] = result;
console.log(`Popped from ${key}: ${elements.join(", ")}`);
}

// Pop 3 elements from right end
const result2 = await redis.blmpop(0.5, 1, "mylist", "RIGHT", "COUNT", 3);
// Returns: ["mylist", ["elem1", "elem2", "elem3"]] or null if timeout
blpop(...args: number | KeyLike[]): Promisenull | [string, string]>;

Blocking pop from head of one or more lists

Blocks until an element is available in one of the lists or the timeout expires. Checks keys in order and pops from the first non-empty list.

@param args

Keys followed by timeout in seconds (can be fractional, 0 = block indefinitely)

@returns

Promise that resolves with [key, element] or null on timeout

// Block for up to 1 second
const result = await redis.blpop("mylist", 1.0);
if (result) {
const [key, element] = result;
console.log(`Popped ${element} from ${key}`);
}

// Block indefinitely (timeout = 0)
const result2 = await redis.blpop("list1", "list2", 0);
brpop(...args: number | KeyLike[]): Promisenull | [string, string]>;

Blocking pop from tail of one or more lists

Blocks until an element is available in one of the lists or the timeout expires. Checks keys in order and pops from the first non-empty list.

@param args

Keys followed by timeout in seconds (can be fractional, 0 = block indefinitely)

@returns

Promise that resolves with [key, element] or null on timeout

// Block for up to 1 second
const result = await redis.brpop("mylist", 1.0);
if (result) {
const [key, element] = result;
console.log(`Popped ${element} from ${key}`);
}

// Block indefinitely (timeout = 0)
const result2 = await redis.brpop("list1", "list2", 0);
brpoplpush(source: KeyLike,destination: KeyLike,timeout: number): Promisenull | string>;

Blocking right pop from source and left push to destination

Atomically pops an element from the tail of source list and pushes it to the head of destination list, blocking until an element is available or the timeout expires. This is the blocking version of RPOPLPUSH.

@param source

Source list key

@param destination

Destination list key

@param timeout

Timeout in seconds (can be fractional, 0 = block indefinitely)

@returns

Promise that resolves with the moved element or null on timeout

// Block for up to 1 second
const element = await redis.brpoplpush("tasks", "processing", 1.0);
if (element) {
console.log(`Processing task: ${element}`);
} else {
console.log("No tasks available");
}

// Block indefinitely (timeout = 0)
const task = await redis.brpoplpush("queue", "active", 0);
bzmpop(timeout: number,numkeys: number,...args: string | number[]): Promisenull | [string, [string, number][]]>;

Blocking version of ZMPOP. Blocks until a member is available or timeout expires.

// Block for 5 seconds waiting for a member
const result1 = await redis.bzmpop(5, 1, "myzset", "MIN");
// Returns: ["myzset", [["member1", 1]]] or null if timeout

// Block indefinitely (timeout 0)
const result2 = await redis.bzmpop(0, 2, "zset1", "zset2", "MAX");
// Returns: ["zset1", [["member5", 5]]]

// Block with COUNT option
const result3 = await redis.bzmpop(1, 1, "myzset", "MIN", "COUNT", 2);
// Returns: ["myzset", [["member1", 1], ["member2", 2]]] or null if timeout
bzpopmax(...args: number | KeyLike[]): Promisenull | [string, string, number]>;

Remove and return the member with the highest score from one or more sorted sets, or block until one is available

@param args

Keys followed by timeout in seconds (e.g., "key1", "key2", 1.0)

@returns

Promise that resolves with [key, member, score] or null if timeout

// Block for up to 1 second waiting for an element
const result = await redis.bzpopmax("myzset", 1.0);
if (result) {
const [key, member, score] = result;
console.log(`Popped ${member} with score ${score} from ${key}`);
}
bzpopmin(...args: number | KeyLike[]): Promisenull | [string, string, number]>;

Remove and return the member with the lowest score from one or more sorted sets, or block until one is available

@param args

Keys followed by timeout in seconds (e.g., "key1", "key2", 1.0)

@returns

Promise that resolves with [key, member, score] or null if timeout

// Block for up to 1 second waiting for an element
const result = await redis.bzpopmin("myzset", 1.0);
if (result) {
const [key, member, score] = result;
console.log(`Popped ${member} with score ${score} from ${key}`);
}
close(): void;

Disconnect from the Redis server

connect(): Promisevoid>;

Connect to the Redis server

@returns

A promise that resolves when connected

copy(source: KeyLike,destination: KeyLike): Promisenumber>;

Copy the value stored at the source key to the destination key

By default, the destination key is created in the logical database used by the connection. The REPLACE option removes the destination key before copying the value to it.

@param source

The source key to copy from

@param destination

The destination key to copy to

@returns

Promise that resolves with 1 if the key was copied, 0 if not

await redis.set("mykey", "Hello");
await redis.copy("mykey", "myotherkey");
console.log(await redis.get("myotherkey")); // "Hello"
copy(source: KeyLike,destination: KeyLike,replace: 'REPLACE'): Promisenumber>;

Copy the value stored at the source key to the destination key, optionally replacing it

The REPLACE option removes the destination key before copying the value to it.

@param source

The source key to copy from

@param destination

The destination key to copy to

@param replace

"REPLACE" - Remove the destination key before copying

@returns

Promise that resolves with 1 if the key was copied, 0 if not

await redis.set("mykey", "Hello");
await redis.set("myotherkey", "World");
await redis.copy("mykey", "myotherkey", "REPLACE");
console.log(await redis.get("myotherkey")); // "Hello"
decr(key: KeyLike): Promisenumber>;

Decrement the integer value of a key by one

@param key

The key to decrement

@returns

Promise that resolves with the new value

decrby(key: KeyLike,decrement: number): Promisenumber>;

Decrement the integer value of a key by the given amount

@param key

The key to decrement

@param decrement

The amount to decrement by

@returns

Promise that resolves with the new value after decrementing

del(...keys: KeyLike[]): Promisenumber>;

Delete a key(s)

@param keys

The keys to delete

@returns

Promise that resolves with the number of keys removed

dump(key: KeyLike): Promisenull | string>;

Return a serialized version of the value stored at the specified key

@param key

The key to dump

@returns

Promise that resolves with the serialized value, or null if the key doesn't exist

duplicate(): PromiseRedisClient>;
exists(key: KeyLike): Promiseboolean>;

Determine if a key exists

@param key

The key to check

@returns

Promise that resolves with true if the key exists, false otherwise

expire(key: KeyLike,seconds: number): Promisenumber>;

Set a key's time to live in seconds

@param key

The key to set the expiration for

@param seconds

The number of seconds until expiration

@returns

Promise that resolves with 1 if the timeout was set, 0 if not

expireat(key: KeyLike,timestamp: number): Promisenumber>;

Set the expiration for a key as a Unix timestamp (in seconds)

@param key

The key to set expiration on

@param timestamp

Unix timestamp in seconds when the key should expire

@returns

Promise that resolves with 1 if timeout was set, 0 if key does not exist

expiretime(key: KeyLike): Promisenumber>;

Get the expiration time of a key as a UNIX timestamp in seconds

@param key

The key to check

@returns

Promise that resolves with the timestamp, or -1 if the key has no expiration, or -2 if the key doesn't exist

get(key: KeyLike): Promisenull | string>;

Get the value of a key

@param key

The key to get

@returns

Promise that resolves with the key's value as a string, or null if the key doesn't exist

getbit(key: KeyLike,offset: number): Promisenumber>;

Returns the bit value at offset in the string value stored at key

@param key

The key containing the string value

@param offset

The bit offset (zero-based)

@returns

Promise that resolves with the bit value (0 or 1) at the specified offset

getBuffer(key: KeyLike): Promisenull | Uint8ArrayArrayBuffer>>;

Get the value of a key as a Uint8Array

@param key

The key to get

@returns

Promise that resolves with the key's value as a Uint8Array, or null if the key doesn't exist

getdel(key: KeyLike): Promisenull | string>;

Get the value of a key and delete the key

@param key

The key to get and delete

@returns

Promise that resolves with the value of the key, or null if the key doesn't exist

getex(key: KeyLike): Promisenull | string>;

Get the value of a key and optionally set its expiration

@param key

The key to get

@returns

Promise that resolves with the value of the key, or null if the key doesn't exist

getex(key: KeyLike,ex: 'EX',seconds: number): Promisenull | string>;

Get the value of a key and set its expiration in seconds

@param key

The key to get

@param ex

Set the specified expire time, in seconds

@param seconds

The number of seconds until expiration

@returns

Promise that resolves with the value of the key, or null if the key doesn't exist

getex(key: KeyLike,px: 'PX',milliseconds: number): Promisenull | string>;

Get the value of a key and set its expiration in milliseconds

@param key

The key to get

@param px

Set the specified expire time, in milliseconds

@param milliseconds

The number of milliseconds until expiration

@returns

Promise that resolves with the value of the key, or null if the key doesn't exist

getex(key: KeyLike,exat: 'EXAT',timestampSeconds: number): Promisenull | string>;

Get the value of a key and set its expiration at a specific Unix timestamp in seconds

@param key

The key to get

@param exat

Set the specified Unix time at which the key will expire, in seconds

@param timestampSeconds

The Unix timestamp in seconds

@returns

Promise that resolves with the value of the key, or null if the key doesn't exist

getex(key: KeyLike,pxat: 'PXAT',timestampMilliseconds: number): Promisenull | string>;

Get the value of a key and set its expiration at a specific Unix timestamp in milliseconds

@param key

The key to get

@param pxat

Set the specified Unix time at which the key will expire, in milliseconds

@param timestampMilliseconds

The Unix timestamp in milliseconds

@returns

Promise that resolves with the value of the key, or null if the key doesn't exist

getex(key: KeyLike,persist: 'PERSIST'): Promisenull | string>;

Get the value of a key and remove its expiration

@param key

The key to get

@param persist

Remove the expiration from the key

@returns

Promise that resolves with the value of the key, or null if the key doesn't exist

getrange(key: KeyLike,start: number,end: number): Promisestring>;

Get a substring of the string stored at a key

@param key

The key to get the substring from

@param start

The starting offset (can be negative to count from the end)

@param end

The ending offset (can be negative to count from the end)

@returns

Promise that resolves with the substring, or an empty string if the key doesn't exist

getset(key: KeyLike,value: KeyLike): Promisenull | string>;

Set the value of a key and return its old value

@param key

The key to set

@param value

The value to set

@returns

Promise that resolves with the old value, or null if the key didn't exist

hdel(key: KeyLike,field: KeyLike,...rest: KeyLike[]): Promisenumber>;

Delete one or more hash fields

@param key

The hash key

@param field

The field to delete

@param rest

Additional fields to delete

@returns

Promise that resolves with the number of fields that were removed

hexists(key: KeyLike,field: KeyLike): Promiseboolean>;

Determine if a hash field exists

@param key

The hash key

@param field

The field to check

@returns

Promise that resolves with true if the field exists, false otherwise

hexpire(key: KeyLike,seconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Set expiration for hash fields (Redis 7.4+) Syntax: HEXPIRE key seconds [NX | XX | GT | LT] FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), 0 (condition not met), 1 (expiration set), 2 (field deleted)

redis.hexpire("mykey", 10, "FIELDS", 1, "field1")
hexpire(key: KeyLike,seconds: number,condition: 'NX' | 'XX' | 'GT' | 'LT',fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Set expiration for hash fields (Redis 7.4+) Syntax: HEXPIRE key seconds [NX | XX | GT | LT] FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), 0 (condition not met), 1 (expiration set), 2 (field deleted)

redis.hexpire("mykey", 10, "FIELDS", 1, "field1")
hexpireat(key: KeyLike,unixTimeSeconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Set expiration for hash fields using Unix timestamp in seconds (Redis 7.4+) Syntax: HEXPIREAT key unix-time-seconds [NX | XX | GT | LT] FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), 0 (condition not met), 1 (expiration set), 2 (field deleted)

redis.hexpireat("mykey", 1735689600, "FIELDS", 1, "field1")
hexpireat(key: KeyLike,unixTimeSeconds: number,condition: 'NX' | 'XX' | 'GT' | 'LT',fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Set expiration for hash fields using Unix timestamp in seconds (Redis 7.4+) Syntax: HEXPIREAT key unix-time-seconds [NX | XX | GT | LT] FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), 0 (condition not met), 1 (expiration set), 2 (field deleted)

redis.hexpireat("mykey", 1735689600, "FIELDS", 1, "field1")
hexpiretime(key: KeyLike,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Get expiration time of hash fields as Unix timestamp in seconds (Redis 7.4+) Syntax: HEXPIRETIME key FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), -1 (no expiration), Unix timestamp in seconds

redis.hexpiretime("mykey", "FIELDS", 2, "field1", "field2")
hget(key: KeyLike,field: KeyLike): Promisenull | string>;

Get the value of a hash field

@param key

The hash key

@param field

The field to get

@returns

Promise that resolves with the field value or null if the field doesn't exist

hgetall(key: KeyLike): PromiseRecordstring, string>>;

Get all the fields and values in a hash

@param key

The hash key

@returns

Promise that resolves with an object containing all fields and values, or empty object if key does not exist

hgetdel(key: KeyLike,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenull | string[]>;

Get and delete one or more hash fields (Redis 8.0.0+) Syntax: HGETDEL key FIELDS numfields field [field ...]

@param key

The hash key

@param fieldsKeyword

Must be the literal string "FIELDS"

@param numfields

Number of fields to follow

@param fields

The field names to get and delete

@returns

Promise that resolves with array of field values (null for non-existent fields)

redis.hgetdel("mykey", "FIELDS", 2, "field1", "field2")
hgetex(key: KeyLike,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenull | string[]>;

Get hash field values with expiration options (Redis 8.0.0+) Syntax: HGETEX key [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | PERSIST] FIELDS numfields field [field ...]

redis.hgetex("mykey", "FIELDS", 1, "field1")
hgetex(key: KeyLike,ex: 'EX',seconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenull | string[]>;

Get hash field values with expiration options (Redis 8.0.0+) Syntax: HGETEX key [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | PERSIST] FIELDS numfields field [field ...]

redis.hgetex("mykey", "FIELDS", 1, "field1")
hgetex(key: KeyLike,px: 'PX',milliseconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenull | string[]>;

Get hash field values with expiration options (Redis 8.0.0+) Syntax: HGETEX key [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | PERSIST] FIELDS numfields field [field ...]

redis.hgetex("mykey", "FIELDS", 1, "field1")
hgetex(key: KeyLike,exat: 'EXAT',unixTimeSeconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenull | string[]>;

Get hash field values with expiration options (Redis 8.0.0+) Syntax: HGETEX key [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | PERSIST] FIELDS numfields field [field ...]

redis.hgetex("mykey", "FIELDS", 1, "field1")
hgetex(key: KeyLike,pxat: 'PXAT',unixTimeMilliseconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenull | string[]>;

Get hash field values with expiration options (Redis 8.0.0+) Syntax: HGETEX key [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | PERSIST] FIELDS numfields field [field ...]

redis.hgetex("mykey", "FIELDS", 1, "field1")
hgetex(key: KeyLike,persist: 'PERSIST',fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenull | string[]>;

Get hash field values with expiration options (Redis 8.0.0+) Syntax: HGETEX key [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | PERSIST] FIELDS numfields field [field ...]

redis.hgetex("mykey", "FIELDS", 1, "field1")
hincrby(key: KeyLike,field: string,increment: string | number): Promisenumber>;

Increment the integer value of a hash field by the given number

@param key

The hash key

@param field

The field to increment

@param increment

The amount to increment by

@returns

Promise that resolves with the new value

hincrbyfloat(key: KeyLike,field: string,increment: string | number): Promisestring>;

Increment the float value of a hash field by the given amount

@param key

The hash key

@param field

The field to increment

@param increment

The amount to increment by

@returns

Promise that resolves with the new value as a string

hkeys(key: KeyLike): Promisestring[]>;

Get all field names in a hash

@param key

The hash key

@returns

Promise that resolves with an array of field names

hlen(key: KeyLike): Promisenumber>;

Get the number of fields in a hash

@param key

The hash key

@returns

Promise that resolves with the number of fields

hmget(key: KeyLike,fields: string[]): Promisenull | string[]>;

Get the values of all the given hash fields

@param key

The hash key

@param fields

The fields to get

@returns

Promise that resolves with an array of values

hpersist(key: KeyLike,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Remove expiration from hash fields (Redis 7.4+) Syntax: HPERSIST key FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), -1 (no expiration), 1 (expiration removed)

redis.hpersist("mykey", "FIELDS", 1, "field1")
hpexpire(key: KeyLike,milliseconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Set expiration for hash fields in milliseconds (Redis 7.4+) Syntax: HPEXPIRE key milliseconds [NX | XX | GT | LT] FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), 0 (condition not met), 1 (expiration set), 2 (field deleted)

redis.hpexpire("mykey", 10000, "FIELDS", 1, "field1")
hpexpire(key: KeyLike,milliseconds: number,condition: 'NX' | 'XX' | 'GT' | 'LT',fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Set expiration for hash fields in milliseconds (Redis 7.4+) Syntax: HPEXPIRE key milliseconds [NX | XX | GT | LT] FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), 0 (condition not met), 1 (expiration set), 2 (field deleted)

redis.hpexpire("mykey", 10000, "FIELDS", 1, "field1")
hpexpireat(key: KeyLike,unixTimeMilliseconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Set expiration for hash fields using Unix timestamp in milliseconds (Redis 7.4+) Syntax: HPEXPIREAT key unix-time-milliseconds [NX | XX | GT | LT] FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), 0 (condition not met), 1 (expiration set), 2 (field deleted)

redis.hpexpireat("mykey", 1735689600000, "FIELDS", 1, "field1")
hpexpireat(key: KeyLike,unixTimeMilliseconds: number,condition: 'NX' | 'XX' | 'GT' | 'LT',fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Set expiration for hash fields using Unix timestamp in milliseconds (Redis 7.4+) Syntax: HPEXPIREAT key unix-time-milliseconds [NX | XX | GT | LT] FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), 0 (condition not met), 1 (expiration set), 2 (field deleted)

redis.hpexpireat("mykey", 1735689600000, "FIELDS", 1, "field1")
hpexpiretime(key: KeyLike,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Get expiration time of hash fields as Unix timestamp in milliseconds (Redis 7.4+) Syntax: HPEXPIRETIME key FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), -1 (no expiration), Unix timestamp in milliseconds

redis.hpexpiretime("mykey", "FIELDS", 2, "field1", "field2")
hpttl(key: KeyLike,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Get TTL of hash fields in milliseconds (Redis 7.4+) Syntax: HPTTL key FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), -1 (no expiration), TTL in milliseconds

redis.hpttl("mykey", "FIELDS", 2, "field1", "field2")
hrandfield(key: KeyLike): Promisenull | string>;

Get one or multiple random fields from a hash

@param key

The hash key

@returns

Promise that resolves with a random field name, or null if the hash doesn't exist

hrandfield(key: KeyLike,count: number): Promisestring[]>;

Get one or multiple random fields from a hash

@param key

The hash key

@param count

The number of fields to return (positive for unique fields, negative for potentially duplicate fields)

@returns

Promise that resolves with an array of random field names

hrandfield(key: KeyLike,count: number,withValues: 'WITHVALUES'): Promise[string, string][]>;

Get one or multiple random fields with values from a hash

@param key

The hash key

@param count

The number of fields to return

@param withValues

Literal "WITHVALUES" to include values

@returns

Promise that resolves with an array of alternating field names and values

hscan(key: KeyLike,cursor: string | number): Promise[string, string[]]>;

Incrementally iterate hash fields and values

@param key

The hash key

@param cursor

The cursor value (0 to start iteration)

@returns

Promise that resolves with [next_cursor, [field1, value1, field2, value2, ...]]

hscan(key: KeyLike,cursor: string | number,match: 'MATCH',pattern: string): Promise[string, string[]]>;

Incrementally iterate hash fields and values with pattern matching

@param key

The hash key

@param cursor

The cursor value (0 to start iteration)

@param match

Literal "MATCH"

@param pattern

Pattern to match field names against

@returns

Promise that resolves with [next_cursor, [field1, value1, field2, value2, ...]]

hscan(key: KeyLike,cursor: string | number,count: 'COUNT',limit: number): Promise[string, string[]]>;

Incrementally iterate hash fields and values with count limit

@param key

The hash key

@param cursor

The cursor value (0 to start iteration)

@param count

Literal "COUNT"

@param limit

Maximum number of fields to return per call

@returns

Promise that resolves with [next_cursor, [field1, value1, field2, value2, ...]]

hscan(key: KeyLike,cursor: string | number,match: 'MATCH',pattern: string,count: 'COUNT',limit: number): Promise[string, string[]]>;

Incrementally iterate hash fields and values with pattern and count

@param key

The hash key

@param cursor

The cursor value (0 to start iteration)

@param match

Literal "MATCH"

@param pattern

Pattern to match field names against

@param count

Literal "COUNT"

@param limit

Maximum number of fields to return per call

@returns

Promise that resolves with [next_cursor, [field1, value1, field2, value2, ...]]

hset(key: KeyLike,fields: Recordstring | number, number | KeyLike>): Promisenumber>;

Set the value of a hash field or multiple fields

@param key

The hash key

@param fields

Object/Record with field-value pairs

@returns

Promise that resolves with the number of fields that were added

hset(key: KeyLike,field: KeyLike,value: KeyLike,...rest: KeyLike[]): Promisenumber>;

Set the value of a hash field or multiple fields (variadic)

@param key

The hash key

@param field

The field name

@param value

The value to set

@param rest

Additional field-value pairs

@returns

Promise that resolves with the number of fields that were added

hsetex(key: KeyLike,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fnx: 'FNX',fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fxx: 'FXX',fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,ex: 'EX',seconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,px: 'PX',milliseconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,exat: 'EXAT',unixTimeSeconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,pxat: 'PXAT',unixTimeMilliseconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,keepttl: 'KEEPTTL',fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fnx: 'FNX',ex: 'EX',seconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fnx: 'FNX',px: 'PX',milliseconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fnx: 'FNX',exat: 'EXAT',unixTimeSeconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fnx: 'FNX',pxat: 'PXAT',unixTimeMilliseconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fnx: 'FNX',keepttl: 'KEEPTTL',fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fxx: 'FXX',ex: 'EX',seconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fxx: 'FXX',px: 'PX',milliseconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fxx: 'FXX',exat: 'EXAT',unixTimeSeconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fxx: 'FXX',pxat: 'PXAT',unixTimeMilliseconds: number,fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetex(key: KeyLike,fxx: 'FXX',keepttl: 'KEEPTTL',fieldsKeyword: 'FIELDS',numfields: number,...fieldValues: KeyLike[]): Promisenumber>;

Set hash fields with expiration options (Redis 8.0.0+) Syntax: HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]

redis.hsetex("mykey", "FIELDS", 1, "field1", "value1")
hsetnx(key: KeyLike,field: KeyLike,value: KeyLike): Promiseboolean>;

Set the value of a hash field, only if the field does not exist

@param key

The hash key

@param field

The field to set

@param value

The value to set

@returns

Promise that resolves with true if field was set, false if field already exists

hstrlen(key: KeyLike,field: string): Promisenumber>;

Get the string length of the value stored in a hash field

@param key

The hash key

@param field

The field name

@returns

Promise that resolves with the length of the string value, or 0 if the field doesn't exist

httl(key: KeyLike,fieldsKeyword: 'FIELDS',numfields: number,...fields: KeyLike[]): Promisenumber[]>;

Get TTL of hash fields in seconds (Redis 7.4+) Syntax: HTTL key FIELDS numfields field [field ...]

@returns

Array where each element is: -2 (field doesn't exist), -1 (no expiration), TTL in seconds

redis.httl("mykey", "FIELDS", 2, "field1", "field2")
hvals(key: KeyLike): Promisestring[]>;

Get all values in a hash

@param key

The hash key

@returns

Promise that resolves with an array of values

incr(key: KeyLike): Promisenumber>;

Increment the integer value of a key by one

@param key

The key to increment

@returns

Promise that resolves with the new value

incrby(key: KeyLike,increment: number): Promisenumber>;

Increment the integer value of a key by the given amount

@param key

The key to increment

@param increment

The amount to increment by

@returns

Promise that resolves with the new value after incrementing

incrbyfloat(key: KeyLike,increment: string | number): Promisestring>;

Increment the float value of a key by the given amount

@param key

The key to increment

@param increment

The amount to increment by (can be a float)

@returns

Promise that resolves with the new value as a string after incrementing

keys(pattern: string): Promisestring[]>;

Find all keys matching the given pattern

@param pattern

The pattern to match

@returns

Promise that resolves with an array of matching keys

lindex(key: KeyLike,index: number): Promisenull | string>;

Get element at index from a list

@param key

The list key

@param index

Zero-based index (negative indexes count from the end, -1 is last element)

@returns

Promise that resolves with the element at index, or null if index is out of range

await redis.lpush("mylist", "three", "two", "one");
console.log(await redis.lindex("mylist", 0)); // "one"
console.log(await redis.lindex("mylist", -1)); // "three"
console.log(await redis.lindex("mylist", 5)); // null
linsert(key: KeyLike,position: 'BEFORE' | 'AFTER',pivot: KeyLike,element: KeyLike): Promisenumber>;

Insert an element before or after another element in a list

@param key

The list key

@param position

"BEFORE" or "AFTER" to specify where to insert

@param pivot

The pivot element to insert before or after

@param element

The element to insert

@returns

Promise that resolves with the length of the list after insert, -1 if pivot not found, or 0 if key doesn't exist

await redis.lpush("mylist", "World");
await redis.lpush("mylist", "Hello");
await redis.linsert("mylist", "BEFORE", "World", "There");
// List is now: ["Hello", "There", "World"]
llen(key: KeyLike): Promisenumber>;

Get the length of a list

@param key

The list key

@returns

Promise that resolves with the length of the list

lmove(source: KeyLike,destination: KeyLike,from: 'LEFT' | 'RIGHT',to: 'LEFT' | 'RIGHT'): Promisenull | string>;

Atomically pop an element from a source list and push it to a destination list

Pops an element from the source list (from LEFT or RIGHT) and pushes it to the destination list (to LEFT or RIGHT).

@param source

The source list key

@param destination

The destination list key

@param from

Direction to pop from source: "LEFT" (head) or "RIGHT" (tail)

@param to

Direction to push to destination: "LEFT" (head) or "RIGHT" (tail)

@returns

Promise that resolves with the element moved, or null if the source list is empty

await redis.lpush("source", "a", "b", "c");
const result1 = await redis.lmove("source", "dest", "LEFT", "RIGHT");
// result1: "c" (popped from head of source, pushed to tail of dest)

const result2 = await redis.lmove("source", "dest", "RIGHT", "LEFT");
// result2: "a" (popped from tail of source, pushed to head of dest)
lmpop(numkeys: number,...args: string | number[]): Promisenull | [string, string[]]>;

Pop one or more elements from one or more lists

Pops elements from the first non-empty list in the specified order (LEFT = from head, RIGHT = from tail). Optionally specify COUNT to pop multiple elements at once.

@param numkeys

The number of keys that follow

@param args

Keys followed by LEFT or RIGHT, optionally followed by "COUNT" and count value

@returns

Promise that resolves with [key, [elements]] or null if all lists are empty

await redis.lpush("list1", "a", "b", "c");
const result1 = await redis.lmpop(1, "list1", "LEFT");
// result1: ["list1", ["c"]]

const result2 = await redis.lmpop(1, "list1", "RIGHT", "COUNT", 2);
// result2: ["list1", ["a", "b"]]

const result3 = await redis.lmpop(2, "emptylist", "list1", "LEFT");
// result3: null (if both lists are empty)
lpop(key: KeyLike): Promisenull | string>;

Remove and get the first element in a list

@param key

The list key

@returns

Promise that resolves with the first element, or null if the list is empty

lpop(key: KeyLike,count: number): Promisenull | string[]>;

Remove and get the first count elements in a list

@param key

The list key

@returns

Promise that resolves with a list of elements, or null if the list doesn't exist

lpos(key: KeyLike,element: KeyLike,...options: string | number[]): Promisenull | number | number[]>;

Find the position(s) of an element in a list

Returns the index of matching elements inside a Redis list. By default, returns the index of the first match. Use RANK to find the nth occurrence, COUNT to get multiple positions, and MAXLEN to limit the search.

@param key

The list key

@param element

The element to search for

@param options

Optional arguments: "RANK", rank, "COUNT", num, "MAXLEN", len

@returns

Promise that resolves with the index (number), an array of indices (number[]), or null if element is not found. Returns array when COUNT option is used.

await redis.lpush("mylist", "a", "b", "c", "b", "d");
const pos1 = await redis.lpos("mylist", "b");
// pos1: 1 (first occurrence of "b")

const pos2 = await redis.lpos("mylist", "b", "RANK", 2);
// pos2: 3 (second occurrence of "b")

const positions = await redis.lpos("mylist", "b", "COUNT", 0);
// positions: [1, 3] (all occurrences of "b")

const pos3 = await redis.lpos("mylist", "x");
// pos3: null (element not found)
lpush(key: KeyLike,value: KeyLike,...rest: KeyLike[]): Promisenumber>;

Prepend one or multiple values to a list

@param key

The list key

@param value

The value to prepend

@returns

Promise that resolves with the length of the list after the push operation

lpushx(key: KeyLike,value: KeyLike): Promisenumber>;

Prepend a value to a list, only if the list exists

@param key

The list key

@param value

The value to prepend

@returns

Promise that resolves with the length of the list after the push operation, or 0 if the list doesn't exist

lrange(key: KeyLike,start: number,stop: number): Promisestring[]>;

Get a range of elements from a list

@param key

The list key

@param start

Zero-based start index (negative indexes count from the end)

@param stop

Zero-based stop index (negative indexes count from the end)

@returns

Promise that resolves with array of elements in the specified range

await redis.lpush("mylist", "three", "two", "one");
console.log(await redis.lrange("mylist", 0, -1)); // ["one", "two", "three"]
console.log(await redis.lrange("mylist", 0, 1)); // ["one", "two"]
console.log(await redis.lrange("mylist", -2, -1)); // ["two", "three"]
lrem(key: KeyLike,count: number,element: KeyLike): Promisenumber>;

Remove elements from a list

@param key

The list key

@param count

Number of elements to remove

count > 0: Remove count occurrences from head to tailcount count = 0: Remove all occurrences
@param element

The element to remove

@returns

Promise that resolves with the number of elements removed

await redis.rpush("mylist", "hello", "hello", "world", "hello");
await redis.lrem("mylist", 2, "hello"); // Removes first 2 "hello"
// List is now: ["world", "hello"]
lset(key: KeyLike,index: number,element: KeyLike): Promisestring>;

Set element at index in a list

@param key

The list key

@param index

Zero-based index (negative indexes count from the end)

@param element

The value to set

@returns

Promise that resolves with "OK" on success

await redis.lpush("mylist", "three", "two", "one");
await redis.lset("mylist", 0, "zero");
console.log(await redis.lrange("mylist", 0, -1)); // ["zero", "two", "three"]
await redis.lset("mylist", -1, "last");
console.log(await redis.lrange("mylist", 0, -1)); // ["zero", "two", "last"]
ltrim(key: KeyLike,start: number,stop: number): Promisestring>;

Trim a list to the specified range

@param key

The list key

@param start

The start index (0-based, can be negative)

@param stop

The stop index (0-based, can be negative)

@returns

Promise that resolves with "OK"

await redis.rpush("mylist", "one", "two", "three", "four");
await redis.ltrim("mylist", 1, 2);
// List is now: ["two", "three"]
mget(...keys: KeyLike[]): Promisenull | string[]>;

Get the values of all specified keys

@param keys

The keys to get

@returns

Promise that resolves with an array of values, with null for keys that don't exist

mset(...keyValuePairs: KeyLike[]): Promise'OK'>;

Set multiple keys to multiple values atomically

Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. Use MSETNX if you don't want to overwrite existing values.

MSET is atomic, so all given keys are set at once. It is not possible for clients to see that some of the keys were updated while others are unchanged.

@param keyValuePairs

Alternating keys and values (key1, value1, key2, value2, ...)

@returns

Promise that resolves with "OK" on success

await redis.mset("key1", "value1", "key2", "value2");
msetnx(...keyValuePairs: KeyLike[]): Promisenumber>;

Set multiple keys to multiple values, only if none of the keys exist

Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.

Because of this semantic, MSETNX can be used in order to set different keys representing different fields of a unique logic object in a way that ensures that either all the fields or none at all are set.

MSETNX is atomic, so all given keys are set at once. It is not possible for clients to see that some of the keys were updated while others are unchanged.

@param keyValuePairs

Alternating keys and values (key1, value1, key2, value2, ...)

@returns

Promise that resolves with 1 if all keys were set, 0 if no key was set

// Returns 1 if keys don't exist
await redis.msetnx("key1", "value1", "key2", "value2");

// Returns 0 if any key already exists
await redis.msetnx("key1", "newvalue", "key3", "value3");
persist(key: KeyLike): Promisenumber>;

Remove the expiration from a key

@param key

The key to persist

@returns

Promise that resolves with 1 if the timeout was removed, 0 if the key doesn't exist or has no timeout

pexpire(key: KeyLike,milliseconds: number): Promisenumber>;

Set a key's time to live in milliseconds

@param key

The key to set the expiration for

@param milliseconds

The number of milliseconds until expiration

@returns

Promise that resolves with 1 if the timeout was set, 0 if the key does not exist

pexpireat(key: KeyLike,millisecondsTimestamp: number): Promisenumber>;

Set the expiration for a key as a Unix timestamp in milliseconds

@param key

The key to set expiration on

@param millisecondsTimestamp

Unix timestamp in milliseconds when the key should expire

@returns

Promise that resolves with 1 if timeout was set, 0 if key does not exist

pexpiretime(key: KeyLike): Promisenumber>;

Get the expiration time of a key as a UNIX timestamp in milliseconds

@param key

The key to check

@returns

Promise that resolves with the timestamp, or -1 if the key has no expiration, or -2 if the key doesn't exist

pfadd(key: KeyLike,element: string): Promisenumber>;

Add one or more members to a HyperLogLog

@param key

The HyperLogLog key

@param element

The element to add

@returns

Promise that resolves with 1 if the HyperLogLog was altered, 0 otherwise

ping(): Promise'PONG'>;

Ping the server

@returns

Promise that resolves with "PONG" if the server is reachable, or throws an error if the server is not reachable

ping(message: KeyLike): Promisestring>;

Ping the server with a message

@param message

The message to send to the server

@returns

Promise that resolves with the message if the server is reachable, or throws an error if the server is not reachable

psetex(key: KeyLike,milliseconds: number,value: KeyLike): Promise'OK'>;

Set key to hold the string value with expiration time in milliseconds

@param key

The key to set

@param milliseconds

The expiration time in milliseconds

@param value

The value to set

@returns

Promise that resolves with "OK" on success

await redis.psetex("mykey", 10000, "Hello");
// Key will expire after 10000 milliseconds (10 seconds)
pttl(key: KeyLike): Promisenumber>;

Get the time to live for a key in milliseconds

@param key

The key to check

@returns

Promise that resolves with the TTL in milliseconds, or -1 if the key has no expiration, or -2 if the key doesn't exist

publish(channel: string,message: string): Promisenumber>;

Publish a message to a Redis channel.

@param channel

The channel to publish to.

@param message

The message to publish.

@returns

The number of clients that received the message. Note that in a cluster this returns the total number of clients in the same node.

randomkey(): Promisenull | string>;

Return a random key from the keyspace

Returns a random key from the currently selected database.

@returns

Promise that resolves with a random key name, or null if the database is empty

await redis.set("key1", "value1");
await redis.set("key2", "value2");
await redis.set("key3", "value3");
const randomKey = await redis.randomkey();
console.log(randomKey); // One of: "key1", "key2", or "key3"
rename(key: KeyLike,newkey: KeyLike): Promise'OK'>;

Rename a key to a new key

Renames key to newkey. If newkey already exists, it is overwritten. If key does not exist, an error is returned.

@param key

The key to rename

@param newkey

The new key name

@returns

Promise that resolves with "OK" on success

await redis.set("mykey", "Hello");
await redis.rename("mykey", "myotherkey");
const value = await redis.get("myotherkey"); // "Hello"
const oldValue = await redis.get("mykey"); // null
renamenx(key: KeyLike,newkey: KeyLike): Promisenumber>;

Rename a key to a new key only if the new key does not exist

Renames key to newkey only if newkey does not yet exist. If key does not exist, an error is returned.

@param key

The key to rename

@param newkey

The new key name

@returns

Promise that resolves with 1 if the key was renamed, 0 if newkey already exists

await redis.set("mykey", "Hello");
await redis.renamenx("mykey", "myotherkey"); // Returns 1
await redis.set("mykey2", "World");
await redis.renamenx("mykey2", "myotherkey"); // Returns 0 (myotherkey exists)
rpop(key: KeyLike): Promisenull | string>;

Remove and get the last element in a list

@param key

The list key

@returns

Promise that resolves with the last element, or null if the list is empty

rpop(key: KeyLike,count: number): Promisestring[]>;

Remove and get the last element in a list

@param key

The list key

@returns

Promise that resolves with the last element, or null if the list is empty

rpoplpush(source: KeyLike,destination: KeyLike): Promisenull | string>;

Atomically pop the last element from a source list and push it to the head of a destination list

This is equivalent to LMOVE with "RIGHT" "LEFT". It's an atomic operation that removes the last element (tail) from the source list and pushes it to the head of the destination list.

@param source

The source list key

@param destination

The destination list key

@returns

Promise that resolves with the element moved, or null if the source list is empty

await redis.lpush("source", "a", "b", "c");
// source: ["c", "b", "a"]

const result = await redis.rpoplpush("source", "dest");
// result: "a" (removed from tail of source, added to head of dest)
// source: ["c", "b"]
// dest: ["a"]
rpush(key: KeyLike,value: KeyLike,...rest: KeyLike[]): Promisenumber>;

Append one or multiple values to a list

@param key

The list key

@param value

The value to append

@returns

Promise that resolves with the length of the list after the push operation

rpushx(key: KeyLike,value: KeyLike): Promisenumber>;

Append a value to a list, only if the list exists

@param key

The list key

@param value

The value to append

@returns

Promise that resolves with the length of the list after the push operation, or 0 if the list doesn't exist

sadd(key: KeyLike,...members: string[]): Promisenumber>;

Add one or more members to a set

@param key

The set key

@param members

The members to add

@returns

Promise that resolves with the number of members added

scan(cursor: string | number): Promise[string, string[]]>;

Incrementally iterate the keyspace

The SCAN command is used to incrementally iterate over a collection of elements. SCAN iterates the set of keys in the currently selected Redis database.

SCAN is a cursor based iterator. This means that at every call of the command, the server returns an updated cursor that the user needs to use as the cursor argument in the next call.

An iteration starts when the cursor is set to "0", and terminates when the cursor returned by the server is "0".

@param cursor

The cursor value (use "0" to start a new iteration)

@returns

Promise that resolves with a tuple [cursor, keys[]] where cursor is the next cursor to use (or "0" if iteration is complete) and keys is an array of matching keys

// Basic scan - iterate all keys
let cursor = "0";
const allKeys: string[] = [];
do {
const [nextCursor, keys] = await redis.scan(cursor);
allKeys.push(...keys);
cursor = nextCursor;
} while (cursor !== "0");
scan(cursor: string | number,match: 'MATCH',pattern: string): Promise[string, string[]]>;

Incrementally iterate the keyspace with a pattern match

@param cursor

The cursor value (use "0" to start a new iteration)

@param match

The "MATCH" keyword

@param pattern

The pattern to match (supports glob-style patterns like "user:*")

@returns

Promise that resolves with a tuple [cursor, keys[]]

scan(cursor: string | number,count: 'COUNT',hint: number): Promise[string, string[]]>;

Incrementally iterate the keyspace with a count hint

@param cursor

The cursor value (use "0" to start a new iteration)

@param count

The "COUNT" keyword

@param hint

The number of elements to return per call (hint only, not exact)

@returns

Promise that resolves with a tuple [cursor, keys[]]

scan(cursor: string | number,match: 'MATCH',pattern: string,count: 'COUNT',hint: number): Promise[string, string[]]>;

Incrementally iterate the keyspace with pattern match and count hint

@param cursor

The cursor value (use "0" to start a new iteration)

@param match

The "MATCH" keyword

@param pattern

The pattern to match

@param count

The "COUNT" keyword

@param hint

The number of elements to return per call

@returns

Promise that resolves with a tuple [cursor, keys[]]

scan(cursor: string | number,...options: string | number[]): Promise[string, string[]]>;

Incrementally iterate the keyspace with options

@param cursor

The cursor value

@param options

Additional SCAN options (MATCH pattern, COUNT hint, etc.)

@returns

Promise that resolves with a tuple [cursor, keys[]]

scard(key: KeyLike): Promisenumber>;

Get the number of members in a set

@param key

The set key

@returns

Promise that resolves with the cardinality (number of elements) of the set

sdiff(key: KeyLike,...keys: KeyLike[]): Promisestring[]>;

Get the difference of multiple sets

@param key

The first set key

@param keys

Additional set keys to subtract from the first set

@returns

Promise that resolves with an array of members in the difference

sdiffstore(destination: KeyLike,key: KeyLike,...keys: KeyLike[]): Promisenumber>;

Store the difference of multiple sets in a key

@param destination

The destination key to store the result

@param key

The first set key

@param keys

Additional set keys to subtract from the first set

@returns

Promise that resolves with the number of elements in the resulting set

send(command: string,args: string[]): Promiseany>;

Send a raw command to the Redis server

@param command

The command to send

@param args

The arguments to the command

@returns

A promise that resolves with the command result

set(key: KeyLike,value: KeyLike): Promise'OK'>;

Set key to hold the string value

@param key

The key to set

@param value

The value to set

@returns

Promise that resolves with "OK" on success

set(key: KeyLike,value: KeyLike,ex: 'EX',seconds: number): Promise'OK'>;

Set key to hold the string value with expiration

@param key

The key to set

@param value

The value to set

@param ex

Set the specified expire time, in seconds

@returns

Promise that resolves with "OK" on success

set(key: KeyLike,value: KeyLike,px: 'PX',milliseconds: number): Promise'OK'>;

Set key to hold the string value with expiration

@param key

The key to set

@param value

The value to set

@param px

Set the specified expire time, in milliseconds

@returns

Promise that resolves with "OK" on success

set(key: KeyLike,value: KeyLike,exat: 'EXAT',timestampSeconds: number): Promise'OK'>;

Set key to hold the string value with expiration at a specific Unix timestamp

@param key

The key to set

@param value

The value to set

@param exat

Set the specified Unix time at which the key will expire, in seconds

@returns

Promise that resolves with "OK" on success

set(key: KeyLike,value: KeyLike,pxat: 'PXAT',timestampMilliseconds: number): Promise'OK'>;

Set key to hold the string value with expiration at a specific Unix timestamp

@param key

The key to set

@param value

The value to set

@param pxat

Set the specified Unix time at which the key will expire, in milliseconds

@returns

Promise that resolves with "OK" on success

set(key: KeyLike,value: KeyLike,nx: 'NX'): Promisenull | 'OK'>;

Set key to hold the string value only if key does not exist

@param key

The key to set

@param value

The value to set

@param nx

Only set the key if it does not already exist

@returns

Promise that resolves with "OK" on success, or null if the key already exists

set(key: KeyLike,value: KeyLike,xx: 'XX'): Promisenull | 'OK'>;

Set key to hold the string value only if key already exists

@param key

The key to set

@param value

The value to set

@param xx

Only set the key if it already exists

@returns

Promise that resolves with "OK" on success, or null if the key does not exist

set(key: KeyLike,value: KeyLike,get: 'GET'): Promisenull | string>;

Set key to hold the string value and return the old value

@param key

The key to set

@param value

The value to set

@param get

Return the old string stored at key, or null if key did not exist

@returns

Promise that resolves with the old value, or null if key did not exist

set(key: KeyLike,value: KeyLike,keepttl: 'KEEPTTL'): Promise'OK'>;

Set key to hold the string value and retain the time to live

@param key

The key to set

@param value

The value to set

@param keepttl

Retain the time to live associated with the key

@returns

Promise that resolves with "OK" on success

set(key: KeyLike,value: KeyLike,...options: string[]): Promisenull | string>;

Set key to hold the string value with various options

@param key

The key to set

@param value

The value to set

@param options

Array of options (EX, PX, EXAT, PXAT, NX, XX, KEEPTTL, GET)

@returns

Promise that resolves with "OK" on success, null if NX/XX condition not met, or the old value if GET is specified

setbit(key: KeyLike,offset: number,value: 0 | 1): Promisenumber>;

Sets or clears the bit at offset in the string value stored at key

@param key

The key to modify

@param offset

The bit offset (zero-based)

@param value

The bit value to set (0 or 1)

@returns

Promise that resolves with the original bit value stored at offset

setex(key: KeyLike,seconds: number,value: KeyLike): Promise'OK'>;

Set key to hold the string value with expiration time in seconds

@param key

The key to set

@param seconds

The expiration time in seconds

@param value

The value to set

@returns

Promise that resolves with "OK" on success

await redis.setex("mykey", 10, "Hello");
// Key will expire after 10 seconds
setnx(key: KeyLike,value: KeyLike): Promisenumber>;

Set the value of a key, only if the key does not exist

@param key

The key to set

@param value

The value to set

@returns

Promise that resolves with 1 if the key was set, 0 if the key was not set

setrange(key: KeyLike,offset: number,value: KeyLike): Promisenumber>;

Overwrite part of a string at key starting at the specified offset

@param key

The key to modify

@param offset

The offset at which to start overwriting (zero-based)

@param value

The string value to write at the offset

@returns

Promise that resolves with the length of the string after modification

sinter(key: KeyLike,...keys: KeyLike[]): Promisestring[]>;

Get the intersection of multiple sets

@param key

The first set key

@param keys

Additional set keys to intersect

@returns

Promise that resolves with an array of members in the intersection

sintercard(numkeys: number,key: KeyLike,...args: number | KeyLike[]): Promisenumber>;

Get the cardinality of the intersection of multiple sets

@param numkeys

The number of keys to intersect

@param key

The first set key

@param args

Additional set keys and optional LIMIT argument

@returns

Promise that resolves with the number of elements in the intersection

sinterstore(destination: KeyLike,key: KeyLike,...keys: KeyLike[]): Promisenumber>;

Store the intersection of multiple sets in a key

@param destination

The destination key to store the result

@param key

The first set key

@param keys

Additional set keys to intersect

@returns

Promise that resolves with the number of elements in the resulting set

sismember(key: KeyLike,member: string): Promiseboolean>;

Check if a value is a member of a set

@param key

The set key

@param member

The member to check

@returns

Promise that resolves with true if the member exists, false otherwise

smembers(key: KeyLike): Promisestring[]>;

Get all the members in a set

@param key

The set key

@returns

Promise that resolves with an array of all members

smismember(key: KeyLike,member: KeyLike,...members: KeyLike[]): Promisenumber[]>;

Check if multiple members are members of a set

@param key

The set key

@param member

The first member to check

@param members

Additional members to check

@returns

Promise that resolves with an array of 1s and 0s indicating membership

smove(source: KeyLike,destination: KeyLike,member: string): Promiseboolean>;

Move a member from one set to another

@param source

The source set key

@param destination

The destination set key

@param member

The member to move

@returns

Promise that resolves with true if the element was moved, false if it wasn't a member of source

spop(key: KeyLike): Promisenull | string>;

Remove and return a random member from a set

@param key

The set key

@returns

Promise that resolves with the removed member, or null if the set is empty

spop(key: KeyLike,count: number): Promisenull | string[]>;

Remove and return count members from the set

@param key

The set key

@returns

Promise that resolves with the removed members, or null if the set is empty

spublish(channel: KeyLike,message: string): Promisenumber>;

Post a message to a shard channel

@param channel

The shard channel name

@param message

The message to publish

@returns

Promise that resolves with the number of clients that received the message

srandmember(key: KeyLike): Promisenull | string>;

Get a random member from a set

@param key

The set key

@returns

Promise that resolves with a random member, or null if the set is empty

srandmember(key: KeyLike,count: number): Promisenull | string[]>;

Get count random members from a set

@param key

The set key

@returns

Promise that resolves with an array of up to count random members, or null if the set doesn't exist

srem(key: KeyLike,...members: string[]): Promisenumber>;

Remove one or more members from a set

@param key

The set key

@param members

The members to remove

@returns

Promise that resolves with the number of members removed

sscan(key: KeyLike,cursor: string | number,...args: string | number[]): Promise[string, string[]]>;

Incrementally iterate over a set

@param key

The set key

@param cursor

The cursor value

@param args

Additional SSCAN options (MATCH pattern, COUNT hint)

@returns

Promise that resolves with a tuple [cursor, members[]]

strlen(key: KeyLike): Promisenumber>;

Get the length of the value stored in a key

@param key

The key to check

@returns

Promise that resolves with the length of the string value, or 0 if the key doesn't exist

subscribe(channel: string,listener: StringPubSubListener): Promisenumber>;

Subscribe to a Redis channel.

Subscribing disables automatic pipelining, so all commands will be received immediately.

Subscribing moves the channel to a dedicated subscription state which prevents most other commands from being executed until unsubscribed. Only .ping(), .subscribe(), and .unsubscribe() are legal to invoke in a subscribed upon channel.

@param channel

The channel to subscribe to.

@param listener

The listener to call when a message is received on the channel. The listener will receive the message as the first argument and the channel as the second argument.

await client.subscribe("my-channel", (message, channel) => {
console.log(`Received message on ${channel}: ${message}`);
});
subscribe(channels: string[],listener: StringPubSubListener): Promisenumber>;

Subscribe to multiple Redis channels.

Subscribing disables automatic pipelining, so all commands will be received immediately.

Subscribing moves the channels to a dedicated subscription state in which only a limited set of commands can be executed.

@param channels

An array of channels to subscribe to.

@param listener

The listener to call when a message is received on any of the subscribed channels. The listener will receive the message as the first argument and the channel as the second argument.

sunion(key: KeyLike,...keys: KeyLike[]): Promisestring[]>;

Get the union of multiple sets

@param key

The first set key

@param keys

Additional set keys to union

@returns

Promise that resolves with an array of members in the union

sunionstore(destination: KeyLike,key: KeyLike,...keys: KeyLike[]): Promisenumber>;

Store the union of multiple sets in a key

@param destination

The destination key to store the result

@param key

The first set key

@param keys

Additional set keys to union

@returns

Promise that resolves with the number of elements in the resulting set

touch(...keys: KeyLike[]): Promisenumber>;

Alters the last access time of one or more keys

A key is ignored if it does not exist. The command returns the number of keys that were touched.

This command is useful in conjunction with maxmemory-policy allkeys-lru / volatile-lru to change the last access time of keys for eviction purposes.

@param keys

One or more keys to touch

@returns

Promise that resolves with the number of keys that were touched

await redis.set("key1", "Hello");
await redis.set("key2", "World");
const touched = await redis.touch("key1", "key2", "key3");
console.log(touched); // 2 (key3 doesn't exist)
ttl(key: KeyLike): Promisenumber>;

Get the time to live for a key in seconds

@param key

The key to get the TTL for

@returns

Promise that resolves with the TTL, -1 if no expiry, or -2 if key doesn't exist

type(key: KeyLike): Promise'string' | 'stream' | 'set' | 'none' | 'list' | 'zset' | 'hash'>;

Determine the type of value stored at key

The TYPE command returns the string representation of the type of the value stored at key. The different types that can be returned are: string, list, set, zset, hash and stream.

@param key

The key to check

@returns

Promise that resolves with the type of value stored at key, or "none" if the key doesn't exist

await redis.set("mykey", "Hello");
console.log(await redis.type("mykey")); // "string"

await redis.lpush("mylist", "value");
console.log(await redis.type("mylist")); // "list"

await redis.sadd("myset", "value");
console.log(await redis.type("myset")); // "set"

await redis.hset("myhash", "field", "value");
console.log(await redis.type("myhash")); // "hash"

console.log(await redis.type("nonexistent")); // "none"
unlink(...keys: KeyLike[]): Promisenumber>;

Asynchronously delete one or more keys

This command is very similar to DEL: it removes the specified keys. Just like DEL a key is ignored if it does not exist. However, the command performs the actual memory reclaiming in a different thread, so it is not blocking, while DEL is. This is particularly useful when deleting large values or large numbers of keys.

@param keys

The keys to delete

@returns

Promise that resolves with the number of keys that were unlinked

await redis.set("key1", "Hello");
await redis.set("key2", "World");
const count = await redis.unlink("key1", "key2", "key3");
console.log(count); // 2
unsubscribe(channel: string): Promisevoid>;

Unsubscribe from a singular Redis channel.

@param channel

The channel to unsubscribe from.

If there are no more channels subscribed to, the client automatically re-enables pipelining if it was previously enabled.

Unsubscribing moves the channel back to a normal state out of the subscription state if all channels have been unsubscribed from. For further details on the subscription state, see .subscribe().

unsubscribe(channel: string,listener: StringPubSubListener): Promisevoid>;

Remove a listener from a given Redis channel.

If there are no more channels subscribed to, the client automatically re-enables pipelining if it was previously enabled.

Unsubscribing moves the channel back to a normal state out of the subscription state if all channels have been unsubscribed from. For further details on the subscription state, see .subscribe().

@param channel

The channel to unsubscribe from.

@param listener

The listener to remove. This is tested against referential equality so you must pass the exact same listener instance as when subscribing.

unsubscribe(): Promisevoid>;

Unsubscribe from all registered Redis channels.

The client will automatically re-enable pipelining if it was previously enabled.

Unsubscribing moves the channel back to a normal state out of the subscription state if all channels have been unsubscribed from. For further details on the subscription state, see .subscribe().

unsubscribe(channels: string[]): Promisevoid>;

Unsubscribe from multiple Redis channels.

@param channels

An array of channels to unsubscribe from.

If there are no more channels subscribed to, the client automatically re-enables pipelining if it was previously enabled.

Unsubscribing moves the channel back to a normal state out of the subscription state if all channels have been unsubscribed from. For further details on the subscription state, see .subscribe().

zadd(key: KeyLike,...args: string | number[]): Promisenumber>;

Add one or more members to a sorted set, or update scores if they already exist

ZADD adds all the specified members with the specified scores to the sorted set stored at key. It is possible to specify multiple score / member pairs. If a specified member is already a member of the sorted set, the score is updated and the element reinserted at the right position to ensure the correct ordering.

If key does not exist, a new sorted set with the specified members as sole members is created. If the key exists but does not hold a sorted set, an error is returned.

The score values should be the string representation of a double precision floating point number. +inf and -inf values are valid values as well.

Options:

NX: Only add new elements. Don't update already existing elements.XX: Only update elements that already exist. Never add elements.GT: Only update existing elements if the new score is greater than the current score. This flag doesn't prevent adding new elements.LT: Only update existing elements if the new score is less than the current score. This flag doesn't prevent adding new elements.CH: Modify the return value from the number of new elements added, to the total number of elements changed (CH is an abbreviation of changed).INCR: When this option is specified ZADD acts like ZINCRBY. Only one score-member pair can be specified in this mode.

Note: The GT, LT and NX options are mutually exclusive.

@param key

The sorted set key

@param args

Score-member pairs and optional flags (NX, XX, GT, LT, CH, INCR)

@returns

Promise that resolves with the number of elements added (or changed if CH is used, or new score if INCR is used)

// Add members with scores
await redis.zadd("myzset", "1", "one", "2", "two", "3", "three");

// Add with NX option (only if member doesn't exist)
await redis.zadd("myzset", "NX", "4", "four");

// Add with XX option (only if member exists)
await redis.zadd("myzset", "XX", "2.5", "two");

// Add with CH option (return count of changed elements)
await redis.zadd("myzset", "CH", "5", "five", "2.1", "two");

// Use INCR option (increment score)
await redis.zadd("myzset", "INCR", "1.5", "one");
zcard(key: KeyLike): Promisenumber>;

Get the number of members in a sorted set

@param key

The sorted set key

@returns

Promise that resolves with the cardinality (number of elements) of the sorted set

zcount(key: KeyLike,min: string | number,max: string | number): Promisenumber>;

Count the members in a sorted set with scores within the given range

@param key

The sorted set key

@param min

Minimum score (inclusive, use "-inf" for negative infinity)

@param max

Maximum score (inclusive, use "+inf" for positive infinity)

@returns

Promise that resolves with the count of elements in the specified score range

zdiff(numkeys: number,...args: [...keys: KeyLike[], withscores: 'WITHSCORES']): Promise[string, number][]>;

Compute the difference between sorted sets with scores

@param numkeys

The number of sorted set keys

@returns

Promise that resolves with an array of [member, score] pairs

await redis.send("ZADD", ["zset1", "1", "one", "2", "two", "3", "three"]);
await redis.send("ZADD", ["zset2", "1", "one", "2", "two"]);
const diff = await redis.zdiff(2, "zset1", "zset2", "WITHSCORES");
console.log(diff); // ["three", "3"]
zdiff(numkeys: number,...keys: KeyLike[]): Promisestring[]>;

Compute the difference between the first sorted set and all successive sorted sets

Returns the members of the sorted set resulting from the difference between the first sorted set and all the successive sorted sets. The first key is the only one used to compute the members of the difference.

@param numkeys

The number of sorted set keys

@param keys

The sorted set keys to compare

@returns

Promise that resolves with an array of members

await redis.send("ZADD", ["zset1", "1", "one", "2", "two", "3", "three"]);
await redis.send("ZADD", ["zset2", "1", "one", "2", "two"]);
const diff = await redis.zdiff(2, "zset1", "zset2");
console.log(diff); // ["three"]
zdiffstore(destination: KeyLike,numkeys: number,...keys: KeyLike[]): Promisenumber>;

Compute the difference between sorted sets and store the result

Computes the difference between the first and all successive sorted sets given by the specified keys and stores the result in destination. Keys that do not exist are considered to be empty sets.

@param destination

The destination key to store the result

@param numkeys

The number of input sorted set keys

@param keys

The sorted set keys to compare

@returns

Promise that resolves with the number of elements in the resulting sorted set

await redis.send("ZADD", ["zset1", "1", "one", "2", "two", "3", "three"]);
await redis.send("ZADD", ["zset2", "1", "one"]);
const count = await redis.zdiffstore("out", 2, "zset1", "zset2");
console.log(count); // 2 (two, three)
zincrby(key: KeyLike,increment: number,member: KeyLike): Promisenumber>;

Increment the score of a member in a sorted set

@param key

The sorted set key

@param increment

The increment value

@param member

The member to increment

@returns

Promise that resolves with the new score

zinter(numkeys: number,...args: [...args: string | number[], withscores: 'WITHSCORES']): Promise[string, number][]>;

Compute the intersection of multiple sorted sets

Returns the members of the set resulting from the intersection of all the given sorted sets. Keys that do not exist are considered to be empty sets.

By default, the resulting score of each member is the sum of its scores in the sorted sets where it exists.

Options:

WEIGHTS: Multiply the score of each member in the corresponding sorted set by the given weight before aggregationAGGREGATE SUM|MIN|MAX: Specify how the scores are aggregated (default: SUM)WITHSCORES: Return the scores along with the members
@param numkeys

The number of input keys (sorted sets)

@returns

Promise that resolves with an array of members (or [member, score] pairs if WITHSCORES)

// Set up sorted sets
await redis.zadd("zset1", "1", "a", "2", "b", "3", "c");
await redis.zadd("zset2", "1", "b", "2", "c", "3", "d");

// Basic intersection - returns members that exist in all sets
const result1 = await redis.zinter(2, "zset1", "zset2");
// Returns: ["b", "c"]

// With scores (sum by default)
const result2 = await redis.zinter(2, "zset1", "zset2", "WITHSCORES");
// Returns: ["b", "3", "c", "5"] (b: 2+1=3, c: 3+2=5)

// With weights
const result3 = await redis.zinter(2, "zset1", "zset2", "WEIGHTS", "2", "3", "WITHSCORES");
// Returns: ["b", "7", "c", "12"] (b: 2*2+1*3=7, c: 3*2+2*3=12)

// With MIN aggregation
const result4 = await redis.zinter(2, "zset1", "zset2", "AGGREGATE", "MIN", "WITHSCORES");
// Returns: ["b", "1", "c", "2"] (minimum scores)
zinter(numkeys: number,...args: string | number[]): Promisestring[]>;

Compute the intersection of multiple sorted sets

Returns the members of the set resulting from the intersection of all the given sorted sets. Keys that do not exist are considered to be empty sets.

By default, the resulting score of each member is the sum of its scores in the sorted sets where it exists.

Options:

WEIGHTS: Multiply the score of each member in the corresponding sorted set by the given weight before aggregationAGGREGATE SUM|MIN|MAX: Specify how the scores are aggregated (default: SUM)WITHSCORES: Return the scores along with the members
@param numkeys

The number of input keys (sorted sets)

@returns

Promise that resolves with an array of members (or [member, score] pairs if WITHSCORES)

// Set up sorted sets
await redis.zadd("zset1", "1", "a", "2", "b", "3", "c");
await redis.zadd("zset2", "1", "b", "2", "c", "3", "d");

// Basic intersection - returns members that exist in all sets
const result1 = await redis.zinter(2, "zset1", "zset2");
// Returns: ["b", "c"]

// With scores (sum by default)
const result2 = await redis.zinter(2, "zset1", "zset2", "WITHSCORES");
// Returns: ["b", "3", "c", "5"] (b: 2+1=3, c: 3+2=5)

// With weights
const result3 = await redis.zinter(2, "zset1", "zset2", "WEIGHTS", "2", "3", "WITHSCORES");
// Returns: ["b", "7", "c", "12"] (b: 2*2+1*3=7, c: 3*2+2*3=12)

// With MIN aggregation
const result4 = await redis.zinter(2, "zset1", "zset2", "AGGREGATE", "MIN", "WITHSCORES");
// Returns: ["b", "1", "c", "2"] (minimum scores)
zintercard(numkeys: number,...keys: KeyLike[]): Promisenumber>;

Count the number of members in the intersection of multiple sorted sets

Computes the cardinality of the intersection of the sorted sets at the specified keys. The intersection includes only elements that exist in all of the given sorted sets.

When a LIMIT is provided, the command stops counting once the limit is reached, which is useful for performance when you only need to know if the cardinality exceeds a certain threshold.

@param numkeys

The number of sorted set keys

@param keys

The sorted set keys to intersect

@returns

Promise that resolves with the number of elements in the intersection

await redis.send("ZADD", ["zset1", "1", "one", "2", "two", "3", "three"]);
await redis.send("ZADD", ["zset2", "1", "one", "2", "two", "4", "four"]);
const count = await redis.zintercard(2, "zset1", "zset2");
console.log(count); // 2 (one, two)
zintercard(numkeys: number,...args: number | KeyLike[]): Promisenumber>;

Count the number of members in the intersection with a limit

@param numkeys

The number of sorted set keys

@returns

Promise that resolves with the number of elements (up to limit)

await redis.send("ZADD", ["zset1", "1", "a", "2", "b", "3", "c"]);
await redis.send("ZADD", ["zset2", "1", "a", "2", "b", "3", "c"]);
const count = await redis.zintercard(2, "zset1", "zset2", "LIMIT", 2);
console.log(count); // 2 (stopped at limit)
zinterstore(destination: KeyLike,numkeys: number,...args: string | number[]): Promisenumber>;

Compute the intersection of multiple sorted sets and store in destination

This command is similar to ZINTER, but instead of returning the result, it stores it in the destination key. If the destination key already exists, it is overwritten.

Options:

WEIGHTS: Multiply the score of each member in the corresponding sorted set by the given weight before aggregationAGGREGATE SUM|MIN|MAX: Specify how the scores are aggregated (default: SUM)
@param destination

The destination key to store the result

@param numkeys

The number of input keys (sorted sets)

@returns

Promise that resolves with the number of elements in the resulting sorted set

// Set up sorted sets
await redis.zadd("zset1", "1", "a", "2", "b", "3", "c");
await redis.zadd("zset2", "1", "b", "2", "c", "3", "d");

// Basic intersection store
const count1 = await redis.zinterstore("out", 2, "zset1", "zset2");
// Returns: 2 (stored "b" and "c" in "out")

// With weights
const count2 = await redis.zinterstore("out2", 2, "zset1", "zset2", "WEIGHTS", "2", "3");
// Returns: 2

// With MAX aggregation
const count3 = await redis.zinterstore("out3", 2, "zset1", "zset2", "AGGREGATE", "MAX");
// Returns: 2 (stores maximum scores)
zlexcount(key: KeyLike,min: string,max: string): Promisenumber>;

Count the members in a sorted set within a lexicographical range

@param key

The sorted set key

@param min

Minimum value (use "[" for inclusive, "(" for exclusive, e.g., "[aaa")

@param max

Maximum value (use "[" for inclusive, "(" for exclusive, e.g., "[zzz")

@returns

Promise that resolves with the count of elements in the specified range

zmpop(numkeys: number,...args: string | number[]): Promisenull | [string, [string, number][]]>;

Remove and return members with scores from one or more sorted sets. Pops from the first non-empty sorted set.

// Pop lowest score from one set
const result1 = await redis.zmpop(1, "myzset", "MIN");
// Returns: ["myzset", [["member1", 1]]]

// Pop highest score from multiple sets
const result2 = await redis.zmpop(2, "zset1", "zset2", "MAX");
// Returns: ["zset1", [["member5", 5]]] (pops from first non-empty)

// Pop multiple members
const result3 = await redis.zmpop(1, "myzset", "MIN", "COUNT", 3);
// Returns: ["myzset", [["member1", 1], ["member2", 2], ["member3", 3]]]

// Empty set returns null
const result4 = await redis.zmpop(1, "emptyset", "MIN");
// Returns: null
zmscore(key: KeyLike,member: KeyLike,...members: KeyLike[]): Promisenull | number[]>;

Returns the scores associated with the specified members in the sorted set

@param key

The sorted set key

@param member

The first member to get the score for

@param members

Additional members to get scores for

@returns

Promise that resolves with an array of scores (number for each score, or null if member doesn't exist)

zpopmax(key: KeyLike): Promise[] | [string, number]>;

Remove and return members with the highest scores in a sorted set

@param key

The sorted set key

@returns

Promise that resolves with either [member, score] or empty array if the set is empty

zpopmax(key: KeyLike,count: number): Promise[string, number][]>;

Remove and return members with the highest scores in a sorted set

@param key

The sorted set key

@param count

Optional number of members to pop (default: 1)

@returns

Promise that resolves with an array of [member, score] tuples

zpopmin(key: KeyLike): Promise[] | [string, number]>;

Remove and return members with the lowest scores in a sorted set

@param key

The sorted set key

@returns

Promise that resolves with array of [member, score] tuples, or empty array if the set is empty

zpopmin(key: KeyLike,count: number): Promise[string, number][]>;

Remove and return members with the lowest scores in a sorted set

@param key

The sorted set key

@param count

Optional number of members to pop (default: 1)

@returns

Promise that resolves with an array of [member, score] tuples

zrandmember(key: KeyLike): Promisenull | string>;

Get one or multiple random members from a sorted set

@param key

The sorted set key

@returns

Promise that resolves with a random member, or null if the set is empty

zrandmember(key: KeyLike,count: number): Promisenull | string[]>;

Get one or multiple random members from a sorted set

@param key

The sorted set key

@returns

Promise that resolves with a random member, or null if the set is empty

zrandmember(key: KeyLike,count: number,withscores: 'WITHSCORES'): Promisenull | [string, number][]>;

Get one or multiple random members from a sorted set, with scores

@param key

The sorted set key

@returns

Promise that resolves with a random member, or null if the set is empty

zrange(key: KeyLike,start: string | number,stop: string | number,withscores: 'WITHSCORES'): Promise[string, number][]>;

Return a range of members in a sorted set with their scores

@param key

The sorted set key

@param start

The starting index

@param stop

The stopping index

@param withscores

Return members with their scores

@returns

Promise that resolves with an array of [member, score, member, score, ...]

const results = await redis.zrange("myzset", 0, -1, "WITHSCORES");
// Returns ["member1", "1.5", "member2", "2.5", ...]
zrange(key: KeyLike,start: string | number,stop: string | number,byscore: 'BYSCORE'): Promisestring[]>;

Return a range of members in a sorted set by score

@param key

The sorted set key

@param start

The minimum score (use "-inf" for negative infinity, "(" prefix for exclusive)

@param stop

The maximum score (use "+inf" for positive infinity, "(" prefix for exclusive)

@param byscore

Indicates score-based range

@returns

Promise that resolves with an array of members with scores in the range

// Get members with score between 1 and 3
const members = await redis.zrange("myzset", "1", "3", "BYSCORE");

// Get members with score > 1 and
const members2 = await redis.zrange("myzset", "(1", "3", "BYSCORE");
zrange(key: KeyLike,start: string,stop: string,bylex: 'BYLEX'): Promisestring[]>;

Return a range of members in a sorted set lexicographically

@param key

The sorted set key

@param start

The minimum lexicographical value (use "-" for start, "[" for inclusive, "(" for exclusive)

@param stop

The maximum lexicographical value (use "+" for end, "[" for inclusive, "(" for exclusive)

@param bylex

Indicates lexicographical range

@returns

Promise that resolves with an array of members in the lexicographical range

// Get members lexicographically from "a" to "c" (inclusive)
const members = await redis.zrange("myzset", "[a", "[c", "BYLEX");
zrange(key: KeyLike,start: string | number,stop: string | number,...options: string[]): Promisestring[]>;

Return a range of members in a sorted set with various options

@param key

The sorted set key

@param start

The starting value (index, score, or lex depending on options)

@param stop

The stopping value

@param options

Additional options (BYSCORE, BYLEX, REV, LIMIT offset count, WITHSCORES)

@returns

Promise that resolves with an array of members (or with scores if WITHSCORES)

// Get members by score with limit
const members = await redis.zrange("myzset", "1", "10", "BYSCORE", "LIMIT", "0", "5");

// Get members in reverse order with scores
const reversed = await redis.zrange("myzset", "0", "-1", "REV", "WITHSCORES");
zrange(key: KeyLike,start: string | number,stop: string | number): Promisestring[]>;

Return a range of members in a sorted set

Returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the lowest to the highest score by default.

@param key

The sorted set key

@param start

The starting index (0-based, can be negative to count from end)

@param stop

The stopping index (0-based, can be negative to count from end)

@returns

Promise that resolves with an array of members in the specified range

// Get all members
const members = await redis.zrange("myzset", 0, -1);

// Get first 3 members
const top3 = await redis.zrange("myzset", 0, 2);
zrangebylex(key: KeyLike,min: string,max: string): Promisestring[]>;

Return members in a sorted set within a lexicographical range

When all the elements in a sorted set have the same score, this command returns the elements between min and max in lexicographical order.

Lex ranges:

[member for inclusive lower bound(member for exclusive lower bound- for negative infinity+ for positive infinity
@param key

The sorted set key (all members must have the same score)

@param min

Minimum lexicographical value (use "-" for negative infinity, "[" or "(" for inclusive/exclusive)

@param max

Maximum lexicographical value (use "+" for positive infinity, "[" or "(" for inclusive/exclusive)

@returns

Promise that resolves with array of members

await redis.send("ZADD", ["myzset", "0", "apple", "0", "banana", "0", "cherry"]);
const members = await redis.zrangebylex("myzset", "[banana", "[cherry");
// Returns: ["banana", "cherry"]
zrangebylex(key: KeyLike,min: string,max: string,limit: 'LIMIT',offset: number,count: number): Promisestring[]>;

Return members in a sorted set within a lexicographical range, with pagination

@param key

The sorted set key

@param min

Minimum lexicographical value

@param max

Maximum lexicographical value

@param limit

The "LIMIT" keyword

@param offset

The number of elements to skip

@param count

The maximum number of elements to return

@returns

Promise that resolves with array of members

await redis.send("ZADD", ["myzset", "0", "a", "0", "b", "0", "c", "0", "d"]);
const result = await redis.zrangebylex("myzset", "-", "+", "LIMIT", 1, 2);
// Returns: ["b", "c"]
zrangebylex(key: KeyLike,min: string,max: string,...options: string | number[]): Promisestring[]>;

Return members in a sorted set within a lexicographical range, with options

@param key

The sorted set key

@param min

Minimum lexicographical value

@param max

Maximum lexicographical value

@param options

Additional options (LIMIT offset count)

@returns

Promise that resolves with array of members

zrangebyscore(key: KeyLike,min: string | number,max: string | number): Promisestring[]>;

Return members in a sorted set with scores within a given range

Returns all the elements in the sorted set at key with a score between min and max (inclusive by default). The elements are considered to be ordered from low to high scores.

Score ranges support:

-inf and +inf for negative and positive infinity( prefix for exclusive bounds (e.g., (5 means greater than 5, not including 5)
@param key

The sorted set key

@param min

Minimum score (can be "-inf", a number, or prefixed with "(" for exclusive)

@param max

Maximum score (can be "+inf", a number, or prefixed with "(" for exclusive)

@returns

Promise that resolves with array of members

await redis.send("ZADD", ["myzset", "1", "one", "2", "two", "3", "three"]);
const members = await redis.zrangebyscore("myzset", 1, 2);
// Returns: ["one", "two"]
zrangebyscore(key: KeyLike,min: string | number,max: string | number,withscores: 'WITHSCORES'): Promise[string, number][]>;

Return members in a sorted set with scores within a given range, with scores

@param key

The sorted set key

@param min

Minimum score

@param max

Maximum score

@param withscores

The "WITHSCORES" keyword to return scores along with members

@returns

Promise that resolves with array of [member, score, member, score, ...]

await redis.send("ZADD", ["myzset", "1", "one", "2", "two", "3", "three"]);
const result = await redis.zrangebyscore("myzset", 1, 2, "WITHSCORES");
// Returns: ["one", "1", "two", "2"]
zrangebyscore(key: KeyLike,min: string | number,max: string | number,limit: 'LIMIT',offset: number,count: number): Promisestring[]>;

Return members in a sorted set with scores within a given range, with pagination

@param key

The sorted set key

@param min

Minimum score

@param max

Maximum score

@param limit

The "LIMIT" keyword

@param offset

The number of elements to skip

@param count

The maximum number of elements to return

@returns

Promise that resolves with array of members

await redis.send("ZADD", ["myzset", "1", "one", "2", "two", "3", "three", "4", "four"]);
const result = await redis.zrangebyscore("myzset", "-inf", "+inf", "LIMIT", 1, 2);
// Returns: ["two", "three"]
zrangebyscore(key: KeyLike,min: string | number,max: string | number,withscores: 'WITHSCORES',...options: string | number[]): Promise[string, number][]>;

Return members in a sorted set with scores within a given range, with the score values

@param key

The sorted set key

@param min

Minimum score

@param max

Maximum score

@param options

Additional options (WITHSCORES, LIMIT offset count)

@returns

Promise that resolves with array of members (and scores if WITHSCORES is used)

zrangebyscore(key: KeyLike,min: string | number,max: string | number,withscores: 'WITHSCORES',limit: 'LIMIT',offset: number,count: number,...options: string | number[]): Promise[string, number][]>;

Return members in a sorted set with scores within a given range, with the score values

@param key

The sorted set key

@param min

Minimum score

@param max

Maximum score

@param options

Additional options (WITHSCORES, LIMIT offset count)

@returns

Promise that resolves with array of members (and scores if WITHSCORES is used)

zrangebyscore(key: KeyLike,min: string | number,max: string | number,...options: string | number[]): Promisestring[]>;

Return members in a sorted set with scores within a given range, with various options

@param key

The sorted set key

@param min

Minimum score

@param max

Maximum score

@param options

Additional options (WITHSCORES, LIMIT offset count)

@returns

Promise that resolves with array of members (and scores if WITHSCORES is used)

zrangestore(destination: KeyLike,source: KeyLike,start: string | number,stop: string | number,...options: string[]): Promisenumber>;

Store a range of members from a sorted set into a destination key

This command is like ZRANGE but stores the result in a destination key instead of returning it. Supports all the same options as ZRANGE including BYSCORE, BYLEX, REV, and LIMIT.

@param destination

The destination key to store results

@param source

The source sorted set key

@param start

The starting index or score

@param stop

The ending index or score

@param options

Optional flags: ["BYSCORE"], ["BYLEX"], ["REV"], ["LIMIT", offset, count]

@returns

Promise that resolves with the number of elements in the resulting sorted set

// Add members to source set
await redis.send("ZADD", ["source", "1", "one", "2", "two", "3", "three"]);

// Store range by rank
const count1 = await redis.zrangestore("dest1", "source", 0, 1);
console.log(count1); // 2

// Store range by score
const count2 = await redis.zrangestore("dest2", "source", "1", "2", "BYSCORE");
console.log(count2); // 2

// Store in reverse order with limit
const count3 = await redis.zrangestore("dest3", "source", "0", "-1", "REV", "LIMIT", "0", "2");
console.log(count3); // 2
zrank(key: KeyLike,member: string): Promisenull | number>;

Determine the index of a member in a sorted set

@param key

The sorted set key

@param member

The member to find

@returns

Promise that resolves with the rank (index) of the member, or null if the member doesn't exist

zrank(key: KeyLike,member: string,withscore: 'WITHSCORE'): Promisenull | [number, number]>;

Determine the index of a member in a sorted set with score

@param key

The sorted set key

@param member

The member to find

@param withscore

"WITHSCORE" to include the score

@returns

Promise that resolves with [rank, score] or null if the member doesn't exist

zrem(key: KeyLike,member: KeyLike,...members: KeyLike[]): Promisenumber>;

Remove one or more members from a sorted set

@param key

The sorted set key

@param member

The first member to remove

@param members

Additional members to remove

@returns

Promise that resolves with the number of members removed (not including non-existing members)

zremrangebylex(key: KeyLike,min: string,max: string): Promisenumber>;

Remove all members in a sorted set within the given lexicographical range

@param key

The sorted set key

@param min

Minimum value (use "[" for inclusive, "(" for exclusive, e.g., "[aaa")

@param max

Maximum value (use "[" for inclusive, "(" for exclusive, e.g., "[zzz")

@returns

Promise that resolves with the number of elements removed

zremrangebyrank(key: KeyLike,start: number,stop: number): Promisenumber>;

Remove all members in a sorted set within the given rank range

@param key

The sorted set key

@param start

Start rank (0-based, can be negative to indicate offset from end)

@param stop

Stop rank (0-based, can be negative to indicate offset from end)

@returns

Promise that resolves with the number of elements removed

zremrangebyscore(key: KeyLike,min: string | number,max: string | number): Promisenumber>;

Remove all members in a sorted set within the given score range

@param key

The sorted set key

@param min

Minimum score (inclusive, use "-inf" for negative infinity, "(" prefix for exclusive)

@param max

Maximum score (inclusive, use "+inf" for positive infinity, "(" prefix for exclusive)

@returns

Promise that resolves with the number of elements removed

zrevrange(key: KeyLike,start: number,stop: number): Promisestring[]>;

Return a range of members in a sorted set, by index, with scores ordered from high to low

This is equivalent to ZRANGE with the REV option. Returns members in reverse order.

@param key

The sorted set key

@param start

The starting index (0-based, can be negative to count from end)

@param stop

The stopping index (0-based, can be negative to count from end)

@returns

Promise that resolves with an array of members in reverse order

// Get all members in reverse order (highest to lowest score)
const members = await redis.zrevrange("myzset", 0, -1);

// Get top 3 members with highest scores
const top3 = await redis.zrevrange("myzset", 0, 2);
zrevrange(key: KeyLike,start: number,stop: number,withscores: 'WITHSCORES'): Promise[string, number][]>;

Return a range of members in a sorted set with their scores, ordered from high to low

@param key

The sorted set key

@param start

The starting index

@param stop

The stopping index

@param withscores

Return members with their scores

@returns

Promise that resolves with an array of [member, score, member, score, ...] in reverse order

const results = await redis.zrevrange("myzset", 0, -1, "WITHSCORES");
// Returns ["member3", "3.5", "member2", "2.5", "member1", "1.5", ...]
zrevrange(key: KeyLike,start: number,stop: number,...options: string[]): Promisestring[]>;

Return a range of members in a sorted set with options, ordered from high to low

@param key

The sorted set key

@param start

The starting index

@param stop

The stopping index

@param options

Additional options (WITHSCORES)

@returns

Promise that resolves with an array of members (or with scores if WITHSCORES)

zrevrangebylex(key: KeyLike,max: string,min: string,...options: string[]): Promisestring[]>;

Return members in a sorted set within a lexicographical range, ordered from high to low

All members in a sorted set must have the same score for this command to work correctly. The max and min arguments have the same meaning as in ZRANGEBYLEX, but in reverse order.

Use "[" for inclusive bounds and "(" for exclusive bounds. Use "-" for negative infinity and "+" for positive infinity.

@param key

The sorted set key

@param max

The maximum lexicographical value (inclusive with "[", exclusive with "(")

@param min

The minimum lexicographical value (inclusive with "[", exclusive with "(")

@param options

Optional LIMIT clause: ["LIMIT", offset, count]

@returns

Promise that resolves with an array of members in reverse lexicographical order

// Add members with same score
await redis.send("ZADD", ["myzset", "0", "a", "0", "b", "0", "c", "0", "d"]);

// Get range from highest to lowest
const members = await redis.zrevrangebylex("myzset", "[d", "[b");
console.log(members); // ["d", "c", "b"]

// With LIMIT
const limited = await redis.zrevrangebylex("myzset", "+", "-", "LIMIT", "0", "2");
console.log(limited); // ["d", "c"] (first 2 members)
zrevrangebyscore(key: KeyLike,max: string | number,min: string | number): Promisestring[]>;

Return members in a sorted set with scores within a given range, ordered from high to low

Returns all the elements in the sorted set at key with a score between max and min (note: max comes before min). The elements are considered to be ordered from high to low scores.

Score ranges support:

-inf and +inf for negative and positive infinity( prefix for exclusive bounds (e.g., (5 means less than 5, not including 5)
@param key

The sorted set key

@param max

Maximum score (can be "+inf", a number, or prefixed with "(" for exclusive)

@param min

Minimum score (can be "-inf", a number, or prefixed with "(" for exclusive)

@returns

Promise that resolves with array of members

await redis.send("ZADD", ["myzset", "1", "one", "2", "two", "3", "three"]);
const members = await redis.zrevrangebyscore("myzset", 2, 1);
// Returns: ["two", "one"]
zrevrangebyscore(key: KeyLike,max: string | number,min: string | number,withscores: 'WITHSCORES'): Promise[string, number][]>;

Return members in a sorted set with scores within a given range, ordered from high to low, with scores

@param key

The sorted set key

@param max

Maximum score

@param min

Minimum score

@param withscores

The "WITHSCORES" keyword to return scores along with members

@returns

Promise that resolves with array of [member, score, member, score, ...]

await redis.send("ZADD", ["myzset", "1", "one", "2", "two", "3", "three"]);
const result = await redis.zrevrangebyscore("myzset", 2, 1, "WITHSCORES");
// Returns: ["two", "2", "one", "1"]
zrevrangebyscore(key: KeyLike,max: string | number,min: string | number,limit: 'LIMIT',offset: number,count: number): Promisestring[]>;

Return members in a sorted set with scores within a given range, ordered from high to low, with pagination

@param key

The sorted set key

@param max

Maximum score

@param min

Minimum score

@param limit

The "LIMIT" keyword

@param offset

The number of elements to skip

@param count

The maximum number of elements to return

@returns

Promise that resolves with array of members

zrevrangebyscore(key: KeyLike,max: string | number,min: string | number,...options: string | number[]): Promisestring[]>;

Return members in a sorted set with scores within a given range, ordered from high to low, with options

@param key

The sorted set key

@param max

Maximum score

@param min

Minimum score

@param options

Additional options (WITHSCORES, LIMIT offset count)

@returns

Promise that resolves with array of members (and scores if WITHSCORES is used)

zrevrank(key: KeyLike,member: string): Promisenull | number>;

Determine the index of a member in a sorted set, with scores ordered from high to low

@param key

The sorted set key

@param member

The member to find

@returns

Promise that resolves with the rank (index) of the member, or null if the member doesn't exist

zrevrank(key: KeyLike,member: string,withscore: 'WITHSCORE'): Promisenull | [number, number]>;

Determine the index of a member in a sorted set with score, with scores ordered from high to low

@param key

The sorted set key

@param member

The member to find

@param withscore

"WITHSCORE" to include the score

@returns

Promise that resolves with [rank, score] or null if the member doesn't exist

zscan(key: KeyLike,cursor: string | number,...options: string[]): Promise[string, string[]]>;

Incrementally iterate sorted set elements and their scores

The ZSCAN command is used in order to incrementally iterate over sorted set elements and their scores. ZSCAN is a cursor based iterator. This means that at every call of the command, the server returns an updated cursor that the user needs to use as the cursor argument in the next call.

An iteration starts when the cursor is set to 0, and terminates when the cursor returned by the server is 0.

ZSCAN and the other SCAN family commands are able to provide to the user a set of guarantees associated to full iterations:

A full iteration always retrieves all the elements that were present in the collection from the start to the end of a full iteration. This means that if a given element is inside the collection when an iteration is started, and is still there when an iteration terminates, then at some point ZSCAN returned it.A full iteration never returns any element that was NOT present in the collection from the start to the end of a full iteration. So if an element was removed before the start of an iteration, and is never added back to the collection for all the time an iteration lasts, ZSCAN ensures that this element will never be returned.

Options:

MATCH pattern: Only return elements matching the pattern (glob-style)COUNT count: Amount of work done at every call (hint, not exact)
@param key

The sorted set key

@param cursor

The cursor value (use 0 to start a new iteration)

@param options

Additional ZSCAN options (MATCH pattern, COUNT hint, etc.)

@returns

Promise that resolves with a tuple [cursor, [member1, score1, member2, score2, ...]]

// Basic scan - iterate all elements
let cursor = "0";
const allElements: string[] = [];
do {
const [nextCursor, elements] = await redis.zscan("myzset", cursor);
allElements.push(...elements);
cursor = nextCursor;
} while (cursor !== "0");
zscore(key: KeyLike,member: string): Promisenull | number>;

Get the score associated with the given member in a sorted set

@param key

The sorted set key

@param member

The member to get the score for

@returns

Promise that resolves with the score of the member as a number, or null if the member or key doesn't exist

zunion(numkeys: number,...args: [...args: string | number[], withscores: 'WITHSCORES']): Promise[string, number][]>;

Compute the union of multiple sorted sets

Returns the union of the sorted sets given by the specified keys. For every element that appears in at least one of the input sorted sets, the output will contain that element.

Options:

WEIGHTS: Multiply the score of each member in the corresponding sorted set by the given weight before aggregationAGGREGATE SUM|MIN|MAX: Specify how the scores are aggregated (default: SUM)WITHSCORES: Include scores in the result
@param numkeys

The number of input keys (sorted sets)

@returns

Promise that resolves with an array of members (or members with scores if WITHSCORES is used)

// Set up sorted sets
await redis.zadd("zset1", "1", "a", "2", "b", "3", "c");
await redis.zadd("zset2", "4", "b", "5", "c", "6", "d");

// Basic union
const members1 = await redis.zunion(2, "zset1", "zset2");
// Returns: ["a", "b", "c", "d"]

// With weights
const members2 = await redis.zunion(2, "zset1", "zset2", "WEIGHTS", "2", "3");
// Returns: ["a", "b", "c", "d"] with calculated scores

// With MIN aggregation
const members3 = await redis.zunion(2, "zset1", "zset2", "AGGREGATE", "MIN");
// Returns: ["a", "b", "c", "d"] with minimum scores

// With scores
const withScores = await redis.zunion(2, "zset1", "zset2", "WITHSCORES");
// Returns: ["a", "1", "b", "2", "c", "3", "d", "6"] (alternating member and score)
zunion(numkeys: number,...args: string | number[]): Promisestring[]>;

Compute the union of multiple sorted sets

Returns the union of the sorted sets given by the specified keys. For every element that appears in at least one of the input sorted sets, the output will contain that element.

Options:

WEIGHTS: Multiply the score of each member in the corresponding sorted set by the given weight before aggregationAGGREGATE SUM|MIN|MAX: Specify how the scores are aggregated (default: SUM)WITHSCORES: Include scores in the result
@param numkeys

The number of input keys (sorted sets)

@returns

Promise that resolves with an array of members (or members with scores if WITHSCORES is used)

// Set up sorted sets
await redis.zadd("zset1", "1", "a", "2", "b", "3", "c");
await redis.zadd("zset2", "4", "b", "5", "c", "6", "d");

// Basic union
const members1 = await redis.zunion(2, "zset1", "zset2");
// Returns: ["a", "b", "c", "d"]

// With weights
const members2 = await redis.zunion(2, "zset1", "zset2", "WEIGHTS", "2", "3");
// Returns: ["a", "b", "c", "d"] with calculated scores

// With MIN aggregation
const members3 = await redis.zunion(2, "zset1", "zset2", "AGGREGATE", "MIN");
// Returns: ["a", "b", "c", "d"] with minimum scores

// With scores
const withScores = await redis.zunion(2, "zset1", "zset2", "WITHSCORES");
// Returns: ["a", "1", "b", "2", "c", "3", "d", "6"] (alternating member and score)
zunionstore(destination: KeyLike,numkeys: number,...args: string | number[]): Promisenumber>;

Compute the union of multiple sorted sets and store in destination

This command is similar to ZUNION, but instead of returning the result, it stores it in the destination key. If the destination key already exists, it is overwritten.

Options:

WEIGHTS: Multiply the score of each member in the corresponding sorted set by the given weight before aggregationAGGREGATE SUM|MIN|MAX: Specify how the scores are aggregated (default: SUM)
@param destination

The destination key to store the result

@param numkeys

The number of input keys (sorted sets)

@returns

Promise that resolves with the number of elements in the resulting sorted set

// Set up sorted sets
await redis.zadd("zset1", "1", "a", "2", "b", "3", "c");
await redis.zadd("zset2", "4", "b", "5", "c", "6", "d");

// Basic union store
const count1 = await redis.zunionstore("out", 2, "zset1", "zset2");
// Returns: 4 (stored "a", "b", "c", "d" in "out")

// With weights
const count2 = await redis.zunionstore("out2", 2, "zset1", "zset2", "WEIGHTS", "2", "3");
// Returns: 4

// With MAX aggregation
const count3 = await redis.zunionstore("out3", 2, "zset1", "zset2", "AGGREGATE", "MAX");
// Returns: 4 (stores maximum scores)
class S3Client

A configured S3 bucket instance for managing files. The instance is callable to create S3File instances and provides methods for common operations.

// Basic bucket setup
const bucket = new S3Client({
bucket: "my-bucket",
accessKeyId: "key",
secretAccessKey: "secret"
});

// Get file instance
const file = bucket.file("image.jpg");

// Common operations
await bucket.write("data.json", JSON.stringify({hello: "world"}));
const url = bucket.presign("file.pdf");
await bucket.unlink("old.txt");
delete(path: string,options?: S3Options): Promisevoid>;

Delete a file from the bucket. Alias for S3Client.unlink.

@param path

The path to the file in the bucket

@param options

Additional S3 options to override defaults

@returns

A promise that resolves when deletion is complete

// Simple delete
await bucket.delete("old-file.txt");

// With error handling
try {
await bucket.delete("file.dat");
console.log("File deleted");
} catch (err) {
console.error("Delete failed:", err);
}
exists(path: string,options?: S3Options): Promiseboolean>;

Check if a file exists in the bucket. Uses HEAD request to check existence.

@param path

The path to the file in the bucket

@param options

Additional S3 options to override defaults

@returns

A promise that resolves to true if the file exists, false otherwise

// Check existence
if (await bucket.exists("config.json")) {
const file = bucket.file("config.json");
const config = await file.json();
}

// With error handling
try {
if (!await bucket.exists("required.txt")) {
throw new Error("Required file missing");
}
} catch (err) {
console.error("Check failed:", err);
}
file(path: string,options?: S3Options): S3File;

Creates an S3File instance for the given path.

@param path

The path to the file in the bucket

@param options

Additional S3 options to override defaults

@returns

An S3File instance

const file = bucket.file("image.jpg");
await file.write(imageData);

const configFile = bucket.file("config.json", {
type: "application/json",
acl: "private"
});
list(input?: null | S3ListObjectsOptions,options?: PickS3Options, 'accessKeyId' | 'secretAccessKey' | 'sessionToken' | 'region' | 'bucket' | 'endpoint'>): PromiseS3ListObjectsResponse>;

Returns some or all (up to 1,000) of the objects in a bucket with each request.

You can use the request parameters as selection criteria to return a subset of the objects in a bucket.

@param input

Options for listing objects in the bucket

@param options

Additional S3 options to override defaults

@returns

A promise that resolves to the list response

// List (up to) 1000 objects in the bucket
const allObjects = await bucket.list();

// List (up to) 500 objects under `uploads/` prefix, with owner field for each object
const uploads = await bucket.list({
prefix: 'uploads/',
maxKeys: 500,
fetchOwner: true,
});

// Check if more results are available
if (uploads.isTruncated) {
// List next batch of objects under `uploads/` prefix
const moreUploads = await bucket.list({
prefix: 'uploads/',
maxKeys: 500,
startAfter: uploads.contents!.at(-1).key
fetchOwner: true,
});
}
presign(path: string,options?: S3FilePresignOptions): string;

Generate a presigned URL for temporary access to a file. Useful for generating upload/download URLs without exposing credentials.

@param path

The path to the file in the bucket

@param options

Options for generating the presigned URL

@returns

A presigned URL string

// Download URL
const downloadUrl = bucket.presign("file.pdf", {
expiresIn: 3600 // 1 hour
});

// Upload URL
const uploadUrl = bucket.presign("uploads/image.jpg", {
method: "PUT",
expiresIn: 3600,
type: "image/jpeg",
acl: "public-read"
});

// Long-lived public URL
const publicUrl = bucket.presign("public/doc.pdf", {
expiresIn: 7 * 24 * 60 * 60, // 7 days
acl: "public-read"
});
size(path: string,options?: S3Options): Promisenumber>;

Get the size of a file in bytes. Uses HEAD request to efficiently get size.

@param path

The path to the file in the bucket

@param options

Additional S3 options to override defaults

@returns

A promise that resolves to the file size in bytes

// Get size
const bytes = await bucket.size("video.mp4");
console.log(`Size: ${bytes} bytes`);

// Check if file is large
if (await bucket.size("data.zip") > 100 * 1024 * 1024) {
console.log("File is larger than 100MB");
}
stat(path: string,options?: S3Options): PromiseS3Stats>;

Get the stat of a file in an S3-compatible storage service.

@param path

The path to the file in the bucket

@param options

Additional S3 options to override defaults

@returns

A promise that resolves to the file stats

const stat = await bucket.stat("my-file.txt");
unlink(path: string,options?: S3Options): Promisevoid>;

Delete a file from the bucket.

@param path

The path to the file in the bucket

@param options

Additional S3 options to override defaults

@returns

A promise that resolves when deletion is complete

// Simple delete
await bucket.unlink("old-file.txt");

// With error handling
try {
await bucket.unlink("file.dat");
console.log("File deleted");
} catch (err) {
console.error("Delete failed:", err);
}
write(path: string,data: string | ArrayBuffer | SharedArrayBuffer | Blob | BunFile | Request | Response | File | ArrayBufferViewArrayBufferLike> | S3File | Archive,options?: S3Options): Promisenumber>;

Writes data directly to a path in the bucket. Supports strings, buffers, streams, and web API types.

@param path

The path to the file in the bucket

@param data

The data to write to the file

@param options

Additional S3 options to override defaults

@returns

The number of bytes written

// Write string
await bucket.write("hello.txt", "Hello World");

// Write JSON with type
await bucket.write(
"data.json",
JSON.stringify({hello: "world"}),
{type: "application/json"}
);

// Write from fetch
const res = await fetch("https://example.com/data");
await bucket.write("data.bin", res);

// Write with ACL
await bucket.write("public.html", html, {
acl: "public-read",
type: "text/html"
});
static delete(path: string,options?: S3Options): Promisevoid>;

Delete a file from the bucket. Alias for S3Client.unlink.

@param path

The path to the file in the bucket

@param options

S3 credentials and configuration options

@returns

A promise that resolves when deletion is complete

// Simple delete
await S3Client.delete("old-file.txt", credentials);

// With error handling
try {
await S3Client.delete("file.dat", credentials);
console.log("File deleted");
} catch (err) {
console.error("Delete failed:", err);
}
static exists(path: string,options?: S3Options): Promiseboolean>;

Check if a file exists in the bucket. Uses HEAD request to check existence.

@param path

The path to the file in the bucket

@param options

S3 credentials and configuration options

@returns

A promise that resolves to true if the file exists, false otherwise

// Check existence
if (await S3Client.exists("config.json", credentials)) {
const file = bucket.file("config.json");
const config = await file.json();
}

// With error handling
try {
if (!await S3Client.exists("required.txt", credentials)) {
throw new Error("Required file missing");
}
} catch (err) {
console.error("Check failed:", err);
}
static file(path: string,options?: S3Options): S3File;

Creates an S3File instance for the given path.

@param path

The path to the file in the bucket

@param options

S3 credentials and configuration options

@returns

An S3File instance

const file = S3Client.file("image.jpg", credentials);
await file.write(imageData);

const configFile = S3Client.file("config.json", {
...credentials,
type: "application/json",
acl: "private"
});
static list(input?: null | S3ListObjectsOptions,options?: PickS3Options, 'accessKeyId' | 'secretAccessKey' | 'sessionToken' | 'region' | 'bucket' | 'endpoint'>): PromiseS3ListObjectsResponse>;

Returns some or all (up to 1,000) of the objects in a bucket with each request.

You can use the request parameters as selection criteria to return a subset of the objects in a bucket.

@param input

Options for listing objects in the bucket

@param options

S3 credentials and configuration options

@returns

A promise that resolves to the list response

// List (up to) 1000 objects in the bucket
const allObjects = await S3Client.list(null, credentials);

// List (up to) 500 objects under `uploads/` prefix, with owner field for each object
const uploads = await S3Client.list({
prefix: 'uploads/',
maxKeys: 500,
fetchOwner: true,
}, credentials);

// Check if more results are available
if (uploads.isTruncated) {
// List next batch of objects under `uploads/` prefix
const moreUploads = await S3Client.list({
prefix: 'uploads/',
maxKeys: 500,
startAfter: uploads.contents!.at(-1).key
fetchOwner: true,
}, credentials);
}
static presign(path: string,options?: S3FilePresignOptions): string;

Generate a presigned URL for temporary access to a file. Useful for generating upload/download URLs without exposing credentials.

@param path

The path to the file in the bucket

@param options

S3 credentials and presigned URL configuration

@returns

A presigned URL string

// Download URL
const downloadUrl = S3Client.presign("file.pdf", {
...credentials,
expiresIn: 3600 // 1 hour
});

// Upload URL
const uploadUrl = S3Client.presign("uploads/image.jpg", {
...credentials,
method: "PUT",
expiresIn: 3600,
type: "image/jpeg",
acl: "public-read"
});

// Long-lived public URL
const publicUrl = S3Client.presign("public/doc.pdf", {
...credentials,
expiresIn: 7 * 24 * 60 * 60, // 7 days
acl: "public-read"
});
static size(path: string,options?: S3Options): Promisenumber>;

Get the size of a file in bytes. Uses HEAD request to efficiently get size.

@param path

The path to the file in the bucket

@param options

S3 credentials and configuration options

@returns

A promise that resolves to the file size in bytes

// Get size
const bytes = await S3Client.size("video.mp4", credentials);
console.log(`Size: ${bytes} bytes`);

// Check if file is large
if (await S3Client.size("data.zip", credentials) > 100 * 1024 * 1024) {
console.log("File is larger than 100MB");
}
static stat(path: string,options?: S3Options): PromiseS3Stats>;

Get the stat of a file in an S3-compatible storage service.

@param path

The path to the file in the bucket

@param options

S3 credentials and configuration options

@returns

A promise that resolves to the file stats

const stat = await S3Client.stat("my-file.txt", credentials);
static unlink(path: string,options?: S3Options): Promisevoid>;

Delete a file from the bucket.

@param path

The path to the file in the bucket

@param options

S3 credentials and configuration options

@returns

A promise that resolves when deletion is complete

// Simple delete
await S3Client.unlink("old-file.txt", credentials);

// With error handling
try {
await S3Client.unlink("file.dat", credentials);
console.log("File deleted");
} catch (err) {
console.error("Delete failed:", err);
}
static write(path: string,data: string | ArrayBuffer | SharedArrayBuffer | Blob | BunFile | Request | Response | File | ArrayBufferViewArrayBufferLike> | S3File | Archive,options?: S3Options): Promisenumber>;

Writes data directly to a path in the bucket. Supports strings, buffers, streams, and web API types.

@param path

The path to the file in the bucket

@param data

The data to write to the file

@param options

S3 credentials and configuration options

@returns

The number of bytes written

// Write string
await S3Client.write("hello.txt", "Hello World", credentials);

// Write JSON with type
await S3Client.write(
"data.json",
JSON.stringify({hello: "world"}),
{
...credentials,
type: "application/json"
}
);

// Write from fetch
const res = await fetch("https://example.com/data");
await S3Client.write("data.bin", res, credentials);

// Write with ACL
await S3Client.write("public.html", html, {
...credentials,
acl: "public-read",
type: "text/html"
});
class SHA1

This is not the default because it's not cryptographically secure and it's slower than SHA512

Consider using the ugly-named SHA512_256 instead

readonly static byteLength: 20

The number of bytes the hash will produce

digest(encoding: DigestEncoding): string;

Finalize the hash

@param encoding

DigestEncoding to return the hash in. If none is provided, it will return a Uint8Array.

digest(hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Finalize the hash

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

update(data: BlobOrStringOrBuffer): SHA1;

Update the hash with data

static hash(input: BlobOrStringOrBuffer,hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

static hash(input: BlobOrStringOrBuffer,encoding: DigestEncoding): string;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param encoding

DigestEncoding to return the hash in

class SHA224

This class only exists in types

readonly static byteLength: 28

The number of bytes the hash will produce

digest(encoding: DigestEncoding): string;

Finalize the hash

@param encoding

DigestEncoding to return the hash in. If none is provided, it will return a Uint8Array.

digest(hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Finalize the hash

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

update(data: BlobOrStringOrBuffer): SHA224;

Update the hash with data

static hash(input: BlobOrStringOrBuffer,hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

static hash(input: BlobOrStringOrBuffer,encoding: DigestEncoding): string;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param encoding

DigestEncoding to return the hash in

class SHA256

This class only exists in types

readonly static byteLength: 32

The number of bytes the hash will produce

digest(encoding: DigestEncoding): string;

Finalize the hash

@param encoding

DigestEncoding to return the hash in. If none is provided, it will return a Uint8Array.

digest(hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Finalize the hash

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

update(data: BlobOrStringOrBuffer): SHA256;

Update the hash with data

static hash(input: BlobOrStringOrBuffer,hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

static hash(input: BlobOrStringOrBuffer,encoding: DigestEncoding): string;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param encoding

DigestEncoding to return the hash in

class SHA384

This class only exists in types

readonly static byteLength: 48

The number of bytes the hash will produce

digest(encoding: DigestEncoding): string;

Finalize the hash

@param encoding

DigestEncoding to return the hash in. If none is provided, it will return a Uint8Array.

digest(hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Finalize the hash

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

update(data: BlobOrStringOrBuffer): SHA384;

Update the hash with data

static hash(input: BlobOrStringOrBuffer,hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

static hash(input: BlobOrStringOrBuffer,encoding: DigestEncoding): string;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param encoding

DigestEncoding to return the hash in

class SHA512

This class only exists in types

readonly static byteLength: 64

The number of bytes the hash will produce

digest(encoding: DigestEncoding): string;

Finalize the hash

@param encoding

DigestEncoding to return the hash in. If none is provided, it will return a Uint8Array.

digest(hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Finalize the hash

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

update(data: BlobOrStringOrBuffer): SHA512;

Update the hash with data

static hash(input: BlobOrStringOrBuffer,hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

static hash(input: BlobOrStringOrBuffer,encoding: DigestEncoding): string;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param encoding

DigestEncoding to return the hash in

class SHA512_256

See also sha

readonly static byteLength: 32

The number of bytes the hash will produce

digest(encoding: DigestEncoding): string;

Finalize the hash

@param encoding

DigestEncoding to return the hash in. If none is provided, it will return a Uint8Array.

digest(hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Finalize the hash

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

update(data: BlobOrStringOrBuffer): SHA512_256;

Update the hash with data

static hash(input: BlobOrStringOrBuffer,hashInto?: TypedArrayArrayBufferLike>): TypedArray;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param hashInto

TypedArray to write the hash into. Faster than creating a new one each time

static hash(input: BlobOrStringOrBuffer,encoding: DigestEncoding): string;

Run the hash over the given data

@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer is faster.

@param encoding

DigestEncoding to return the hash in

class SQL

Main SQL client interface providing connection and transaction management

options: MergeSQLiteOptions, PostgresOrMySQLOptions> | MergePostgresOrMySQLOptions, SQLiteOptions>

Current client options

[Symbol.asyncDispose](): PromiseLikevoid>;array(values: any[],typeNameOrTypeID?: number | ArrayType): SQLArrayParameter;

Creates a new SQL array parameter

@param values

The values to create the array parameter from

@param typeNameOrTypeID

The type name or type ID to create the array parameter from, if omitted it will default to JSON

@returns

A new SQL array parameter

const array = sql.array([1, 2, 3], "INT");
await sql`CREATE TABLE users_posts (user_id INT, posts_id INT[])`;
await sql`INSERT INTO users_posts (user_id, posts_id) VALUES (${user.id}, ${array})`;
beginT>(fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a new transaction.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.begin(async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
beginT>(options: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a new transaction with options.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.begin("read write", async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
beginDistributedT>(name: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a distributed transaction Also know as Two-Phase Commit, in a distributed transaction, Phase 1 involves the coordinator preparing nodes by ensuring data is written and ready to commit, while Phase 2 finalizes with nodes committing or rolling back based on the coordinator's decision, ensuring durability and releasing locks. In PostgreSQL and MySQL distributed transactions persist beyond the original session, allowing privileged users or coordinators to commit/rollback them, ensuring support for distributed transactions, recovery, and administrative tasks. beginDistributed will automatic rollback if any exception are not caught, and you can commit and rollback later if everything goes well. PostgreSQL natively supports distributed transactions using PREPARE TRANSACTION, while MySQL uses XA Transactions, and MSSQL also supports distributed/XA transactions. However, in MSSQL, distributed transactions are tied to the original session, the DTC coordinator, and the specific connection. These transactions are automatically committed or rolled back following the same rules as regular transactions, with no option for manual intervention from other sessions, in MSSQL distributed transactions are used to coordinate transactions using Linked Servers.

await sql.beginDistributed("numbers", async sql => {
await sql`create table if not exists numbers (a int)`;
await sql`insert into numbers values(1)`;
});
// later you can call
await sql.commitDistributed("numbers");
// or await sql.rollbackDistributed("numbers");
close(options?: { timeout: number }): Promisevoid>;

Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing.

@param options

The options for the close

await sql.close({ timeout: 1 });
commitDistributed(name: string): Promisevoid>;

Commits a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL

@param name

The name of the distributed transaction

await sql.commitDistributed("my_distributed_transaction");
connect(): PromiseSQL>;

Waits for the database connection to be established

await sql.connect();
distributedT>(name: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a distributed transaction

end(options?: { timeout: number }): Promisevoid>;

Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing. This is an alias of SQL.close

@param options

The options for the close

await sql.end({ timeout: 1 });
fileT = any>(filename: string,values?: any[]): QueryT>;

Reads a file and uses the contents as a query. Optional parameters can be used if the file includes $1, $2, etc

const result = await sql.file("query.sql", [1, 2, 3]);
flush(): void;

Flushes any pending operations

sql.flush();
reserve(): PromiseReservedSQL>;

The reserve method pulls out a connection from the pool, and returns a client that wraps the single connection.

This can be used for running queries on an isolated connection. Calling reserve in a reserved Sql will return a new reserved connection, not the same connection (behavior matches postgres package).

const reserved = await sql.reserve();
await reserved`select * from users`;
await reserved.release();
// with in a production scenario would be something more like
const reserved = await sql.reserve();
try {
// ... queries
} finally {
await reserved.release();
}

// Bun supports Symbol.dispose and Symbol.asyncDispose
// always release after context (safer)
using reserved = await sql.reserve()
await reserved`select * from users`
rollbackDistributed(name: string): Promisevoid>;

Rolls back a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL

@param name

The name of the distributed transaction

await sql.rollbackDistributed("my_distributed_transaction");
transactionT>(fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a transaction.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.transaction(async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
transactionT>(options: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a transaction with options Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.transaction("read write", async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
});
unsafeT = any>(string: string,values?: any[]): QueryT>;

If you know what you're doing, you can use unsafe to pass any string you'd like. Please note that this can lead to SQL injection if you're not careful. You can also nest sql.unsafe within a safe sql expression. This is useful if only part of your fraction has unsafe elements.

const result = await sql.unsafe(`select ${danger} from users where id = ${dragons}`)
class Terminal

A pseudo-terminal (PTY) that can be used to spawn interactive terminal programs.

await using terminal = new Bun.Terminal({
cols: 80,
rows: 24,
data(term, data) {
console.log("Received:", new TextDecoder().decode(data));
},
});

// Spawn a shell connected to the PTY
const proc = Bun.spawn(["bash"], { terminal });

// Write to the terminal
terminal.write("echo hello\n");

// Wait for process to exit
await proc.exited;

// Terminal is closed automatically by `await using`
readonly closed: boolean

Whether the terminal is closed.

controlFlags: number

Terminal control flags (c_cflag from termios). Controls hardware characteristics like CSIZE, PARENB, etc. Returns 0 if terminal is closed. Setting returns true on success, false on failure.

inputFlags: number

Terminal input flags (c_iflag from termios). Controls input processing behavior like ICRNL, IXON, etc. Returns 0 if terminal is closed. Setting returns true on success, false on failure.

localFlags: number

Terminal local flags (c_lflag from termios). Controls local processing like ICANON, ECHO, ISIG, etc. Returns 0 if terminal is closed. Setting returns true on success, false on failure.

outputFlags: number

Terminal output flags (c_oflag from termios). Controls output processing behavior like OPOST, ONLCR, etc. Returns 0 if terminal is closed. Setting returns true on success, false on failure.

[Symbol.asyncDispose](): Promisevoid>;

Async dispose for use with await using.

close(): void;

Close the terminal.

ref(): void;

Reference the terminal to keep the event loop alive.

resize(cols: number,rows: number): void;

Resize the terminal.

@param cols

New number of columns

@param rows

New number of rows

setRawMode(enabled: boolean): void;

Set raw mode on the terminal. In raw mode, input is passed directly without processing.

@param enabled

Whether to enable raw mode

unref(): void;

Unreference the terminal to allow the event loop to exit.

write(data: string | BufferSource): number;

Write data to the terminal.

@param data

The data to write (string or BufferSource)

@returns

The number of bytes written

class Transpiler

Quickly transpile TypeScript, JSX, or JS to modern JavaScript.

const transpiler = new Bun.Transpiler();
transpiler.transformSync(`
const App = () => Hello World;
export default App;
`);
// This outputs:
const output = `
const App = () => jsx("div", {
children: "Hello World"
}, undefined, false, undefined, this);
export default App;
`
scan(code: StringOrBuffer): { exports: string[]; imports: Import[] };

Get a list of import paths and paths from a TypeScript, JSX, TSX, or JavaScript file.

@param code

The code to scan

const {imports, exports} = transpiler.scan(`
import {foo} from "baz";
export const hello = "hi!";
`);

console.log(imports); // ["baz"]
console.log(exports); // ["hello"]
scanImports(code: StringOrBuffer): Import[];

Get a list of import paths from a TypeScript, JSX, TSX, or JavaScript file.

@param code

The code to scan

const imports = transpiler.scanImports(`
import {foo} from "baz";
import type {FooType} from "bar";
import type {DogeType} from "wolf";
`);

console.log(imports); // ["baz"]

This is a fast path which performs less work than scan.

transform(code: StringOrBuffer,loader?: JavaScriptLoader): Promisestring>;

Transpile code from TypeScript or JSX into valid JavaScript. This function does not resolve imports.

@param code

The code to transpile

transformSync(code: StringOrBuffer,loader: JavaScriptLoader,ctx: object): string;

Transpile code from TypeScript or JSX into valid JavaScript. This function does not resolve imports.

@param code

The code to transpile

transformSync(code: StringOrBuffer,ctx: object): string;

Transpile code from TypeScript or JSX into valid JavaScript. This function does not resolve imports.

@param code

The code to transpile

@param ctx

An object to pass to macros

transformSync(code: StringOrBuffer,loader?: JavaScriptLoader): string;

Transpile code from TypeScript or JSX into valid JavaScript. This function does not resolve imports.

@param code

The code to transpile

class WebView

A headless browser view for automation. WKWebView on macOS (zero dependencies), Chrome DevTools Protocol elsewhere (or with backend: "chrome").

Each view runs its page in a separate renderer process. All input methods dispatch native events — the resulting DOM events have isTrusted: true.

await using view = new Bun.WebView({ width: 800, height: 600 });
await view.navigate("https://example.com");
await view.click("button[type=submit]"); // waits for actionability
const title = await view.evaluate("document.title");
const png = await view.screenshot();
readonly loading: boolean

True while a navigation is in flight.

onNavigated: null | (url: string, title: string) => void

Fired when a navigation completes successfully. The callback runs before the corresponding navigate() promise resolves.

onNavigationFailed: null | (error: Error) => void

Fired when a navigation fails. The callback runs before the corresponding navigate() promise rejects.

`. Updated when a navigation completes." data-algolia-static="false" data-algolia-merged="false" data-type="Property">readonly title: string

The page's . Updated when a navigation completes.

readonly url: string

The last-navigated URL. Updated when a navigation completes.

[Symbol.asyncDispose](): void;

Alias for close. Enables await using view = new Bun.WebView(...).

[Symbol.dispose](): void;

Alias for close. Enables using view = new Bun.WebView(...).

addEventListenerT = unknown>(type: `${string}.${string}`,listener: (event: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>) => void,options?: boolean | AddEventListenerOptions): void;

Subscribe to CDP events. Chrome backend only.

Event types are CDP method names directly — "Network.responseReceived", "Page.frameStartedLoading", "DOM.documentUpdated", etc. The listener receives a MessageEvent with the CDP params as event.data.

Enable the domain first with cdp("Domain.enable"), or Chrome won't send those events. Events without a registered listener are dropped before JSON parsing (no overhead for domains you enabled but don't fully listen to).

await view.navigate("about:blank");
await view.cdp("Network.enable");
view.addEventListener("Network.responseReceived", e => {
console.log(e.data.response.status, e.data.response.url);
});
await view.navigate("https://example.com");
addEventListener(type: string,listener: EventListenerOrEventListenerObject,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.

back(): Promisevoid>;

Navigate back in session history.

cdpT = unknown>(method: string,params?: Recordstring, unknown>): PromiseT>;

Send a raw Chrome DevTools Protocol command. Chrome backend only.

The command is scoped to this view's session (targets the current tab). Returns the decoded result object from the CDP response, or rejects with the error.message if Chrome reports a protocol error.

Call await view.navigate(...) at least once before using cdp() — the first navigate sets up the CDP session.

@param method

Domain-qualified method name, e.g. "Runtime.evaluate", "DOM.querySelector", "Emulation.setUserAgentOverride".

@param params

Command parameters. Must be JSON-serializable.

const view = new Bun.WebView({ backend: "chrome" });
await view.navigate("https://example.com");

const { root } = await view.cdp("DOM.getDocument");
const { nodeId } = await view.cdp("DOM.querySelector", {
nodeId: root.nodeId,
selector: "input#search",
});
await view.cdp("DOM.focus", { nodeId });
click(x: number,y: number,options?: ClickOptions): Promisevoid>;

Click at the given viewport coordinates.

Fires native pointerdown/mousedown/pointerup/mouseup/click events with isTrusted: true. The promise resolves after WebContent has processed the full event sequence (including all JS handlers) — no polling, WebKit's own mouse-queue-drain barrier.

click(selector: string,options?: ClickSelectorOptions): Promisevoid>;

Wait for an element to become actionable, then click its center.

Actionability is checked page-side at rAF rate: the element must be attached, have non-zero size, be in the viewport, be stable (bounding box unchanged for 2 consecutive frames), and be the topmost element at its center point (not obscured). Once actionable, a native click fires at the center coordinates.

// Waits for the button to appear and stop animating, then clicks.
await view.click("#submit");
close(): void;

Close the view and release its WebContent process. After close, all methods throw. Idempotent.

dispatchEvent(event: Event): boolean;

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

r.json())"); // awaited ``` **`script` must be an expression.** For statement sequences, wrap in an IIFE: `evaluate("(() => { let x = f(); return x + 1 })()")`. Values that `JSON.stringify` collapses to `undefined` (functions, symbols, `undefined` itself) resolve to `undefined`. Circular references reject. Only one `evaluate()` may be in flight at a time per view; a second concurrent call throws `ERR_INVALID_STATE`." data-algolia-static="false" data-algolia-merged="false" data-type="Method">evaluateT = unknown>(script: string): PromiseT>;

Run a JavaScript expression in the page's main frame and return the result as a native JS value.

The expression is wrapped as await (${script}) — if it evaluates to a Promise, the promise is awaited. The resolved value is serialized page-side via JSON.stringify and deserialized here, so arrays and objects come back as real structures:

await view.evaluate("document.title"); // string
await view.evaluate("[1, 2, 3]"); // number[]
await view.evaluate("({ a: 1, b: true })"); // { a: number, b: boolean }
await view.evaluate("fetch('/api').then(r => r.json())"); // awaited

script must be an expression. For statement sequences, wrap in an IIFE: evaluate("(() => { let x = f(); return x + 1 })()").

Values that JSON.stringify collapses to undefined (functions, symbols, undefined itself) resolve to undefined. Circular references reject.

Only one evaluate() may be in flight at a time per view; a second concurrent call throws ERR_INVALID_STATE.

forward(): Promisevoid>;

Navigate forward in session history.

navigate(url: string): Promisevoid>;

Navigate to a URL. Resolves when the main frame's load completes (WKNavigationDelegate didFinishNavigation).

await view.navigate("https://example.com");
await view.navigate("data:text/html,hello");
press(key: string & {} | VirtualKey,options?: PressOptions): Promisevoid>;

Press a key.

Named keys ("Enter", "Backspace", "ArrowLeft", etc.) map to editing commands where available and resolve when WebContent has processed them. "Escape" and keys with modifiers fall back to raw keyDown/keyUp (no WebKit barrier exists for keyboard events — a following evaluate() serializes).

A single character (e.g. "a") combined with modifiers sends a chord like Cmd+A.

reload(): Promisevoid>;

Reload the current page.

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

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

MDN Reference

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

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

resize(width: number,height: number): Promisevoid>;

Resize the viewport.

screenshot(options?: { encoding: 'blob'; format: 'jpeg' | 'png' | 'webp'; quality: number }): PromiseBlob>;

Capture a screenshot of the current viewport.

encoding controls the return type:

"blob" (default) — Blob with the right MIME type. WebKit: zero-copy mmap-backed store. Composes with Bun.write(), new Response(), blob.bytes()."buffer" — Node Buffer. WebKit: zero-copy (the same mmap'd pages wrapped as an ArrayBuffer that munmap's on GC)."base64" — base64-encoded string. Chrome: zero decode (CDP returns base64 natively). Direct Kitty t=d transmission."shmem" — { name, size }. The POSIX shm name is left linked; caller owns shm_unlink. Kitty t=s transmission: pass name as the payload, Kitty unlinks after reading. Not on Windows.
const { name, size } = await view.screenshot({ encoding: "shmem" });
process.stdout.write(
`\x1b_Gf=100,t=s,a=T,S=${size};${btoa(name)}\x1b\\`
);
// Kitty shm_open's the name, reads ${size} PNG bytes, unlinks.
screenshot(options: { encoding: 'buffer'; format: 'jpeg' | 'png' | 'webp'; quality: number }): PromiseBufferArrayBufferLike>>;

Capture a screenshot of the current viewport.

encoding controls the return type:

"blob" (default) — Blob with the right MIME type. WebKit: zero-copy mmap-backed store. Composes with Bun.write(), new Response(), blob.bytes()."buffer" — Node Buffer. WebKit: zero-copy (the same mmap'd pages wrapped as an ArrayBuffer that munmap's on GC)."base64" — base64-encoded string. Chrome: zero decode (CDP returns base64 natively). Direct Kitty t=d transmission."shmem" — { name, size }. The POSIX shm name is left linked; caller owns shm_unlink. Kitty t=s transmission: pass name as the payload, Kitty unlinks after reading. Not on Windows.
const { name, size } = await view.screenshot({ encoding: "shmem" });
process.stdout.write(
`\x1b_Gf=100,t=s,a=T,S=${size};${btoa(name)}\x1b\\`
);
// Kitty shm_open's the name, reads ${size} PNG bytes, unlinks.
screenshot(options: { encoding: 'base64'; format: 'jpeg' | 'png' | 'webp'; quality: number }): Promisestring>;

Capture a screenshot of the current viewport.

encoding controls the return type:

"blob" (default) — Blob with the right MIME type. WebKit: zero-copy mmap-backed store. Composes with Bun.write(), new Response(), blob.bytes()."buffer" — Node Buffer. WebKit: zero-copy (the same mmap'd pages wrapped as an ArrayBuffer that munmap's on GC)."base64" — base64-encoded string. Chrome: zero decode (CDP returns base64 natively). Direct Kitty t=d transmission."shmem" — { name, size }. The POSIX shm name is left linked; caller owns shm_unlink. Kitty t=s transmission: pass name as the payload, Kitty unlinks after reading. Not on Windows.
const { name, size } = await view.screenshot({ encoding: "shmem" });
process.stdout.write(
`\x1b_Gf=100,t=s,a=T,S=${size};${btoa(name)}\x1b\\`
);
// Kitty shm_open's the name, reads ${size} PNG bytes, unlinks.
screenshot(options: { encoding: 'shmem'; format: 'jpeg' | 'png' | 'webp'; quality: number }): Promise{ name: string; size: number }>;

Capture a screenshot of the current viewport.

encoding controls the return type:

"blob" (default) — Blob with the right MIME type. WebKit: zero-copy mmap-backed store. Composes with Bun.write(), new Response(), blob.bytes()."buffer" — Node Buffer. WebKit: zero-copy (the same mmap'd pages wrapped as an ArrayBuffer that munmap's on GC)."base64" — base64-encoded string. Chrome: zero decode (CDP returns base64 natively). Direct Kitty t=d transmission."shmem" — { name, size }. The POSIX shm name is left linked; caller owns shm_unlink. Kitty t=s transmission: pass name as the payload, Kitty unlinks after reading. Not on Windows.
const { name, size } = await view.screenshot({ encoding: "shmem" });
process.stdout.write(
`\x1b_Gf=100,t=s,a=T,S=${size};${btoa(name)}\x1b\\`
);
// Kitty shm_open's the name, reads ${size} PNG bytes, unlinks.
scroll(dx: number,dy: number): Promisevoid>;

Scroll the viewport by the given pixel delta.

Fires a native wheel event with isTrusted: true at the viewport center. Positive dy scrolls down (content up), matching window.scrollBy semantics.

scrollTo(selector: string,options?: ScrollToOptions): Promisevoid>;

Wait for an element to exist, then scroll it into view.

Uses Element.scrollIntoView({ block, behavior: 'instant' }) — scrolls every scrollable ancestor in the chain, not just the document. scrollY is updated synchronously before the promise resolves. No wheel event fires (this is a programmatic scroll).

await view.scrollTo("#footer"); // center (default)
await view.scrollTo("#hero", { block: "start" });
await view.scrollTo(".item", { block: "nearest" }); // minimal scroll
type(text: string): Promisevoid>;

Insert text into the focused element.

Uses WebKit's InsertText editing command (not keystroke simulation), so no keydown events fire — this is the same path as paste. No IME, no smart-quote substitution; the text lands exactly as given. Fires beforeinput/input with isTrusted: true.

static closeAll(): void;

Force-kill all browser subprocesses (Chrome and the WKWebView host). Pending promises on all views reject on the next event loop tick.

Called automatically at process exit. Call manually to reclaim browser resources early — subsequent new Bun.WebView() calls will respawn. Idempotent: calling when no subprocesses are alive is a no-op.

interface BunFile

Blob powered by the fastest system calls available for operating on files.

This Blob is lazy. That means it won't do any work until you read from it.

size will not be valid until the contents of the file are read at least once.type is auto-set based on the file extension when possible
const file = Bun.file("./hello.json");
console.log(file.type); // "application/json"
console.log(await file.text()); // '{"hello":"world"}'
lastModified: number

A UNIX timestamp indicating when the file was last modified.

readonly name?: string

The name or path of the file, as specified in the constructor.

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

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

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

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

delete(): Promisevoid>;

Deletes the file (same as unlink)

exists(): Promiseboolean>;

Does the file exist?

This returns true for regular files and FIFOs. It returns false for directories. Note that a race condition can occur where the file is deleted or renamed after this is called but before you open it.

This does a system call to check if the file exists, which can be slow.

If using this in an HTTP server, it's faster to instead use return new Response(Bun.file(path)) and then an error handler to handle exceptions.

Instead of checking for a file's existence and then performing the operation, it is faster to just perform the operation and handle the error.

For empty Blob, this always returns true.

formData(): PromiseFormData>;

Read the data from the blob as a FormData object.

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

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

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

image(options?: ConstructorOptions): Image;

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

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

Read the data from the blob as a JSON object.

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

0, () will be slower on macOS" data-algolia-static="false" data-algolia-merged="false" data-type="Method">slice(begin?: number,end?: number,contentType?: string): BunFile;

Offset any operation on the file starting at begin and ending at end. end is relative to 0

Similar to TypedArray.subarray. Does not copy the file, open the file, or modify the file.

If begin > 0, () will be slower on macOS

@param begin

start offset in bytes

@param end

absolute offset in bytes (relative to 0)

@param contentType

MIME type for the new BunFile

slice(begin?: number,contentType?: string): BunFile;

Offset any operation on the file starting at begin

Similar to TypedArray.subarray. Does not copy the file, open the file, or modify the file.

If begin > 0, Bun.write() will be slower on macOS

@param begin

start offset in bytes

@param contentType

MIME type for the new BunFile

slice(contentType?: string): BunFile;

Slice the file from the beginning to the end, optionally with a new MIME type.

@param contentType

MIME type for the new BunFile

stat(): PromiseStats>;

Provides useful information about the file.

stream(): ReadableStreamUint8ArrayArrayBufferLike>>;stream(): ReadableStreamUint8ArrayArrayBuffer>>;

Returns a readable stream of the blob's contents

text(): Promisestring>;

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

unlink(): Promisevoid>;

Deletes the file.

write(data: string | ArrayBuffer | SharedArrayBuffer | BunFile | Request | Response | ArrayBufferViewArrayBufferLike>,options?: { highWaterMark: number }): Promisenumber>;

Write data to the file. This is equivalent to using Bun.write with a BunFile.

@param data

The data to write.

@param options

The options to use for the write.

writer(options?: { highWaterMark: number }): FileSink;

Incremental writer for files and pipes.

interface S3File

Represents a file in an S3-compatible storage service. Extends the Blob interface for compatibility with web APIs.

readonly bucket?: string

The bucket name containing the file.

const file = s3.file("s3:http://my-bucket/file.txt");
console.log(file.bucket); // "my-bucket"
readonly name?: string

The name or path of the file in the bucket.

const file = s3.file("folder/image.jpg");
console.log(file.name); // "folder/image.jpg"
readonly readable: ReadableStreamUint8ArrayArrayBuffer>>

Gets a readable stream of the file's content. Useful for processing large files without loading them entirely into memory.

// Basic streaming read
const stream = file.stream();
for await (const chunk of stream) {
console.log('Received chunk:', chunk);
}
readonly size: numberreadonly type: stringunlink: () => Promisevoid>

Alias for delete() method. Provided for compatibility with Node.js fs API naming.

await file.unlink();
arrayBuffer(): PromiseArrayBuffer>;

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

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

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

delete(): Promisevoid>;

Deletes the file from S3.

@returns

Promise that resolves when deletion is complete

// Basic deletion
await file.delete();
exists(): Promiseboolean>;

Checks if the file exists in S3. Uses HTTP HEAD request to efficiently check existence without downloading.

@returns

Promise resolving to true if file exists, false otherwise

// Basic existence check
if (await file.exists()) {
console.log("File exists in S3");
}
formData(): PromiseFormData>;

Read the data from the blob as a FormData object.

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

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

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

image(options?: ConstructorOptions): Image;

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

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

Read the data from the blob as a JSON object.

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

presign(options?: S3FilePresignOptions): string;

Generates a presigned URL for the file. Allows temporary access to the file without exposing credentials.

@param options

Configuration for the presigned URL

@returns

Presigned URL string

// Basic download URL
const url = file.presign({
expiresIn: 3600 // 1 hour
});
slice(begin?: number,end?: number,contentType?: string): S3File;

Creates a new S3File representing a slice of the original file. Uses HTTP Range headers for efficient partial downloads.

@param begin

Starting byte offset

@param end

Ending byte offset (exclusive)

@param contentType

Optional MIME type for the slice

@returns

A new S3File representing the specified range

// Reading file header
const header = file.slice(0, 1024);
const headerText = await header.text();
slice(begin?: number,contentType?: string): S3File;slice(contentType?: string): S3File;stat(): PromiseS3Stats>;

Get the stat of a file in an S3-compatible storage service.

@returns

Promise resolving to S3Stat

stream(): ReadableStreamUint8ArrayArrayBuffer>>;text(): Promisestring>;

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

write(data: string | ArrayBuffer | SharedArrayBuffer | Blob | BunFile | Request | Response | ArrayBufferViewArrayBufferLike> | S3File | Archive,options?: S3Options): Promisenumber>;

Uploads data to S3. Supports various input types and automatically handles large files.

@param data

The data to upload

@param options

Upload configuration options

@returns

Promise resolving to number of bytes written

// Writing string data
await file.write("Hello World", {
type: "text/plain"
});
writer(options?: S3Options): NetworkSink;

Creates a writable stream for uploading data. Suitable for large files as it uses multipart upload.

@param options

Configuration for the upload

@returns

A NetworkSink for writing data

// Basic streaming write
const writer = file.writer({
type: "application/json"
});
writer.write('{"hello": ');
writer.write('"world"}');
await writer.end();
interface ServerWebSocketData>

HTTP & HTTPS Server

To start the server, see serve

For performance, Bun pre-allocates most of the data for 2048 concurrent requests. That means starting a new server allocates about 500 KB of memory. Try to avoid starting and stopping the server often (unless it's a new instance of bun).

Powered by a fork of uWebSockets. Thank you @alexhultman.

readonly development: boolean

Is the server running in development mode?

In development mode, Bun.serve() returns rendered error messages with stack traces instead of a generic 500 error. This makes debugging easier, but development mode shouldn't be used in production or you will risk leaking sensitive information.

readonly hostname: undefined | string

The hostname the server is listening on. Does not include the port.

This will be undefined when the server is listening on a unix socket.

"localhost"
readonly id: string

An identifier of the server instance

When bun is started with the --hot flag, this ID is used to hot reload the server without interrupting pending requests or websockets.

When bun is not started with the --hot flag, this ID is currently unused.

readonly pendingRequests: number

How many requests are in-flight right now?

readonly pendingWebSockets: number

How many ServerWebSockets are in-flight right now?

readonly port: undefined | number

The port the server is listening on.

This will be undefined when the server is listening on a unix socket.

3000
readonly protocol: null | 'http' | 'https'

The protocol the server is listening on.

"http" for normal servers"https" when TLS is enablednull for unix sockets or when unavailable
readonly url: URL[Symbol.dispose](): void;fetch(request: string | Request): Response | PromiseResponse>;

Mock the fetch handler for a running server.

This feature is not fully implemented yet. It doesn't normalize URLs consistently in all cases and it doesn't yet call the error handler consistently. This needs to be fixed

publish(topic: string,data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>,compress?: boolean): number;

Send a message to all connected ServerWebSocket subscribed to a topic

@param topic

The topic to publish to

@param data

The data to send

@param compress

Should the data be compressed? Ignored if the client does not support compression.

@returns

0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.

server.publish("chat", "Hello World");
ref(): void;

Undo a call to Server.unref

If the Server has already been stopped, this does nothing.

If Server.ref is called multiple times, this does nothing. Think of it as a boolean toggle.

reloadR extends string>(options: OptionsWebSocketData, R>): ServerWebSocketData>;

Update the fetch and error handlers without restarting the server.

This is useful if you want to change the behavior of your server without restarting it or for hot reloading.

// create the server
const server = Bun.serve({
fetch(request) {
return new Response("Hello World v1")
}
});

// Update the server to return a different response
server.reload({
fetch(request) {
return new Response("Hello World v2")
}
});

Passing other options such as port or hostname won't do anything.

requestIP(request: Request): null | SocketAddress;

Returns the client IP address and port of the given Request. If the request was closed or is a unix socket, returns null.

export default {
async fetch(request, server) {
return new Response(server.requestIP(request));
}
}
stop(closeActiveConnections?: boolean): Promisevoid>;

Stop listening to prevent new connections from being accepted.

By default, it does not cancel in-flight requests or websockets. That means it may take some time before all network activity stops.

@param closeActiveConnections

Immediately terminate in-flight requests, websockets, and stop accepting new connections.

subscriberCount(topic: string): number;

A count of connections subscribed to a given topic

This operation will loop through each topic internally to get the count.

@param topic

the websocket topic to check how many subscribers are connected to

@returns

the number of subscribers

timeout(request: Request,seconds: number): void;

Reset the idleTimeout of the given Request to the number in seconds. 0 means no timeout.

export default {
async fetch(request, server) {
server.timeout(request, 60);
await Bun.sleep(30000);
return new Response("30 seconds have passed");
}
}
unref(): void;

Don't keep the process alive if this server is the only thing left. Active connections may continue to keep the process alive.

By default, the server is ref'd.

To prevent new connections from being accepted, use Server.stop

upgrade(request: Request,...options: [WebSocketData] extends [undefined] ? [options?: { data: undefined; headers: HeadersInit }] : [options: { data: WebSocketData; headers: HeadersInit }]): boolean;

Upgrade a Request to a ServerWebSocket

@param request

The Request to upgrade

@param options

Pass headers or attach data to the ServerWebSocket

@returns

true if the upgrade was successful and false if it failed

import { serve } from "bun";
const server: Bun.Server: string }> = serve({
websocket: {
open: (ws) => {
console.log("Client connected");
},
message: (ws, message) => {
console.log("Client sent message", message);
},
close: (ws) => {
console.log("Client disconnected");
},
},
fetch(req, server) {
const url = new URL(req.url);
if (url.pathname === "/chat") {
const upgraded = server.upgrade(req, {
data: {user: "John Doe"}
});
if (!upgraded) {
return new Response("Upgrade failed", { status: 400 });
}
}
return new Response("Hello World");
},
});

What you pass to data is available on the ServerWebSocket.data property

const argv: string[]

The raw arguments passed to the process, including flags passed to Bun. If you want to easily read flags passed to your script, consider using process.argv instead.

const cron: {(schedule: CronWithAutocomplete, handler: (this: CronJob) => unknown) => CronJob; (path: string, schedule: CronWithAutocomplete, title: string) => Promisevoid>}const embeddedFiles: ReadonlyArrayBlob>

A list of files embedded into the standalone executable. Lexigraphically sorted by name.

If the process is not a standalone executable, this returns an empty array.

const enableANSIColors: boolean

Are ANSI colors enabled for stdin and stdout?

Used for console.log

const env: Env & NodeJS.ProcessEnv & ImportMetaEnv

The environment variables of the process

Defaults to process.env as it was when the current Bun process launched.

Changes to process.env at runtime won't automatically be reflected in the default value. For that, you can pass process.env explicitly.

const fetch: typeof globalThis.fetchconst hash: (data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, seed?: number | bigint) => number | bigint & Hash

Hash a string or array buffer using Wyhash

This is not a cryptographic hash function.

const isMainThread: boolean

Is the current global scope the main thread?

const main: string

What script launched Bun?

Absolute file path

"/never-gonna-give-you-up.js"
const password: { hash(password: StringOrBuffer, algorithm?: 'argon2d' | 'argon2i' | 'argon2id' | Argon2Algorithm | BCryptAlgorithm | 'bcrypt'): Promisestring>; hashSync(password: StringOrBuffer, algorithm?: 'argon2d' | 'argon2i' | 'argon2id' | Argon2Algorithm | BCryptAlgorithm | 'bcrypt'): string; verify(password: StringOrBuffer, hash: StringOrBuffer, algorithm?: 'argon2d' | 'argon2i' | 'argon2id' | 'bcrypt'): Promiseboolean>; verifySync(password: StringOrBuffer, hash: StringOrBuffer, algorithm?: 'argon2d' | 'argon2i' | 'argon2id' | 'bcrypt'): boolean }

Hash and verify passwords using argon2 or bcrypt. The default is argon2. Password hashing functions are necessarily slow, and this object will automatically run in a worker thread.

Example with argon2

import {password} from "bun";

const hash = await password.hash("hello world");
const verify = await password.verify("hello world", hash);
console.log(verify); // true

Example with bcrypt

import {password} from "bun";

const hash = await password.hash("hello world", "bcrypt");
// algorithm is optional, will be inferred from the hash if not specified
const verify = await password.verify("hello world", hash, "bcrypt");

console.log(verify); // true
const plugin: BunRegisterPluginconst redis: RedisClient

Default Redis client

Connection information populated from one of, in order of preference:

process.env.VALKEY_URLprocess.env.REDIS_URL"valkey:http://localhost:6379"
const revision: string

The git sha at the time the currently-running version of Bun was compiled

"a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2"
const s3: S3Client

A default instance of S3Client

Pulls credentials from environment variables. Use new Bun.S3Client() if you need to explicitly set credentials.

const secrets: { delete(options: { name: string; service: string }): Promiseboolean>; get(options: { name: string; service: string }): Promisenull | string>; set(options: { allowUnrestrictedAccess: boolean; name: string; service: string; value: string }): Promisevoid> }

Securely store and retrieve sensitive credentials using the operating system's native credential storage.

Uses platform-specific secure storage:

macOS: Keychain ServicesLinux: libsecret (GNOME Keyring, KWallet, etc.)Windows: Windows Credential Manager
import { secrets } from "bun";

// Store a credential
await secrets.set({
service: "my-cli-tool",
name: "github-token",
value: "ghp_xxxxxxxxxxxxxxxxxxxx"
});

// Retrieve a credential
const token = await secrets.get({
service: "my-cli-tool",
name: "github-token"
});

if (token) {
console.log("Token found:", token);
} else {
console.log("Token not found");
}

// Delete a credential
const deleted = await secrets.delete({
service: "my-cli-tool",
name: "github-token"
});
console.log("Deleted:", deleted); // true if deleted, false if not found
const sql: SQL

SQL client

const stderr: BunFile

Write to stderr

const stdin: BunFile

Read from stdin

This is a read-only BunFile

const stdout: BunFile

Write to stdout

const version: string

The current version of Bun

"1.2.0"
const version_with_sha: string

The current version of Bun with the shortened commit sha of the build

"v1.2.0 (a1b2c3d4)"
function $(strings: TemplateStringsArray,...expressions: ShellExpression[]): ShellPromise;

The Bun shell is a powerful tool for running shell commands.

const result = await $`echo "Hello, world!"`.text();
console.log(result); // "Hello, world!"
class ShellError

ShellError represents an error that occurred while executing a shell command with the Bun Shell.

try {
const result = await $`exit 1`;
} catch (error) {
if (error instanceof $.ShellError) {
console.log(error.exitCode); // 1
}
}
cause?: unknown

The cause of the error.

readonly exitCode: numbermessage: stringname: stringstack?: stringreadonly stderr: Bufferreadonly stdout: Bufferstatic stackTraceLimit: number

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

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

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

arrayBuffer(): ArrayBuffer;

Read from stdout as an ArrayBuffer

@returns

Stdout as an ArrayBuffer

const output = await $`echo hello`;
console.log(output.arrayBuffer()); // ArrayBuffer { byteLength: 6 }
blob(): Blob;

Read from stdout as a Blob

@returns

Stdout as a blob

const output = await $`echo hello`;
console.log(output.blob()); // Blob { size: 6, type: "" }
bytes(): Uint8ArrayArrayBuffer>;

Read from stdout as an Uint8Array

@returns

Stdout as an Uint8Array

const output = await $`echo hello`;
console.log(output.bytes()); // Uint8Array { byteLength: 6 }
json(): any;

Read from stdout as a JSON object

@returns

Stdout as a JSON object

const output = await $`echo '{"hello": 123}'`;
console.log(output.json()); // { hello: 123 }
text(encoding?: BufferEncoding): string;

Read from stdout as a string

@param encoding

The encoding to use when decoding the output

@returns

Stdout as a string with the given encoding

Read as UTF-8 string

const output = await $`echo hello`;
console.log(output.text()); // "hello\n"

Read as base64 string

const output = await $`echo ${atob("hello")}`;
console.log(output.text("base64")); // "hello\n"
static captureStackTrace(targetObject: object,constructorOpt?: Function): void;

Create .stack property on a target object

static isError(value: unknown): value is Error;

Check if a value is an instance of Error

@param value

The value to check

@returns

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

static prepareStackTrace(err: Error,stackTraces: CallSite[]): any;
class ShellPromise

The Bun.$.ShellPromise class represents a shell command that gets executed once awaited, or called with .text(), .json(), etc.

const myShellPromise = $`echo "Hello, world!"`;
const result = await myShellPromise.text();
console.log(result); // "Hello, world!"
readonly [Symbol.toStringTag]: stringreadonly static [Symbol.species]: PromiseConstructorarrayBuffer(): PromiseArrayBuffer>;

Read from stdout as an ArrayBuffer

Automatically calls quiet

@returns

A promise that resolves with stdout as an ArrayBuffer

const output = await $`echo hello`.arrayBuffer();
console.log(output); // ArrayBuffer { byteLength: 6 }
blob(): PromiseBlob>;

Read from stdout as a Blob

Automatically calls quiet

@returns

A promise that resolves with stdout as a Blob

const output = await $`echo hello`.blob();
console.log(output); // Blob { size: 6, type: "" }
catchTResult = never>(onrejected?: null | (reason: any) => TResult | PromiseLikeTResult>): PromiseShellOutput | TResult>;

Attaches a callback for only the rejection of the Promise.

@param onrejected

The callback to execute when the Promise is rejected.

@returns

A Promise for the completion of the callback.

cwd(newCwd: string): this;

Change the current working directory of the shell.

@param newCwd

The new working directory

env(newEnv: undefined | Dictstring> | Recordstring, undefined | string>): this;

Set environment variables for the shell.

@param newEnv

The new environment variables

await $`echo $FOO`.env({ ...process.env, FOO: "LOL!" })
expect(stdout.toString()).toBe("LOL!");
finally(onfinally?: null | () => void): PromiseShellOutput>;

Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The resolved value cannot be modified from the callback.

@param onfinally

The callback to execute when the Promise is settled (fulfilled or rejected).

@returns

A Promise for the completion of the callback.

json(): Promiseany>;

Read from stdout as a JSON object

Automatically calls quiet

@returns

A promise that resolves with stdout as a JSON object

const output = await $`echo '{"hello": 123}'`.json();
console.log(output); // { hello: 123 }
lines(): AsyncIterablestring>;

Read from stdout as a string, line by line

Automatically calls quiet to disable echoing to stdout.

nothrow(): this;

Configure the shell to not throw an exception on non-zero exit codes. Throwing can be re-enabled with .throws(true).

By default, the shell with throw an exception on commands which return non-zero exit codes.

quiet(isQuiet?: boolean): this;

By default, the shell will write to the current process's stdout and stderr, as well as buffering that output.

This configures the shell to only buffer the output.

@param isQuiet

Whether to suppress output. Defaults to true.

text(encoding?: BufferEncoding): Promisestring>;

Read from stdout as a string.

Automatically calls quiet to disable echoing to stdout.

@param encoding

The encoding to use when decoding the output

@returns

A promise that resolves with stdout as a string

Read as UTF-8 string

const output = await $`echo hello`.text();
console.log(output); // "hello\n"

Read as base64 string

const output = await $`echo ${atob("hello")}`.text("base64");
console.log(output); // "hello\n"
thenTResult1 = ShellOutput, TResult2 = never>(onfulfilled?: null | (value: ShellOutput) => TResult1 | PromiseLikeTResult1>,onrejected?: null | (reason: any) => TResult2 | PromiseLikeTResult2>): PromiseTResult1 | TResult2>;

Attaches callbacks for the resolution and/or rejection of the Promise.

@param onfulfilled

The callback to execute when the Promise is resolved.

@param onrejected

The callback to execute when the Promise is rejected.

@returns

A Promise for the completion of which ever callback is executed.

throws(shouldThrow: boolean): this;

Configure whether or not the shell should throw an exception on non-zero exit codes.

By default, this is configured to true.

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

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

@param values

An array of Promises.

@returns

A new Promise.

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

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

@param values

An array of Promises.

@returns

A new Promise.

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

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

@param values

An array or iterable of Promises.

@returns

A new Promise.

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

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

@param values

An array of Promises.

@returns

A new Promise.

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

Creates a new rejected promise for the provided reason.

@param reason

The reason the promise was rejected.

@returns

A new rejected Promise.

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

Creates a new resolved promise for the provided value.

@param value

A promise.

@returns

A promise whose internal state matches the provided promise.

static tryT, A extends any[] = []>(fn: (...args: A) => T | PromiseLikeT>,...args: A): PromiseT>;

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

@param fn

The function to run

@param args

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

@returns

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

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

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

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

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

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

await promise; // "Hello world!"
interface ShellOutputreadonly exitCode: numberreadonly stderr: Bufferreadonly stdout: BufferarrayBuffer(): ArrayBuffer;

Read from stdout as an ArrayBuffer

@returns

Stdout as an ArrayBuffer

const output = await $`echo hello`;
console.log(output.arrayBuffer()); // ArrayBuffer { byteLength: 6 }
blob(): Blob;

Read from stdout as a Blob

@returns

Stdout as a blob

const output = await $`echo hello`;
console.log(output.blob()); // Blob { size: 6, type: "" }
bytes(): Uint8ArrayArrayBuffer>;

Read from stdout as an Uint8Array

@returns

Stdout as an Uint8Array

const output = await $`echo hello`;
console.log(output.bytes()); // Uint8Array { byteLength: 6 }
json(): any;

Read from stdout as a JSON object

@returns

Stdout as a JSON object

const output = await $`echo '{"hello": 123}'`;
console.log(output.json()); // { hello: 123 }
text(encoding?: BufferEncoding): string;

Read from stdout as a string

@param encoding

The encoding to use when decoding the output

@returns

Stdout as a string with the given encoding

Read as UTF-8 string

const output = await $`echo hello`;
console.log(output.text()); // "hello\n"

Read as base64 string

const output = await $`echo ${atob("hello")}`;
console.log(output.text("base64")); // "hello\n"
const Shell: new () => $function braces(pattern: string): string[];

Perform bash-like brace expansion on the given pattern.

@param pattern

Brace pattern to expand

const result = braces('index.{js,jsx,ts,tsx}');
console.log(result) // ['index.js', 'index.jsx', 'index.ts', 'index.tsx']
function cwd(newCwd?: string): typeof $;@param newCwd

Default working directory to use for shells created by this instance.

function env(newEnv?: Dictstring> | Recordstring, undefined | string>): typeof $;

Change the default environment variables for shells created by this instance.

@param newEnv

Default environment variables to use for shells created by this instance.

import {$} from 'bun';
$.env({ BUN: "bun" });
await $`echo $BUN`;
// "bun"
function escape(input: string): string;

Escape strings for input into shell commands.

function nothrow(): typeof $;

Configure the shell to not throw an exception on non-zero exit codes.

function throws(shouldThrow: boolean): typeof $;

Configure whether or not the shell should throw an exception on non-zero exit codes.

function allocUnsafe(size: number): Uint8ArrayArrayBuffer>;

Allocate a new Uint8Array without zeroing the bytes.

This can be 3.5x faster than new Uint8Array(size), but if you send uninitialized memory to your users (even unintentionally), it can potentially leak anything recently in memory.

function build(config: BuildConfig): PromiseBuildOutput>;

Bundles JavaScript, TypeScript, CSS, HTML and other supported files into optimized outputs.

@param config

Build configuration options

@returns

Promise that resolves to build output containing generated artifacts and build status

Basic usage - Bundle a single entrypoint and check results

const result = await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist'
});

if (!result.success) {
console.error('Build failed:', result.logs);
process.exit(1);
}
function color(input: ColorInput,outputFormat?: 'number' | 'hex' | 'ansi' | 'ansi-16' | 'ansi-16m' | 'ansi-256' | 'css' | 'HEX' | 'hsl' | 'lab' | 'rgb' | 'rgba'): null | string;

Converts formats of colors

@param input

A value that could possibly be a color

@param outputFormat

An optional output format

function color(input: ColorInput,outputFormat: '[rgb]'): null | [number, number, number];

Convert any color input to rgb

@param input

Any color input

@param outputFormat

Specify [rgb] to output as an array with r, g, and b properties

function color(input: ColorInput,outputFormat: '[rgba]'): null | [number, number, number, number];

Convert any color input to rgba

@param input

Any color input

@param outputFormat

Specify [rgba] to output as an array with r, g, b, and a properties

function color(input: ColorInput,outputFormat: '{rgb}'): null | { b: number; g: number; r: number };

Convert any color input to a number

@param input

Any color input

@param outputFormat

Specify {rgb} to output as an object with r, g, and b properties

function color(input: ColorInput,outputFormat: '{rgba}'): null | { a: number; b: number; g: number; r: number };

Convert any color input to rgba

@param input

Any color input

@param outputFormat

Specify {rgba} to output as an object with r, g, b, and a properties

function color(input: ColorInput,outputFormat: 'number'): null | number;

Convert any color input to a number

@param input

Any color input

@param outputFormat

Specify number to output as a number

function concatArrayBuffers(buffers: ArrayBufferLike | ArrayBufferViewArrayBufferLike>[],maxLength?: number): ArrayBuffer;

Concatenate an array of typed arrays into a single ArrayBuffer. This is a fast path.

You can do this manually if you'd like, but this function will generally be a little faster.

If you want a Uint8Array instead, consider Buffer.concat.

@param buffers

An array of typed arrays to concatenate.

@returns

An ArrayBuffer with the data from all the buffers.

Here is similar code to do it manually, except about 30% slower:

 var chunks = [...];
var size = 0;
for (const chunk of chunks) {
size += chunk.byteLength;
}
var buffer = new ArrayBuffer(size);
var view = new Uint8Array(buffer);
var offset = 0;
for (const chunk of chunks) {
view.set(chunk, offset);
offset += chunk.byteLength;
}
return buffer;

This function is faster because it uses uninitialized memory when copying. Since the entire length of the buffer is known, it is safe to use uninitialized memory.

function concatArrayBuffers(buffers: ArrayBufferLike | ArrayBufferViewArrayBufferLike>[],maxLength: number,asUint8Array: false): ArrayBuffer;

Concatenate an array of typed arrays into a single ArrayBuffer. This is a fast path.

You can do this manually if you'd like, but this function will generally be a little faster.

If you want a Uint8Array instead, consider Buffer.concat.

@param buffers

An array of typed arrays to concatenate.

@returns

An ArrayBuffer with the data from all the buffers.

Here is similar code to do it manually, except about 30% slower:

 var chunks = [...];
var size = 0;
for (const chunk of chunks) {
size += chunk.byteLength;
}
var buffer = new ArrayBuffer(size);
var view = new Uint8Array(buffer);
var offset = 0;
for (const chunk of chunks) {
view.set(chunk, offset);
offset += chunk.byteLength;
}
return buffer;

This function is faster because it uses uninitialized memory when copying. Since the entire length of the buffer is known, it is safe to use uninitialized memory.

function concatArrayBuffers(buffers: ArrayBufferLike | ArrayBufferViewArrayBufferLike>[],maxLength: number,asUint8Array: true): Uint8ArrayArrayBuffer>;

Concatenate an array of typed arrays into a single ArrayBuffer. This is a fast path.

You can do this manually if you'd like, but this function will generally be a little faster.

If you want a Uint8Array instead, consider Buffer.concat.

@param buffers

An array of typed arrays to concatenate.

@returns

An ArrayBuffer with the data from all the buffers.

Here is similar code to do it manually, except about 30% slower:

 var chunks = [...];
var size = 0;
for (const chunk of chunks) {
size += chunk.byteLength;
}
var buffer = new ArrayBuffer(size);
var view = new Uint8Array(buffer);
var offset = 0;
for (const chunk of chunks) {
view.set(chunk, offset);
offset += chunk.byteLength;
}
return buffer;

This function is faster because it uses uninitialized memory when copying. Since the entire length of the buffer is known, it is safe to use uninitialized memory.

function connectData = undefined>(options: TCPSocketConnectOptionsData>): PromiseSocketData>>;

Create a TCP client that connects to a server via a TCP socket

function connectData = undefined>(options: UnixSocketOptionsData>): PromiseSocketData>>;

Create a TCP client that connects to a server via a unix socket

function deepEquals(a: any,b: any,strict?: boolean): boolean;

Fast deep-equality check two objects.

This also powers expect().toEqual in bun:test

@param strict
function deepMatch(subset: unknown,a: unknown): boolean;

Returns true if all properties in the subset exist in the other and have equal values.

This also powers expect().toMatchObject in bun:test

function deflateSync(data: string | ArrayBuffer | Uint8ArrayArrayBuffer>,options?: ZlibCompressionOptions | LibdeflateCompressionOptions): Uint8ArrayArrayBuffer>;

Compresses a chunk of data with zlib DEFLATE algorithm.

@param data

The buffer of data to compress

@param options

Compression options to use

@returns

The output buffer with the compressed data

function escapeHTML(input: string | number | boolean | object): string;

Escape the following characters in a string:

function file(path: string | URL,options?: BlobPropertyBag): BunFile;

Blob powered by the fastest system calls available for operating on files.

This Blob is lazy. That means it won't do any work until you read from it.

size will not be valid until the contents of the file are read at least once.type is auto-set based on the file extension when possible
@param path

The path to the file (lazily loaded) if the path starts with s3:http:// it will behave like S3File

const file = Bun.file("./hello.json");
console.log(file.type); // "application/json"
console.log(await file.json()); // { hello: "world" }
function file(path: ArrayBufferLike | Uint8ArrayArrayBuffer>,options?: BlobPropertyBag): BunFile;

Blob that leverages the fastest system calls available to operate on files.

This Blob is lazy. It won't do any work until you read from it. Errors propagate as promise rejections.

Blob.size will not be valid until the contents of the file are read at least once. Blob.type will have a default set based on the file extension

@param path

The path to the file as a byte buffer (the buffer is copied) if the path starts with s3:http:// it will behave like S3File

const file = Bun.file(new TextEncoder.encode("./hello.json"));
console.log(file.type); // "application/json"
function file(fileDescriptor: number,options?: BlobPropertyBag): BunFile;

Blob powered by the fastest system calls available for operating on files.

This Blob is lazy. That means it won't do any work until you read from it.

size will not be valid until the contents of the file are read at least once.
@param fileDescriptor

The file descriptor of the file

const file = Bun.file(fd);
function fileURLToPath(url: string | URL): string;

Convert a URL to a filesystem path.

@param url

The URL to convert.

@returns

A filesystem path.

const path = Bun.fileURLToPath(new URL("file:http:///foo/bar.txt"));
console.log(path); // "/foo/bar.txt"
function gc(force?: boolean): void;

Manually trigger the garbage collector

This does two things:

It tells JavaScriptCore to run the garbage collectorIt tells mimalloc to clean up fragmented memory. Mimalloc manages the heap not used in JavaScriptCore.
@param force

Synchronously run the garbage collector

function generateHeapSnapshot(format?: 'jsc'): HeapSnapshot;

Show precise statistics about memory usage of your application

Generate a heap snapshot in JavaScriptCore's format that can be viewed with bun --inspect or Safari's Web Inspector

function generateHeapSnapshot(format: 'v8'): string;

Show precise statistics about memory usage of your application

Generate a V8 Heap Snapshot that can be used with Chrome DevTools & Visual Studio Code

This is a JSON string that can be saved to a file.

const snapshot = Bun.generateHeapSnapshot("v8");
await Bun.write("heap.heapsnapshot", snapshot);
function generateHeapSnapshot(format: 'v8',encoding: 'arraybuffer'): ArrayBuffer;

Show precise statistics about memory usage of your application

Generate a V8 Heap Snapshot as an ArrayBuffer.

This avoids the overhead of creating a JavaScript string for large heap snapshots. The ArrayBuffer contains the UTF-8 encoded JSON.

const snapshot = Bun.generateHeapSnapshot("v8", "arraybuffer");
await Bun.write("heap.heapsnapshot", snapshot);
function gunzipSync(data: string | ArrayBuffer | Uint8ArrayArrayBuffer>,options?: ZlibCompressionOptions | LibdeflateCompressionOptions): Uint8ArrayArrayBuffer>;

Decompresses a chunk of data with zlib GUNZIP algorithm.

@param data

The buffer of data to decompress

@returns

The output buffer with the decompressed data

function gzipSync(data: string | ArrayBuffer | Uint8ArrayArrayBuffer>,options?: ZlibCompressionOptions | LibdeflateCompressionOptions): Uint8ArrayArrayBuffer>;

Compresses a chunk of data with zlib GZIP algorithm.

@param data

The buffer of data to compress

@param options

Compression options to use

@returns

The output buffer with the compressed data

function indexOfLine(buffer: ArrayBufferLike | ArrayBufferViewArrayBufferLike>,offset?: number): number;

Find the index of a newline character in potentially ill-formed UTF-8 text.

This is sort of like readline() except without the IO.

function inflateSync(data: string | ArrayBuffer | Uint8ArrayArrayBuffer>,options?: ZlibCompressionOptions | LibdeflateCompressionOptions): Uint8ArrayArrayBuffer>;

Decompresses a chunk of data with zlib INFLATE algorithm.

@param data

The buffer of data to decompress

@returns

The output buffer with the decompressed data

function inspect(arg: any,options?: BunInspectOptions): string;

Pretty-print an object the same as console.log to a string

Supports JSX

@param arg

The value to inspect

@param options

Options for the inspection

const custom: inspect.custom

That can be used to declare custom inspect functions.

function table(tabularData: object | unknown[],properties?: string[],options?: { colors: boolean }): string;

Pretty-print an object or array as a table

Like console.table, except it returns a string

function table(tabularData: object | unknown[],options?: { colors: boolean }): string;

Pretty-print an object or array as a table

Like console.table, except it returns a string

function listenData = undefined>(options: TCPSocketListenOptionsData>): TCPSocketListenerData>;

Create a TCP server that listens on a port

function listenData = undefined>(options: UnixSocketOptionsData>): UnixSocketListenerData>;

Create a TCP server that listens on a unix socket

function mmap(path: PathLike,opts?: MMapOptions): Uint8ArrayArrayBuffer>;

Open a file as a live-updating Uint8Array without copying memory

Writing to the array writes to the file.Reading from the array reads from the file.

This uses the mmap() syscall under the hood.

This API inherently has some rough edges:

It does not support empty files. It will throw a SystemError with EINVALUsage on shared/networked filesystems is discouraged. It will be very slow.If you delete or truncate the file, that will crash bun. This is called a segmentation fault.

To close the file, set the array to null and it will be garbage collected eventually.

function nanoseconds(): number;

Returns the number of nanoseconds since the process was started.

This function uses a high-resolution monotonic system timer to provide precise time measurements. In JavaScript, numbers are represented as double-precision floating-point values (IEEE 754), which can safely represent integers up to 2^53 - 1 (Number.MAX_SAFE_INTEGER).

Due to this limitation, while the internal counter may continue beyond this point, the precision of the returned value will degrade after 14.8 weeks of uptime (when the nanosecond count exceeds Number.MAX_SAFE_INTEGER). Beyond this point, the function will continue to count but with reduced precision, which might affect time calculations and comparisons in long-running applications.

@returns

The number of nanoseconds since the process was started, with precise values up to Number.MAX_SAFE_INTEGER.

function openInEditor(path: string,options?: EditorOptions): void;

Open a file in your local editor. Auto-detects via $VISUAL || $EDITOR

@param path

path to open

function pathToFileURL(path: string): URL;

Convert a filesystem path to a file:// URL.

@param path

The path to convert.

@returns

A URL with the file:// scheme.

const url = Bun.pathToFileURL("/foo/bar.txt");
console.log(url.href); // "file:http:///foo/bar.txt"

Internally, this function uses WebKit's URL API to convert the path to a file:// URL.

function peekT = undefined>(promise: T | PromiseT>): T | PromiseT>;

Extract the value from the Promise in the same tick of the event loop

function statusT = undefined>(promise: T | PromiseT>): 'pending' | 'fulfilled' | 'rejected';function randomUUIDv5(name: string | BufferSource,namespace: string | BufferSource,encoding?: 'base64' | 'base64url' | 'hex'): string;

Generate a UUIDv5, which is a name-based UUID based on the SHA-1 hash of a namespace UUID and a name.

@param name

The name to use for the UUID

@param namespace

The namespace to use for the UUID

@param encoding

The encoding to use for the UUID

import { randomUUIDv5 } from "bun";
const uuid = randomUUIDv5("www.example.com", "dns");
console.log(uuid); // "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
import { randomUUIDv5 } from "bun";
const uuid = randomUUIDv5("www.example.com", "url");
console.log(uuid); // "6ba7b811-9dad-11d1-80b4-00c04fd430c8"
function randomUUIDv5(name: string | BufferSource,namespace: string | BufferSource,encoding: 'buffer'): Buffer;

Generate a UUIDv5 as a Buffer

@param name

The name to use for the UUID

@param namespace

The namespace to use for the UUID

@param encoding

The encoding to use for the UUID

import { randomUUIDv5 } from "bun";
const uuid = randomUUIDv5("www.example.com", "url", "buffer");
console.log(uuid); //
function randomUUIDv7(encoding?: 'base64' | 'base64url' | 'hex',timestamp?: number | Date): string;

Generate a UUIDv7, which is a sequential ID based on the current timestamp with a random component.

When the same timestamp is used multiple times, a monotonically increasing counter is appended to allow sorting. The final 8 bytes are cryptographically random. When the timestamp changes, the counter resets to a psuedo-random integer.

@param encoding

"hex" | "base64" | "base64url"

@param timestamp

Unix timestamp in milliseconds, defaults to Date.now()

import { randomUUIDv7 } from "bun";
const array = [
randomUUIDv7(),
randomUUIDv7(),
randomUUIDv7(),
]
[
"0192ce07-8c4f-7d66-afec-2482b5c9b03c",
"0192ce07-8c4f-7d67-805f-0f71581b5622",
"0192ce07-8c4f-7d68-8170-6816e4451a58"
]
function randomUUIDv7(encoding: 'buffer',timestamp?: number | Date): Buffer;

Generate a UUIDv7 as a Buffer

@param encoding

"buffer"

@param timestamp

Unix timestamp in milliseconds, defaults to Date.now()

function readableStreamToArrayT>(stream: ReadableStreamT>): T[] | PromiseT[]>;

Consume all data from a ReadableStream until it closes or errors.

@param stream

The stream to consume

@returns

A promise that resolves with the chunks as an array

function readableStreamToArrayBuffer(stream: ReadableStreamArrayBufferLike | ArrayBufferViewArrayBufferLike>>): ArrayBuffer | PromiseArrayBuffer>;

Consume all data from a ReadableStream until it closes or errors.

Concatenate the chunks into a single ArrayBuffer.

Each chunk must be a TypedArray or an ArrayBuffer. If you need to support chunks of different types, consider readableStreamToBlob

@param stream

The stream to consume.

@returns

A promise that resolves with the concatenated chunks or the concatenated chunks as an ArrayBuffer.

function readableStreamToFormData(stream: ReadableStreamstring | Uint8ArrayArrayBufferLike> | Uint8ClampedArrayArrayBufferLike> | Uint16ArrayArrayBufferLike> | Uint32ArrayArrayBufferLike> | Int8ArrayArrayBufferLike> | Int16ArrayArrayBufferLike> | Int32ArrayArrayBufferLike> | BigUint64ArrayArrayBufferLike> | BigInt64ArrayArrayBufferLike> | Float16ArrayArrayBufferLike> | Float32ArrayArrayBufferLike> | Float64ArrayArrayBufferLike> | DataViewArrayBufferLike>>,multipartBoundaryExcludingDashes?: string | Uint8ArrayArrayBufferLike> | Uint8ClampedArrayArrayBufferLike> | Uint16ArrayArrayBufferLike> | Uint32ArrayArrayBufferLike> | Int8ArrayArrayBufferLike> | Int16ArrayArrayBufferLike> | Int32ArrayArrayBufferLike> | BigUint64ArrayArrayBufferLike> | BigInt64ArrayArrayBufferLike> | Float16ArrayArrayBufferLike> | Float32ArrayArrayBufferLike> | Float64ArrayArrayBufferLike> | DataViewArrayBufferLike>): PromiseFormData>;

Consume all data from a ReadableStream until it closes or errors.

Reads the multi-part or URL-encoded form data into a FormData object

@param stream

The stream to consume.

@param multipartBoundaryExcludingDashes

Optional boundary to use for multipart form data. If none is provided, assumes it is a URLEncoded form.

@returns

A promise that resolves with the data encoded into a FormData object.

Multipart form data example

// without dashes
const boundary = "WebKitFormBoundary" + Math.random().toString(16).slice(2);

const myStream = getStreamFromSomewhere() // ...
const formData = await Bun.readableStreamToFormData(stream, boundary);
formData.get("foo"); // "bar"

URL-encoded form data example

const stream = new Response("hello=123").body;
const formData = await Bun.readableStreamToFormData(stream);
formData.get("hello"); // "123"
function resolve(moduleId: string,parent: string): Promisestring>;

Resolve a moduleId as though it were imported from parent

On failure, throws a ResolveMessage

For now, use the sync version. There is zero performance benefit to using this async version. It exists for future-proofing.

function resolveSync(moduleId: string,parent: string): string;

Synchronously resolve a moduleId as though it were imported from parent

On failure, throws a ResolveMessage

function serveWebSocketData = undefined, R extends string = never>(options: OptionsWebSocketData, R>): ServerWebSocketData>;

Bun.serve provides a high-performance HTTP server with built-in routing support. It enables both function-based and object-based route handlers with type-safe parameters and method-specific handling.

@param options

Server configuration options

Basic Usage

Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello World");
}
});
function sha(input: StringOrBuffer,hashInto?: TypedArrayArrayBufferLike>): TypedArray;@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer will be faster

@param hashInto

optional Uint8Array to write the hash to. 32 bytes minimum.

This hashing function balances speed with cryptographic strength. This does not encrypt or decrypt data.

The implementation uses BoringSSL (used in Chromium & Go)

The equivalent openssl command is:

# You will need OpenSSL 3 or later
openssl sha512-256 /path/to/file
function sha(input: StringOrBuffer,encoding: DigestEncoding): string;@param input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer will be faster

@param encoding

DigestEncoding to return the hash in

This hashing function balances speed with cryptographic strength. This does not encrypt or decrypt data.

The implementation uses BoringSSL (used in Chromium & Go)

The equivalent openssl command is:

# You will need OpenSSL 3 or later
openssl sha512-256 /path/to/file
function sleep(ms: number | Date): Promisevoid>;

Resolve a Promise after milliseconds. This is like setTimeout except it returns a Promise.

@param ms

milliseconds to delay resolving the promise. This is a minimum number. It may take longer. If a Date is passed, it will sleep until the Date is reached.

Sleep for 1 second
import { sleep } from "bun";

await sleep(1000);
Sleep for 10 milliseconds
await Bun.sleep(10);
Sleep until Date
const target = new Date();
target.setSeconds(target.getSeconds() + 1);
await Bun.sleep(target);

Internally, Bun.sleep is the equivalent of

await new Promise((resolve) => setTimeout(resolve, ms));

As always, you can use Bun.sleep or the imported sleep function interchangeably.

function sleepSync(ms: number): void;

Sleep the thread for a given number of milliseconds

This is a blocking function.

Internally, it calls nanosleep(2)

function sliceAnsi(input: string,start?: number,end?: number,options?: string | boolean | SliceAnsiOptions,ambiguousIsNarrow?: boolean): string;

Slice a string by visible column width, preserving ANSI escape codes.

Like String.prototype.slice, but indices are terminal column widths (accounting for wide CJK characters, emoji grapheme clusters, and zero-width joiners), and ANSI escape sequences (SGR colors, OSC 8 hyperlinks, etc.) are preserved and correctly re-opened/closed at the slice boundaries.

@param input

The string to slice

@param start

Starting column (default 0). Negative counts from end.

@param end

Ending column, exclusive (default end of string). Negative counts from end.

@param options

Optional behavior flags (e.g. ellipsis for truncation)

@param ambiguousIsNarrow

ambiguousIsNarrow as a positional arg, usable when the 4th arg is an ellipsis string (or undefined). Lets you pass both options without an object: sliceAnsi(s, 0, n, "\u2026", false).

@returns

The sliced string with ANSI codes intact

import { sliceAnsi } from "bun";

// Plain slice (replaces the `slice-ansi` npm package)
sliceAnsi("hello", 1, 4); // "ell"
sliceAnsi("\u001b[31mhello\u001b[39m", 1, 4); // "\u001b[31mell\u001b[39m"
sliceAnsi("\u5b89\u5b81\u54c8", 0, 4); // "\u5b89\u5b81" (CJK: width 2 each)

// Truncation (replaces the `cli-truncate` npm package)
sliceAnsi("unicorn", 0, 4, "\u2026"); // "uni\u2026"
sliceAnsi("unicorn", -4, undefined, "\u2026"); // "\u2026orn"
function spawnIn extends Writable = 'ignore', Out extends Readable = 'pipe', Err extends Readable = 'inherit'>(options: SpawnOptionsIn, Out, Err> & { cmd: string[] }): SubprocessIn, Out, Err>;

Spawn a new process

function spawnIn extends Writable = 'ignore', Out extends Readable = 'pipe', Err extends Readable = 'inherit'>(cmds: string[],options?: SpawnOptionsIn, Out, Err>): SubprocessIn, Out, Err>;

Spawn a new process

const proc = Bun.spawn(["echo", "hello"]);
const text = await proc.stdout.text();
console.log(text); // "hello\n"

Internally, this uses posix_spawn(2)

@param cmds

The command to run

The first argument will be resolved to an absolute executable path. It must be a file, not a directory.

If you explicitly set PATH in env, that PATH will be used to resolve the executable instead of the default PATH.

To check if the command exists before running it, use Bun.which(bin).

function spawnSyncIn extends Writable = 'ignore', Out extends Readable = 'pipe', Err extends Readable = 'pipe'>(options: SpawnSyncOptionsIn, Out, Err> & { cmd: string[]; onExit: undefined }): SyncSubprocessOut, Err>;

Spawn a new process

function spawnSyncIn extends Writable = 'ignore', Out extends Readable = 'pipe', Err extends Readable = 'pipe'>(cmds: string[],options?: SpawnSyncOptionsIn, Out, Err>): SyncSubprocessOut, Err>;

Synchronously spawn a new process

const {stdout} = Bun.spawnSync(["echo", "hello"]);
console.log(stdout.toString()); // "hello\n"

Internally, this uses posix_spawn(2)

@param cmds

The command to run

The first argument will be resolved to an absolute executable path. It must be a file, not a directory.

If you explicitly set PATH in env, that PATH will be used to resolve the executable instead of the default PATH.

To check if the command exists before running it, use Bun.which(bin).

function stringWidth(input: string,options?: StringWidthOptions): number;

Get the column count of a string as it would be displayed in a terminal. Supports ANSI escape codes, emoji, and wide characters.

This is useful for:

Aligning text in a terminalQuickly checking if a string contains ANSI escape codesMeasuring the width of a string in a terminal

This API is designed to match the popular "string-width" package, so that existing code can be easily ported to Bun and vice versa.

@param input

The string to measure

@returns

The width of the string in columns

import { stringWidth } from "bun";

console.log(stringWidth("abc")); // 3
console.log(stringWidth("👩‍👩‍👧‍👦")); // 1
console.log(stringWidth("\u001b[31mhello\u001b[39m")); // 5
console.log(stringWidth("\u001b[31mhello\u001b[39m", { countAnsiEscapeCodes: false })); // 5
console.log(stringWidth("\u001b[31mhello\u001b[39m", { countAnsiEscapeCodes: true })); // 13
function stripANSI(input: string): string;

Remove ANSI escape codes from a string.

@param input

The string to remove ANSI escape codes from.

@returns

The string with ANSI escape codes removed.

import { stripANSI } from "bun";

console.log(stripANSI("\u001b[31mhello\u001b[39m")); // "hello"
function udpSocketDataBinaryType extends keyof BinaryTypeList = 'buffer'>(options: SocketOptionsDataBinaryType>): PromiseSocketDataBinaryType>>;

Create a UDP socket

@param options

The options to use when creating the server

function udpSocketDataBinaryType extends keyof BinaryTypeList = 'buffer'>(options: ConnectSocketOptionsDataBinaryType>): PromiseConnectedSocketDataBinaryType>>;

Create a UDP socket

@param options

The options to use when creating the server

function which(command: string,options?: WhichOptions): null | string;

Find the path to an executable, similar to typing which in your terminal. Reads the PATH environment variable unless overridden with options.PATH.

@param command

The name of the executable or script to find

@param options

Options for the search

function wrapAnsi(input: string,columns: number,options?: WrapAnsiOptions): string;

Wrap a string to fit within the specified column width, preserving ANSI escape codes.

This function is designed to be compatible with the popular "wrap-ansi" NPM package.

Features:

Preserves ANSI escape codes (colors, styles) across line breaksSupports SGR codes (colors, bold, italic, etc.) and OSC 8 hyperlinksRespects Unicode display widths (full-width characters, emoji)Word wrapping at word boundaries (configurable)
@param input

The string to wrap

@param columns

The maximum column width

@param options

Wrapping options

@returns

The wrapped string

import { wrapAnsi } from "bun";

console.log(wrapAnsi("hello world", 5));
// Output:
// hello
// world

// Preserves ANSI colors across line breaks
console.log(wrapAnsi("\u001b[31mhello world\u001b[0m", 5));
// Output:
// \u001b[31mhello\u001b[0m
// \u001b[31mworld\u001b[0m

// Hard wrap long words
console.log(wrapAnsi("abcdefghij", 3, { hard: true }));
// Output:
// abc
// def
// ghi
// j
function write(destination: BunFile | PathLike | S3File,input: string | ArrayBufferLike | TypedArrayArrayBufferLike> | Blob | Archive | BlobPart[],options?: { createPath: boolean; mode: number }): Promisenumber>;

Use the fastest syscalls available to copy from input into destination.

If destination exists, it must be a regular file or symlink to a file. If destination's directory does not exist, it will be created by default.

@param destination

The file or file path to write to

@param input

The data to copy into destination.

@param options

Options for the write

@returns

A promise that resolves with the number of bytes written.

function write(destination: BunFile,input: Response,options?: { createPath: boolean }): Promisenumber>;

Persist a Response body to disk.

@param destination

The file to write to. If the file doesn't exist, it will be created and if the file does exist, it will be overwritten. If input's size is less than destination's size, destination will be truncated.

@param input

Response object

@param options

Options for the write

@returns

A promise that resolves with the number of bytes written.

function write(destinationPath: PathLike,input: Response,options?: { createPath: boolean }): Promisenumber>;

Persist a Response body to disk.

@param destinationPath

The file path to write to. If the file doesn't exist, it will be created and if the file does exist, it will be overwritten. If input's size is less than destination's size, destination will be truncated.

@param input

Response object

@returns

A promise that resolves with the number of bytes written.

function write(destination: BunFile,input: BunFile,options?: { createPath: boolean; mode: number }): Promisenumber>;

Use the fastest syscalls available to copy from input into destination.

If destination exists, it must be a regular file or symlink to a file.

On Linux, this uses copy_file_range.

On macOS, when the destination doesn't already exist, this uses clonefile() and falls back to fcopyfile()

@param destination

The file to write to. If the file doesn't exist, it will be created and if the file does exist, it will be overwritten. If input's size is less than destination's size, destination will be truncated.

@param input

The file to copy from.

@returns

A promise that resolves with the number of bytes written.

function write(destinationPath: PathLike,input: BunFile,options?: { createPath: boolean; mode: number }): Promisenumber>;

Use the fastest syscalls available to copy from input into destination.

If destination exists, it must be a regular file or symlink to a file.

On Linux, this uses copy_file_range.

On macOS, when the destination doesn't already exist, this uses clonefile() and falls back to fcopyfile()

@param destinationPath

The file path to write to. If the file doesn't exist, it will be created and if the file does exist, it will be overwritten. If input's size is less than destination's size, destination will be truncated.

@param input

The file to copy from.

@returns

A promise that resolves with the number of bytes written.

function zstdCompress(data: string | ArrayBuffer | TypedArrayArrayBufferLike> | BufferArrayBufferLike>,options?: { level: number }): PromiseBufferArrayBufferLike>>;

Compresses a chunk of data with the Zstandard (zstd) compression algorithm.

@param data

The buffer of data to compress

@param options

Compression options to use

@returns

A promise that resolves to the output buffer with the compressed data

function zstdCompressSync(data: string | ArrayBuffer | TypedArrayArrayBufferLike> | BufferArrayBufferLike>,options?: { level: number }): Buffer;

Compresses a chunk of data with the Zstandard (zstd) compression algorithm.

@param data

The buffer of data to compress

@param options

Compression options to use

@returns

The output buffer with the compressed data

function zstdDecompress(data: string | ArrayBuffer | TypedArrayArrayBufferLike> | BufferArrayBufferLike>): PromiseBufferArrayBufferLike>>;

Decompresses a chunk of data with the Zstandard (zstd) decompression algorithm.

@param data

The buffer of data to decompress

@returns

A promise that resolves to the output buffer with the decompressed data

function zstdDecompressSync(data: string | ArrayBuffer | TypedArrayArrayBufferLike> | BufferArrayBufferLike>): Buffer;

Decompresses a chunk of data with the Zstandard (zstd) decompression algorithm.

@param data

The buffer of data to decompress

@returns

The output buffer with the decompressed data

class EventSource

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

MDN Reference

readonly CLOSED: 2readonly CONNECTING: 0onerror: null | (this: EventSource, ev: Event) => anyonmessage: null | (this: EventSource, ev: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>) => anyonopen: null | (this: EventSource, ev: Event) => anyreadonly OPEN: 1readonly readyState: number

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

readonly url: string

Returns the URL providing the event stream.

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.

Not supported in Bun

readonly static CLOSED: 2readonly static CONNECTING: 0readonly static OPEN: 1addEventListenerK extends keyof EventSourceEventMap>(type: K,listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;

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

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

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

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

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

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

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

MDN Reference

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

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

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

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

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

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

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

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

MDN Reference

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

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

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

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

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

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

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

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

MDN Reference

close(): void;

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

dispatchEvent(event: Event): boolean;

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

ref(): void;

Keep the event loop alive while connection is open or reconnecting

Not available in browsers

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

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

MDN Reference

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

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

MDN Reference

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

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

MDN Reference

unref(): void;

Do not keep the event loop alive while connection is open or reconnecting

Not available in browsers

class WebSocket

A WebSocket client implementation

const ws = new WebSocket("ws:http://localhost:8080", {
headers: {
"x-custom-header": "hello",
},
});

ws.addEventListener("open", () => {
console.log("Connected to server");
});

ws.addEventListener("message", (event) => {
console.log("Received message:", event.data);
});

ws.send("Hello, server!");
ws.terminate();
binaryType: 'arraybuffer' | 'nodebuffer'

The type of binary data being received.

readonly bufferedAmount: number

The number of bytes of data that have been queued using send() but not yet transmitted to the network

readonly extensions: string

The extensions selected by the server

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

Event handler for close event

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

Event handler for error event

onmessage: null | (this: WebSocket, ev: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>) => any

Event handler for message event

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

Event handler for open event

readonly protocol: string

The protocol selected by the server

readonly readyState: 0 | 1 | 2 | 3

The current state of the connection

readonly url: string

The URL of the WebSocket connection

readonly static CLOSED: 3readonly static CLOSING: 2readonly static CONNECTING: 0readonly static OPEN: 1addEventListenerK extends keyof WebSocketEventMap>(type: K,listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;

Registers an event handler of a specific event type on the WebSocket.

@param type

A case-sensitive string representing the event type to listen for

@param listener

The function to be called when the event occurs

@param options

An options object that specifies characteristics about the event listener

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

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

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

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

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

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

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

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

MDN Reference

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

Closes the WebSocket connection

@param code

A numeric value indicating the status code

@param reason

A human-readable string explaining why the connection is closing

dispatchEvent(event: Event): boolean;

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

ping(data?: string | ArrayBufferLike | ArrayBufferViewArrayBufferLike>): void;

Sends a ping frame to the server

@param data

Optional data to include in the ping frame

pong(data?: string | ArrayBufferLike | ArrayBufferViewArrayBufferLike>): void;

Sends a pong frame to the server

@param data

Optional data to include in the pong frame

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

Removes an event listener previously registered with addEventListener()

@param type

A case-sensitive string representing the event type to remove

@param listener

The function to remove from the event target

@param options

An options object that specifies characteristics about the event listener

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

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

MDN Reference

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

Transmits data to the server

@param data

The data to send to the server

terminate(): void;

Immediately terminates the connection

class Worker

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

MDN Reference

onerror: null | (this: AbstractWorker, ev: ErrorEvent) => anyonmessage: null | (this: Worker, ev: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>) => anyonmessageerror: null | (this: Worker, ev: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>) => anythreadId: number

An integer identifier for the referenced thread. Inside the worker thread, it is available as require('node:worker_threads').threadId. This value is unique for each Worker instance inside a single process.

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

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

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

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

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

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

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

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

MDN Reference

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

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

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

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

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

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

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

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

MDN Reference

dispatchEvent(event: Event): boolean;

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

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

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

MDN Reference

postMessage(message: any,options?: StructuredSerializeOptions): void;ref(): void;

Opposite of unref(), calling ref() on a previously unref()ed worker does not let the program exit if it's the only active handle left (the default behavior). If the worker is ref()ed, calling ref() again has no effect.

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

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

MDN Reference

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

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

MDN Reference

terminate(): void;unref(): void;

Calling unref() on a worker allows the thread to exit if this is the only active handle in the event system. If the worker is already unref()ed callingunref() again has no effect.

Type definitionsnamespace __internalinterface BunHeadersOverridereadonly count: number

Get the total number of headers

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

Get all headers matching the name

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

@param name

The header name to get

@returns

An array of header values

const headers = new Headers();
headers.append("Set-Cookie", "foo=bar");
headers.append("Set-Cookie", "baz=qux");
headers.getAll("Set-Cookie"); // ["foo=bar", "baz=qux"]
toJSON(): Recordstring, string> & { set-cookie: string[] };

Convert Headers to a plain JavaScript object.

About 10x faster than Object.fromEntries(headers.entries())

Called when you run JSON.stringify(headers)

Does not preserve insertion order. Well-known header names are lowercased. Other header names are left as-is.

interface BunRequestOverrideheaders: BunHeadersOverrideinterface BunResponseOverrideheaders: BunHeadersOverridetype DistributedMergeT, Else = T> = T extends T ? MergeT, ExcludeElse, T>> : nevertype DistributedOmitT, K extends PropertyKey> = T extends T ? OmitT, K> : never

Like Omit, but correctly distributes over unions. Most useful for removing properties from union options objects, like Bun.SQL.Options

type X = Bun.DistributedOmit?: 'a', url?: string} | {type?: 'b', flag?: boolean}, "url">
// `{type?: 'a'} | {type?: 'b', flag?: boolean}` (Omit applied to each union item instead of entire type)

type X = Omit?: 'a', url?: string} | {type?: 'b', flag?: boolean}, "url">;
// `{type?: "a" | "b" | undefined}` (Missing `flag` property and no longer a union)
type KeysInBothA, B> = Extractkeyof A, keyof B>type LibDomIsLoaded = typeof globalThis extends { onabort: any } ? true : falsetype LibEmptyOrBroadcastChannel = LibDomIsLoaded extends true ? {} : BroadcastChanneltype LibEmptyOrBunWebSocket = LibDomIsLoaded extends true ? {} : Bun.WebSockettype LibEmptyOrEventSource = LibDomIsLoaded extends true ? {} : EventSourcetype LibEmptyOrNodeCryptoWebcryptoSubtleCrypto = LibDomIsLoaded extends true ? {} : webcrypto.SubtleCryptotype LibEmptyOrNodeMessagePort = LibDomIsLoaded extends true ? {} : MessagePorttype LibEmptyOrNodeReadableStreamT> = LibDomIsLoaded extends true ? {} : ReadableStreamtype LibEmptyOrNodeStreamWebCompressionStream = LibDomIsLoaded extends true ? {} : CompressionStreamtype LibEmptyOrNodeStreamWebDecompressionStream = LibDomIsLoaded extends true ? {} : DecompressionStreamtype LibEmptyOrNodeStreamWebTextDecoderStream = LibDomIsLoaded extends true ? {} : TextDecoderStreamtype LibEmptyOrNodeStreamWebTextEncoderStream = LibDomIsLoaded extends true ? {} : TextEncoderStreamtype LibEmptyOrNodeUtilTextDecoder = LibDomIsLoaded extends true ? {} : TextDecodertype LibEmptyOrNodeUtilTextEncoder = LibDomIsLoaded extends true ? {} : TextEncodertype LibEmptyOrNodeWritableStreamT> = LibDomIsLoaded extends true ? {} : WritableStreamtype LibEmptyOrPerformanceEntry = LibDomIsLoaded extends true ? {} : PerformanceEntrytype LibEmptyOrPerformanceMark = LibDomIsLoaded extends true ? {} : PerformanceMarktype LibEmptyOrPerformanceMeasure = LibDomIsLoaded extends true ? {} : PerformanceMeasuretype LibEmptyOrPerformanceObserver = LibDomIsLoaded extends true ? {} : PerformanceObservertype LibEmptyOrPerformanceObserverEntryList = LibDomIsLoaded extends true ? {} : PerformanceObserverEntryListtype LibEmptyOrPerformanceResourceTiming = LibDomIsLoaded extends true ? {} : PerformanceResourceTimingtype LibEmptyOrReadableByteStreamController = LibDomIsLoaded extends true ? {} : ReadableByteStreamControllertype LibEmptyOrReadableStreamBYOBReader = LibDomIsLoaded extends true ? {} : ReadableStreamBYOBReadertype LibEmptyOrReadableStreamBYOBRequest = LibDomIsLoaded extends true ? {} : ReadableStreamBYOBRequesttype LibOrFallbackHeaders = LibDomIsLoaded extends true ? {} : Headerstype LibOrFallbackRequest = LibDomIsLoaded extends true ? {} : Requesttype LibOrFallbackRequestInit = LibDomIsLoaded extends true ? {} : OmitRequestInit, 'body' | 'headers'> & { body: Bun.BodyInit | null; headers: Bun.HeadersInit }type LibOrFallbackResponse = LibDomIsLoaded extends true ? {} : Responsetype LibOrFallbackResponseInit = LibDomIsLoaded extends true ? {} : ResponseInittype LibPerformanceOrNodePerfHooksPerformance = LibDomIsLoaded extends true ? {} : Performancetype LibWorkerOrBunWorker = LibDomIsLoaded extends true ? {} : Bun.Workertype MergeA, B> = MergeInnerA, B> & MergeInnerB, A>type MergeInnerA, B> = OmitA, KeysInBothA, B>> & OmitB, KeysInBothA, B>> & { [K in KeysInBothA, B>]: A[Key] | B[Key] }type NodeCryptoWebcryptoCryptoKey = webcrypto.CryptoKeytype NodeCryptoWebcryptoCryptoKeyPair = webcrypto.CryptoKeyPairtype UseLibDomIfAvailableGlobalThisKeyName extends PropertyKey, Otherwise> = LibDomIsLoaded extends true ? typeof globalThis extends { [K in GlobalThisKeyName]: infer T } ? T : Otherwise : Otherwise

Helper type for avoiding conflicts in types.

Uses the lib.dom.d.ts definition if it exists, otherwise defines it locally.

This is to avoid type conflicts between lib.dom.d.ts and @types/bun.

Unfortunately some symbols cannot be defined when both Bun types and lib.dom.d.ts types are loaded, and since we can't redeclare the symbol in a way that satisfies both, we need to fallback to the type that lib.dom.d.ts provides.

type WithoutA, B> = A & { [K in Excludekeyof B, keyof A>]: never }type XORA, B> = WithoutA, B> | WithoutB, A>namespace Buildtype Architecture = 'x64' | 'arm64' | 'aarch64'type CompileTarget = `bun-darwin-${Architecture}` | `bun-darwin-${Architecture}-${SIMD}` | `bun-linux-${Architecture}` | `bun-linux-${Architecture}-${Libc}` | `bun-linux-${Architecture}-${SIMD}` | `bun-linux-${Architecture}-${SIMD}-${Libc}` | `bun-windows-${Architecture}` | `bun-windows-x64-${SIMD}`type Libc = 'glibc' | 'musl'type SIMD = 'baseline' | 'modern'namespace Imageinterface ConstructorOptionsautoOrient?: boolean

Apply EXIF Orientation (JPEG) before any other operation.

maxPixels?: number

Reject inputs whose width × height exceeds this many pixels. The check runs after the header is read but before any pixel buffer is allocated, so a tiny file claiming a huge canvas is refused cheaply.

interface Metadataformat: Formatheight: numberwidth: numberinterface ModulateOptionsbrightness?: number

Multiplier; 1 leaves brightness unchanged.

1` = more saturated." data-algolia-static="false" data-algolia-merged="false" data-type="Property">saturation?: number

0 = greyscale, 1 = unchanged, >1 = more saturated.

interface ResizeOptionsfilter?: Filter

Resampling kernel.

fit?: 'fill' | 'inside'

"fill" stretches to exactly width×height. "inside" preserves aspect ratio so the result fits within width×height.

withoutEnlargement?: boolean

Never upscale — if the source is already smaller, leave it.

type ErrorCode = 'ERR_IMAGE_FORMAT_UNSUPPORTED' | 'ERR_IMAGE_TOO_MANY_PIXELS' | 'ERR_IMAGE_DECODE_FAILED' | 'ERR_IMAGE_ENCODE_FAILED' | 'ERR_IMAGE_UNKNOWN_FORMAT' | 'ERR_INVALID_STATE'

Stable error.code values set on rejections from Bun.Image terminals. Branch on these instead of parsing the message.

ERR_IMAGE_FORMAT_UNSUPPORTED — the requested format isn't available on this machine (HEIC/AVIF without the OS codec, TIFF on Linux). Catch this to fall back to a portable format.ERR_IMAGE_TOO_MANY_PIXELS — header dimensions or resize output exceed maxPixels, or a path-backed input is over the 256 MiB cap.ERR_IMAGE_DECODE_FAILED / ERR_IMAGE_ENCODE_FAILED — codec error.ERR_IMAGE_UNKNOWN_FORMAT — input bytes didn't match any sniffer.ERR_INVALID_STATE — the input ArrayBuffer was transferred between construction and the terminal call.File-backed inputs surface the underlying syscall code (ENOENT, EACCES, …) directly.
type Filter = 'nearest' | 'box' | 'bilinear' | 'linear' | 'cubic' | 'mitchell' | 'lanczos2' | 'lanczos3' | 'mks2013' | 'mks2021'type Format = 'jpeg' | 'png' | 'webp' | 'heic' | 'avif' | 'bmp' | 'tiff' | 'gif'

bmp/tiff/gif are decode-only — metadata().format may report them but there are no .bmp()/.tiff()/.gif() encoder methods. tiff decode rejects with error.code === "ERR_IMAGE_FORMAT_UNSUPPORTED" on Linux; gif decodes the first frame everywhere.

namespace Password

Hash and verify passwords using argon2 or bcrypt

These are fast APIs that can run in a worker thread if used asynchronously.

interface Argon2Algorithmalgorithm: 'argon2d' | 'argon2i' | 'argon2id'memoryCost?: number

Memory cost, which defines the memory usage, given in kibibytes. Minimum 8.

timeCost?: number

Defines the amount of computation realized and therefore the execution time, given in number of iterations.

interface BCryptAlgorithmalgorithm: 'bcrypt'cost?: number

A number between 4 and 31. The default is 10.

type AlgorithmLabel = BCryptAlgorithm | Argon2Algorithm['algorithm']namespace RedisClienttype KeyLike = string | ArrayBufferView | Blobtype StringPubSubListener = (message: string, channel: string) => voidnamespace Security

bun install security related declarations

interface Advisory

Advisory represents the result of a security scan result of a package

description: null | string

If available, this is a brief description of the advisory that Bun will print to the user.

In any case, Bun *always* pretty prints *all* the advisories, > but... > > → if any **fatal**, Bun will immediately cancel the installation > and quit with a non-zero exit code > > → else if any **warn**, Bun will either ask the user if they'd like > to continue with the install if in a TTY environment, or > immediately exit if not." data-algolia-static="false" data-algolia-merged="false" data-type="Property">level: 'warn' | 'fatal'

Level represents the degree of danger for a security advisory

Bun behaves differently depending on the values returned from the scan() hook:

In any case, Bun always pretty prints all the advisories, but...

→ if any fatal, Bun will immediately cancel the installation and quit with a non-zero exit code

→ else if any warn, Bun will either ask the user if they'd like to continue with the install if in a TTY environment, or immediately exit if not.

package: string

The name of the package attempting to be installed.

url: null | string

If available, this is a url linking to a CVE or report online so users can learn more about the advisory.

interface Packagename: string

The name of the package

=4.0.0`" data-algolia-static="false" data-algolia-merged="false" data-type="Property">requestedRange: string

The range that was requested by the command

This could be a tag like beta or a semver range like >=4.0.0

tarball: string

The URL of the tgz of this package that Bun will download

version: string

The resolved version to be installed that matches the requested range.

This is the exact version string, not a range.

interface Scanner [...packages]` or other related/similar commands. If this function throws an error, Bun will immediately stop the install process and print the error to the user." data-algolia-static="false" data-algolia-merged="false" data-type="Property">scan: (info: { packages: Package[] }) => PromiseAdvisory[]>

Perform an advisory check when a user ran bun add [...packages] or other related/similar commands.

If this function throws an error, Bun will immediately stop the install process and print the error to the user.

version: '1'

This is the version of the scanner implementation. It may change in future versions, so we will use this version to discriminate between such versions. It's entirely possible this API changes in the future so much that version 1 would no longer be supported.

The version is required because third-party scanner package versions are inherently unrelated to Bun versions

namespace Serveinterface BaseServeOptionsWebSocketData>development?: Development

Render contextual errors? This enables bun's error page

error?: (this: ServerWebSocketData>, error: ErrorLike) => void | Promisevoid> | Response | PromiseResponse>

Callback called when an error is thrown during request handling

error: (error) => {
return new Response("Internal Server Error", { status: 500 });
}
id?: null | string

Uniquely identify a server instance with an ID

When bun is started with the --hot flag:

This string will be used to hot reload the server without interrupting pending requests or websockets. If not provided, a value will be generated. To disable hot reloading, set this value to null.

When bun is not started with the --hot flag:

This string will currently do nothing. But in the future it could be useful for logs or metrics.

maxRequestBodySize?: number

What is the maximum size of a request body? (in bytes)

tls?: TLSOptions | TLSOptions[]

Set options for using TLS with this server

const server = Bun.serve({
fetch: request => new Response("Welcome to Bun!"),
tls: {
cert: Bun.file("cert.pem"),
key: Bun.file("key.pem"),
ca: [Bun.file("ca1.pem"), Bun.file("ca2.pem")],
},
});
interface HostnamePortServeOptionsWebSocketData>development?: Development

Render contextual errors? This enables bun's error page

error?: (this: ServerWebSocketData>, error: ErrorLike) => void | Promisevoid> | Response | PromiseResponse>

Callback called when an error is thrown during request handling

error: (error) => {
return new Response("Internal Server Error", { status: 500 });
}
hostname?: string & {} | '0.0.0.0' | '127.0.0.1' | 'localhost'

What hostname should the server listen on?

"127.0.0.1" // Only listen locally
http1?: boolean

Listen for HTTP/1.1 over TCP. Set to false together with http3: true to serve HTTP/3 only.

http3?: boolean

Also listen for HTTP/3 (QUIC) on the same port. Requires tls.

id?: null | string

Uniquely identify a server instance with an ID

When bun is started with the --hot flag:

This string will be used to hot reload the server without interrupting pending requests or websockets. If not provided, a value will be generated. To disable hot reloading, set this value to null.

When bun is not started with the --hot flag:

This string will currently do nothing. But in the future it could be useful for logs or metrics.

idleTimeout?: number

Sets the number of seconds to wait before timing out a connection due to inactivity.

ipv6Only?: boolean

Whether the IPV6_V6ONLY flag should be set.

maxRequestBodySize?: number

What is the maximum size of a request body? (in bytes)

port?: string | number

What port should the server listen on?

reusePort?: boolean

Whether the SO_REUSEPORT flag should be set.

This allows multiple processes to bind to the same port, which is useful for load balancing.

tls?: TLSOptions | TLSOptions[]

Set options for using TLS with this server

const server = Bun.serve({
fetch: request => new Response("Welcome to Bun!"),
tls: {
cert: Bun.file("cert.pem"),
key: Bun.file("key.pem"),
ca: [Bun.file("ca1.pem"), Bun.file("ca2.pem")],
},
});
interface UnixServeOptionsWebSocketData>development?: Development

Render contextual errors? This enables bun's error page

error?: (this: ServerWebSocketData>, error: ErrorLike) => void | Promisevoid> | Response | PromiseResponse>

Callback called when an error is thrown during request handling

error: (error) => {
return new Response("Internal Server Error", { status: 500 });
}
id?: null | string

Uniquely identify a server instance with an ID

When bun is started with the --hot flag:

This string will be used to hot reload the server without interrupting pending requests or websockets. If not provided, a value will be generated. To disable hot reloading, set this value to null.

When bun is not started with the --hot flag:

This string will currently do nothing. But in the future it could be useful for logs or metrics.

maxRequestBodySize?: number

What is the maximum size of a request body? (in bytes)

tls?: TLSOptions | TLSOptions[]

Set options for using TLS with this server

const server = Bun.serve({
fetch: request => new Response("Welcome to Bun!"),
tls: {
cert: Bun.file("cert.pem"),
key: Bun.file("key.pem"),
ca: [Bun.file("ca1.pem"), Bun.file("ca2.pem")],
},
});
unix?: string

If set, the HTTP server will listen on a unix socket instead of a port. (Cannot be used with hostname+port)

type BaseRouteValue = Response | false | HTMLBundle | BunFiletype Development = boolean | { chromeDevToolsAutomaticWorkspaceFolders: boolean; console: boolean; hmr: boolean }

Development configuration for Bun.serve

type ExtractRouteParamsT> = string extends T ? Recordstring, string> : T extends `${string}:${infer Param}/${infer Rest}` ? { [K in Param]: string } & ExtractRouteParamsRest> : T extends `${string}:${infer Param}` ? { [K in Param]: string } : T extends `${string}*` ? {} : {}type FetchOrRoutesWebSocketData, R extends string> = { routes: RoutesWebSocketData, R>; fetch(this: ServerWebSocketData>, req: Request, server: ServerWebSocketData>): MaybePromiseResponse> } | { routes: RoutesWebSocketData, R>; fetch(this: ServerWebSocketData>, req: Request, server: ServerWebSocketData>): MaybePromiseResponse> }type FetchOrRoutesWithWebSocketWebSocketData, R extends string> = { websocket: WebSocketHandlerWebSocketData> } & { routes: RoutesWithUpgradeWebSocketData, R>; fetch(this: ServerWebSocketData>, req: Request, server: ServerWebSocketData>): MaybePromiseundefined | void | Response> } | { routes: RoutesWithUpgradeWebSocketData, R>; fetch(this: ServerWebSocketData>, req: Request, server: ServerWebSocketData>): MaybePromiseundefined | void | Response> }type HandlerReq extends Request, S, Res> = (request: Req, server: S) => MaybePromiseRes>type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'type OptionsWebSocketData, R extends string = string> = Bun.__internal.XORHostnamePortServeOptionsWebSocketData>, UnixServeOptionsWebSocketData>> & Bun.__internal.XORFetchOrRoutesWebSocketData, R>, FetchOrRoutesWithWebSocketWebSocketData, R>>

The type of options that can be passed to serve, with support for routes and a safer requirement for fetch

export default {
fetch: req => Response.json(req.url),

websocket: {
message(ws) {
ws.data.name; // string
},
},
} satisfies Bun.Serve.Options{ name: string }>;
type RoutesWebSocketData, R extends string> = { [K in R]: BaseRouteValue | HandlerBunRequestPath>, ServerWebSocketData>, Response> | PartialRecordHTTPMethod, HandlerBunRequestPath>, ServerWebSocketData>, Response> | Response>> }type RoutesWithUpgradeWebSocketData, R extends string> = { [K in R]: BaseRouteValue | HandlerBunRequestPath>, ServerWebSocketData>, Response | undefined | void> | PartialRecordHTTPMethod, HandlerBunRequestPath>, ServerWebSocketData>, Response | undefined | void> | Response>> }namespace Spawninterface BaseOptionsIn extends Writable, Out extends Readable, Err extends Readable>argv0?: string

Path to the executable to run in the subprocess. This defaults to cmds[0].

One use-case for this is for applications which wrap other applications or to simulate a symlink.

cwd?: string

The current working directory of the process

Defaults to process.cwd()

detached?: boolean

Run the child in a separate process group, detached from the parent.

POSIX: calls setsid() so the child starts a new session and becomes the process group leader. It can outlive the parent and receive signals independently of the parent’s terminal/process group.Windows: sets UV_PROCESS_DETACHED, allowing the child to outlive the parent and receive signals independently.

Note: stdio may keep the parent process alive. Pass stdio: ["ignore", "ignore", "ignore"] to the spawn constructor to prevent this.

env?: Recordstring, undefined | string>

The environment variables of the process

Defaults to process.env as it was when the current Bun process launched.

Changes to process.env at runtime won't automatically be reflected in the default value. For that, you can pass process.env explicitly.

killSignal?: string | number

The signal to use when killing the process after a timeout, when the AbortSignal is aborted, or when the process goes over the maxBuffer limit.

// Kill the process with SIGKILL after 5 seconds
const subprocess = Bun.spawn({
cmd: ["sleep", "10"],
timeout: 5000,
killSignal: "SIGKILL",
});
maxBuffer?: number

The maximum number of bytes the process may output. If the process goes over this limit, it is killed with signal killSignal (defaults to SIGTERM).

serialization?: 'json' | 'advanced'

The serialization format to use for IPC messages. Defaults to "advanced".

To communicate with Node.js processes, use "json".

When ipc is not specified, this is ignored.

signal?: AbortSignal

An AbortSignal that can be used to abort the subprocess.

This is useful for aborting a subprocess when some other part of the program is aborted, such as a fetch response.

If the signal is aborted, the process will be killed with the signal specified by killSignal (defaults to SIGTERM).

const controller = new AbortController();
const { signal } = controller;
const start = performance.now();
const subprocess = Bun.spawn({
cmd: ["sleep", "100"],
signal,
});
await Bun.sleep(1);
controller.abort();
await subprocess.exited;
const end = performance.now();
console.log(end - start); // 1ms instead of 101ms
stderr?: Err

The file descriptor for the standard error. It may be:

"pipe", undefined: The process will have a ReadableStream for standard output/error"ignore", null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
stdin?: In

The file descriptor for the standard input. It may be:

"ignore", null, undefined: The process will have no standard input"pipe": The process will have a new FileSink for standard input"inherit": The process will inherit the standard input of the current processArrayBufferView, Blob: The process will read from the buffernumber: The process will read from the file descriptor
stdio?: [In, Out, Err, ...Readable[]]

The standard file descriptors of the process, in the form [stdin, stdout, stderr]. This overrides the stdin, stdout, and stderr properties.

For stdin you may pass:

"ignore", null, undefined: The process will have no standard input (default)"pipe": The process will have a new FileSink for standard input"inherit": The process will inherit the standard input of the current processArrayBufferView, Blob, Bun.file(), Response, Request: The process will read from buffer/stream.number: The process will read from the file descriptor

For stdout and stdin you may pass:

"pipe", undefined: The process will have a ReadableStream for standard output/error"ignore", null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
stdout?: Out

The file descriptor for the standard output. It may be:

"pipe", undefined: The process will have a ReadableStream for standard output/error"ignore", null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
timeout?: number

The maximum amount of time the process is allowed to run in milliseconds.

If the timeout is reached, the process will be killed with the signal specified by killSignal (defaults to SIGTERM).

// Kill the process after 5 seconds
const subprocess = Bun.spawn({
cmd: ["sleep", "10"],
timeout: 5000,
});
await subprocess.exited; // Will resolve after 5 seconds
windowsHide?: boolean

If true, the subprocess will have a hidden window.

windowsVerbatimArguments?: boolean

If true, no quoting or escaping of arguments is done on Windows.

ipc(message: any,subprocess: SubprocessIn, Out, Err>,handle?: unknown): void;

When specified, Bun will open an IPC channel to the subprocess. The passed callback is called for incoming messages, and subprocess.send can send messages to the subprocess. Messages are serialized using the JSC serialize API, which allows for the same types that postMessage/structuredClone supports.

The subprocess can send and receive messages by using process.send and process.on("message"), respectively. This is the same API as what Node.js exposes when child_process.fork() is used.

Currently, this is only compatible with processes that are other bun instances.

@param subprocess

The Subprocess that received the message

onDisconnect(): void | Promisevoid>;

Called exactly once when the IPC channel between the parent and this subprocess is closed. After this runs, no further IPC messages will be delivered.

When it fires:

The child called process.disconnect() or the parent called subprocess.disconnect().The child exited for any reason (normal exit or due to a signal like SIGILL, SIGKILL, etc.).The child replaced itself with a program that does not support Bun IPC.

Notes:

This callback indicates that the pipe is closed; it is not an error by itself. Use onExit or Subprocess.exited to determine why the process ended.It may occur before or after onExit depending on timing; do not rely on ordering. Typically, if you or the child call disconnect() first, this fires before onExit; if the process exits without an explicit disconnect, either may happen first.Only runs when ipc is enabled and runs at most once per subprocess.If the child becomes a zombie (exited but not yet reaped), the IPC is already closed, and this callback will fire (or may already have fired).
const subprocess = spawn({
cmd: ["echo", "hello"],
ipc: (message) => console.log(message),
onDisconnect: () => {
console.log("IPC channel disconnected");
},
});
onExit(subprocess: SubprocessIn, Out, Err>,exitCode: null | number,signalCode: null | number,error?: ErrorLike): void | Promisevoid>;

Callback that runs when the Subprocess exits

This is called even if the process exits with a non-zero exit code.

Warning: this may run before the Bun.spawn function returns.

A simple alternative is await subprocess.exited.

@param error

If an error occurred in the call to waitpid2, this will be the error.

const subprocess = spawn({
cmd: ["echo", "hello"],
onExit: (subprocess, code) => {
console.log(`Process exited with code ${code}`);
},
});
interface SpawnOptionsIn extends Writable, Out extends Readable, Err extends Readable>argv0?: string

Path to the executable to run in the subprocess. This defaults to cmds[0].

One use-case for this is for applications which wrap other applications or to simulate a symlink.

cwd?: string

The current working directory of the process

Defaults to process.cwd()

detached?: boolean

Run the child in a separate process group, detached from the parent.

POSIX: calls setsid() so the child starts a new session and becomes the process group leader. It can outlive the parent and receive signals independently of the parent’s terminal/process group.Windows: sets UV_PROCESS_DETACHED, allowing the child to outlive the parent and receive signals independently.

Note: stdio may keep the parent process alive. Pass stdio: ["ignore", "ignore", "ignore"] to the spawn constructor to prevent this.

env?: Recordstring, undefined | string>

The environment variables of the process

Defaults to process.env as it was when the current Bun process launched.

Changes to process.env at runtime won't automatically be reflected in the default value. For that, you can pass process.env explicitly.

killSignal?: string | number

The signal to use when killing the process after a timeout, when the AbortSignal is aborted, or when the process goes over the maxBuffer limit.

// Kill the process with SIGKILL after 5 seconds
const subprocess = Bun.spawn({
cmd: ["sleep", "10"],
timeout: 5000,
killSignal: "SIGKILL",
});
lazy?: boolean

If true, stdout and stderr pipes will not automatically start reading data. Reading will only begin when you access the stdout or stderr properties.

This can improve performance when you don't need to read output immediately.

const subprocess = Bun.spawn({
cmd: ["echo", "hello"],
lazy: true, // Don't start reading stdout until accessed
});
// stdout reading hasn't started yet
await subprocess.stdout.text(); // Now reading starts
maxBuffer?: number

The maximum number of bytes the process may output. If the process goes over this limit, it is killed with signal killSignal (defaults to SIGTERM).

serialization?: 'json' | 'advanced'

The serialization format to use for IPC messages. Defaults to "advanced".

To communicate with Node.js processes, use "json".

When ipc is not specified, this is ignored.

signal?: AbortSignal

An AbortSignal that can be used to abort the subprocess.

This is useful for aborting a subprocess when some other part of the program is aborted, such as a fetch response.

If the signal is aborted, the process will be killed with the signal specified by killSignal (defaults to SIGTERM).

const controller = new AbortController();
const { signal } = controller;
const start = performance.now();
const subprocess = Bun.spawn({
cmd: ["sleep", "100"],
signal,
});
await Bun.sleep(1);
controller.abort();
await subprocess.exited;
const end = performance.now();
console.log(end - start); // 1ms instead of 101ms
stderr?: Err

The file descriptor for the standard error. It may be:

"pipe", undefined: The process will have a ReadableStream for standard output/error"ignore", null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
stdin?: In

The file descriptor for the standard input. It may be:

"ignore", null, undefined: The process will have no standard input"pipe": The process will have a new FileSink for standard input"inherit": The process will inherit the standard input of the current processArrayBufferView, Blob: The process will read from the buffernumber: The process will read from the file descriptor
stdio?: [In, Out, Err, ...Readable[]]

The standard file descriptors of the process, in the form [stdin, stdout, stderr]. This overrides the stdin, stdout, and stderr properties.

For stdin you may pass:

"ignore", null, undefined: The process will have no standard input (default)"pipe": The process will have a new FileSink for standard input"inherit": The process will inherit the standard input of the current processArrayBufferView, Blob, Bun.file(), Response, Request: The process will read from buffer/stream.number: The process will read from the file descriptor

For stdout and stdin you may pass:

"pipe", undefined: The process will have a ReadableStream for standard output/error"ignore", null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
stdout?: Out

The file descriptor for the standard output. It may be:

"pipe", undefined: The process will have a ReadableStream for standard output/error"ignore", null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
terminal?: TerminalOptions | Terminal

Spawn the subprocess with a pseudo-terminal (PTY) attached.

When this option is provided:

stdin, stdout, and stderr are all connected to the terminalThe subprocess sees itself running in a real terminal (isTTY = true)Access the terminal via subprocess.terminalsubprocess.stdin, subprocess.stdout, subprocess.stderr return null

Only available on POSIX systems (Linux, macOS).

const proc = Bun.spawn(["bash"], {
terminal: {
cols: 80,
rows: 24,
data: (term, data) => console.log(data.toString()),
},
});

proc.terminal.write("echo hello\n");
await proc.exited;
proc.terminal.close();

You can also pass an existing Terminal object for reuse across multiple spawns:

const terminal = new Bun.Terminal({ ... });
const proc1 = Bun.spawn(["echo", "first"], { terminal });
await proc1.exited;
const proc2 = Bun.spawn(["echo", "second"], { terminal });
await proc2.exited;
terminal.close();
timeout?: number

The maximum amount of time the process is allowed to run in milliseconds.

If the timeout is reached, the process will be killed with the signal specified by killSignal (defaults to SIGTERM).

// Kill the process after 5 seconds
const subprocess = Bun.spawn({
cmd: ["sleep", "10"],
timeout: 5000,
});
await subprocess.exited; // Will resolve after 5 seconds
windowsHide?: boolean

If true, the subprocess will have a hidden window.

windowsVerbatimArguments?: boolean

If true, no quoting or escaping of arguments is done on Windows.

ipc(message: any,subprocess: SubprocessIn, Out, Err>,handle?: unknown): void;

When specified, Bun will open an IPC channel to the subprocess. The passed callback is called for incoming messages, and subprocess.send can send messages to the subprocess. Messages are serialized using the JSC serialize API, which allows for the same types that postMessage/structuredClone supports.

The subprocess can send and receive messages by using process.send and process.on("message"), respectively. This is the same API as what Node.js exposes when child_process.fork() is used.

Currently, this is only compatible with processes that are other bun instances.

@param subprocess

The Subprocess that received the message

onDisconnect(): void | Promisevoid>;

Called exactly once when the IPC channel between the parent and this subprocess is closed. After this runs, no further IPC messages will be delivered.

When it fires:

The child called process.disconnect() or the parent called subprocess.disconnect().The child exited for any reason (normal exit or due to a signal like SIGILL, SIGKILL, etc.).The child replaced itself with a program that does not support Bun IPC.

Notes:

This callback indicates that the pipe is closed; it is not an error by itself. Use onExit or Subprocess.exited to determine why the process ended.It may occur before or after onExit depending on timing; do not rely on ordering. Typically, if you or the child call disconnect() first, this fires before onExit; if the process exits without an explicit disconnect, either may happen first.Only runs when ipc is enabled and runs at most once per subprocess.If the child becomes a zombie (exited but not yet reaped), the IPC is already closed, and this callback will fire (or may already have fired).
const subprocess = spawn({
cmd: ["echo", "hello"],
ipc: (message) => console.log(message),
onDisconnect: () => {
console.log("IPC channel disconnected");
},
});
onExit(subprocess: SubprocessIn, Out, Err>,exitCode: null | number,signalCode: null | number,error?: ErrorLike): void | Promisevoid>;

Callback that runs when the Subprocess exits

This is called even if the process exits with a non-zero exit code.

Warning: this may run before the Bun.spawn function returns.

A simple alternative is await subprocess.exited.

@param error

If an error occurred in the call to waitpid2, this will be the error.

const subprocess = spawn({
cmd: ["echo", "hello"],
onExit: (subprocess, code) => {
console.log(`Process exited with code ${code}`);
},
});
interface SpawnSyncOptionsIn extends Writable, Out extends Readable, Err extends Readable>argv0?: string

Path to the executable to run in the subprocess. This defaults to cmds[0].

One use-case for this is for applications which wrap other applications or to simulate a symlink.

cwd?: string

The current working directory of the process

Defaults to process.cwd()

detached?: boolean

Run the child in a separate process group, detached from the parent.

POSIX: calls setsid() so the child starts a new session and becomes the process group leader. It can outlive the parent and receive signals independently of the parent’s terminal/process group.Windows: sets UV_PROCESS_DETACHED, allowing the child to outlive the parent and receive signals independently.

Note: stdio may keep the parent process alive. Pass stdio: ["ignore", "ignore", "ignore"] to the spawn constructor to prevent this.

env?: Recordstring, undefined | string>

The environment variables of the process

Defaults to process.env as it was when the current Bun process launched.

Changes to process.env at runtime won't automatically be reflected in the default value. For that, you can pass process.env explicitly.

killSignal?: string | number

The signal to use when killing the process after a timeout, when the AbortSignal is aborted, or when the process goes over the maxBuffer limit.

// Kill the process with SIGKILL after 5 seconds
const subprocess = Bun.spawn({
cmd: ["sleep", "10"],
timeout: 5000,
killSignal: "SIGKILL",
});
maxBuffer?: number

The maximum number of bytes the process may output. If the process goes over this limit, it is killed with signal killSignal (defaults to SIGTERM).

serialization?: 'json' | 'advanced'

The serialization format to use for IPC messages. Defaults to "advanced".

To communicate with Node.js processes, use "json".

When ipc is not specified, this is ignored.

signal?: AbortSignal

An AbortSignal that can be used to abort the subprocess.

This is useful for aborting a subprocess when some other part of the program is aborted, such as a fetch response.

If the signal is aborted, the process will be killed with the signal specified by killSignal (defaults to SIGTERM).

const controller = new AbortController();
const { signal } = controller;
const start = performance.now();
const subprocess = Bun.spawn({
cmd: ["sleep", "100"],
signal,
});
await Bun.sleep(1);
controller.abort();
await subprocess.exited;
const end = performance.now();
console.log(end - start); // 1ms instead of 101ms
stderr?: Err

The file descriptor for the standard error. It may be:

"pipe", undefined: The process will have a ReadableStream for standard output/error"ignore", null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
stdin?: In

The file descriptor for the standard input. It may be:

"ignore", null, undefined: The process will have no standard input"pipe": The process will have a new FileSink for standard input"inherit": The process will inherit the standard input of the current processArrayBufferView, Blob: The process will read from the buffernumber: The process will read from the file descriptor
stdio?: [In, Out, Err, ...Readable[]]

The standard file descriptors of the process, in the form [stdin, stdout, stderr]. This overrides the stdin, stdout, and stderr properties.

For stdin you may pass:

"ignore", null, undefined: The process will have no standard input (default)"pipe": The process will have a new FileSink for standard input"inherit": The process will inherit the standard input of the current processArrayBufferView, Blob, Bun.file(), Response, Request: The process will read from buffer/stream.number: The process will read from the file descriptor

For stdout and stdin you may pass:

"pipe", undefined: The process will have a ReadableStream for standard output/error"ignore", null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
stdout?: Out

The file descriptor for the standard output. It may be:

"pipe", undefined: The process will have a ReadableStream for standard output/error"ignore", null: The process will have no standard output/error"inherit": The process will inherit the standard output/error of the current processArrayBufferView: The process write to the preallocated buffer. Not implemented.number: The process will write to the file descriptor
timeout?: number

The maximum amount of time the process is allowed to run in milliseconds.

If the timeout is reached, the process will be killed with the signal specified by killSignal (defaults to SIGTERM).

// Kill the process after 5 seconds
const subprocess = Bun.spawn({
cmd: ["sleep", "10"],
timeout: 5000,
});
await subprocess.exited; // Will resolve after 5 seconds
windowsHide?: boolean

If true, the subprocess will have a hidden window.

windowsVerbatimArguments?: boolean

If true, no quoting or escaping of arguments is done on Windows.

ipc(message: any,subprocess: SubprocessIn, Out, Err>,handle?: unknown): void;

When specified, Bun will open an IPC channel to the subprocess. The passed callback is called for incoming messages, and subprocess.send can send messages to the subprocess. Messages are serialized using the JSC serialize API, which allows for the same types that postMessage/structuredClone supports.

The subprocess can send and receive messages by using process.send and process.on("message"), respectively. This is the same API as what Node.js exposes when child_process.fork() is used.

Currently, this is only compatible with processes that are other bun instances.

@param subprocess

The Subprocess that received the message

onDisconnect(): void | Promisevoid>;

Called exactly once when the IPC channel between the parent and this subprocess is closed. After this runs, no further IPC messages will be delivered.

When it fires:

The child called process.disconnect() or the parent called subprocess.disconnect().The child exited for any reason (normal exit or due to a signal like SIGILL, SIGKILL, etc.).The child replaced itself with a program that does not support Bun IPC.

Notes:

This callback indicates that the pipe is closed; it is not an error by itself. Use onExit or Subprocess.exited to determine why the process ended.It may occur before or after onExit depending on timing; do not rely on ordering. Typically, if you or the child call disconnect() first, this fires before onExit; if the process exits without an explicit disconnect, either may happen first.Only runs when ipc is enabled and runs at most once per subprocess.If the child becomes a zombie (exited but not yet reaped), the IPC is already closed, and this callback will fire (or may already have fired).
const subprocess = spawn({
cmd: ["echo", "hello"],
ipc: (message) => console.log(message),
onDisconnect: () => {
console.log("IPC channel disconnected");
},
});
onExit(subprocess: SubprocessIn, Out, Err>,exitCode: null | number,signalCode: null | number,error?: ErrorLike): void | Promisevoid>;

Callback that runs when the Subprocess exits

This is called even if the process exits with a non-zero exit code.

Warning: this may run before the Bun.spawn function returns.

A simple alternative is await subprocess.exited.

@param error

If an error occurred in the call to waitpid2, this will be the error.

const subprocess = spawn({
cmd: ["echo", "hello"],
onExit: (subprocess, code) => {
console.log(`Process exited with code ${code}`);
},
});
type Readable = 'pipe' | 'inherit' | 'ignore' | null | undefined | BunFile | ArrayBufferView | number

Option for stdout/stderr

type ReadableToIOX extends Readable> = X extends 'pipe' | undefined ? ReadableStreamUint8ArrayArrayBuffer>> : X extends BunFile | ArrayBufferView | number ? number : undefinedtype ReadableToSyncIOX extends Readable> = X extends 'pipe' | undefined ? Buffer : undefinedtype Writable = 'pipe' | 'inherit' | 'ignore' | null | undefined | BunFile | ArrayBufferView | number | ReadableStream | Blob | Response | Request

Option for stdin

type WritableIO = FileSink | number | undefinedtype WritableToIOX extends Writable> = X extends 'pipe' ? FileSink : X extends BunFile | ArrayBufferView | Blob | Request | Response | number ? number : undefinednamespace udp
interface BaseUDPSocketreadonly address: SocketAddressreadonly binaryType: keyof BinaryTypeListreadonly closed: booleanreadonly hostname: stringreadonly port: numberaddMembership(multicastAddress: string,interfaceAddress?: string): boolean;

Join a multicast group.

@param multicastAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

addSourceSpecificMembership(sourceAddress: string,groupAddress: string,interfaceAddress?: string): boolean;

Join a source-specific multicast group.

@param sourceAddress

The source address

@param groupAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

close(): void;dropMembership(multicastAddress: string,interfaceAddress?: string): boolean;

Leave a multicast group.

@param multicastAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

dropSourceSpecificMembership(sourceAddress: string,groupAddress: string,interfaceAddress?: string): boolean;

Leave a source-specific multicast group.

@param sourceAddress

The source address

@param groupAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

ref(): void;setBroadcast(enabled: boolean): boolean;

Enable or disable SO_BROADCAST socket option.

@param enabled

Whether to enable broadcast

@returns

The enabled value

setMulticastInterface(interfaceAddress: string): boolean;

Set the IP_MULTICAST_IF socket option to specify the outgoing interface for multicast packets.

@param interfaceAddress

The address of the interface to use

@returns

true on success

setMulticastLoopback(enabled: boolean): boolean;

Enable or disable IP_MULTICAST_LOOP socket option.

@param enabled

Whether to enable multicast loopback

@returns

The enabled value

setMulticastTTL(ttl: number): number;

Set the IP_MULTICAST_TTL socket option.

@param ttl

Time to live value for multicast packets

@returns

The TTL value

setTTL(ttl: number): number;

Set the IP_TTL socket option.

@param ttl

Time to live value

@returns

The TTL value

unref(): void;interface ConnectedSocketDataBinaryType extends BinaryType>readonly address: SocketAddressreadonly binaryType: keyof BinaryTypeListreadonly closed: booleanreadonly hostname: stringreadonly port: numberreadonly remoteAddress: SocketAddressaddMembership(multicastAddress: string,interfaceAddress?: string): boolean;

Join a multicast group.

@param multicastAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

addSourceSpecificMembership(sourceAddress: string,groupAddress: string,interfaceAddress?: string): boolean;

Join a source-specific multicast group.

@param sourceAddress

The source address

@param groupAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

close(): void;dropMembership(multicastAddress: string,interfaceAddress?: string): boolean;

Leave a multicast group.

@param multicastAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

dropSourceSpecificMembership(sourceAddress: string,groupAddress: string,interfaceAddress?: string): boolean;

Leave a source-specific multicast group.

@param sourceAddress

The source address

@param groupAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

ref(): void;reload(handler: ConnectedSocketHandlerDataBinaryType>): void;send(data: Data): boolean;sendMany(packets: readonly Data[]): number;setBroadcast(enabled: boolean): boolean;

Enable or disable SO_BROADCAST socket option.

@param enabled

Whether to enable broadcast

@returns

The enabled value

setMulticastInterface(interfaceAddress: string): boolean;

Set the IP_MULTICAST_IF socket option to specify the outgoing interface for multicast packets.

@param interfaceAddress

The address of the interface to use

@returns

true on success

setMulticastLoopback(enabled: boolean): boolean;

Enable or disable IP_MULTICAST_LOOP socket option.

@param enabled

Whether to enable multicast loopback

@returns

The enabled value

setMulticastTTL(ttl: number): number;

Set the IP_MULTICAST_TTL socket option.

@param ttl

Time to live value for multicast packets

@returns

The TTL value

setTTL(ttl: number): number;

Set the IP_TTL socket option.

@param ttl

Time to live value

@returns

The TTL value

unref(): void;interface ConnectedSocketHandlerDataBinaryType extends BinaryType>data(socket: ConnectedSocketDataBinaryType>,data: BinaryTypeList[DataBinaryType],port: number,address: string,flags: ReceiveFlags): void | Promisevoid>;drain(socket: ConnectedSocketDataBinaryType>): void | Promisevoid>;error(socket: ConnectedSocketDataBinaryType>,error: Error): void | Promisevoid>;interface ConnectSocketOptionsDataBinaryType extends BinaryType>binaryType?: DataBinaryTypeconnect: { hostname: string; port: number }hostname?: stringport?: numbersocket?: ConnectedSocketHandlerDataBinaryType>interface ReceiveFlags

Extra metadata passed to the data callback for each received datagram.

truncated: boolean

true if the datagram was larger than the receive buffer and was truncated by the kernel (MSG_TRUNC). The data passed to the callback contains only the portion that fit in the buffer.

interface SocketDataBinaryType extends BinaryType>readonly address: SocketAddressreadonly binaryType: keyof BinaryTypeListreadonly closed: booleanreadonly hostname: stringreadonly port: numberaddMembership(multicastAddress: string,interfaceAddress?: string): boolean;

Join a multicast group.

@param multicastAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

addSourceSpecificMembership(sourceAddress: string,groupAddress: string,interfaceAddress?: string): boolean;

Join a source-specific multicast group.

@param sourceAddress

The source address

@param groupAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

close(): void;dropMembership(multicastAddress: string,interfaceAddress?: string): boolean;

Leave a multicast group.

@param multicastAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

dropSourceSpecificMembership(sourceAddress: string,groupAddress: string,interfaceAddress?: string): boolean;

Leave a source-specific multicast group.

@param sourceAddress

The source address

@param groupAddress

The multicast group address

@param interfaceAddress

Optional interface address to use

@returns

true on success

ref(): void;reload(handler: SocketHandlerDataBinaryType>): void;send(data: Data,port: number,address: string): boolean;sendMany(packets: readonly number | Data[]): number;setBroadcast(enabled: boolean): boolean;

Enable or disable SO_BROADCAST socket option.

@param enabled

Whether to enable broadcast

@returns

The enabled value

setMulticastInterface(interfaceAddress: string): boolean;

Set the IP_MULTICAST_IF socket option to specify the outgoing interface for multicast packets.

@param interfaceAddress

The address of the interface to use

@returns

true on success

setMulticastLoopback(enabled: boolean): boolean;

Enable or disable IP_MULTICAST_LOOP socket option.

@param enabled

Whether to enable multicast loopback

@returns

The enabled value

setMulticastTTL(ttl: number): number;

Set the IP_MULTICAST_TTL socket option.

@param ttl

Time to live value for multicast packets

@returns

The TTL value

setTTL(ttl: number): number;

Set the IP_TTL socket option.

@param ttl

Time to live value

@returns

The TTL value

unref(): void;interface SocketHandlerDataBinaryType extends BinaryType>data(socket: SocketDataBinaryType>,data: BinaryTypeList[DataBinaryType],port: number,address: string,flags: ReceiveFlags): void | Promisevoid>;drain(socket: SocketDataBinaryType>): void | Promisevoid>;error(socket: SocketDataBinaryType>,error: Error): void | Promisevoid>;interface SocketOptionsDataBinaryType extends BinaryType>binaryType?: DataBinaryTypehostname?: stringport?: numbersocket?: SocketHandlerDataBinaryType>type Data = string | ArrayBufferView | ArrayBufferLikenamespace WebAssemblyinterface CompileErrorcause?: unknown

The cause of the error.

message: stringname: stringstack?: stringinterface GlobalT extends ValueType = ValueType>value: ValueTypeMap[T]valueOf(): ValueTypeMap[T];interface GlobalDescriptorT extends ValueType = ValueType>mutable?: booleanvalue: Tinterface Instancereadonly exports: Exportsinterface LinkErrorcause?: unknown

The cause of the error.

message: stringname: stringstack?: stringinterface Memoryreadonly buffer: ArrayBuffergrow(delta: number): number;interface MemoryDescriptorinitial: numbermaximum?: numbershared?: booleaninterface Moduleinterface ModuleExportDescriptorkind: ImportExportKindname: stringinterface ModuleImportDescriptorkind: ImportExportKindmodule: stringname: stringinterface RuntimeErrorcause?: unknown

The cause of the error.

message: stringname: stringstack?: stringinterface Tablereadonly length: numberget(index: number): any;grow(delta: number,value?: any): number;set(index: number,value?: any): void;interface TableDescriptorelement: TableKindinitial: numbermaximum?: numberinterface ValueTypeMapanyfunc: Functionexternref: anyf32: numberf64: numberi32: numberi64: bigintv128: neverinterface WebAssemblyInstantiatedSourceinstance: Instancemodule: Moduletype Exports = Recordstring, ExportValue>type ExportValue = Function | Global | WebAssembly.Memory | WebAssembly.Tabletype ImportExportKind = 'function' | 'global' | 'memory' | 'table' | 'tag'type Imports = Recordstring, ModuleImports>type ImportValue = ExportValue | numbertype ModuleImports = Recordstring, ImportValue>type TableKind = 'anyfunc' | 'externref'type ValueType = keyof ValueTypeMapnamespace WebViewinterface ClickOptionsbutton?: 'left' | 'right' | 'middle'
clickCount?: 2 | 1 | 3

Number of clicks (1 = single, 2 = double, 3 = triple).

modifiers?: Modifier[]

Modifier keys to hold during the click.

interface ClickSelectorOptionsbutton?: 'left' | 'right' | 'middle'
clickCount?: 2 | 1 | 3

Number of clicks (1 = single, 2 = double, 3 = triple).

modifiers?: Modifier[]

Modifier keys to hold during the click.

timeout?: number

Maximum time in milliseconds to wait for the element to become actionable (attached, visible, stable for 2 frames, not obscured).

interface ConstructorOptionsbackend?: Backend

Browser backend. Defaults to "webkit" on macOS, throws on other platforms unless "chrome" is specified.

console?: ConsoleCapture

Capture page-side console.* calls. See ConsoleCapture.

dataStore?: 'ephemeral' | { directory: string }

Storage backing for cookies, localStorage, IndexedDB, etc.

"ephemeral" (default): in-memory only, nothing written to disk.{ directory }: persistent storage rooted at the given path. Multiple views with the same directory share state.

Chrome backend: directory is per-Chrome-process (--user-data-dir), not per-view. The first view's directory applies to all views spawned in the same Bun process.

headless?: boolean

Only true (headless) is implemented.

height?: number

Viewport height in pixels. Range: [1, 16384].

url?: string

Initial URL to navigate to. The navigation starts before the constructor returns; await view.navigate(otherUrl) or any other operation will wait for it to complete first.

Equivalent to calling view.navigate(url) immediately after construction.

width?: number

Viewport width in pixels. Range: [1, 16384].

interface PressOptionsmodifiers?: Modifier[]

Modifier keys to hold during the keypress.

interface ScrollToOptionsblock?: 'end' | 'center' | 'start' | 'nearest'

Vertical alignment. "nearest" scrolls minimally (no-op if already in view); "center" snaps the element's center to the viewport center.

timeout?: number

Maximum time in milliseconds to wait for the element to exist.

`." data-algolia-static="false" data-algolia-merged="false" data-type="Type alias">type Backend = 'webkit' | 'chrome' | { type: 'chrome'; url: string } | { argv: string[]; path: string; stderr: 'inherit' | 'ignore'; stdout: 'inherit' | 'ignore'; type: 'chrome'; url: false } | { stderr: 'inherit' | 'ignore'; stdout: 'inherit' | 'ignore'; type: 'webkit' }

Browser backend selection.

"webkit" (default): WKWebView. macOS only. Zero external dependencies — uses the system WebKit.framework."chrome": Chrome/Chromium via DevTools Protocol over --remote-debugging-pipe. Works anywhere Chrome is installed. Auto-detects the binary in standard locations; override with backend.path or the BUN_CHROME_PATH environment variable.

The object form lets you pass extra launch flags. Chrome switches are last-wins for duplicates, so argv can override the defaults.

Chrome is spawned once per process — the first new Bun.WebView() call's path/argv/dataStore.directory win; subsequent views reuse the same Chrome instance via Target.createTarget.

Default flags: --remote-debugging-pipe --headless --no-first-run --no-default-browser-check --disable-gpu --user-data-dir=.

void`: custom callback. `type` is the method name (`"log"` | `"warn"` | `"error"` | `"info"` | `"debug"` | ...). Primitive args unwrap to their raw values; object args arrive as a structured descriptor — for Chrome, the CDP `RemoteObject` with `.type`/`.className`/`.description`/`.preview.properties`; for WebKit, the JSON round-trip of the object (lossy for functions/ circular refs, which stringify to their `String(...)` coercion)." data-algolia-static="false" data-algolia-merged="false" data-type="Type alias">type ConsoleCapture = typeof console | (type: string, ...args: unknown[]) => void

Console capture. Called for each console.* invocation in the page.

globalThis.console: forward directly to the parent's console. console.log("hi") in the page prints hi to stdout with Bun's formatter; console.error goes to stderr. Zero JS overhead per call — dispatches through ConsoleClient directly.(type, ...args) => void: custom callback. type is the method name ("log" | "warn" | "error" | "info" | "debug" | ...). Primitive args unwrap to their raw values; object args arrive as a structured descriptor — for Chrome, the CDP RemoteObject with .type/.className/.description/.preview.properties; for WebKit, the JSON round-trip of the object (lossy for functions/ circular refs, which stringify to their String(...) coercion).
type Modifier = 'Shift' | 'Control' | 'Alt' | 'Meta'type VirtualKey = 'Enter' | 'Tab' | 'Space' | 'Backspace' | 'Delete' | 'Escape' | 'ArrowLeft' | 'ArrowRight' | 'ArrowUp' | 'ArrowDown' | 'Home' | 'End' | 'PageUp' | 'PageDown'interface AbstractWorkeronerror: null | (this: AbstractWorker, ev: ErrorEvent) => anyaddEventListenerK extends 'error'>(type: K,listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any,options?: boolean | AddEventListenerOptions): void;addEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | AddEventListenerOptions): void;removeEventListenerK extends 'error'>(type: K,listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any,options?: boolean | EventListenerOptions): void;removeEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | EventListenerOptions): void;interface AbstractWorkerEventMaperror: ErrorEventinterface AddEventListenerOptionscapture?: booleanonce?: boolean

When true, the listener is automatically removed when it is first invoked. Default: false.

passive?: boolean

When true, serves as a hint that the listener will not call the Event object's preventDefault() method. Default: false.

signal?: AbortSignalinterface ArchiveExtractOptions

Options for extracting archive contents.

glob?: string | readonly string[]

Glob pattern(s) to filter which entries are extracted. Uses the same syntax as Bun.Glob, including support for wildcards (*, **), character classes ([abc]), alternation ({a,b}), and negation (!pattern).

Patterns are matched against archive entry paths normalized to use forward slashes (/), regardless of the host operating system. Always write patterns using / as the separator.

Positive patterns: Only entries matching at least one pattern will be extracted.Negative patterns (prefixed with !): Entries matching these patterns will be excluded. Negative patterns are applied after positive patterns.

If not specified, all entries are extracted.

// Extract only TypeScript files
await archive.extract("./out", { glob: "**" + "/*.ts" });

// Extract files from multiple directories
await archive.extract("./out", { glob: ["src/**", "lib/**"] });

// Exclude node_modules using negative pattern
await archive.extract("./out", { glob: ["**", "!node_modules/**"] });

// Extract source files but exclude tests
await archive.extract("./out", { glob: ["src/**", "!**" + "/*.test.ts"] });
interface ArchiveOptions

Options for creating an Archive instance.

By default, archives are not compressed. Use { compress: "gzip" } to enable compression.

// No compression (default)
new Bun.Archive(data);

// Enable gzip with default level (6)
new Bun.Archive(data, { compress: "gzip" });

// Specify compression level
new Bun.Archive(data, { compress: "gzip", level: 9 });
compress?: 'gzip'

Compression algorithm to use. Currently only "gzip" is supported. If not specified, no compression is applied.

level?: number

Compression level (1-12). Only applies when compress is set.

1: Fastest compression, lowest ratio6: Default balance of speed and ratio12: Best compression ratio, slowest
interface BinaryTypeListarraybuffer: ArrayBufferbuffer: Bufferuint8array: Uint8ArrayArrayBuffer>interface BuildArtifact

A build artifact represents a file that was generated by the bundler

hash: null | stringkind: 'entry-point' | 'chunk' | 'asset' | 'sourcemap' | 'bytecode'loader: Loaderpath: stringreadonly size: numbersourcemap: null | BuildArtifactreadonly type: stringarrayBuffer(): PromiseArrayBuffer>;

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

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

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

formData(): PromiseFormData>;

Read the data from the blob as a FormData object.

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

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

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

image(options?: ConstructorOptions): Image;

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

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

Read the data from the blob as a JSON object.

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

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

Returns a readable stream of the blob's contents

text(): Promisestring>;

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

interface BuildConfig
allowUnresolved?: string[]

Control whether dynamic import(), require(), or require.resolve() specifiers (non-literal arguments like `./locales/${lang}.json`) are allowed to pass through to runtime without being bundled.

["*"] (default) — allow all dynamic specifiers[] — fail the build on any dynamic specifier["./locales/*.json", ...] — allow only specifiers whose static template parts match one of these glob patterns

Add "" to the list to allow fully opaque specifiers like import(fn()).

banner?: string

Add a banner to the bundled code such as "use client";

bytecode?: boolean

Generate bytecode for the output. This can dramatically improve cold start times, but will make the final output larger and slightly increase memory usage.

CommonJS: works with or without compile: trueESM: requires compile: true

Without an explicit format, defaults to CommonJS.

Must be target: "bun"

conditions?: string | string[]

package.json exports conditions used when resolving imports

Equivalent to --conditions in bun build or bun run.

https://nodejs.org/api/packages.html#exports

define?: Recordstring, string>drop?: string[]

Drop function calls to matching property accesses.

emitDCEAnnotations?: boolean

Force emitting @PURE annotations even if minify.whitespace is true.

entrypoints: string[]

List of entrypoints, usually file paths

env?: 'inline' | 'disable' | `${string}*`

Controls how environment variables are handled during bundling.

Can be one of:

"inline": Injects environment variables into the bundled output by converting process.env.FOO references to string literals containing the actual environment variable values"disable": Disables environment variable injection entirelyA string ending in *: Inlines environment variables that match the given prefix. For example, "MY_PUBLIC_*" will only include env vars starting with "MY_PUBLIC_"
Bun.build({
env: "MY_PUBLIC_*",
entrypoints: ["src/index.ts"],
})
external?: string[]features?: string[]

Enable feature flags for dead-code elimination via import { feature } from "bun:bundle".

When feature("FLAG_NAME") is called, it returns true if FLAG_NAME is in this array, or false otherwise. This enables static dead-code elimination at bundle time.

Equivalent to the CLI --feature flag.

await Bun.build({
entrypoints: ['./src/index.ts'],
features: ['FEATURE_A', 'FEATURE_B'],
});
files?: Recordstring, string | ArrayBufferLike | TypedArrayArrayBufferLike> | Blob>

A map of file paths to their contents for in-memory bundling.

This allows you to bundle virtual files that don't exist on disk, or override the contents of files that do exist on disk. The keys are file paths (which should match how they're imported) and the values are the file contents.

File contents can be provided as:

string - The source code as a stringBlob - A Blob containing the source codeNodeJS.TypedArray - A typed array (e.g., Uint8Array) containing the source codeArrayBufferLike - An ArrayBuffer containing the source code
// Bundle entirely from memory (no files on disk needed)
await Bun.build({
entrypoints: ["/app/index.ts"],
files: {
"/app/index.ts": `
import { helper } from "./helper.ts";
console.log(helper());
`,
"/app/helper.ts": `
export function helper() {
return "Hello from memory!";
}
`,
},
});
footer?: string

Add a footer to the bundled code such as a comment block like

// made with bun!

format?: 'esm' | 'cjs' | 'iife'

Output module format. Top-level await is only supported for "esm".

Can be:

"esm""cjs" (experimental)"iife" (experimental)
ignoreDCEAnnotations?: boolean

Ignore dead code elimination/tree-shaking annotations such as @PURE and package.json "sideEffects" fields. This should only be used as a temporary workaround for incorrect annotations in libraries.

jsx?: { development: boolean; factory: string; fragment: string; importSource: string; runtime: 'classic' | 'automatic'; sideEffects: boolean }

JSX configuration options

loader?: { __index[key: string]: Loader; }metafile?: boolean

Generate a JSON file containing metadata about the build.

The metafile contains information about inputs, outputs, imports, and exports which can be used for bundle analysis, visualization, or integration with other tools.

When true, the metafile JSON string is included in the BuildOutput.metafile property.

const result = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
metafile: true,
});

// Write metafile to disk for analysis
if (result.metafile) {
await Bun.write('./dist/meta.json', result.metafile);
}

// Parse and analyze the metafile
const meta = JSON.parse(result.metafile!);
console.log('Input files:', Object.keys(meta.inputs));
console.log('Output files:', Object.keys(meta.outputs));
minify?: boolean | { identifiers: boolean; keepNames: boolean; syntax: boolean; whitespace: boolean }

Whether to enable minification.

Use true/false to enable/disable all minification options. Alternatively, you can pass an object for granular control over certain minifications.

naming?: string | { asset: string; chunk: string; entry: string }optimizeImports?: string[]

List of package names whose barrel files (re-export index files) should be optimized. When a named import comes from one of these packages, only the submodules actually used are parsed — unused re-exports are skipped entirely.

This is also enabled automatically for any package with "sideEffects": false in its package.json.

await Bun.build({
entrypoints: ['./app.ts'],
optimizeImports: ['antd', '@mui/material', 'lodash-es'],
});
outdir?: stringpackages?: 'external' | 'bundle'plugins?: BunPlugin[]publicPath?: stringreactFastRefresh?: boolean

Enable React Fast Refresh transform.

This adds the necessary code transformations for React Fast Refresh (hot module replacement for React components), but does not emit hot-module code itself.

root?: stringsourcemap?: boolean | 'linked' | 'external' | 'none' | 'inline'

Specifies if and how to generate source maps.

"none" - No source maps are generated"linked" - A separate *.ext.map file is generated alongside each *.ext file. A http://# sourceMappingURL comment is added to the output file to link the two. Requires outdir to be set."inline" - an inline source map is appended to the output file."external" - Generate a separate source map file for each input file. No http://# sourceMappingURL comment is added to the output file.

true and false are aliases for "inline" and "none", respectively.

splitting?: boolean

Enable code splitting

target?: Target
throw?: boolean
When set to true, the returned promise rejects with an AggregateError when a build failure happens.When set to false, returns a BuildOutput with {success: false}
tsconfig?: string

Custom tsconfig.json file path to use for path resolution. Equivalent to --tsconfig-override in the CLI.

await Bun.build({
entrypoints: ['./src/index.ts'],
tsconfig: './custom-tsconfig.json'
});
interface BuildMetafile

Metafile structure containing build metadata for analysis.

inputs: { __index[path: string]: { bytes: number; format: 'json' | 'css' | 'esm' | 'cjs'; imports: { external: boolean; kind: ImportKind; original: string; path: string; with: Recordstring, string> }[] }; }

Information about all input source files

outputs: { __index[path: string]: { bytes: number; cssBundle: string; entryPoint: string; exports: string[]; imports: { kind: ImportKind; path: string }[]; inputs: { __index[path: string]: { bytesInOutput: number }; } }; }

Information about all output files

interface BuildOutput

The output of a build

logs: BuildMessage | ResolveMessage[]metafile?: BuildMetafile

Metadata about the build including inputs, outputs, and their relationships.

Only present when BuildConfig.metafile is true.

The metafile contains detailed information about:

inputs: All source files that were bundled, their byte sizes, imports, and formatoutputs: All generated output files, their byte sizes, which inputs contributed to each output, imports between chunks, and exports

This can be used for:

Bundle size analysis and visualizationDetecting unused code or dependenciesUnderstanding the dependency graphIntegration with bundle analyzer tools
const result = await Bun.build({
entrypoints: ['./src/index.ts'],
outdir: './dist',
metafile: true,
});

if (result.metafile) {
// Analyze input files
for (const [path, input] of Object.entries(result.metafile.inputs)) {
console.log(`${path}: ${input.bytes} bytes, ${input.imports.length} imports`);
}

// Analyze output files
for (const [path, output] of Object.entries(result.metafile.outputs)) {
console.log(`${path}: ${output.bytes} bytes`);
for (const [inputPath, info] of Object.entries(output.inputs)) {
console.log(` - ${inputPath}: ${info.bytesInOutput} bytes`);
}
}

// Write to disk for external analysis tools
await Bun.write('./dist/meta.json', JSON.stringify(result.metafile));
}
outputs: BuildArtifact[]success: booleaninterface BunInspectOptions

Options for Bun.inspect

colors?: boolean

Whether to colorize the output

compact?: boolean

Whether to compact the output

depth?: number

The depth of the inspection

sorted?: boolean

Whether to sort the properties of the object

interface BunMessageEventT = any>

A message received by a target object.

readonly AT_TARGET: 2readonly bubbles: boolean

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

MDN Reference

readonly BUBBLING_PHASE: 3readonly cancelable: boolean

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

MDN Reference

readonly CAPTURING_PHASE: 1readonly composed: boolean

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

MDN Reference

readonly currentTarget: null | EventTarget

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

MDN Reference

readonly data: T

Returns the data of the message.

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.

readonly NONE: 0readonly origin: string

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

readonly ports: readonly MessagePort[]

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

readonly source: undefined | nullreadonly target: null | EventTarget

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

MDN Reference

readonly timeStamp: number

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

MDN Reference

readonly type: string

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

MDN Reference

composedPath(): EventTarget[];

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

MDN Reference

composedPath(): [EventTarget?];

Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness.

preventDefault(): void;

Sets the defaultPrevented property to true if cancelable is true.

stopImmediatePropagation(): void;

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

stopPropagation(): void;

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

interface BunPlugin

A Bun plugin. Used for extending Bun's behavior at runtime, or with Bun.build

name: string

Human-readable name of the plugin

In a future version of Bun, this will be used in error messages.

target?: Target

The target JavaScript environment the plugin should be applied to.

bun: The default environment when using bun run or bun to load a scriptbrowser: The plugin will be applied to browser buildsnode: The plugin will be applied to Node.js builds

If unspecified, it is assumed that the plugin is compatible with all targets.

This field is not read by Bun.plugin, only Bun.build and bun build

setup(build: PluginBuilder): void | Promisevoid>;

A function that will be called when the plugin is loaded.

This function may be called in the same tick that it is registered, or it may be called later. It could potentially be called multiple times for different targets.

@param build

A builder object that can be used to register plugin hooks

interface BunRegisterPlugin

Extend Bun's module resolution and loading behavior

Plugins are applied in the order they are defined.

Today, there are two kinds of hooks:

onLoad lets you return source code or an object that will become the module's exportsonResolve lets you redirect a module specifier to another module specifier. It does not chain.

Plugin hooks must define a filter RegExp and will only be matched if the import specifier contains a "." or a ":".

ES Module resolution semantics mean that plugins may be initialized after a module is resolved. You might need to load plugins at the very beginning of the application and then use a dynamic import to load the rest of the application. A future version of Bun may also support specifying plugins via bunfig.toml.

A YAML loader plugin

Bun.plugin({
setup(builder) {
builder.onLoad({ filter: /\.yaml$/ }, ({path}) => ({
loader: "object",
exports: require("js-yaml").load(fs.readFileSync(path, "utf8"))
}));
});

// You can use require()
const {foo} = require("./file.yaml");

// Or import
await import("./file.yaml");

clearAll(): void;

Deactivate all plugins

This prevents registered plugins from being applied to future builds.

interface BunRequestT extends string = string>

This Fetch API interface represents a resource request.

MDN Reference

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

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

MDN Reference

readonly cookies: CookieMapreadonly 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 params: { [K in string | number | symbol]: ExtractRouteParamsT>[Key] }readonly redirect: RequestRedirect

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

MDN Reference

readonly referrer: string

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

MDN Reference

readonly referrerPolicy: ReferrerPolicy

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

MDN Reference

readonly signal: AbortSignal

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

MDN Reference

readonly url: stringarrayBuffer(): PromiseArrayBuffer>;blob(): PromiseBlob>;bytes(): PromiseUint8ArrayArrayBufferLike>>;clone(): BunRequestT>;formData(): PromiseFormData>;json(): Promiseany>;text(): Promisestring>;interface CloseEventInitbubbles?: booleancancelable?: booleancode?: numbercomposed?: booleanreason?: stringwasClean?: booleaninterface CompileBuildOptionsautoloadBunfig?: boolean

Whether to autoload bunfig.toml when the standalone executable runs

Standalone-only: applies only when building/running the standalone executable.

Equivalent CLI flags: --compile-autoload-bunfig, --no-compile-autoload-bunfig

autoloadDotenv?: boolean

Whether to autoload .env files when the standalone executable runs

Standalone-only: applies only when building/running the standalone executable.

Equivalent CLI flags: --compile-autoload-dotenv, --no-compile-autoload-dotenv

autoloadPackageJson?: boolean

Whether to autoload package.json when the standalone executable runs

Standalone-only: applies only when building/running the standalone executable.

Equivalent CLI flags: --compile-autoload-package-json, --no-compile-autoload-package-json

autoloadTsconfig?: boolean

Whether to autoload tsconfig.json when the standalone executable runs

Standalone-only: applies only when building/running the standalone executable.

Equivalent CLI flags: --compile-autoload-tsconfig, --no-compile-autoload-tsconfig

execArgv?: string[]executablePath?: stringoutfile?: stringtarget?: CompileTargetwindows?: { copyright: string; description: string; hideConsole: boolean; icon: string; publisher: string; title: string; version: string }interface CookieInitdomain?: stringexpires?: string | number | DatehttpOnly?: booleanmaxAge?: numbername?: stringpartitioned?: booleanpath?: string

Defaults to '/'. To allow the browser to set the path, use an empty string.

sameSite?: CookieSameSite

Defaults to lax.

secure?: booleanvalue?: stringinterface CookieStoreDeleteOptionsdomain?: null | stringname: stringpath?: stringinterface CookieStoreGetOptionsname?: stringurl?: stringinterface CronControllerreadonly cron: string

The cron expression that triggered this invocation.

readonly scheduledTime: number

Timestamp (ms since epoch) when the job was scheduled to run.

readonly type: 'scheduled'

The type of event that triggered the handler. Always "scheduled".

interface CronJob

A handle to an in-process cron job returned by Bun.cron when called with a callback.

const job = Bun.cron("0 * * * *", async () => {
await cleanupTempFiles();
});
// Later:
job.stop();
readonly cron: string

The cron expression string.

[Symbol.dispose](): void;ref(): CronJob;

Keep the process alive while this job is scheduled (default).

stop(): CronJob;

Cancel this cron job. The callback will not fire again.

unref(): CronJob;

Allow the process to exit even while this job is scheduled.

interface CSRFGenerateOptionsalgorithm?: CSRFAlgorithm

The algorithm to use for the token.

encoding?: 'base64' | 'base64url' | 'hex'

The encoding of the token.

expiresIn?: number

The number of milliseconds until the token expires. 0 means the token never expires.

interface CSRFVerifyOptionsalgorithm?: CSRFAlgorithm

The algorithm to use for the token.

encoding?: 'base64' | 'base64url' | 'hex'

The encoding of the token.

maxAge?: number

The number of milliseconds until the token expires. 0 means the token never expires.

secret?: string

The secret to use for the token. If not provided, a random default secret will be generated in memory and used.

interface CustomEventInitT = any>bubbles?: booleancancelable?: booleancomposed?: booleandetail?: Tinterface DirectUnderlyingSourceR = any>cancel?: UnderlyingSourceCancelCallbackpull: (controller: ReadableStreamDirectController) => void | PromiseLikevoid>type: 'direct'interface DNSLookupaddress: string

The IP address of the host as a string in IPv4 or IPv6 format.

"127.0.0.1"
family: 4 | 6ttl: number

Time to live in seconds

Only supported when using the c-ares DNS resolver via "backend" option to dns.lookup. Otherwise, it's 0.

interface EditorOptionscolumn?: numbereditor?: 'vscode' | 'subl'line?: numberinterface EnvNODE_ENV?: stringTZ?: string

Can be used to change the default timezone at runtime

interface ErrorEventInitbubbles?: booleancancelable?: booleancolno?: numbercomposed?: booleanerror?: anyfilename?: stringlineno?: numbermessage?: stringinterface ErrorLikecause?: unknown

The cause of the error.

code?: stringerrno?: numbermessage: stringname: stringstack?: stringsyscall?: stringinterface EventInitbubbles?: booleancancelable?: booleancomposed?: booleaninterface EventListenerinterface EventListenerObjecthandleEvent(object: Event): void;interface EventListenerOptionscapture?: booleaninterface EventMapfetch: FetchEventmessage: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>messageerror: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>interface EventSourceEventMaperror: Eventmessage: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>open: Eventinterface FdSocketOptionsData = undefined>allowHalfOpen?: boolean

Whether to allow half-open connections.

A half-open connection occurs when one end of the connection has called close() or sent a FIN packet, while the other end remains open. When set to true:

The socket won't automatically send FIN when the remote side closes its endThe local side can continue sending data even after the remote side has closedThe application must explicitly call end() to fully close the connection

When false, the socket automatically closes both ends of the connection when either side closes.

data?: Data

The per-instance data context

fd: number

The file descriptor to connect to

socket: SocketHandlerData>

Handlers for socket events

tls?: boolean | TLSOptions

TLS Configuration with which to create the socket

interface FetchEventreadonly AT_TARGET: 2readonly bubbles: boolean

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

MDN Reference

readonly BUBBLING_PHASE: 3readonly cancelable: boolean

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

MDN Reference

readonly CAPTURING_PHASE: 1readonly composed: boolean

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

MDN Reference

readonly currentTarget: null | EventTarget

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

MDN Reference

readonly defaultPrevented: boolean

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

MDN Reference

readonly eventPhase: number

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

MDN Reference

readonly isTrusted: boolean

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

MDN Reference

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

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

MDN Reference

readonly timeStamp: number

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

MDN Reference

readonly type: string

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

MDN Reference

readonly url: stringcomposedPath(): EventTarget[];

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

MDN Reference

composedPath(): [EventTarget?];

Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness.

preventDefault(): void;

Sets the defaultPrevented property to true if cancelable is true.

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

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

stopPropagation(): void;

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

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

Blob powered by the fastest system calls available for operating on files.

This Blob is lazy. That means it won't do any work until you read from it.

size will not be valid until the contents of the file are read at least once.type is auto-set based on the file extension when possible
const file = Bun.file("./hello.json");
console.log(file.type); // "application/json"
console.log(await file.text()); // '{"hello":"world"}'
lastModified: number

A UNIX timestamp indicating when the file was last modified.

readonly name?: string

The name or path of the file, as specified in the constructor.

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

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

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

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

delete(): Promisevoid>;

Deletes the file (same as unlink)

exists(): Promiseboolean>;

Does the file exist?

This returns true for regular files and FIFOs. It returns false for directories. Note that a race condition can occur where the file is deleted or renamed after this is called but before you open it.

This does a system call to check if the file exists, which can be slow.

If using this in an HTTP server, it's faster to instead use return new Response(Bun.file(path)) and then an error handler to handle exceptions.

Instead of checking for a file's existence and then performing the operation, it is faster to just perform the operation and handle the error.

For empty Blob, this always returns true.

formData(): PromiseFormData>;

Read the data from the blob as a FormData object.

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

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

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

image(options?: ConstructorOptions): Image;

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

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

Read the data from the blob as a JSON object.

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

0, () will be slower on macOS" data-algolia-static="false" data-algolia-merged="false" data-type="Method">slice(begin?: number,end?: number,contentType?: string): BunFile;

Offset any operation on the file starting at begin and ending at end. end is relative to 0

Similar to TypedArray.subarray. Does not copy the file, open the file, or modify the file.

If begin > 0, () will be slower on macOS

@param begin

start offset in bytes

@param end

absolute offset in bytes (relative to 0)

@param contentType

MIME type for the new BunFile

slice(begin?: number,contentType?: string): BunFile;

Offset any operation on the file starting at begin

Similar to TypedArray.subarray. Does not copy the file, open the file, or modify the file.

If begin > 0, Bun.write() will be slower on macOS

@param begin

start offset in bytes

@param contentType

MIME type for the new BunFile

slice(contentType?: string): BunFile;

Slice the file from the beginning to the end, optionally with a new MIME type.

@param contentType

MIME type for the new BunFile

stat(): PromiseStats>;

Provides useful information about the file.

stream(): ReadableStreamUint8ArrayArrayBufferLike>>;stream(): ReadableStreamUint8ArrayArrayBuffer>>;

Returns a readable stream of the blob's contents

text(): Promisestring>;

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

unlink(): Promisevoid>;

Deletes the file.

write(data: string | ArrayBuffer | SharedArrayBuffer | BunFile | Request | Response | ArrayBufferViewArrayBufferLike>,options?: { highWaterMark: number }): Promisenumber>;

Write data to the file. This is equivalent to using Bun.write with a BunFile.

@param data

The data to write.

@param options

The options to use for the write.

writer(options?: { highWaterMark: number }): FileSink;

Incremental writer for files and pipes.

interface FileSink

Fast incremental writer for files and pipes.

This uses the same interface as ArrayBufferSink, but writes to a file or pipe.

end(error?: Error): number | Promisenumber>;

Close the file descriptor. This also flushes the internal buffer.

@param error

Optional error to associate with the close operation

@returns

Number of bytes written or a Promise resolving to the number of bytes

flush(): number | Promisenumber>;

Flush the internal buffer, committing the data to disk or the pipe.

@returns

Number of bytes flushed or a Promise resolving to the number of bytes

ref(): void;

For FIFOs & pipes, this lets you decide whether Bun's process should remain alive until the pipe is closed.

By default, it is automatically managed. While the stream is open, the process remains alive and once the other end hangs up or the stream closes, the process exits.

If you previously called unref, you can call this again to re-enable automatic management.

Internally, it will reference count the number of times this is called. By default, that number is 1

If the file is not a FIFO or pipe, ref and unref do nothing. If the pipe is already closed, this does nothing.

start(options?: { highWaterMark: number }): void;

Start the file sink with provided options.

@param options

Configuration options for the file sink

unref(): void;

For FIFOs & pipes, this lets you decide whether Bun's process should remain alive until the pipe is closed.

If you want to allow Bun's process to terminate while the stream is open, call this.

If the file is not a FIFO or pipe, ref and unref do nothing. If the pipe is already closed, this does nothing.

write(chunk: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>): number | Promisenumber>;

Write a chunk of data to the file.

If the file descriptor is not writable yet, the data is buffered.

@param chunk

The data to write

@returns

Number of bytes written or, if the write is pending, a Promise resolving to the number of bytes

interface GenericTransformStreamreadonly readable: ReadableStreamreadonly writable: WritableStreaminterface GlobScanOptionsabsolute?: boolean

Return the absolute path for entries.

cwd?: string

The root directory to start matching from. Defaults to process.cwd()

dot?: boolean

Allow patterns to match entries that begin with a period (.).

followSymlinks?: boolean

Indicates whether to traverse descendants of symbolic link directories.

onlyFiles?: boolean

Return only files.

throwErrorOnBrokenSymlink?: boolean

Throw an error when symbolic link is broken

interface Hashadler32: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>) => numbercityHash32: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>) => numbercityHash64: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>, seed?: bigint) => bigintcrc32: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>, seed?: number) => numbermurmur32v2: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>, seed?: number) => numbermurmur32v3: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>, seed?: number) => numbermurmur64v2: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>, seed?: bigint) => bigintrapidhash: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>, seed?: bigint) => bigintwyhash: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>, seed?: bigint) => bigintxxHash3: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>, seed?: bigint) => bigintxxHash32: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>, seed?: number) => numberxxHash64: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>, seed?: bigint) => bigintinterface HeapSnapshot

JavaScriptCore engine's internal heap snapshot

I don't know how to make this something Chrome or Safari can read.

If you have any ideas, please file an issue https://github.com/oven-sh/bun

edgeNames: string[]edges: number[]edgeTypes: string[]nodeClassNames: string[]nodes: number[]type: string

"Inspector"

version: number

2

interface HTMLBundle

Used when importing an HTML file at runtime or at build time.

import app from "./index.html";
files?: { headers: { content-type: string; etag: string }; input: string; isEntry: boolean; loader: Loader; path: string }[]

Array of generated output files with metadata. This only exists when built ahead of time with Bun.build or bun build

index: stringinterface Importkind: ImportKindpath: stringinterface LibdeflateCompressionOptionslevel?: 0 | 2 | 1 | 5 | 3 | 4 | 6 | 7 | 8 | 9 | 10 | 11 | 12library?: 'libdeflate'interface MatchedRoutereadonly filePath: stringreadonly kind: 'exact' | 'catch-all' | 'optional-catch-all' | 'dynamic'readonly name: stringreadonly params: Recordstring, string>

A map of the parameters from the route

const router = new FileSystemRouter({
dir: "/path/to/files",
style: "nextjs",
});
const {params} = router.match("/blog/2020/01/01/hello-world");
console.log(params.year); // "2020"
console.log(params.month); // "01"
console.log(params.day); // "01"
console.log(params.slug); // "hello-world"
readonly pathname: stringreadonly query: Recordstring, string>readonly src: stringinterface MessageEventInitT = any>bubbles?: booleancancelable?: booleancomposed?: booleandata?: TlastEventId?: stringorigin?: stringsource?: nullinterface MMapOptionsshared?: boolean

Allow other processes to see results instantly? This enables MAP_SHARED. If false, it enables MAP_PRIVATE.

sync?: boolean

Sets MAP_SYNC flag on Linux. Ignored on macOS due to lack of support.

interface NetworkSink

Fast incremental writer for files and pipes.

This uses the same interface as ArrayBufferSink, but writes to a file or pipe.

end(error?: Error): number | Promisenumber>;

Finish the upload. This also flushes the internal buffer.

@param error

Optional error to associate with the end operation

@returns

Number of bytes written or a Promise resolving to the number of bytes

flush(): number | Promisenumber>;

Flush the internal buffer, committing the data to the network.

@returns

Number of bytes flushed or a Promise resolving to the number of bytes

ref(): void;

For FIFOs & pipes, this lets you decide whether Bun's process should remain alive until the pipe is closed.

By default, it is automatically managed. While the stream is open, the process remains alive and once the other end hangs up or the stream closes, the process exits.

If you previously called unref, you can call this again to re-enable automatic management.

Internally, it will reference count the number of times this is called. By default, that number is 1

If the file is not a FIFO or pipe, ref and unref do nothing. If the pipe is already closed, this does nothing.

start(options?: { highWaterMark: number }): void;

Start the file sink with provided options.

@param options

Configuration options for the file sink

stat(): PromiseStats>;

Get the stat of the file.

@returns

Promise resolving to the file stats

unref(): void;

For FIFOs & pipes, this lets you decide whether Bun's process should remain alive until the pipe is closed.

If you want to allow Bun's process to terminate while the stream is open, call this.

If the file is not a FIFO or pipe, ref and unref do nothing. If the pipe is already closed, this does nothing.

write(chunk: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>): number | Promisenumber>;

Write a chunk of data to the network.

If the network is not writable yet, the data is buffered.

@param chunk

The data to write

@returns

Number of bytes written or, if the write is pending, a Promise resolving to the number of bytes

interface OnLoadArgsdefer: () => Promisevoid>

Defer the execution of this callback until all other modules have been parsed.

loader: Loader

The default loader for this file extension

namespace: string

The namespace of the module being loaded

path: string

The resolved import specifier of the module being loaded

builder.onLoad({ filter: /^hello:world$/ }, (args) => {
console.log(args.path); // "hello:world"
return { exports: { foo: "bar" }, loader: "object" };
});
interface OnLoadResultObjectexports: Recordstring, unknown>

The object to use as the module

// In your loader
builder.onLoad({ filter: /^hello:world$/ }, (args) => {
return { exports: { foo: "bar" }, loader: "object" };
});

// In your script
import {foo} from "hello:world";
console.log(foo); // "bar"
loader: 'object'

The loader to use for this file

interface OnLoadResultSourceCodecontents: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferViewArrayBufferLike>

The source code of the module

loader?: Loader

The loader to use for this file

"css" will be added in a future version of Bun.

interface OnResolveArgsimporter: string

The module that imported the module being resolved

kind: ImportKind

The kind of import this resolve is for.

namespace: string

The namespace of the importer.

path: string

The import specifier of the module being loaded

resolveDir: string

The directory to perform file-based resolutions in.

interface OnResolveResultexternal?: booleannamespace?: string

The namespace of the destination It will be concatenated with path to form the final import specifier

"foo" // "foo:bar"
path: string

The destination of the import

interface PluginBuilder

The builder object passed to Bun.plugin

config: BuildConfig & { plugins: BunPlugin[] }

The config object passed to Bun.build as is. Can be mutated.

module(specifier: string,callback: () => OnLoadResult | PromiseOnLoadResult>): this;

Create a lazy-loaded virtual module that can be imported or required from other modules

@param specifier

The module specifier to register the callback for

@param callback

The function to run when the module is imported or required

@returns

this for method chaining

Bun.plugin({
setup(builder) {
builder.module("hello:world", () => {
return { exports: { foo: "bar" }, loader: "object" };
});
},
});

// sometime later
const { foo } = await import("hello:world");
console.log(foo); // "bar"

// or
const { foo } = require("hello:world");
console.log(foo); // "bar"
onBeforeParse(constraints: PluginConstraints,callback: OnBeforeParseCallback): this;onEnd(callback: OnEndCallback): this;

Register a callback which will be invoked when bundling ends. This is called after all modules have been bundled and the build is complete.

@returns

this for method chaining

const plugin: Bun.BunPlugin = {
name: "my-plugin",
setup(builder) {
builder.onEnd((result) => {
console.log("bundle just finished!!", result);
});
},
};
onLoad(constraints: PluginConstraints,callback: OnLoadCallback): this;

Register a callback to load imports with a specific import specifier

@param constraints

The constraints to apply the plugin to

@param callback

The callback to handle the import

@returns

this for method chaining

Bun.plugin({
setup(builder) {
builder.onLoad({ filter: /^hello:world$/ }, (args) => {
return { exports: { foo: "bar" }, loader: "object" };
});
},
});
onResolve(constraints: PluginConstraints,callback: OnResolveCallback): this;

Register a callback to resolve imports matching a filter and/or namespace

@param constraints

The constraints to apply the plugin to

@param callback

The callback to handle the import

@returns

this for method chaining

Bun.plugin({
setup(builder) {
builder.onResolve({ filter: /^wat$/ }, (args) => {
return { path: "/tmp/woah.js" };
});
},
});
onStart(callback: OnStartCallback): this;

Register a callback which will be invoked when bundling starts. When using hot module reloading, this is called at the start of each incremental rebuild.

@returns

this for method chaining

Bun.plugin({
setup(builder) {
builder.onStart(() => {
console.log("bundle just started!!")
});
},
});
interface PluginConstraintsfilter: RegExp

Only apply the plugin when the import specifier matches this regular expression

// Only apply the plugin when the import specifier matches the regex
Bun.plugin({
setup(builder) {
builder.onLoad({ filter: /node_modules/underscore/ }, (args) => {
return { contents: "throw new Error('Please use lodash instead of underscore.')" };
});
}
})
namespace?: string

Only apply the plugin when the import specifier has a namespace matching this string

Namespaces are prefixes in import specifiers. For example, "bun:ffi" has the namespace "bun".

The default namespace is "file" and it can be omitted from import specifiers.

interface ReadableStreamDefaultReadManyResultT>done: booleansize: number

Number of bytes

value: T[]interface RedisOptionsautoReconnect?: boolean

Whether to automatically reconnect

connectionTimeout?: number

Connection timeout in milliseconds

enableAutoPipelining?: boolean

Whether to enable auto-pipelining

enableOfflineQueue?: boolean

Whether to queue commands when disconnected

idleTimeout?: number

Idle timeout in milliseconds

maxRetries?: number

Maximum number of reconnection attempts

tls?: boolean | TLSOptions

TLS options Can be a boolean or an object with TLS options

interface ReservedSQL

Represents a reserved connection from the connection pool Extends SQL with additional release functionality

options: MergeSQLiteOptions, PostgresOrMySQLOptions> | MergePostgresOrMySQLOptions, SQLiteOptions>

Current client options

[Symbol.asyncDispose](): PromiseLikevoid>;[Symbol.dispose](): void;array(values: any[],typeNameOrTypeID?: number | ArrayType): SQLArrayParameter;

Creates a new SQL array parameter

@param values

The values to create the array parameter from

@param typeNameOrTypeID

The type name or type ID to create the array parameter from, if omitted it will default to JSON

@returns

A new SQL array parameter

const array = sql.array([1, 2, 3], "INT");
await sql`CREATE TABLE users_posts (user_id INT, posts_id INT[])`;
await sql`INSERT INTO users_posts (user_id, posts_id) VALUES (${user.id}, ${array})`;
beginT>(fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a new transaction.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.begin(async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
beginT>(options: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a new transaction with options.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.begin("read write", async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
beginDistributedT>(name: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a distributed transaction Also know as Two-Phase Commit, in a distributed transaction, Phase 1 involves the coordinator preparing nodes by ensuring data is written and ready to commit, while Phase 2 finalizes with nodes committing or rolling back based on the coordinator's decision, ensuring durability and releasing locks. In PostgreSQL and MySQL distributed transactions persist beyond the original session, allowing privileged users or coordinators to commit/rollback them, ensuring support for distributed transactions, recovery, and administrative tasks. beginDistributed will automatic rollback if any exception are not caught, and you can commit and rollback later if everything goes well. PostgreSQL natively supports distributed transactions using PREPARE TRANSACTION, while MySQL uses XA Transactions, and MSSQL also supports distributed/XA transactions. However, in MSSQL, distributed transactions are tied to the original session, the DTC coordinator, and the specific connection. These transactions are automatically committed or rolled back following the same rules as regular transactions, with no option for manual intervention from other sessions, in MSSQL distributed transactions are used to coordinate transactions using Linked Servers.

await sql.beginDistributed("numbers", async sql => {
await sql`create table if not exists numbers (a int)`;
await sql`insert into numbers values(1)`;
});
// later you can call
await sql.commitDistributed("numbers");
// or await sql.rollbackDistributed("numbers");
close(options?: { timeout: number }): Promisevoid>;

Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing.

@param options

The options for the close

await sql.close({ timeout: 1 });
commitDistributed(name: string): Promisevoid>;

Commits a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL

@param name

The name of the distributed transaction

await sql.commitDistributed("my_distributed_transaction");
connect(): PromiseSQL>;

Waits for the database connection to be established

await sql.connect();
distributedT>(name: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a distributed transaction

end(options?: { timeout: number }): Promisevoid>;

Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing. This is an alias of SQL.close

@param options

The options for the close

await sql.end({ timeout: 1 });
fileT = any>(filename: string,values?: any[]): QueryT>;

Reads a file and uses the contents as a query. Optional parameters can be used if the file includes $1, $2, etc

const result = await sql.file("query.sql", [1, 2, 3]);
flush(): void;

Flushes any pending operations

sql.flush();
release(): void;

Releases the client back to the connection pool

reserve(): PromiseReservedSQL>;

The reserve method pulls out a connection from the pool, and returns a client that wraps the single connection.

This can be used for running queries on an isolated connection. Calling reserve in a reserved Sql will return a new reserved connection, not the same connection (behavior matches postgres package).

const reserved = await sql.reserve();
await reserved`select * from users`;
await reserved.release();
// with in a production scenario would be something more like
const reserved = await sql.reserve();
try {
// ... queries
} finally {
await reserved.release();
}

// Bun supports Symbol.dispose and Symbol.asyncDispose
// always release after context (safer)
using reserved = await sql.reserve()
await reserved`select * from users`
rollbackDistributed(name: string): Promisevoid>;

Rolls back a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL

@param name

The name of the distributed transaction

await sql.rollbackDistributed("my_distributed_transaction");
transactionT>(fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a transaction.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.transaction(async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
transactionT>(options: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a transaction with options Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.transaction("read write", async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
});
unsafeT = any>(string: string,values?: any[]): QueryT>;

If you know what you're doing, you can use unsafe to pass any string you'd like. Please note that this can lead to SQL injection if you're not careful. You can also nest sql.unsafe within a safe sql expression. This is useful if only part of your fraction has unsafe elements.

const result = await sql.unsafe(`select ${danger} from users where id = ${dragons}`)
interface ResourceUsagecontextSwitches: { involuntary: number; voluntary: number }

The number of voluntary and involuntary context switches that the process made.

cpuTime: { system: number; total: number; user: number }

The amount of CPU time used by the process, in microseconds.

maxRSS: number

The maximum amount of resident set size (in bytes) used by the process during its lifetime.

messages: { received: number; sent: number }

IPC messages sent and received by the process.

ops: { in: number; out: number }

The number of IO operations done by the process.

shmSize: number

The amount of shared memory that the process used.

signalCount: number

The number of signals delivered to the process.

swapCount: number

The number of times the process was swapped out of main memory.

interface S3FilePresignOptions

Options for generating presigned URLs

accessKeyId?: string

The access key ID for authentication. Defaults to S3_ACCESS_KEY_ID or AWS_ACCESS_KEY_ID environment variables.

acl?: 'private' | 'public-read' | 'public-read-write' | 'aws-exec-read' | 'authenticated-read' | 'bucket-owner-read' | 'bucket-owner-full-control' | 'log-delivery-write'

The Access Control List (ACL) policy for the file. Controls who can access the file and what permissions they have.

// Setting public read access
const file = s3.file("public-file.txt", {
acl: "public-read",
bucket: "my-bucket"
});
bucket?: string

The S3 bucket name. Defaults to S3_BUCKET or AWS_BUCKET environment variables.

// Using explicit bucket
const file = s3.file("my-file.txt", { bucket: "my-bucket" });
contentDisposition?: string

The Content-Disposition header value. Controls how the file is presented when downloaded.

// Setting attachment disposition with filename
const file = s3.file("report.pdf", {
contentDisposition: "attachment; filename=\"quarterly-report.pdf\""
});
contentEncoding?: string

The Content-Encoding header value. Specifies what content encodings have been applied to the object, for example to indicate that it has been compressed.

// Setting gzip encoding
const file = s3.file("data.json.gz", {
contentEncoding: "gzip"
});
endings?: EndingTypeendpoint?: string

The S3-compatible service endpoint URL. Defaults to S3_ENDPOINT or AWS_ENDPOINT environment variables.

// AWS S3
const file = s3.file("my-file.txt", {
endpoint: "https://s3.us-east-1.amazonaws.com"
});
expiresIn?: number

Number of seconds until the presigned URL expires.

Default: 86400 (1 day)
// Short-lived URL
const url = file.presign({
expiresIn: 3600 // 1 hour
});
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD'

The HTTP method allowed for the presigned URL.

// GET URL for downloads
const downloadUrl = file.presign({
method: "GET",
expiresIn: 3600
});
partSize?: number

The size of each part in multipart uploads (in bytes).

Minimum: 5 MiBMaximum: 5120 MiBDefault: 5 MiB
// Configuring multipart uploads
const file = s3.file("large-file.dat", {
partSize: 10 * 1024 * 1024, // 10 MiB parts
queueSize: 4 // Upload 4 parts in parallel
});

const writer = file.writer();
// ... write large file in chunks
queueSize?: number

Number of parts to upload in parallel for multipart uploads.

Default: 5Maximum: 255

Increasing this value can improve upload speeds for large files but will use more memory.

region?: string

The AWS region. Defaults to S3_REGION or AWS_REGION environment variables.

const file = s3.file("my-file.txt", {
bucket: "my-bucket",
region: "us-west-2"
});
requestPayer?: boolean

When set to true, confirms that the requester knows they will be charged for the request and data transfer costs. Required for accessing objects in Requester Pays buckets.

// Accessing a file in a Requester Pays bucket
const file = s3.file("data.csv", {
bucket: "requester-pays-bucket",
requestPayer: true
});
const content = await file.text();
retry?: number

Number of retry attempts for failed uploads.

Default: 3Maximum: 255
// Setting retry attempts
const file = s3.file("my-file.txt", {
retry: 5 // Retry failed uploads up to 5 times
});
secretAccessKey?: string

The secret access key for authentication. Defaults to S3_SECRET_ACCESS_KEY or AWS_SECRET_ACCESS_KEY environment variables.

sessionToken?: string

Optional session token for temporary credentials. Defaults to S3_SESSION_TOKEN or AWS_SESSION_TOKEN environment variables.

// Using temporary credentials
const file = s3.file("my-file.txt", {
accessKeyId: tempAccessKey,
secretAccessKey: tempSecretKey,
sessionToken: tempSessionToken
});
storageClass?: 'STANDARD' | 'DEEP_ARCHIVE' | 'EXPRESS_ONEZONE' | 'GLACIER' | 'GLACIER_IR' | 'INTELLIGENT_TIERING' | 'ONEZONE_IA' | 'OUTPOSTS' | 'REDUCED_REDUNDANCY' | 'SNOW' | 'STANDARD_IA'

By default, Amazon S3 uses the STANDARD Storage Class to store newly created objects.

// Setting explicit Storage class
const file = s3.file("my-file.json", {
storageClass: "STANDARD_IA"
});
type?: string

The Content-Type of the file. Automatically set based on file extension when possible.

// Setting explicit content type
const file = s3.file("data.bin", {
type: "application/octet-stream"
});
virtualHostedStyle?: boolean

Use virtual hosted style endpoint. default to false, when true if endpoint is informed it will ignore the bucket

// Using virtual hosted style
const file = s3.file("my-file.txt", {
virtualHostedStyle: true,
endpoint: "https://my-bucket.s3.us-east-1.amazonaws.com"
});
interface S3ListObjectsOptionscontinuationToken?: string

ContinuationToken indicates to S3 that the list is being continued on this bucket with a token. ContinuationToken is obfuscated and is not a real key. You can use this ContinuationToken for pagination of the list results.

delimiter?: string

A delimiter is a character that you use to group keys.

encodingType?: 'url'

Encoding type used by S3 to encode the object keys in the response. Responses are encoded only in UTF-8. An object key can contain any Unicode character. However, the XML 1.0 parser can't parse certain characters, such as characters with an ASCII value from 0 to 10. For characters that aren't supported in XML 1.0, you can add this parameter to request that S3 encode the keys in the response.

fetchOwner?: boolean

If you want to return the owner field with each key in the result, then set the FetchOwner field to true.

maxKeys?: number

Sets the maximum number of keys returned in the response. By default, the action returns up to 1,000 key names. The response might contain fewer keys but will never contain more.

prefix?: string

Limits the response to keys that begin with the specified prefix.

startAfter?: string

StartAfter is where you want S3 to start listing from. S3 starts listing after this specified key. StartAfter can be any key in the bucket.

interface S3ListObjectsResponsecommonPrefixes?: { prefix: string }[]

All of the keys (up to 1,000) that share the same prefix are grouped together. When counting the total numbers of returns by this API operation, this group of keys is considered as one item.

A response can contain CommonPrefixes only if you specify a delimiter.

CommonPrefixes contains all (if there are any) keys between Prefix and the next occurrence of the string specified by a delimiter.

CommonPrefixes lists keys that act like subdirectories in the directory specified by Prefix.

For example, if the prefix is notes/ and the delimiter is a slash (/) as in notes/summer/july, the common prefix is notes/summer/. All of the keys that roll up into a common prefix count as a single return when calculating the number of returns.

contents?: { checksumAlgorithm: 'CRC32' | 'CRC32C' | 'SHA1' | 'SHA256' | 'CRC64NVME'; checksumType: 'COMPOSITE' | 'FULL_OBJECT'; eTag: string; key: string; lastModified: string; owner: { displayName: string; id: string }; restoreStatus: { isRestoreInProgress: boolean; restoreExpiryDate: string }; size: number; storageClass: 'STANDARD' | 'DEEP_ARCHIVE' | 'EXPRESS_ONEZONE' | 'GLACIER' | 'GLACIER_IR' | 'INTELLIGENT_TIERING' | 'ONEZONE_IA' | 'OUTPOSTS' | 'REDUCED_REDUNDANCY' | 'SNOW' | 'STANDARD_IA' }[]

Metadata about each object returned.

continuationToken?: string

If ContinuationToken was sent with the request, it is included in the response. You can use the returned ContinuationToken for pagination of the list response.

delimiter?: string

Causes keys that contain the same string between the prefix and the first occurrence of the delimiter to be rolled up into a single result element in the CommonPrefixes collection. These rolled-up keys are not returned elsewhere in the response. Each rolled-up result counts as only one return against the MaxKeys value.

encodingType?: 'url'

Encoding type used by S3 to encode object key names in the XML response.

isTruncated?: boolean

Set to false if all of the results were returned. Set to true if more keys are available to return. If the number of results exceeds that specified by MaxKeys, all of the results might not be returned.

keyCount?: number

KeyCount is the number of keys returned with this request. KeyCount will always be less than or equal to the MaxKeys field. For example, if you ask for 50 keys, your result will include 50 keys or fewer.

maxKeys?: number

Sets the maximum number of keys returned in the response. By default, the action returns up to 1,000 key names. The response might contain fewer keys but will never contain more.

name?: string

The bucket name.

nextContinuationToken?: string

NextContinuationToken is sent when isTruncated is true, which means there are more keys in the bucket that can be listed. The next list requests to S3 can be continued with this NextContinuationToken. NextContinuationToken is obfuscated and is not a real key.

prefix?: string

Keys that begin with the indicated prefix.

startAfter?: string

If StartAfter was sent with the request, it is included in the response.

interface S3Options

Configuration options for S3 operations

accessKeyId?: string

The access key ID for authentication. Defaults to S3_ACCESS_KEY_ID or AWS_ACCESS_KEY_ID environment variables.

acl?: 'private' | 'public-read' | 'public-read-write' | 'aws-exec-read' | 'authenticated-read' | 'bucket-owner-read' | 'bucket-owner-full-control' | 'log-delivery-write'

The Access Control List (ACL) policy for the file. Controls who can access the file and what permissions they have.

// Setting public read access
const file = s3.file("public-file.txt", {
acl: "public-read",
bucket: "my-bucket"
});
bucket?: string

The S3 bucket name. Defaults to S3_BUCKET or AWS_BUCKET environment variables.

// Using explicit bucket
const file = s3.file("my-file.txt", { bucket: "my-bucket" });
contentDisposition?: string

The Content-Disposition header value. Controls how the file is presented when downloaded.

// Setting attachment disposition with filename
const file = s3.file("report.pdf", {
contentDisposition: "attachment; filename=\"quarterly-report.pdf\""
});
contentEncoding?: string

The Content-Encoding header value. Specifies what content encodings have been applied to the object, for example to indicate that it has been compressed.

// Setting gzip encoding
const file = s3.file("data.json.gz", {
contentEncoding: "gzip"
});
endings?: EndingTypeendpoint?: string

The S3-compatible service endpoint URL. Defaults to S3_ENDPOINT or AWS_ENDPOINT environment variables.

// AWS S3
const file = s3.file("my-file.txt", {
endpoint: "https://s3.us-east-1.amazonaws.com"
});
partSize?: number

The size of each part in multipart uploads (in bytes).

Minimum: 5 MiBMaximum: 5120 MiBDefault: 5 MiB
// Configuring multipart uploads
const file = s3.file("large-file.dat", {
partSize: 10 * 1024 * 1024, // 10 MiB parts
queueSize: 4 // Upload 4 parts in parallel
});

const writer = file.writer();
// ... write large file in chunks
queueSize?: number

Number of parts to upload in parallel for multipart uploads.

Default: 5Maximum: 255

Increasing this value can improve upload speeds for large files but will use more memory.

region?: string

The AWS region. Defaults to S3_REGION or AWS_REGION environment variables.

const file = s3.file("my-file.txt", {
bucket: "my-bucket",
region: "us-west-2"
});
requestPayer?: boolean

When set to true, confirms that the requester knows they will be charged for the request and data transfer costs. Required for accessing objects in Requester Pays buckets.

// Accessing a file in a Requester Pays bucket
const file = s3.file("data.csv", {
bucket: "requester-pays-bucket",
requestPayer: true
});
const content = await file.text();
retry?: number

Number of retry attempts for failed uploads.

Default: 3Maximum: 255
// Setting retry attempts
const file = s3.file("my-file.txt", {
retry: 5 // Retry failed uploads up to 5 times
});
secretAccessKey?: string

The secret access key for authentication. Defaults to S3_SECRET_ACCESS_KEY or AWS_SECRET_ACCESS_KEY environment variables.

sessionToken?: string

Optional session token for temporary credentials. Defaults to S3_SESSION_TOKEN or AWS_SESSION_TOKEN environment variables.

// Using temporary credentials
const file = s3.file("my-file.txt", {
accessKeyId: tempAccessKey,
secretAccessKey: tempSecretKey,
sessionToken: tempSessionToken
});
storageClass?: 'STANDARD' | 'DEEP_ARCHIVE' | 'EXPRESS_ONEZONE' | 'GLACIER' | 'GLACIER_IR' | 'INTELLIGENT_TIERING' | 'ONEZONE_IA' | 'OUTPOSTS' | 'REDUCED_REDUNDANCY' | 'SNOW' | 'STANDARD_IA'

By default, Amazon S3 uses the STANDARD Storage Class to store newly created objects.

// Setting explicit Storage class
const file = s3.file("my-file.json", {
storageClass: "STANDARD_IA"
});
type?: string

The Content-Type of the file. Automatically set based on file extension when possible.

// Setting explicit content type
const file = s3.file("data.bin", {
type: "application/octet-stream"
});
virtualHostedStyle?: boolean

Use virtual hosted style endpoint. default to false, when true if endpoint is informed it will ignore the bucket

// Using virtual hosted style
const file = s3.file("my-file.txt", {
virtualHostedStyle: true,
endpoint: "https://my-bucket.s3.us-east-1.amazonaws.com"
});
interface S3Statsetag: stringlastModified: Datesize: numbertype: stringinterface SavepointSQL

Represents a savepoint within a transaction

options: MergeSQLiteOptions, PostgresOrMySQLOptions> | MergePostgresOrMySQLOptions, SQLiteOptions>

Current client options

[Symbol.asyncDispose](): PromiseLikevoid>;array(values: any[],typeNameOrTypeID?: number | ArrayType): SQLArrayParameter;

Creates a new SQL array parameter

@param values

The values to create the array parameter from

@param typeNameOrTypeID

The type name or type ID to create the array parameter from, if omitted it will default to JSON

@returns

A new SQL array parameter

const array = sql.array([1, 2, 3], "INT");
await sql`CREATE TABLE users_posts (user_id INT, posts_id INT[])`;
await sql`INSERT INTO users_posts (user_id, posts_id) VALUES (${user.id}, ${array})`;
beginT>(fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a new transaction.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.begin(async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
beginT>(options: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a new transaction with options.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.begin("read write", async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
beginDistributedT>(name: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a distributed transaction Also know as Two-Phase Commit, in a distributed transaction, Phase 1 involves the coordinator preparing nodes by ensuring data is written and ready to commit, while Phase 2 finalizes with nodes committing or rolling back based on the coordinator's decision, ensuring durability and releasing locks. In PostgreSQL and MySQL distributed transactions persist beyond the original session, allowing privileged users or coordinators to commit/rollback them, ensuring support for distributed transactions, recovery, and administrative tasks. beginDistributed will automatic rollback if any exception are not caught, and you can commit and rollback later if everything goes well. PostgreSQL natively supports distributed transactions using PREPARE TRANSACTION, while MySQL uses XA Transactions, and MSSQL also supports distributed/XA transactions. However, in MSSQL, distributed transactions are tied to the original session, the DTC coordinator, and the specific connection. These transactions are automatically committed or rolled back following the same rules as regular transactions, with no option for manual intervention from other sessions, in MSSQL distributed transactions are used to coordinate transactions using Linked Servers.

await sql.beginDistributed("numbers", async sql => {
await sql`create table if not exists numbers (a int)`;
await sql`insert into numbers values(1)`;
});
// later you can call
await sql.commitDistributed("numbers");
// or await sql.rollbackDistributed("numbers");
close(options?: { timeout: number }): Promisevoid>;

Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing.

@param options

The options for the close

await sql.close({ timeout: 1 });
commitDistributed(name: string): Promisevoid>;

Commits a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL

@param name

The name of the distributed transaction

await sql.commitDistributed("my_distributed_transaction");
connect(): PromiseSQL>;

Waits for the database connection to be established

await sql.connect();
distributedT>(name: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a distributed transaction

end(options?: { timeout: number }): Promisevoid>;

Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing. This is an alias of SQL.close

@param options

The options for the close

await sql.end({ timeout: 1 });
fileT = any>(filename: string,values?: any[]): QueryT>;

Reads a file and uses the contents as a query. Optional parameters can be used if the file includes $1, $2, etc

const result = await sql.file("query.sql", [1, 2, 3]);
flush(): void;

Flushes any pending operations

sql.flush();
reserve(): PromiseReservedSQL>;

The reserve method pulls out a connection from the pool, and returns a client that wraps the single connection.

This can be used for running queries on an isolated connection. Calling reserve in a reserved Sql will return a new reserved connection, not the same connection (behavior matches postgres package).

const reserved = await sql.reserve();
await reserved`select * from users`;
await reserved.release();
// with in a production scenario would be something more like
const reserved = await sql.reserve();
try {
// ... queries
} finally {
await reserved.release();
}

// Bun supports Symbol.dispose and Symbol.asyncDispose
// always release after context (safer)
using reserved = await sql.reserve()
await reserved`select * from users`
rollbackDistributed(name: string): Promisevoid>;

Rolls back a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL

@param name

The name of the distributed transaction

await sql.rollbackDistributed("my_distributed_transaction");
transactionT>(fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a transaction.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.transaction(async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
transactionT>(options: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a transaction with options Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.transaction("read write", async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
});
unsafeT = any>(string: string,values?: any[]): QueryT>;

If you know what you're doing, you can use unsafe to pass any string you'd like. Please note that this can lead to SQL injection if you're not careful. You can also nest sql.unsafe within a safe sql expression. This is useful if only part of your fraction has unsafe elements.

const result = await sql.unsafe(`select ${danger} from users where id = ${dragons}`)
interface ServerWebSocketT = undefined>

A fast WebSocket designed for servers.

Features:

Message compression - Messages can be compressedBackpressure - If the client is not ready to receive data, the server will tell you.Dropped messages - If the client cannot receive data, the server will tell you.Topics - Messages can be ServerWebSocket.published to a specific topic and the client can ServerWebSocket.subscribe to topics

This is slightly different than the browser WebSocket which Bun supports for clients.

Powered by uWebSockets.

Bun.serve({
websocket: {
open(ws) {
console.log("Connected", ws.remoteAddress);
},
message(ws, data) {
console.log("Received", data);
ws.send(data);
},
close(ws, code, reason) {
console.log("Disconnected", code, reason);
},
}
});
binaryType?: 'arraybuffer' | 'uint8array' | 'nodebuffer'

Sets how binary data is returned in events.

if nodebuffer, binary data is returned as Buffer objects. (default)if arraybuffer, binary data is returned as ArrayBuffer objects.if uint8array, binary data is returned as Uint8Array objects.
let ws: WebSocket;
ws.binaryType = "uint8array";
ws.addEventListener("message", ({ data }) => {
console.log(data instanceof Uint8Array); // true
});
data: T

Custom data that you can assign to a client, can be read and written at any time.

import { serve } from "bun";

serve({
fetch(request, server) {
const data = {
accessToken: request.headers.get("Authorization"),
};
if (server.upgrade(request, { data })) {
return;
}
return new Response();
},
websocket: {
data: {} as {accessToken: string | null},
message(ws) {
console.log(ws.data.accessToken);
}
}
});
readonly readyState: WebSocketReadyState

The ready state of the client.

if 0, the client is connecting.if 1, the client is connected.if 2, the client is closing.if 3, the client is closed.
console.log(socket.readyState); // 1
readonly remoteAddress: string

The IP address of the client.

console.log(socket.remoteAddress); // "127.0.0.1"
readonly subscriptions: string[]

Returns an array of all topics the client is currently subscribed to.

ws.subscribe("chat");
ws.subscribe("notifications");
console.log(ws.subscriptions); // ["chat", "notifications"]
close(code?: number,reason?: string): void;

Closes the connection.

Here is a list of close codes:

1000 means "normal closure" (default)1009 means a message was too big and was rejected1011 means the server encountered an error1012 means the server is restarting1013 means the server is too busy or the client is rate-limited4000 through 4999 are reserved for applications (you can use it!)

To close the connection abruptly, use terminate().

@param code

The close code to send

@param reason

The close reason to send

corkT = unknown>(callback: (ws: ServerWebSocketT>) => T): T;

Batches send() and publish() operations, which makes it faster to send data.

The message, open, and drain callbacks are automatically corked, so you only need to call this if you are sending messages outside of those callbacks or in async functions.

@param callback

The callback to run.

ws.cork((ctx) => {
ctx.send("These messages");
ctx.sendText("are sent");
ctx.sendBinary(new TextEncoder().encode("together!"));
});
getBufferedAmount(): number;isSubscribed(topic: string): boolean;

Is the client subscribed to a topic?

@param topic

The topic name.

ws.subscribe("chat");
console.log(ws.isSubscribed("chat")); // true
ping(data?: string | BufferSource): number;

Sends a ping.

@param data

The data to send

pong(data?: string | BufferSource): number;

Sends a pong.

@param data

The data to send

publish(topic: string,data: string | BufferSource,compress?: boolean): number;

Sends a message to subscribers of the topic.

@param topic

The topic name.

@param data

The data to send.

@param compress

Should the data be compressed? If the client does not support compression, this is ignored.

ws.publish("chat", "Hello!");
ws.publish("chat", "Compress this.", true);
ws.publish("chat", new Uint8Array([1, 2, 3, 4]));
publishBinary(topic: string,data: BufferSource,compress?: boolean): number;

Sends a binary message to subscribers of the topic.

@param topic

The topic name.

@param data

The data to send.

@param compress

Should the data be compressed? If the client does not support compression, this is ignored.

ws.publish("chat", new TextEncoder().encode("Hello!"));
ws.publish("chat", new Uint8Array([1, 2, 3, 4]), true);
publishText(topic: string,data: string,compress?: boolean): number;

Sends a text message to subscribers of the topic.

@param topic

The topic name.

@param data

The data to send.

@param compress

Should the data be compressed? If the client does not support compression, this is ignored.

ws.publish("chat", "Hello!");
ws.publish("chat", "Compress this.", true);
send(data: string | BufferSource,compress?: boolean): number;

Sends a message to the client.

@param data

The data to send.

@param compress

Should the data be compressed? If the client does not support compression, this is ignored.

ws.send("Hello!");
ws.send("Compress this.", true);
ws.send(new Uint8Array([1, 2, 3, 4]));
sendBinary(data: BufferSource,compress?: boolean): number;

Sends a binary message to the client.

@param data

The data to send.

@param compress

Should the data be compressed? If the client does not support compression, this is ignored.

ws.send(new TextEncoder().encode("Hello!"));
ws.send(new Uint8Array([1, 2, 3, 4]), true);
sendText(data: string,compress?: boolean): number;

Sends a text message to the client.

@param data

The data to send.

@param compress

Should the data be compressed? If the client does not support compression, this is ignored.

ws.send("Hello!");
ws.send("Compress this.", true);
subscribe(topic: string): void;

Subscribes a client to the topic.

@param topic

The topic name.

ws.subscribe("chat");
terminate(): void;

Abruptly close the connection.

To gracefully close the connection, use close().

unsubscribe(topic: string): void;

Unsubscribes a client to the topic.

@param topic

The topic name.

ws.unsubscribe("chat");
interface SliceAnsiOptionsambiguousIsNarrow?: boolean

Count characters with East Asian Width "Ambiguous" as 1 column (narrow) instead of 2 (wide). Affects Greek, Cyrillic, some symbols, etc. that render wide in CJK-encoded terminals but narrow in Western ones.

Matches the option of the same name in stringWidth and wrapAnsi.

ellipsis?: string

If set, and content was cut at either edge of the requested range, insert this string at the cut edge(s). The ellipsis is counted against the visible-width budget and is emitted inside any active SGR styles (color, bold, etc.) so it inherits them, but outside any active OSC 8 hyperlink.

This turns sliceAnsi into a drop-in cli-truncate replacement:

truncate-end: sliceAnsi(str, 0, max, { ellipsis: "\u2026" })truncate-start: sliceAnsi(str, -max, undefined, { ellipsis: "\u2026" })
interface SocketData = undefined>

Represents a TCP or TLS socket connection used for network communication. This interface provides methods for reading, writing, managing the connection state, and handling TLS-specific features if applicable.

Sockets are created using Bun.connect() or accepted by a Bun.listen() server.

readonly alpnProtocol: null | string | false

String containing the selected ALPN protocol. Before a handshake has completed, this value is always null. When a handshake is completed but not ALPN protocol was selected, socket.alpnProtocol equals false.

readonly authorized: boolean

This property is true if the peer certificate was signed by one of the CAs specified when creating the Socket instance, otherwise false.

readonly bytesWritten: number

The total number of bytes successfully written to the socket since it was established. This includes data currently buffered by the OS but not yet acknowledged by the remote peer.

data: Data

The user-defined data associated with this socket instance. This can be set when the socket is created via Bun.connect({ data: ... }). It can be read or updated at any time.

// In a socket handler
function open(socket: Socket: string }>) {
console.log(`Socket opened for user: ${socket.data.userId}`);
socket.data.lastActivity = Date.now(); // Update data
}
readonly listener?: SocketListenerundefined>

Get the server that created this socket

This will return undefined if the socket was created by Bun.connect or if the listener has already closed.

readonly localAddress: string

Local IP address connected to the socket

"192.168.1.100" | "2001:db8::1"
readonly localFamily: 'IPv4' | 'IPv6'

IP protocol family used for the local endpoint of the socket

"IPv4" | "IPv6"
readonly localPort: number

local port connected to the socket

8080
readonly readyState: -2 | -1 | 0 | 1 | 2

The ready state of the socket.

You can assume that a positive value means the socket is open and usable

-2 = Shutdown-1 = Detached0 = Closed1 = Established2 = Else
readonly remoteAddress: string

Remote IP address connected to the socket

"192.168.1.100" | "2001:db8::1"
readonly remoteFamily: 'IPv4' | 'IPv6'readonly remotePort: number

Remote port connected to the socket

8080
[Symbol.dispose](): void;

Alias for socket.end(). Allows the socket to be used with using declarations for automatic resource management.

async function processSocket() {
using socket = await Bun.connect({ ... });
socket.write("Data");
// socket.end() is called automatically when exiting the scope
}
close(): void;

Closes the socket.

This is a wrapper around end() and shutdown().

disableRenegotiation(): void;

Disables TLS renegotiation for this Socket instance. Once called, attempts to renegotiate will trigger an error handler on the Socket.

There is no support for renegotiation as a server. (Attempts by clients will result in a fatal alert so that ClientHello messages cannot be used to flood a server and escape higher-level limits.)

end(data?: string | BufferSource,byteOffset?: number,byteLength?: number): number;

Sends the final data chunk and initiates a graceful shutdown of the socket's write side. After calling end(), no more data can be written using write() or end(). The socket remains readable until the remote end also closes its write side or the connection is terminated. This sends a TCP FIN packet after writing the data.

@param data

Optional final data to write before closing. Same types as write().

@param byteOffset

Optional offset for buffer data.

@param byteLength

Optional length for buffer data.

@returns

The number of bytes written for the final chunk. Returns -1 if the socket was already closed or shutting down.

// send some data and close the write side
socket.end("Goodbye!");
// or close write side without sending final data
socket.end();
end(): void;

Close the socket immediately

```" data-algolia-static="false" data-algolia-merged="false" data-type="Method">exportKeyingMaterial(length: number,label: string,context: Buffer): Buffer;

Keying material is used for validations to prevent different kind of attacks in network protocols, for example in the specifications of IEEE 802.1X.

Example

const keyingMaterial = socket.exportKeyingMaterial(
128,
'client finished');

/*
Example return value of keyingMaterial:

12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
74 ef 2c ... 78 more bytes>

@param length

number of bytes to retrieve from keying material

@param label@param context

Optionally provide a context.

@returns

requested bytes of the keying material

exportKeyingMaterial(length: number,label: string,context?: string | BufferSource): void;

Exports the keying material of the socket.

@param length

The length of the keying material to export.

@param label

The label of the keying material to export.

@param context

The context of the keying material to export.

flush(): void;

Flush any buffered data to the socket This attempts to send the data immediately, but success depends on the network conditions and the receiving end. It might be necessary after several write calls if immediate sending is critical, though often the OS handles flushing efficiently. Note that write calls outside open/data/drain might benefit from manual cork/flush.

getAuthorizationError(): null | Error;

Returns the reason why the peer's certificate was not been verified. This property is set only when socket.authorized === false.

getCertificate(): null | object | PeerCertificate;

Returns an object representing the local certificate. The returned object has some properties corresponding to the fields of the certificate.

If there is no local certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.

getCipher(): CipherNameAndProtocol;

Returns an object containing information on the negotiated cipher suite.

For example, a TLSv1.2 protocol with AES256-SHA cipher:

{
"name": "AES256-SHA",
"standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",
"version": "SSLv3"
}
getEphemeralKeyInfo(): null | object | EphemeralKeyInfo;

Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in perfect forward secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; null is returned if called on a server socket. The supported types are 'DH' and 'ECDH'. Thename property is available only when type is 'ECDH'.

For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.

getPeerCertificate(): PeerCertificate;

Returns an object representing the peer's certificate. If the peer does not provide a certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.

If the full certificate chain was requested, each certificate will include anissuerCertificate property containing an object representing its issuer's certificate.

@returns

A certificate object.

getPeerX509Certificate(): X509Certificate;getServername(): string;

Returns the servername of the socket.

getSession(): void;getSharedSigalgs(): string[];@returns

List of signature algorithms shared between the server and the client in the order of decreasing preference.

getTLSFinishedMessage(): undefined | BufferArrayBufferLike>;

As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.

@returns

The latest Finished message that has been sent to the socket as part of a SSL/TLS handshake, or undefined if no Finished message has been sent yet.

getTLSPeerFinishedMessage(): undefined | BufferArrayBufferLike>;

As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.

@returns

The latest Finished message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or undefined if there is no Finished message so far.

getTLSTicket(): undefined | BufferArrayBufferLike>;

For a client, returns the TLS session ticket if one is available, orundefined. For a server, always returns undefined.

It may be useful for debugging.

See Session Resumption for more information.

getTLSVersion(): string;

Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value 'unknown' will be returned for connected sockets that have not completed the handshaking process. The value null will be returned for server sockets or disconnected client sockets.

Protocol versions are:

'SSLv3''TLSv1''TLSv1.1''TLSv1.2''TLSv1.3'
getX509Certificate(): undefined | X509Certificate;isSessionReused(): boolean;

See Session Resumption for more information.

@returns

true if the session was reused, false otherwise. TLS Only: Checks if the current TLS session was resumed from a previous session. Returns true if the session was resumed, false otherwise.

pause(): void;ref(): void;

Keep Bun's process alive at least until this socket is closed

After the socket has closed, the socket is unref'd, the process may exit, and this becomes a no-op

reload(options: PickSocketOptionsData>, 'socket'>): void;

Reset the socket's callbacks. This is useful with bun --hot to facilitate hot reloading.

This will apply to all sockets from the same Listener. it is per socket only for Bun.connect.

renegotiate(): void;

If this is a TLS Socket

resume(): void;setKeepAlive(enable?: boolean,initialDelay?: number): boolean;

Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket. Set initialDelay (in milliseconds) to set the delay between the last data packet received and the first keepalive probe. Only available for already connected sockets, will return false otherwise.

Enabling the keep-alive functionality will set the following socket options: SO_KEEPALIVE=1 TCP_KEEPIDLE=initialDelay TCP_KEEPCNT=10 TCP_KEEPINTVL=1

@param enable

Default: false

@param initialDelay

Default: 0

@returns

true if is able to setNoDelay and false if it fails.

setMaxSendFragment(size?: number): boolean;

The socket.setMaxSendFragment() method sets the maximum TLS fragment size. Returns true if setting the limit succeeded; false otherwise.

Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.

@param size

The maximum TLS fragment size. The maximum value is 16384.

setNoDelay(noDelay?: boolean): boolean;

Enable/disable the use of Nagle's algorithm. Only available for already connected sockets, will return false otherwise

@param noDelay

Default: true

@returns

true if is able to setNoDelay and false if it fails.

setServername(name: string): void;

Sets the servername of the socket.

setSession(session: string | BufferArrayBufferLike> | BufferSource): void;

Sets the session of the socket.

@param session

The session to set.

setVerifyMode(requestCert: boolean,rejectUnauthorized: boolean): void;

Sets the verify mode of the socket.

@param requestCert

Whether to request a certificate.

@param rejectUnauthorized

Whether to reject unauthorized certificates.

shutdown(halfClose?: boolean): void;

Shuts down the write-half or both halves of the connection. This allows the socket to enter a half-closed state where it can still receive data but can no longer send data (halfClose = true), or close both read and write (halfClose = false, similar to end() but potentially more immediate depending on OS). Calls shutdown(2) syscall internally.

@param halfClose

If true, only shuts down the write side (allows receiving). If false or omitted, shuts down both read and write. Defaults to false.

// Stop sending data, but allow receiving
socket.shutdown(true);

// Shutdown both reading and writing
socket.shutdown();
terminate(): void;

Forcefully closes the socket connection immediately. This is an abrupt termination, unlike the graceful shutdown initiated by end(). It uses SO_LINGER with l_onoff=1 and l_linger=0 before calling close(2). Consider using close() or end() for graceful shutdowns.

socket.terminate();
timeout(seconds: number): void;

Set a timeout until the socket automatically closes.

To reset the timeout, call this function again.

When a timeout happens, the timeout callback is called and the socket is closed.

unref(): void;

Allow Bun's process to exit even if this socket is still open

After the socket has closed, this function does nothing.

upgradeTLSData>(options: TLSUpgradeOptionsData>): [raw: SocketData>, tls: SocketData>];

Upgrades the socket to a TLS socket.

@param options

The options for the upgrade.

@returns

A tuple containing the raw socket and the TLS socket.

write(data: string | BufferSource,byteOffset?: number,byteLength?: number): number;

Writes data to the socket. This method is unbuffered and non-blocking. This uses the sendto(2) syscall internally.

For optimal performance with multiple small writes, consider batching multiple writes together into a single socket.write() call.

@param data

The data to write. Can be a string (encoded as UTF-8), ArrayBuffer, TypedArray, or DataView.

@param byteOffset

The offset in bytes within the buffer to start writing from. Defaults to 0. Ignored for strings.

@param byteLength

The number of bytes to write from the buffer. Defaults to the remaining length of the buffer from the offset. Ignored for strings.

@returns

The number of bytes written. Returns -1 if the socket is closed or shutting down. Can return less than the input size if the socket's buffer is full (backpressure).

// Send a string
const bytesWritten = socket.write("Hello, world!\n");

// Send binary data
const buffer = new Uint8Array([0x01, 0x02, 0x03]);
socket.write(buffer);

// Send part of a buffer
const largeBuffer = new Uint8Array(1024);
// ... fill largeBuffer ...
socket.write(largeBuffer, 100, 50); // Write 50 bytes starting from index 100
interface SocketAddressaddress: string

The IP address of the client.

family: 'IPv4' | 'IPv6'

The IP family ("IPv4" or "IPv6").

port: number

The port of the client.

interface SocketHandlerData = unknown, DataBinaryType extends BinaryType = 'buffer'>binaryType?: unknown

Choose what ArrayBufferView is returned in the SocketHandler.data callback.

close(socket: SocketData>,error?: Error): void | Promisevoid>;connectError(socket: SocketData>,error: Error): void | Promisevoid>;

When the socket fails to be created, this function is called.

The promise returned by Bun.connect rejects after this function is called.

When connectError is specified, the rejected promise will not be added to the promise rejection queue (so it won't be reported as an unhandled promise rejection, since connectError handles it).

When connectError is not specified, the rejected promise will be added to the promise rejection queue.

data(socket: SocketData>,data: BinaryTypeList[DataBinaryType]): void | Promisevoid>;drain(socket: SocketData>): void | Promisevoid>;end(socket: SocketData>): void | Promisevoid>;

When the socket has been shutdown from the other end, this function is called. This is a TCP FIN packet.

error(socket: SocketData>,error: Error): void | Promisevoid>;handshake(socket: SocketData>,success: boolean,authorizationError: null | Error): void;

When handshake is completed, this functions is called.

@param success

Indicates if the server authorized despite the authorizationError.

@param authorizationError

Certificate Authorization Error or null.

open(socket: SocketData>): void | Promisevoid>;

Is called when the socket connects, or in case of TLS if no handshake is provided this will be called only after handshake

timeout(socket: SocketData>): void | Promisevoid>;

Called when a message times out.

interface SocketListenerData = undefined>data: Data[Symbol.dispose](): void;ref(): void;reload(options: PickSocketOptionsData>, 'socket'>): void;stop(closeActiveConnections?: boolean): void;unref(): void;interface SocketOptionsData = unknown>allowHalfOpen?: boolean

Whether to allow half-open connections.

A half-open connection occurs when one end of the connection has called close() or sent a FIN packet, while the other end remains open. When set to true:

The socket won't automatically send FIN when the remote side closes its endThe local side can continue sending data even after the remote side has closedThe application must explicitly call end() to fully close the connection

When false, the socket automatically closes both ends of the connection when either side closes.

data?: Data

The per-instance data context

socket: SocketHandlerData>

Handlers for socket events

interface SQLArrayParameter

Represents a SQL array parameter

arrayType: ArrayType

The type of the array parameter

serializedValues: string

The serialized values of the array parameter

interface StringWidthOptionsambiguousIsNarrow?: boolean

When it's ambiugous and true, count emoji as 1 characters wide. If false, emoji are counted as 2 character wide.

countAnsiEscapeCodes?: boolean

If true, count ANSI escape codes as part of the string width. If false, ANSI escape codes are ignored when calculating the string width.

interface StructuredSerializeOptionstransfer?: Transferable[]interface SubprocessIn extends SpawnOptions.Writable = SpawnOptions.Writable, Out extends SpawnOptions.Readable = SpawnOptions.Readable, Err extends SpawnOptions.Readable = SpawnOptions.Readable>

A process created by Bun.spawn.

This type accepts 3 optional type parameters which correspond to the stdio array from the options object. Instead of specifying these, you should use one of the following utility types instead:

ReadableSubprocess (any, pipe, pipe)WritableSubprocess (pipe, any, any)PipedSubprocess (pipe, pipe, pipe)NullSubprocess (ignore, ignore, ignore)
readonly exitCode: null | number

Synchronously get the exit code of the process

If the process hasn't exited yet, this will return null

readonly exited: Promisenumber>

The exit code of the process

The promise will resolve when the process exits

readonly killed: boolean

Has the process exited?

readonly pid: number

The process ID of the child process

const { pid } = Bun.spawn({ cmd: ["echo", "hello"] });
console.log(pid); // 1234
readonly readable: ReadableToIOOut>

This returns the same value as Subprocess.stdout

It exists for compatibility with ReadableStream.pipeThrough

readonly signalCode: null | Signals

Synchronously get the signal code of the process

If the process never sent a signal code, this will return null

To receive signal code changes, use the onExit callback.

If the signal code is unknown, it will return the original signal code number, but that case should essentially never happen.

readonly stderr: ReadableToIOErr>readonly stdin: WritableToIOIn>readonly stdio: [null, null, null, ...null | number[]]

Access extra file descriptors passed to the stdio option in the options object.

Entries beyond index 2 are number for "pipe" slots and, on POSIX, for slots where a raw file descriptor was supplied (the same fd is returned; it remains owned by the caller and is never closed by the subprocess). Other slots — including raw fds on Windows — are null.

readonly stdout: ReadableToIOOut>readonly terminal: undefined | Terminal

The terminal attached to this subprocess, if spawned with the terminal option. Returns undefined if no terminal was attached.

When a terminal is attached, stdin, stdout, and stderr return null. Use terminal.write() and the data callback instead.

const proc = Bun.spawn(["bash"], {
terminal: { data: (term, data) => console.log(data.toString()) },
});

proc.terminal?.write("echo hello\n");
[Symbol.asyncDispose](): PromiseLikevoid>;disconnect(): void;

Disconnect the IPC channel to the subprocess. This is only supported if the subprocess was created with the ipc option.

kill(exitCode?: number | Signals): void;

Kill the process

@param exitCode

The exitCode to send to the process

ref(): void;

This method will tell Bun to wait for this process to exit after you already called unref().

Before shutting down, Bun will wait for all subprocesses to exit by default

resourceUsage(): undefined | ResourceUsage;

Get the resource usage information of the process (max RSS, CPU time, etc)

Only available after the process has exited

If the process hasn't exited yet, this will return undefined

send(message: any): void;

Send a message to the subprocess. This is only supported if the subprocess was created with the ipc option, and is another instance of bun.

Messages are serialized using the JSC serialize API, which allows for the same types that postMessage/structuredClone supports.

unref(): void;

Before shutting down, Bun will wait for all subprocesses to exit by default

This method will tell Bun to not wait for this process to exit before shutting down.

interface SyncSubprocessOut extends SpawnOptions.Readable = SpawnOptions.Readable, Err extends SpawnOptions.Readable = SpawnOptions.Readable>

A process created by Bun.spawnSync.

This type accepts 2 optional type parameters which correspond to the stdout and stderr options. Instead of specifying these, you should use one of the following utility types instead:

ReadableSyncSubprocess (pipe, pipe)NullSyncSubprocess (ignore, ignore)
exitCode: numberexitedDueToMaxBuffer?: booleanexitedDueToTimeout?: booleanpid: numberresourceUsage: ResourceUsage

Get the resource usage information of the process (max RSS, CPU time, etc)

signalCode?: stringstderr: ReadableToSyncIOErr>stdout: ReadableToSyncIOOut>success: booleaninterface SystemErrorcause?: unknown

The cause of the error.

code?: stringerrno?: numbermessage: stringname: stringpath?: stringstack?: stringsyscall?: stringinterface TCPSocket

Represents a TCP or TLS socket connection used for network communication. This interface provides methods for reading, writing, managing the connection state, and handling TLS-specific features if applicable.

Sockets are created using Bun.connect() or accepted by a Bun.listen() server.

readonly alpnProtocol: null | string | false

String containing the selected ALPN protocol. Before a handshake has completed, this value is always null. When a handshake is completed but not ALPN protocol was selected, socket.alpnProtocol equals false.

readonly authorized: boolean

This property is true if the peer certificate was signed by one of the CAs specified when creating the Socket instance, otherwise false.

readonly bytesWritten: number

The total number of bytes successfully written to the socket since it was established. This includes data currently buffered by the OS but not yet acknowledged by the remote peer.

data: undefined

The user-defined data associated with this socket instance. This can be set when the socket is created via Bun.connect({ data: ... }). It can be read or updated at any time.

// In a socket handler
function open(socket: Socket: string }>) {
console.log(`Socket opened for user: ${socket.data.userId}`);
socket.data.lastActivity = Date.now(); // Update data
}
readonly listener?: SocketListenerundefined>

Get the server that created this socket

This will return undefined if the socket was created by Bun.connect or if the listener has already closed.

readonly localAddress: string

Local IP address connected to the socket

"192.168.1.100" | "2001:db8::1"
readonly localFamily: 'IPv4' | 'IPv6'

IP protocol family used for the local endpoint of the socket

"IPv4" | "IPv6"
readonly localPort: number

local port connected to the socket

8080
readonly readyState: -2 | -1 | 0 | 1 | 2

The ready state of the socket.

You can assume that a positive value means the socket is open and usable

-2 = Shutdown-1 = Detached0 = Closed1 = Established2 = Else
readonly remoteAddress: string

Remote IP address connected to the socket

"192.168.1.100" | "2001:db8::1"
readonly remoteFamily: 'IPv4' | 'IPv6'readonly remotePort: number

Remote port connected to the socket

8080
[Symbol.dispose](): void;

Alias for socket.end(). Allows the socket to be used with using declarations for automatic resource management.

async function processSocket() {
using socket = await Bun.connect({ ... });
socket.write("Data");
// socket.end() is called automatically when exiting the scope
}
close(): void;

Closes the socket.

This is a wrapper around end() and shutdown().

disableRenegotiation(): void;

Disables TLS renegotiation for this Socket instance. Once called, attempts to renegotiate will trigger an error handler on the Socket.

There is no support for renegotiation as a server. (Attempts by clients will result in a fatal alert so that ClientHello messages cannot be used to flood a server and escape higher-level limits.)

end(data?: string | BufferSource,byteOffset?: number,byteLength?: number): number;

Sends the final data chunk and initiates a graceful shutdown of the socket's write side. After calling end(), no more data can be written using write() or end(). The socket remains readable until the remote end also closes its write side or the connection is terminated. This sends a TCP FIN packet after writing the data.

@param data

Optional final data to write before closing. Same types as write().

@param byteOffset

Optional offset for buffer data.

@param byteLength

Optional length for buffer data.

@returns

The number of bytes written for the final chunk. Returns -1 if the socket was already closed or shutting down.

// send some data and close the write side
socket.end("Goodbye!");
// or close write side without sending final data
socket.end();
end(): void;

Close the socket immediately

```" data-algolia-static="false" data-algolia-merged="false" data-type="Method">exportKeyingMaterial(length: number,label: string,context: Buffer): Buffer;

Keying material is used for validations to prevent different kind of attacks in network protocols, for example in the specifications of IEEE 802.1X.

Example

const keyingMaterial = socket.exportKeyingMaterial(
128,
'client finished');

/*
Example return value of keyingMaterial:

12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
74 ef 2c ... 78 more bytes>

@param length

number of bytes to retrieve from keying material

@param label@param context

Optionally provide a context.

@returns

requested bytes of the keying material

exportKeyingMaterial(length: number,label: string,context?: string | BufferSource): void;

Exports the keying material of the socket.

@param length

The length of the keying material to export.

@param label

The label of the keying material to export.

@param context

The context of the keying material to export.

flush(): void;

Flush any buffered data to the socket This attempts to send the data immediately, but success depends on the network conditions and the receiving end. It might be necessary after several write calls if immediate sending is critical, though often the OS handles flushing efficiently. Note that write calls outside open/data/drain might benefit from manual cork/flush.

getAuthorizationError(): null | Error;

Returns the reason why the peer's certificate was not been verified. This property is set only when socket.authorized === false.

getCertificate(): null | object | PeerCertificate;

Returns an object representing the local certificate. The returned object has some properties corresponding to the fields of the certificate.

If there is no local certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.

getCipher(): CipherNameAndProtocol;

Returns an object containing information on the negotiated cipher suite.

For example, a TLSv1.2 protocol with AES256-SHA cipher:

{
"name": "AES256-SHA",
"standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",
"version": "SSLv3"
}
getEphemeralKeyInfo(): null | object | EphemeralKeyInfo;

Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in perfect forward secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; null is returned if called on a server socket. The supported types are 'DH' and 'ECDH'. Thename property is available only when type is 'ECDH'.

For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.

getPeerCertificate(): PeerCertificate;

Returns an object representing the peer's certificate. If the peer does not provide a certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.

If the full certificate chain was requested, each certificate will include anissuerCertificate property containing an object representing its issuer's certificate.

@returns

A certificate object.

getPeerX509Certificate(): X509Certificate;getServername(): string;

Returns the servername of the socket.

getSession(): void;getSharedSigalgs(): string[];@returns

List of signature algorithms shared between the server and the client in the order of decreasing preference.

getTLSFinishedMessage(): undefined | BufferArrayBufferLike>;

As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.

@returns

The latest Finished message that has been sent to the socket as part of a SSL/TLS handshake, or undefined if no Finished message has been sent yet.

getTLSPeerFinishedMessage(): undefined | BufferArrayBufferLike>;

As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.

@returns

The latest Finished message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or undefined if there is no Finished message so far.

getTLSTicket(): undefined | BufferArrayBufferLike>;

For a client, returns the TLS session ticket if one is available, orundefined. For a server, always returns undefined.

It may be useful for debugging.

See Session Resumption for more information.

getTLSVersion(): string;

Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value 'unknown' will be returned for connected sockets that have not completed the handshaking process. The value null will be returned for server sockets or disconnected client sockets.

Protocol versions are:

'SSLv3''TLSv1''TLSv1.1''TLSv1.2''TLSv1.3'
getX509Certificate(): undefined | X509Certificate;isSessionReused(): boolean;

See Session Resumption for more information.

@returns

true if the session was reused, false otherwise. TLS Only: Checks if the current TLS session was resumed from a previous session. Returns true if the session was resumed, false otherwise.

pause(): void;ref(): void;

Keep Bun's process alive at least until this socket is closed

After the socket has closed, the socket is unref'd, the process may exit, and this becomes a no-op

reload(options: PickSocketOptionsundefined>, 'socket'>): void;

Reset the socket's callbacks. This is useful with bun --hot to facilitate hot reloading.

This will apply to all sockets from the same Listener. it is per socket only for Bun.connect.

renegotiate(): void;

If this is a TLS Socket

resume(): void;setKeepAlive(enable?: boolean,initialDelay?: number): boolean;

Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket. Set initialDelay (in milliseconds) to set the delay between the last data packet received and the first keepalive probe. Only available for already connected sockets, will return false otherwise.

Enabling the keep-alive functionality will set the following socket options: SO_KEEPALIVE=1 TCP_KEEPIDLE=initialDelay TCP_KEEPCNT=10 TCP_KEEPINTVL=1

@param enable

Default: false

@param initialDelay

Default: 0

@returns

true if is able to setNoDelay and false if it fails.

setMaxSendFragment(size?: number): boolean;

The socket.setMaxSendFragment() method sets the maximum TLS fragment size. Returns true if setting the limit succeeded; false otherwise.

Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.

@param size

The maximum TLS fragment size. The maximum value is 16384.

setNoDelay(noDelay?: boolean): boolean;

Enable/disable the use of Nagle's algorithm. Only available for already connected sockets, will return false otherwise

@param noDelay

Default: true

@returns

true if is able to setNoDelay and false if it fails.

setServername(name: string): void;

Sets the servername of the socket.

setSession(session: string | BufferArrayBufferLike> | BufferSource): void;

Sets the session of the socket.

@param session

The session to set.

setVerifyMode(requestCert: boolean,rejectUnauthorized: boolean): void;

Sets the verify mode of the socket.

@param requestCert

Whether to request a certificate.

@param rejectUnauthorized

Whether to reject unauthorized certificates.

shutdown(halfClose?: boolean): void;

Shuts down the write-half or both halves of the connection. This allows the socket to enter a half-closed state where it can still receive data but can no longer send data (halfClose = true), or close both read and write (halfClose = false, similar to end() but potentially more immediate depending on OS). Calls shutdown(2) syscall internally.

@param halfClose

If true, only shuts down the write side (allows receiving). If false or omitted, shuts down both read and write. Defaults to false.

// Stop sending data, but allow receiving
socket.shutdown(true);

// Shutdown both reading and writing
socket.shutdown();
terminate(): void;

Forcefully closes the socket connection immediately. This is an abrupt termination, unlike the graceful shutdown initiated by end(). It uses SO_LINGER with l_onoff=1 and l_linger=0 before calling close(2). Consider using close() or end() for graceful shutdowns.

socket.terminate();
timeout(seconds: number): void;

Set a timeout until the socket automatically closes.

To reset the timeout, call this function again.

When a timeout happens, the timeout callback is called and the socket is closed.

unref(): void;

Allow Bun's process to exit even if this socket is still open

After the socket has closed, this function does nothing.

upgradeTLSData>(options: TLSUpgradeOptionsData>): [raw: SocketData>, tls: SocketData>];

Upgrades the socket to a TLS socket.

@param options

The options for the upgrade.

@returns

A tuple containing the raw socket and the TLS socket.

write(data: string | BufferSource,byteOffset?: number,byteLength?: number): number;

Writes data to the socket. This method is unbuffered and non-blocking. This uses the sendto(2) syscall internally.

For optimal performance with multiple small writes, consider batching multiple writes together into a single socket.write() call.

@param data

The data to write. Can be a string (encoded as UTF-8), ArrayBuffer, TypedArray, or DataView.

@param byteOffset

The offset in bytes within the buffer to start writing from. Defaults to 0. Ignored for strings.

@param byteLength

The number of bytes to write from the buffer. Defaults to the remaining length of the buffer from the offset. Ignored for strings.

@returns

The number of bytes written. Returns -1 if the socket is closed or shutting down. Can return less than the input size if the socket's buffer is full (backpressure).

// Send a string
const bytesWritten = socket.write("Hello, world!\n");

// Send binary data
const buffer = new Uint8Array([0x01, 0x02, 0x03]);
socket.write(buffer);

// Send part of a buffer
const largeBuffer = new Uint8Array(1024);
// ... fill largeBuffer ...
socket.write(largeBuffer, 100, 50); // Write 50 bytes starting from index 100
interface TCPSocketConnectOptionsData = undefined>allowHalfOpen?: boolean

Whether to allow half-open connections.

A half-open connection occurs when one end of the connection has called close() or sent a FIN packet, while the other end remains open. When set to true:

The socket won't automatically send FIN when the remote side closes its endThe local side can continue sending data even after the remote side has closedThe application must explicitly call end() to fully close the connection

When false, the socket automatically closes both ends of the connection when either side closes.

data?: Data

The per-instance data context

exclusive?: boolean

Whether to use exclusive mode.

When set to true, the socket binds exclusively to the specified address:port combination, preventing other processes from binding to the same port.

When false (default), other sockets may be able to bind to the same port depending on the operating system's socket sharing capabilities and settings.

Exclusive mode is useful in scenarios where you want to ensure only one instance of your server can bind to a specific port at a time.

hostname: string

The hostname to connect to

ipv6Only?: booleanport: number

The port to connect to

reusePort?: booleansocket: SocketHandlerData>

Handlers for socket events

tls?: boolean | TLSOptions

TLS Configuration with which to create the socket

interface TCPSocketListenerData = unknown>data: Datareadonly hostname: stringreadonly port: number[Symbol.dispose](): void;ref(): void;reload(options: PickSocketOptionsData>, 'socket'>): void;stop(closeActiveConnections?: boolean): void;unref(): void;interface TCPSocketListenOptionsData = undefined>allowHalfOpen?: boolean

Whether to allow half-open connections.

A half-open connection occurs when one end of the connection has called close() or sent a FIN packet, while the other end remains open. When set to true:

The socket won't automatically send FIN when the remote side closes its endThe local side can continue sending data even after the remote side has closedThe application must explicitly call end() to fully close the connection

When false (default), the socket automatically closes both ends of the connection when either side closes.

data?: Data

The per-instance data context

exclusive?: boolean

Whether to use exclusive mode.

When set to true, the socket binds exclusively to the specified address:port combination, preventing other processes from binding to the same port.

When false (default), other sockets may be able to bind to the same port depending on the operating system's socket sharing capabilities and settings.

Exclusive mode is useful in scenarios where you want to ensure only one instance of your server can bind to a specific port at a time.

hostname: string

The hostname to listen on

port: number

The port to listen on

socket: SocketHandlerData>

Handlers for socket events

tls?: boolean | TLSOptions

The TLS configuration object with which to create the server

interface TerminalOptions

Options for creating a pseudo-terminal (PTY).

cols?: number

Number of columns for the terminal.

data?: (terminal: Terminal, data: Uint8ArrayArrayBuffer>) => void

Callback invoked when data is received from the terminal.

drain?: (terminal: Terminal) => void

Callback invoked when the terminal is ready to receive more data.

exit?: (terminal: Terminal, exitCode: number, signal: null | string) => void

Callback invoked when the PTY stream closes (EOF or read error). Note: exitCode is a PTY lifecycle status (0=clean EOF, 1=error), NOT the subprocess exit code. Use Subprocess.exited or onExit callback for actual process exit information.

name?: string

Terminal name (e.g., "xterm-256color").

rows?: number

Number of rows for the terminal.

interface TLSOptions

Options for TLS connections

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

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

cert?: string | BunFile | BufferSource | unknown[]

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

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

File path to a .pem file custom Diffie Helman parameters

[, passphrase: ]}. The object form can only occur in an array. object.passphrase is optional. Encrypted keys will be decrypted with object.passphrase if provided, or options.passphrase if it is not." data-algolia-static="false" data-algolia-merged="false" data-type="Property">key?: string | BunFile | BufferSource | unknown[]

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

lowMemoryMode?: boolean

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

passphrase?: string

Passphrase for the TLS key

rejectUnauthorized?: boolean

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

requestCert?: boolean

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

Default is false.

secureOptions?: number

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

serverName?: string

Explicitly set a server name

interface TLSSocket

Represents a TCP or TLS socket connection used for network communication. This interface provides methods for reading, writing, managing the connection state, and handling TLS-specific features if applicable.

Sockets are created using Bun.connect() or accepted by a Bun.listen() server.

readonly alpnProtocol: null | string | false

String containing the selected ALPN protocol. Before a handshake has completed, this value is always null. When a handshake is completed but not ALPN protocol was selected, socket.alpnProtocol equals false.

readonly authorized: boolean

This property is true if the peer certificate was signed by one of the CAs specified when creating the Socket instance, otherwise false.

readonly bytesWritten: number

The total number of bytes successfully written to the socket since it was established. This includes data currently buffered by the OS but not yet acknowledged by the remote peer.

data: undefined

The user-defined data associated with this socket instance. This can be set when the socket is created via Bun.connect({ data: ... }). It can be read or updated at any time.

// In a socket handler
function open(socket: Socket: string }>) {
console.log(`Socket opened for user: ${socket.data.userId}`);
socket.data.lastActivity = Date.now(); // Update data
}
readonly listener?: SocketListenerundefined>

Get the server that created this socket

This will return undefined if the socket was created by Bun.connect or if the listener has already closed.

readonly localAddress: string

Local IP address connected to the socket

"192.168.1.100" | "2001:db8::1"
readonly localFamily: 'IPv4' | 'IPv6'

IP protocol family used for the local endpoint of the socket

"IPv4" | "IPv6"
readonly localPort: number

local port connected to the socket

8080
readonly readyState: -2 | -1 | 0 | 1 | 2

The ready state of the socket.

You can assume that a positive value means the socket is open and usable

-2 = Shutdown-1 = Detached0 = Closed1 = Established2 = Else
readonly remoteAddress: string

Remote IP address connected to the socket

"192.168.1.100" | "2001:db8::1"
readonly remoteFamily: 'IPv4' | 'IPv6'readonly remotePort: number

Remote port connected to the socket

8080
[Symbol.dispose](): void;

Alias for socket.end(). Allows the socket to be used with using declarations for automatic resource management.

async function processSocket() {
using socket = await Bun.connect({ ... });
socket.write("Data");
// socket.end() is called automatically when exiting the scope
}
close(): void;

Closes the socket.

This is a wrapper around end() and shutdown().

disableRenegotiation(): void;

Disables TLS renegotiation for this Socket instance. Once called, attempts to renegotiate will trigger an error handler on the Socket.

There is no support for renegotiation as a server. (Attempts by clients will result in a fatal alert so that ClientHello messages cannot be used to flood a server and escape higher-level limits.)

end(data?: string | BufferSource,byteOffset?: number,byteLength?: number): number;

Sends the final data chunk and initiates a graceful shutdown of the socket's write side. After calling end(), no more data can be written using write() or end(). The socket remains readable until the remote end also closes its write side or the connection is terminated. This sends a TCP FIN packet after writing the data.

@param data

Optional final data to write before closing. Same types as write().

@param byteOffset

Optional offset for buffer data.

@param byteLength

Optional length for buffer data.

@returns

The number of bytes written for the final chunk. Returns -1 if the socket was already closed or shutting down.

// send some data and close the write side
socket.end("Goodbye!");
// or close write side without sending final data
socket.end();
end(): void;

Close the socket immediately

```" data-algolia-static="false" data-algolia-merged="false" data-type="Method">exportKeyingMaterial(length: number,label: string,context: Buffer): Buffer;

Keying material is used for validations to prevent different kind of attacks in network protocols, for example in the specifications of IEEE 802.1X.

Example

const keyingMaterial = socket.exportKeyingMaterial(
128,
'client finished');

/*
Example return value of keyingMaterial:

12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
74 ef 2c ... 78 more bytes>

@param length

number of bytes to retrieve from keying material

@param label@param context

Optionally provide a context.

@returns

requested bytes of the keying material

exportKeyingMaterial(length: number,label: string,context?: string | BufferSource): void;

Exports the keying material of the socket.

@param length

The length of the keying material to export.

@param label

The label of the keying material to export.

@param context

The context of the keying material to export.

flush(): void;

Flush any buffered data to the socket This attempts to send the data immediately, but success depends on the network conditions and the receiving end. It might be necessary after several write calls if immediate sending is critical, though often the OS handles flushing efficiently. Note that write calls outside open/data/drain might benefit from manual cork/flush.

getAuthorizationError(): null | Error;

Returns the reason why the peer's certificate was not been verified. This property is set only when socket.authorized === false.

getCertificate(): null | object | PeerCertificate;

Returns an object representing the local certificate. The returned object has some properties corresponding to the fields of the certificate.

If there is no local certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.

getCipher(): CipherNameAndProtocol;

Returns an object containing information on the negotiated cipher suite.

For example, a TLSv1.2 protocol with AES256-SHA cipher:

{
"name": "AES256-SHA",
"standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",
"version": "SSLv3"
}
getEphemeralKeyInfo(): null | object | EphemeralKeyInfo;

Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in perfect forward secrecy on a client connection. It returns an empty object when the key exchange is not ephemeral. As this is only supported on a client socket; null is returned if called on a server socket. The supported types are 'DH' and 'ECDH'. Thename property is available only when type is 'ECDH'.

For example: { type: 'ECDH', name: 'prime256v1', size: 256 }.

getPeerCertificate(): PeerCertificate;

Returns an object representing the peer's certificate. If the peer does not provide a certificate, an empty object will be returned. If the socket has been destroyed, null will be returned.

If the full certificate chain was requested, each certificate will include anissuerCertificate property containing an object representing its issuer's certificate.

@returns

A certificate object.

getPeerX509Certificate(): X509Certificate;getServername(): string;

Returns the servername of the socket.

getSession(): void;getSharedSigalgs(): string[];@returns

List of signature algorithms shared between the server and the client in the order of decreasing preference.

getTLSFinishedMessage(): undefined | BufferArrayBufferLike>;

As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.

@returns

The latest Finished message that has been sent to the socket as part of a SSL/TLS handshake, or undefined if no Finished message has been sent yet.

getTLSPeerFinishedMessage(): undefined | BufferArrayBufferLike>;

As the Finished messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.

@returns

The latest Finished message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or undefined if there is no Finished message so far.

getTLSTicket(): undefined | BufferArrayBufferLike>;

For a client, returns the TLS session ticket if one is available, orundefined. For a server, always returns undefined.

It may be useful for debugging.

See Session Resumption for more information.

getTLSVersion(): string;

Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value 'unknown' will be returned for connected sockets that have not completed the handshaking process. The value null will be returned for server sockets or disconnected client sockets.

Protocol versions are:

'SSLv3''TLSv1''TLSv1.1''TLSv1.2''TLSv1.3'
getX509Certificate(): undefined | X509Certificate;isSessionReused(): boolean;

See Session Resumption for more information.

@returns

true if the session was reused, false otherwise. TLS Only: Checks if the current TLS session was resumed from a previous session. Returns true if the session was resumed, false otherwise.

pause(): void;ref(): void;

Keep Bun's process alive at least until this socket is closed

After the socket has closed, the socket is unref'd, the process may exit, and this becomes a no-op

reload(options: PickSocketOptionsundefined>, 'socket'>): void;

Reset the socket's callbacks. This is useful with bun --hot to facilitate hot reloading.

This will apply to all sockets from the same Listener. it is per socket only for Bun.connect.

renegotiate(): void;

If this is a TLS Socket

resume(): void;setKeepAlive(enable?: boolean,initialDelay?: number): boolean;

Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket. Set initialDelay (in milliseconds) to set the delay between the last data packet received and the first keepalive probe. Only available for already connected sockets, will return false otherwise.

Enabling the keep-alive functionality will set the following socket options: SO_KEEPALIVE=1 TCP_KEEPIDLE=initialDelay TCP_KEEPCNT=10 TCP_KEEPINTVL=1

@param enable

Default: false

@param initialDelay

Default: 0

@returns

true if is able to setNoDelay and false if it fails.

setMaxSendFragment(size?: number): boolean;

The socket.setMaxSendFragment() method sets the maximum TLS fragment size. Returns true if setting the limit succeeded; false otherwise.

Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.

@param size

The maximum TLS fragment size. The maximum value is 16384.

setNoDelay(noDelay?: boolean): boolean;

Enable/disable the use of Nagle's algorithm. Only available for already connected sockets, will return false otherwise

@param noDelay

Default: true

@returns

true if is able to setNoDelay and false if it fails.

setServername(name: string): void;

Sets the servername of the socket.

setSession(session: string | BufferArrayBufferLike> | BufferSource): void;

Sets the session of the socket.

@param session

The session to set.

setVerifyMode(requestCert: boolean,rejectUnauthorized: boolean): void;

Sets the verify mode of the socket.

@param requestCert

Whether to request a certificate.

@param rejectUnauthorized

Whether to reject unauthorized certificates.

shutdown(halfClose?: boolean): void;

Shuts down the write-half or both halves of the connection. This allows the socket to enter a half-closed state where it can still receive data but can no longer send data (halfClose = true), or close both read and write (halfClose = false, similar to end() but potentially more immediate depending on OS). Calls shutdown(2) syscall internally.

@param halfClose

If true, only shuts down the write side (allows receiving). If false or omitted, shuts down both read and write. Defaults to false.

// Stop sending data, but allow receiving
socket.shutdown(true);

// Shutdown both reading and writing
socket.shutdown();
terminate(): void;

Forcefully closes the socket connection immediately. This is an abrupt termination, unlike the graceful shutdown initiated by end(). It uses SO_LINGER with l_onoff=1 and l_linger=0 before calling close(2). Consider using close() or end() for graceful shutdowns.

socket.terminate();
timeout(seconds: number): void;

Set a timeout until the socket automatically closes.

To reset the timeout, call this function again.

When a timeout happens, the timeout callback is called and the socket is closed.

unref(): void;

Allow Bun's process to exit even if this socket is still open

After the socket has closed, this function does nothing.

upgradeTLSData>(options: TLSUpgradeOptionsData>): [raw: SocketData>, tls: SocketData>];

Upgrades the socket to a TLS socket.

@param options

The options for the upgrade.

@returns

A tuple containing the raw socket and the TLS socket.

write(data: string | BufferSource,byteOffset?: number,byteLength?: number): number;

Writes data to the socket. This method is unbuffered and non-blocking. This uses the sendto(2) syscall internally.

For optimal performance with multiple small writes, consider batching multiple writes together into a single socket.write() call.

@param data

The data to write. Can be a string (encoded as UTF-8), ArrayBuffer, TypedArray, or DataView.

@param byteOffset

The offset in bytes within the buffer to start writing from. Defaults to 0. Ignored for strings.

@param byteLength

The number of bytes to write from the buffer. Defaults to the remaining length of the buffer from the offset. Ignored for strings.

@returns

The number of bytes written. Returns -1 if the socket is closed or shutting down. Can return less than the input size if the socket's buffer is full (backpressure).

// Send a string
const bytesWritten = socket.write("Hello, world!\n");

// Send binary data
const buffer = new Uint8Array([0x01, 0x02, 0x03]);
socket.write(buffer);

// Send part of a buffer
const largeBuffer = new Uint8Array(1024);
// ... fill largeBuffer ...
socket.write(largeBuffer, 100, 50); // Write 50 bytes starting from index 100
interface TLSUpgradeOptionsData>data?: Datasocket: SocketHandlerData>tls: boolean | TLSOptionsinterface TransactionSQL

Represents a client within a transaction context Extends SQL with savepoint functionality

options: MergeSQLiteOptions, PostgresOrMySQLOptions> | MergePostgresOrMySQLOptions, SQLiteOptions>

Current client options

[Symbol.asyncDispose](): PromiseLikevoid>;array(values: any[],typeNameOrTypeID?: number | ArrayType): SQLArrayParameter;

Creates a new SQL array parameter

@param values

The values to create the array parameter from

@param typeNameOrTypeID

The type name or type ID to create the array parameter from, if omitted it will default to JSON

@returns

A new SQL array parameter

const array = sql.array([1, 2, 3], "INT");
await sql`CREATE TABLE users_posts (user_id INT, posts_id INT[])`;
await sql`INSERT INTO users_posts (user_id, posts_id) VALUES (${user.id}, ${array})`;
beginT>(fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a new transaction.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.begin(async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
beginT>(options: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a new transaction with options.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.begin("read write", async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
beginDistributedT>(name: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Begins a distributed transaction Also know as Two-Phase Commit, in a distributed transaction, Phase 1 involves the coordinator preparing nodes by ensuring data is written and ready to commit, while Phase 2 finalizes with nodes committing or rolling back based on the coordinator's decision, ensuring durability and releasing locks. In PostgreSQL and MySQL distributed transactions persist beyond the original session, allowing privileged users or coordinators to commit/rollback them, ensuring support for distributed transactions, recovery, and administrative tasks. beginDistributed will automatic rollback if any exception are not caught, and you can commit and rollback later if everything goes well. PostgreSQL natively supports distributed transactions using PREPARE TRANSACTION, while MySQL uses XA Transactions, and MSSQL also supports distributed/XA transactions. However, in MSSQL, distributed transactions are tied to the original session, the DTC coordinator, and the specific connection. These transactions are automatically committed or rolled back following the same rules as regular transactions, with no option for manual intervention from other sessions, in MSSQL distributed transactions are used to coordinate transactions using Linked Servers.

await sql.beginDistributed("numbers", async sql => {
await sql`create table if not exists numbers (a int)`;
await sql`insert into numbers values(1)`;
});
// later you can call
await sql.commitDistributed("numbers");
// or await sql.rollbackDistributed("numbers");
close(options?: { timeout: number }): Promisevoid>;

Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing.

@param options

The options for the close

await sql.close({ timeout: 1 });
commitDistributed(name: string): Promisevoid>;

Commits a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL

@param name

The name of the distributed transaction

await sql.commitDistributed("my_distributed_transaction");
connect(): PromiseSQL>;

Waits for the database connection to be established

await sql.connect();
distributedT>(name: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a distributed transaction

end(options?: { timeout: number }): Promisevoid>;

Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing. This is an alias of SQL.close

@param options

The options for the close

await sql.end({ timeout: 1 });
fileT = any>(filename: string,values?: any[]): QueryT>;

Reads a file and uses the contents as a query. Optional parameters can be used if the file includes $1, $2, etc

const result = await sql.file("query.sql", [1, 2, 3]);
flush(): void;

Flushes any pending operations

sql.flush();
reserve(): PromiseReservedSQL>;

The reserve method pulls out a connection from the pool, and returns a client that wraps the single connection.

Using reserve() inside of a transaction will return a brand new connection, not one related to the transaction. This matches the behaviour of the postgres package.

rollbackDistributed(name: string): Promisevoid>;

Rolls back a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL

@param name

The name of the distributed transaction

await sql.rollbackDistributed("my_distributed_transaction");
savepointT>(name: string,fn: SavepointContextCallbackT>): PromiseT>;

Creates a savepoint within the current transaction

savepointT>(fn: SavepointContextCallbackT>): PromiseT>;transactionT>(fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a transaction.

Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.transaction(async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
})
transactionT>(options: string,fn: TransactionContextCallbackT>): PromiseContextCallbackResultT>>;

Alternative method to begin a transaction with options Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function. BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.

const [user, account] = await sql.transaction("read write", async sql => {
const [user] = await sql`
insert into users (
name
) values (
'Murray'
)
returning *
`
const [account] = await sql`
insert into accounts (
user_id
) values (
${ user.user_id }
)
returning *
`
return [user, account]
});
unsafeT = any>(string: string,values?: any[]): QueryT>;

If you know what you're doing, you can use unsafe to pass any string you'd like. Please note that this can lead to SQL injection if you're not careful. You can also nest sql.unsafe within a safe sql expression. This is useful if only part of your fraction has unsafe elements.

const result = await sql.unsafe(`select ${danger} from users where id = ${dragons}`)
interface TransformerFlushCallbackO>interface TransformerStartCallbackO>interface TransformerTransformCallbackI, O>interface TranspilerOptionsallowBunRuntime?: booleanautoImportJSX?: booleandeadCodeElimination?: boolean

Experimental

Enabled by default, use this to disable dead code elimination.

Some other transpiler options may still do some specific dead code elimination.

define?: Recordstring, string>

Replace key with value. Value must be a JSON string.

 { "process.env.NODE_ENV": "\"production\"" }
exports?: { eliminate: string[]; replace: Recordstring, string> }inline?: boolean

This does two things (and possibly more in the future):

const declarations to primitive types (excluding Object/Array) at the top of a scope before any let or var declarations will be inlined into their usages.let and const declarations only used once are inlined into their usages.

JavaScript engines typically do these optimizations internally, however it might only happen much later in the compilation pipeline, after code has been executed many many times.

This will typically shrink the output size of code, but it might increase it in some cases. Do your own benchmarks!

jsxOptimizationInline?: booleanloader?: JavaScriptLoader

What is the default loader used for this transpiler?

logLevel?: 'error' | 'verbose' | 'debug' | 'info' | 'warn'
macro?: MacroMap

Replace an import statement with a macro.

This will remove the import statement from the final output and replace any function calls or template strings with the result returned by the macro

 {
"react-relay": {
"graphql": "bun-macro-relay"
}
}

Code that calls graphql will be replaced with the result of the macro.

import {graphql} from "react-relay";

// Input:
const query = graphql`
query {
... on User {
id
}
}
}`;

Will be replaced with:

import UserQuery from "./UserQuery.graphql";
const query = UserQuery;
minifyWhitespace?: boolean

Experimental

Minify whitespace and comments from the output.

replMode?: boolean

Enable REPL mode transforms:

Wraps top-level inputs that appear to be object literals (inputs starting with '{' without trailing ';') in parenthesesHoists all declarations as var for REPL persistence across vm.runInContext callsWraps last expression in { proto: null, value: expr } for result captureWraps code in sync/async IIFE to avoid parentheses around object literals
target?: Target
"browser"
treeShaking?: booleantrimUnusedImports?: booleantsconfig?: string | TSConfig

TSConfig.json file as stringified JSON or an object Use this to set a custom JSX factory, fragment, or import source For example, if you want to use Preact instead of React. Or if you want to use Emotion.

interface TSConfig

tsconfig.json options supported by Bun

compilerOptions?: { baseUrl: string; importsNotUsedAsValues: 'error' | 'preserve' | 'remove'; jsx: 'preserve' | 'react' | 'react-jsx' | 'react-jsxdev'; jsxFactory: string; jsxFragmentFactory: string; jsxImportSource: string; moduleSuffixes: any; paths: Recordstring, string[]>; useDefineForClassFields: boolean }extends?: stringinterface UnderlyingSinkW = any>abort?: UnderlyingSinkAbortCallbackclose?: UnderlyingSinkCloseCallbackstart?: UnderlyingSinkStartCallbacktype?: 'default' | 'bytes'write?: UnderlyingSinkWriteCallbackW>interface UnderlyingSinkAbortCallbackinterface UnderlyingSinkCloseCallbackinterface UnderlyingSinkStartCallbackinterface UnderlyingSinkWriteCallbackW>interface UnderlyingSourceR = any>cancel?: UnderlyingSourceCancelCallbackpull?: UnderlyingSourcePullCallbackR>start?: UnderlyingSourceStartCallbackR>type?: undefined

Mode "bytes" is not currently supported.

interface UnderlyingSourceCancelCallbackinterface UnderlyingSourcePullCallbackR>interface UnderlyingSourceStartCallbackR>interface UnixSocketListenerData>data: Datareadonly unix: string[Symbol.dispose](): void;ref(): void;reload(options: PickSocketOptionsData>, 'socket'>): void;stop(closeActiveConnections?: boolean): void;unref(): void;interface UnixSocketOptionsData = undefined>allowHalfOpen?: boolean

Whether to allow half-open connections.

A half-open connection occurs when one end of the connection has called close() or sent a FIN packet, while the other end remains open. When set to true:

The socket won't automatically send FIN when the remote side closes its endThe local side can continue sending data even after the remote side has closedThe application must explicitly call end() to fully close the connection

When false, the socket automatically closes both ends of the connection when either side closes.

data?: Data

The per-instance data context

socket: SocketHandlerData>

Handlers for socket events

tls?: boolean | TLSOptions

TLS Configuration with which to create the socket

unix: string

The unix socket to listen on or connect to

interface WebSocketEventMapclose: CloseEventerror: Eventmessage: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>open: Eventinterface WebSocketHandlerT>

Create a server-side ServerWebSocket handler for use with Bun.serve

import { websocket, serve } from "bun";

serve: string}>({
port: 3000,
websocket: {
open: (ws) => {
console.log("Client connected");
},
message: (ws, message) => {
console.log(`${ws.data.name}: ${message}`);
},
close: (ws) => {
console.log("Client disconnected");
},
},

fetch(req, server) {
const url = new URL(req.url);
if (url.pathname === "/chat") {
const upgraded = server.upgrade(req, {
data: {
name: new URL(req.url).searchParams.get("name"),
},
});
if (!upgraded) {
return new Response("Upgrade failed", { status: 400 });
}
return;
}
return new Response("Hello World");
},
});
backpressureLimit?: number

Sets the maximum number of bytes that can be buffered on a single connection.

Default is 16 MB, or 1024 * 1024 * 16 in bytes.

closeOnBackpressureLimit?: boolean

Sets if the connection should be closed if backpressureLimit is reached.

data?: T

Specify the type for the ServerWebSocket.data property on connecting websocket clients. You can pass this value when you make a call to Server.upgrade.

This pattern exists in Bun due to a TypeScript limitation (#26242)

Bun.serve({
websocket: {
data: {} as { name: string }, // ← Specify the type of `ws.data` like this
message: (ws, message) => console.log(ws.data.name, 'says:', message);
},
// ...
});
idleTimeout?: number

Sets the number of seconds to wait before timing out a connection due to no messages or pings.

maxPayloadLength?: number

Sets the maximum size of messages in bytes.

Default is 16 MB, or 1024 * 1024 * 16 in bytes.

perMessageDeflate?: boolean | { compress: boolean | WebSocketCompressor; decompress: boolean | WebSocketCompressor }

Sets the compression level for messages, for clients that supports it. By default, compression is disabled.

publishToSelf?: boolean

Should ws.publish() also send a message to ws (itself), if it is subscribed?

sendPings?: boolean

Should the server automatically send and respond to pings to clients?

close(ws: ServerWebSocketT>,code: number,reason: string): void | Promisevoid>;

Called when a connection is closed.

@param ws

The websocket that was closed

@param code

The close code

@param reason

The close reason

drain(ws: ServerWebSocketT>): void | Promisevoid>;

Called when a connection was previously under backpressure, meaning it had too many queued messages, but is now ready to receive more data.

@param ws

The websocket that is ready for more data

message(ws: ServerWebSocketT>,message: string | BufferArrayBuffer>): void | Promisevoid>;

Called when the server receives an incoming message.

If the message is not a string, its type is based on the value of binaryType.

if nodebuffer, then the message is a Buffer.if arraybuffer, then the message is an ArrayBuffer.if uint8array, then the message is a Uint8Array.
@param ws

The websocket that sent the message

@param message

The message received

open(ws: ServerWebSocketT>): void | Promisevoid>;

Called when a connection is opened.

@param ws

The websocket that was opened

ping(ws: ServerWebSocketT>,data: Buffer): void | Promisevoid>;

Called when a ping is sent.

@param ws

The websocket that received the ping

@param data

The data sent with the ping

pong(ws: ServerWebSocketT>,data: Buffer): void | Promisevoid>;

Called when a pong is received.

@param ws

The websocket that received the ping

@param data

The data sent with the ping

interface WhichOptionscwd?: string

When given a relative path, use this path to join it.

PATH?: string

Overrides the PATH environment variable

interface WorkerEventMapclose: CloseEventerror: ErrorEventmessage: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>messageerror: new (type: string, eventInitDict?: MessageEventInitT>) => MessageEventT>open: Eventinterface WorkerOptions

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

argv?: any[]

List of arguments which would be stringified and appended to Bun.argv / process.argv in the worker. This is mostly similar to the data but the values will be available on the global Bun.argv as if they were passed as CLI options to the script.

credentials?: RequestCredentials

In Bun, this does nothing.

env?: Recordstring, string> | typeof SHARE_ENV

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

name?: string

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

preload?: string | string[]

An array of module specifiers to preload in the worker.

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

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

ref?: boolean

When true, the worker will keep the parent thread alive until the worker is terminated or unref'd. When false, the worker will not keep the parent thread alive.

By default, this is false.

smol?: boolean

Use less memory, but make the worker slower.

Internally, this sets the heap size configuration in JavaScriptCore to be the small heap instead of the large heap.

type?: WorkerType

In Bun, this does nothing.

interface WrapAnsiOptionsambiguousIsNarrow?: boolean

When it's ambiguous and true, count ambiguous width characters as 1 character wide. If false, count them as 2 characters wide.

hard?: boolean

If true, break words in the middle if they don't fit on a line. If false, only break at word boundaries.

trim?: boolean

If true, trim leading and trailing whitespace from each line. If false, preserve whitespace.

wordWrap?: boolean

If true, wrap at word boundaries when possible. If false, don't perform word wrapping (only wrap at explicit newlines).

interface ZlibCompressionOptions

Compression options for Bun.deflateSync and Bun.gzipSync

level?: 0 | 2 | 1 | 5 | 3 | 4 | -1 | 6 | 7 | 8 | 9

The compression level to use. Must be between -1 and 9.

A value of -1 uses the default compression level (Currently 6)A value of 0 gives no compressionA value of 1 gives least compression, fastest speedA value of 9 gives best compression, slowest speed
library?: 'zlib'memLevel?: 2 | 1 | 5 | 3 | 4 | 6 | 7 | 8 | 9

How much memory should be allocated for the internal compression state.

A value of 1 uses minimum memory but is slow and reduces compression ratio.

A value of 9 uses maximum memory for optimal speed. The default is 8.

strategy?: number

Tunes the compression algorithm.

Z_DEFAULT_STRATEGY: For normal data (Default)Z_FILTERED: For data produced by a filter or predictorZ_HUFFMAN_ONLY: Force Huffman encoding only (no string match)Z_RLE: Limit match distances to one (run-length encoding)Z_FIXED prevents the use of dynamic Huffman codes

Z_RLE is designed to be almost as fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.

Z_FILTERED forces more Huffman coding and less string matching, it is somewhat intermediate between Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Filtered data consists mostly of small values with a somewhat random distribution.

windowBits?: 25 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 28 | -9 | -10 | -11 | -12 | -13 | -14 | -15 | 26 | 27 | 29 | 30 | 31

The base 2 logarithm of the window size (the size of the history buffer).

Larger values of this parameter result in better compression at the expense of memory usage.

The following value ranges are supported:

9..15: The output will have a zlib header and footer (Deflate)-9..-15: The output will not have a zlib header or footer (Raw Deflate)25..31 (16+9..15): The output will have a gzip header and footer (gzip)

The gzip header will have no file name, no extra data, no comment, no modification time (set to zero) and no header CRC.

type $ = typeof $type ArchiveCompression = 'gzip'

Compression format for archive output. Currently only "gzip" is supported.

type ArchiveInput = Recordstring, BlobPart> | Blob | ArrayBufferView | ArrayBufferLike

Input data for creating an archive. Can be:

An object mapping paths to file contents (string, Blob, TypedArray, or ArrayBuffer)A Blob containing existing archive dataA TypedArray or ArrayBuffer containing existing archive data
type ArrayBufferViewTArrayBuffer extends ArrayBufferLike = ArrayBufferLike> = NodeJS.TypedArrayTArrayBuffer> | DataViewTArrayBuffer>type ArrayType = 'BOOLEAN' | 'BYTEA' | 'CHAR' | 'NAME' | 'TEXT' | 'CHAR' | 'VARCHAR' | 'SMALLINT' | 'INT2VECTOR' | 'INTEGER' | 'INT' | 'BIGINT' | 'REAL' | 'DOUBLE PRECISION' | 'NUMERIC' | 'MONEY' | 'OID' | 'TID' | 'XID' | 'CID' | 'JSON' | 'JSONB' | 'JSONPATH' | 'XML' | 'POINT' | 'LSEG' | 'PATH' | 'BOX' | 'POLYGON' | 'LINE' | 'CIRCLE' | 'CIDR' | 'MACADDR' | 'INET' | 'MACADDR8' | 'DATE' | 'TIME' | 'TIMESTAMP' | 'TIMESTAMPTZ' | 'INTERVAL' | 'TIMETZ' | 'BIT' | 'VARBIT' | 'ACLITEM' | 'PG_DATABASE' | string & {}type BeforeExitListener = (code: number) => voidtype BinaryType = keyof BinaryTypeListtype BlobOrStringOrBuffer = string | NodeJS.TypedArray | ArrayBufferLike | Blobtype BlobPart = string | Blob | BufferSourcetype BodyInit = ReadableStream | Bun.XMLHttpRequestBodyInit | AsyncIterablestring | ArrayBuffer | ArrayBufferView> | AsyncGeneratorstring | ArrayBuffer | ArrayBufferView> | () => AsyncGeneratorstring | ArrayBuffer | ArrayBufferView> | Imagetype BufferSource = NodeJS.TypedArrayArrayBufferLike> | DataViewArrayBufferLike> | ArrayBufferLiketype BunLockFile = catalog?: Recordstring, string>
catalogs?: Recordstring, Recordstring, string>>
configVersion?: 0 | 1

0 / undefined for projects created before v1.3.2, 1 for projects created after.

Right now this only changes the default install linker strategy:

With 0, the linker is hoisted.With 1, the linker is isolated for workspaces and hoisted for single-package projects.
lockfileVersion: 0 | 1overrides?: Recordstring, string>
[ "name@version", registry (TODO: remove if default), INFO, integrity] symlink -> [ "name@link:path", INFO ] folder -> [ "name@file:path", INFO ] workspace -> [ "name@workspace:path" ] // workspace is only path tarball -> [ "name@tarball", INFO ] root -> [ "name@root:", { bin, binDir } ] git -> [ "name@git+repo", INFO, .bun-tag string (TODO: remove this) ] github -> [ "name@github:user/repo", INFO, .bun-tag string (TODO: remove this) ] ```" data-algolia-static="false" data-algolia-merged="false" data-type="Property">packages: { __index[pkg: string]: BunLockFilePackageArray; }
INFO = { prod/dev/optional/peer dependencies, os, cpu, libc (TODO), bin, binDir }

// first index is resolution for each type of package
npm -> [ "name@version", registry (TODO: remove if default), INFO, integrity]
symlink -> [ "name@link:path", INFO ]
folder -> [ "name@file:path", INFO ]
workspace -> [ "name@workspace:path" ] // workspace is only path
tarball -> [ "name@tarball", INFO ]
root -> [ "name@root:", { bin, binDir } ]
git -> [ "name@git+repo", INFO, .bun-tag string (TODO: remove this) ]
github -> [ "name@github:user/repo", INFO, .bun-tag string (TODO: remove this) ]
patchedDependencies?: Recordstring, string>
trustedDependencies?: string[]
workspaces: { __index[workspace: string]: BunLockFileWorkspacePackage; }

Types for bun.lock

type BunLockFileBasePackageInfo = bin?: string | Recordstring, string>binDir?: stringdependencies?: Recordstring, string>devDependencies?: Recordstring, string>optionalDependencies?: Recordstring, string>optionalPeers?: string[]peerDependencies?: Recordstring, string>type BunLockFilePackageArray = [pkg: string, registry: string, info: BunLockFilePackageInfo, integrity: string] | [pkg: string, info: BunLockFilePackageInfo] | [pkg: string] | [pkg: string, info: BunLockFilePackageInfo, bunTag: string] | [pkg: string, info: PickBunLockFileBasePackageInfo, 'bin' | 'binDir'>]
type BunLockFilePackageInfo = BunLockFileBasePackageInfo & { bundled: true; cpu: string | string[]; os: string | string[] }type BunLockFileWorkspacePackage = BunLockFileBasePackageInfo & { name: string; version: string }type ColorInput = { a: number; b: number; g: number; r: number } | [number, number, number] | [number, number, number, number] | Uint8ArrayArrayBuffer> | Uint8ClampedArrayArrayBuffer> | Float32Array | Float64Array | string | number | { toString(): string }

Valid inputs for color

type CompressionFormat = 'gzip' | 'deflate' | 'deflate-raw' | 'brotli' | 'zstd'

Extends the standard web formats with brotli and zstd support.

type CookieSameSite = 'strict' | 'lax' | 'none'type CronWithAutocomplete = '@yearly' | '@annually' | '@monthly' | '@weekly' | '@daily' | '@midnight' | '@hourly' | '* * * * *' | '0 * * * *' | '0 0 * * *' | '0 0 * * 0' | '0 0 1 * *' | '0 0 1 1 *' | `${string} ${string} ${string} ${string} ${string}` | string & {}

A cron schedule: a 5-field expression (minute hour day month weekday) or a nickname.

Nicknames: @yearly, @annually, @monthly, @weekly, @daily, @midnight, @hourly.

Fields support *, numbers, ranges (1-5), steps (1-30/2), comma lists (1,5,10), and month/weekday names (JAN-DEC, SUN-SAT).

Validated at runtime by the cron parser.

type CSRFAlgorithm = 'blake2b256' | 'blake2b512' | 'sha256' | 'sha384' | 'sha512' | 'sha512-256'type DigestEncoding = 'utf8' | 'ucs2' | 'utf16le' | 'latin1' | 'ascii' | 'base64' | 'base64url' | 'hex'type DisconnectListener = () => voidtype DOMHighResTimeStamp = numbertype Encoding = 'utf-8' | 'windows-1252' | 'utf-16'type EventListenerOrEventListenerObject = EventListener | EventListenerObjecttype ExitListener = (code: number) => voidtype FFIFunctionCallable = Function & { __ffi_function_callable: FFIFunctionCallableSymbol }type FormDataEntryValue = File | stringtype HeadersInit = string[][] | Recordstring, string | ReadonlyArraystring>> | Headerstype HMREvent = `bun:${HMREventNames}` | string & {}

The event names for the dev server

type HMREventNames = 'beforeUpdate' | 'afterUpdate' | 'beforeFullReload' | 'beforePrune' | 'invalidate' | 'error' | 'ws:disconnect' | 'ws:connect'type ImportKind = 'import-statement' | 'require-call' | 'require-resolve' | 'dynamic-import' | 'import-rule' | 'url-token' | 'internal' | 'entry-point-run' | 'entry-point-build'type JavaScriptLoader = 'jsx' | 'js' | 'ts' | 'tsx'type Loader = 'js' | 'jsx' | 'ts' | 'tsx' | 'json' | 'jsonc' | 'toml' | 'yaml' | 'file' | 'napi' | 'wasm' | 'text' | 'css' | 'html'

https://bun.com/docs/bundler/loaders

type MacroMap = Recordstring, Recordstring, string>>

This lets you use macros as regular imports

 {
"react-relay": {
"graphql": "bun-macro-relay/bun-macro-relay.tsx"
}
}
type MaybePromiseT> = T | PromiseT>type MessageEventT = any> = Bun.__internal.UseLibDomIfAvailable'MessageEvent', BunMessageEventT>>type MessageEventSource = Bun.__internal.UseLibDomIfAvailable'MessageEventSource', undefined>type MessageListener = (message: unknown, sendHandle: unknown) => voidtype MultipleResolveType = 'resolve' | 'reject'type NullSubprocess = Subprocess'ignore' | 'inherit' | null | undefined, 'ignore' | 'inherit' | null | undefined, 'ignore' | 'inherit' | null | undefined>

Utility type for any process from () with stdin, stdout, stderr all set to null or similar.

type NullSyncSubprocess = SyncSubprocess'ignore' | 'inherit' | null | undefined, 'ignore' | 'inherit' | null | undefined>

Utility type for any process from () with both stdout and stderr set to null or similar

type OnBeforeParseCallback = external?: unknownnapiModule: unknownsymbol: stringtype OnEndCallback = (result: BuildOutput) => void | Promisevoid>type OnLoadCallback = (args: OnLoadArgs) => OnLoadResult | PromiseOnLoadResult>type OnLoadResult = OnLoadResultSourceCode | OnLoadResultObject | undefined | voidtype OnResolveCallback = (args: OnResolveArgs) => OnResolveResult | PromiseOnResolveResult | undefined | null> | undefined | nulltype OnStartCallback = () => void | Promisevoid>type PathLike = string | NodeJS.TypedArray | ArrayBufferLike | URLtype PipedSubprocess = Subprocess'pipe', 'pipe', 'pipe'>

Utility type for any process from () with stdin, stdout, stderr all set to "pipe". A combination of ReadableSubprocess and WritableSubprocess

type ReadableStreamControllerT> = ReadableStreamDefaultControllerT>type ReadableStreamDefaultReadResultT> = ReadableStreamDefaultReadValueResultT> | ReadableStreamDefaultReadDoneResulttype ReadableStreamReaderT> = ReadableStreamDefaultReaderT>type ReadableSubprocess = Subprocessany, 'pipe', 'pipe'>

Utility type for any process from () with both stdout and stderr set to "pipe"

type ReadableSyncSubprocess = SyncSubprocess'pipe', 'pipe'>

Utility type for any process from () with both stdout and stderr set to "pipe"

type RejectionHandledListener = (promise: Promiseunknown>) => void0**, it represents the **number of bytes sent**." data-algolia-static="false" data-algolia-merged="false" data-type="Type alias">type ServerWebSocketSendStatus = number

A status that represents the outcome of a sent message.

if 0, the message was dropped.if -1, there is backpressure of messages.if >0, it represents the number of bytes sent.
const status = ws.send("Hello!");
if (status === 0) {
console.log("Message was dropped");
} else if (status === -1) {
console.log("Backpressure was applied");
} else {
console.log(`Success! Sent ${status} bytes`);
}
type ShellExpression = { toString(): string } | ShellExpression[] | string | { raw: string } | SubprocessSpawnOptions.Writable, SpawnOptions.Readable, SpawnOptions.Readable> | SpawnOptions.Readable | SpawnOptions.Writable | ReadableStreamtype SignalsListener = (signal: NodeJS.Signals) => voidtype StringLike = string | { toString(): string }type StringOrBuffer = string | NodeJS.TypedArray | ArrayBufferLiketype SupportedCryptoAlgorithms = 'blake2b256' | 'blake2b512' | 'blake2s256' | 'md4' | 'md5' | 'ripemd160' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512' | 'sha512-224' | 'sha512-256' | 'sha3-224' | 'sha3-256' | 'sha3-384' | 'sha3-512' | 'shake128' | 'shake256'type Target = 'bun' | 'node' | 'browser'type TimerHandler = (...args: any[]) => voidtype Transferable = ArrayBuffer | MessagePorttype UncaughtExceptionOrigin = 'uncaughtException' | 'unhandledRejection'type WarningListener = (warning: Error) => voidtype WebSocketCompressor = 'disable' | 'shared' | 'dedicated' | '3KB' | '4KB' | '8KB' | '16KB' | '32KB' | '64KB' | '128KB' | '256KB'

Compression options for WebSocket messages.

type WebSocketOptions = WebSocketOptionsProtocolsOrProtocol & WebSocketOptionsTLS & WebSocketOptionsHeaders & WebSocketOptionsProxy & WebSocketOptionsCompression

Constructor options for the Bun.WebSocket client

type WebSocketOptionsCompression = perMessageDeflate?: boolean

Whether to offer the permessage-deflate extension in the WebSocket upgrade request. Pass false to suppress the Sec-WebSocket-Extensions header entirely — matching the ws package's perMessageDeflate: false option.

Defaults to true (the upgrade request advertises permessage-deflate; client_max_window_bits). Any falsy value (false, null, 0, "", explicit undefined) disables the offer.

type WebSocketOptionsHeaders = headers?: OutgoingHttpHeaders

Headers to send to the server

type WebSocketOptionsProtocolsOrProtocol = { protocols: string | string[] } | { protocol: string }type WebSocketOptionsProxy = proxy?: string | { headers: OutgoingHttpHeaders | Headers; url: string }

HTTP proxy to use for the WebSocket connection.

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

// String format
const ws = new WebSocket("wss:http://example.com", {
proxy: "http://proxy.example.com:8080"
});

// With credentials
const ws = new WebSocket("wss:http://example.com", {
proxy: "http://user:pass@proxy.example.com:8080"
});

// Object format with custom headers
const ws = new WebSocket("wss:http://example.com", {
proxy: {
url: "http://proxy.example.com:8080",
headers: {
"Proxy-Authorization": "Bearer token"
}
}
});
type WebSocketOptionsTLS = tls?: TLSOptions

Options for the TLS connection.

Supports full TLS configuration including custom CA certificates, client certificates, and other TLS settings (same as fetch).

// Using BunFile for certificates
const ws = new WebSocket("wss:http://example.com", {
tls: {
ca: Bun.file("./ca.pem")
}
});

// Using Buffer
const ws = new WebSocket("wss:http://example.com", {
tls: {
ca: fs.readFileSync("./ca.pem")
}
});
type WebSocketReadyState = 0 | 1 | 2 | 3

A state that represents if a WebSocket is connected.

WebSocket.CONNECTING is 0, the connection is pending.WebSocket.OPEN is 1, the connection is established and send() is possible.WebSocket.CLOSING is 2, the connection is closing.WebSocket.CLOSED is 3, the connection is closed or couldn't be opened.
type WorkerType = 'classic' | 'module'type WritableSubprocess = Subprocess'pipe', any, any>

Utility type for any process from () with stdin set to "pipe"

type XMLHttpRequestBodyInit = Blob | BufferSource | FormData | URLSearchParams | string

Resources

ReferenceDocsGuidesDiscordMerch StoreGitHubBlog 

Toolkit

RuntimePackage managerTest runnerBundlerPackage runner

Project

Bun 1.0Bun 1.1Bun 1.2Bun 1.3RoadmapContributingLicense

Baked with ❤️ in San Francisco

We're hiring →

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

    The