Bun

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.

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

The Bun shell

classBun.$.ShellErrorextendsErrorimplementsShellOutput

staticprepareStackTrace: (err: Error, stackTraces: CallSite[]) => any

Optional override for formatting stack traces

staticstackTraceLimit: number

The maximum number of stack frames to capture.

staticcaptureStackTrace(targetObject: object, constructorOpt?: Function): void

Create .stack property on a target object

staticisError(value: unknown): asserts value is Error

Check if a value is an instance of Error

value

The value to check

returns

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

constructor(message?: string): ShellError

cause: unknown

The cause of the error.

exitCode: number

message: string

name: string

stack: string

stderr: Buffer

stdout: Buffer

arrayBuffer(): ArrayBuffer

Read from stdout as an ArrayBuffer

returns

Stdout as an ArrayBuffer

blob(): Blob

Read from stdout as a Blob

returns

Stdout as a blob

bytes(): Uint8Array

Read from stdout as an Uint8Array

returns

Stdout as an Uint8Array

json(): any

Read from stdout as a JSON object

returns

Stdout as a JSON object

text(encoding?: BufferEncoding): string

Read from stdout as a string

encoding

The encoding to use when decoding the output

returns

Stdout as a string with the given encoding

classBun.$.ShellPromiseextendsPromise<ShellOutput>

staticall<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]>

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

values

An iterable of Promises.

returns

A new Promise.

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

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

values

An array of Promises.

returns

A new Promise.

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

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

values

An array or iterable of Promises.

returns

A new Promise.

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

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

values

An iterable of Promises.

returns

A new Promise.

staticreject<T=never>(reason?: any): Promise<T>

Creates a new rejected promise for the provided reason.

reason

The reason the promise was rejected.

returns

A new rejected Promise.

staticresolve(): Promise<void>

Creates a new resolved promise.

returns

A resolved promise.

statictry<T, U extends unknown[]>(callbackFn: (args: U) => T | PromiseLike<T>, args: U): Promise<Awaited<T>>

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

callbackFn

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

args

Additional arguments, that will be passed to the callback.

returns

A Promise that is:

  • Already fulfilled, if the callback synchronously returns a value.
  • Already rejected, if the callback synchronously throws an error.
  • Asynchronously fulfilled or rejected, if the callback returns a promise.

staticwithResolvers<T>(): PromiseWithResolvers<T>

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

returns

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

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

constructor(executor: (resolve: (value: ShellOutput | PromiseLike<ShellOutput>) => void, reject: (reason?: any) => void) => void): ShellPromise

Creates a new Promise.

executor

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

arrayBuffer(): Promise<ArrayBuffer>

Read from stdout as an ArrayBuffer

Automatically calls quiet

returns

A promise that resolves with stdout as an ArrayBuffer

blob(): Promise<Blob>

Read from stdout as a Blob

Automatically calls quiet

returns

A promise that resolves with stdout as a Blob

catch<TResult=never>(onrejected?: null | (reason: any) => TResult | PromiseLike<TResult>): Promise<ShellOutput | TResult>

Attaches a callback for only the rejection of the Promise.

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.

newCwd

The new working directory

env(newEnv: undefined | Record<string, string>): this

Set environment variables for the shell.

newEnv

The new environment variables

finally(onfinally?: null | () => void): Promise<ShellOutput>

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

onfinally

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

returns

A Promise for the completion of the callback.

json(): Promise<any>

Read from stdout as a JSON object

Automatically calls quiet

returns

A promise that resolves with stdout as a JSON object

lines(): AsyncIterable<string>

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(): 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.

text(encoding?: BufferEncoding): Promise<string>

Read from stdout as a string

Automatically calls quiet to disable echoing to stdout.

encoding

The encoding to use when decoding the output

returns

A promise that resolves with stdout as a string

then<TResult1=ShellOutput, TResult2=never>(onfulfilled?: null | (value: ShellOutput) => TResult1 | PromiseLike<TResult1>, onrejected?: null | (reason: any) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>

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

onfulfilled

The callback to execute when the Promise is resolved.

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.

interfaceBun.$.ShellOutput

exitCode: number

stderr: Buffer

stdout: Buffer

arrayBuffer(): ArrayBuffer

Read from stdout as an ArrayBuffer

returns

Stdout as an ArrayBuffer

blob(): Blob

Read from stdout as a Blob

returns

Stdout as a blob

bytes(): Uint8Array

Read from stdout as an Uint8Array

returns

Stdout as an Uint8Array

json(): any

Read from stdout as a JSON object

returns

Stdout as a JSON object

text(encoding?: BufferEncoding): string

Read from stdout as a string

encoding

The encoding to use when decoding the output

returns

Stdout as a string with the given encoding

VBun.$.Shell: new () => typeof $

functionBun.$.braces(pattern: string): string[]

Perform bash-like brace expansion on the given pattern.

pattern

Brace pattern to expand

functionBun.$.cwd(newCwd?: string): typeof $

newCwd

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

functionBun.$.env(newEnv?: Record<string, undefined | string>): typeof $

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

newEnv

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

functionBun.$.escape(input: string): string

Escape strings for input into shell commands.

functionBun.$.nothrow(): typeof $

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

functionBun.$.throws(shouldThrow: boolean): typeof $

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

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

The Bun shell

classBun.$.ShellErrorextendsErrorimplementsShellOutput

staticprepareStackTrace: (err: Error, stackTraces: CallSite[]) => any

Optional override for formatting stack traces

staticstackTraceLimit: number

The maximum number of stack frames to capture.

staticcaptureStackTrace(targetObject: object, constructorOpt?: Function): void

Create .stack property on a target object

staticisError(value: unknown): asserts value is Error

Check if a value is an instance of Error

value

The value to check

returns

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

constructor(message?: string): ShellError

cause: unknown

The cause of the error.

exitCode: number

message: string

name: string

stack: string

stderr: Buffer

stdout: Buffer

arrayBuffer(): ArrayBuffer

Read from stdout as an ArrayBuffer

returns

Stdout as an ArrayBuffer

blob(): Blob

Read from stdout as a Blob

returns

Stdout as a blob

bytes(): Uint8Array

Read from stdout as an Uint8Array

returns

Stdout as an Uint8Array

json(): any

Read from stdout as a JSON object

returns

Stdout as a JSON object

text(encoding?: BufferEncoding): string

Read from stdout as a string

encoding

The encoding to use when decoding the output

returns

Stdout as a string with the given encoding

classBun.$.ShellPromiseextendsPromise<ShellOutput>

staticall<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]>

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

values

An iterable of Promises.

returns

A new Promise.

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

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

values

An array of Promises.

returns

A new Promise.

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

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

values

An array or iterable of Promises.

returns

A new Promise.

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

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

values

An iterable of Promises.

returns

A new Promise.

staticreject<T=never>(reason?: any): Promise<T>

Creates a new rejected promise for the provided reason.

reason

The reason the promise was rejected.

returns

A new rejected Promise.

staticresolve(): Promise<void>

Creates a new resolved promise.

returns

A resolved promise.

statictry<T, U extends unknown[]>(callbackFn: (args: U) => T | PromiseLike<T>, args: U): Promise<Awaited<T>>

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

callbackFn

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

args

Additional arguments, that will be passed to the callback.

returns

A Promise that is:

  • Already fulfilled, if the callback synchronously returns a value.
  • Already rejected, if the callback synchronously throws an error.
  • Asynchronously fulfilled or rejected, if the callback returns a promise.

staticwithResolvers<T>(): PromiseWithResolvers<T>

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

returns

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

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

constructor(executor: (resolve: (value: ShellOutput | PromiseLike<ShellOutput>) => void, reject: (reason?: any) => void) => void): ShellPromise

Creates a new Promise.

executor

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

arrayBuffer(): Promise<ArrayBuffer>

Read from stdout as an ArrayBuffer

Automatically calls quiet

returns

A promise that resolves with stdout as an ArrayBuffer

blob(): Promise<Blob>

Read from stdout as a Blob

Automatically calls quiet

returns

A promise that resolves with stdout as a Blob

catch<TResult=never>(onrejected?: null | (reason: any) => TResult | PromiseLike<TResult>): Promise<ShellOutput | TResult>

Attaches a callback for only the rejection of the Promise.

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.

newCwd

The new working directory

env(newEnv: undefined | Record<string, string>): this

Set environment variables for the shell.

newEnv

The new environment variables

finally(onfinally?: null | () => void): Promise<ShellOutput>

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

onfinally

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

returns

A Promise for the completion of the callback.

json(): Promise<any>

Read from stdout as a JSON object

Automatically calls quiet

returns

A promise that resolves with stdout as a JSON object

lines(): AsyncIterable<string>

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(): 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.

text(encoding?: BufferEncoding): Promise<string>

Read from stdout as a string

Automatically calls quiet to disable echoing to stdout.

encoding

The encoding to use when decoding the output

returns

A promise that resolves with stdout as a string

then<TResult1=ShellOutput, TResult2=never>(onfulfilled?: null | (value: ShellOutput) => TResult1 | PromiseLike<TResult1>, onrejected?: null | (reason: any) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>

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

onfulfilled

The callback to execute when the Promise is resolved.

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.

interfaceBun.$.ShellOutput

exitCode: number

stderr: Buffer

stdout: Buffer

arrayBuffer(): ArrayBuffer

Read from stdout as an ArrayBuffer

returns

Stdout as an ArrayBuffer

blob(): Blob

Read from stdout as a Blob

returns

Stdout as a blob

bytes(): Uint8Array

Read from stdout as an Uint8Array

returns

Stdout as an Uint8Array

json(): any

Read from stdout as a JSON object

returns

Stdout as a JSON object

text(encoding?: BufferEncoding): string

Read from stdout as a string

encoding

The encoding to use when decoding the output

returns

Stdout as a string with the given encoding

VBun.$.Shell: new () => typeof $

functionBun.$.braces(pattern: string): string[]

Perform bash-like brace expansion on the given pattern.

pattern

Brace pattern to expand

functionBun.$.cwd(newCwd?: string): typeof $

newCwd

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

functionBun.$.env(newEnv?: Record<string, undefined | string>): typeof $

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

newEnv

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

functionBun.$.escape(input: string): string

Escape strings for input into shell commands.

functionBun.$.nothrow(): typeof $

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

functionBun.$.throws(shouldThrow: boolean): typeof $

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

functionBun.allocUnsafe(size: number): Uint8Array

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.

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

classBun.ArrayBufferSink

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

end(): ArrayBuffer | Uint8Array<ArrayBufferLike>

flush(): number | ArrayBuffer | Uint8Array<ArrayBufferLike>

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

Preallocate an internal buffer of this size This can significantly improve performance when the chunk size is small

stream: boolean

On ArrayBufferSink.flush, return the written data as a Uint8Array. Writes will restart from the beginning of the buffer.

}
): void

write(chunk: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>): number

functionBun.build(config: BuildConfig): Promise<BuildOutput>

Bundles JavaScript, TypeScript, CSS, HTML and other supported files into optimized outputs.

config

Build configuration options

returns

Promise that resolves to build output containing generated artifacts and build status

interfaceBun.BunFileextendsBlob

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

lastModified: number

A UNIX timestamp indicating when the file was last modified.

name: string

The name or path of the file, as specified in the constructor.

bytes(): Promise<Uint8Array<ArrayBufferLike>>

delete(): Promise<void>

Deletes the file (same as unlink)

exists(): Promise<boolean>

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

Read the data from the blob as a FormData object.

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

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

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

json(): Promise<any>

Read the data from the blob as a JSON object.

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

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

begin

start offset in bytes

end

absolute offset in bytes (relative to 0)

contentType

MIME type for the new BunFile

stat(): Promise<Stats>

Provides useful information about the file.

text(): Promise<string>

Deletes the file.

write(data: string | ArrayBuffer | SharedArrayBuffer | Request | Response | BunFile | ArrayBufferView<ArrayBufferLike>, options?:
{

highWaterMark: number

}
): Promise<number>

Write data to the file. This is equivalent to using Bun.write with a BunFile.

data

The data to write.

options

The options to use for the write.

writer(options?:
{

highWaterMark: number

}
): FileSink

Incremental writer for files and pipes.

functionBun.color(input: ColorInput, outputFormat?: 'number' | 'ansi' | 'ansi-16' | 'ansi-16m' | 'ansi-256' | 'css' | 'hex' | 'HEX' | 'hsl' | 'lab' | 'rgb' | 'rgba'): null | string

Converts formats of colors

input

A value that could possibly be a color

outputFormat

An optional output format

functionBun.concatArrayBuffers(buffers: ArrayBufferLike | ArrayBufferView<ArrayBufferLike>[], 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.

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.

functionBun.connect<Data=undefined>(options: TCPSocketConnectOptions<Data>): Promise<Socket<Data>>

Create a TCP client that connects to a server via a TCP socket

classBun.Cookie

A class for working with a single cookie

staticfrom(name: string, value: string, options?: CookieInit): Cookie

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

staticparse(cookieString: string): Cookie

Parse a cookie string into a Cookie object

cookieString

The cookie string

constructor(name: string, value: string, options?: CookieInit): Cookie

Create a new cookie

name

The name of the cookie

value

The value of the cookie

options

Optional cookie attributes

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

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

toJSON(): CookieInit

Serialize the cookie to a JSON object

toString(): string

Serialize the cookie to a string

Alias of Cookie.serialize

classBun.CookieMapimplementsIterable<[string, string]>

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

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

constructor(init?: string | Record<string, string> | string[][]): CookieMap

Creates a new CookieMap instance.

init

Optional initial data for the cookie map:

  • string: A cookie header string (e.g., "name=value; foo=bar")
  • string[][]: An array of name/value pairs (e.g., [["name", "value"], ["foo", "bar"]])
  • Record<string, string>: An object with cookie names as keys (e.g., { name: "value", foo: "bar" })

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.

name

The name of 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.

callback

Function to execute for each entry

get(name: string): null | string

Gets the value of a cookie with the specified name.

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.

name

The name of the cookie to check

returns

true if the cookie exists, false otherwise

keys(): IterableIterator<string>

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.

name

The name of the cookie

value

The value of the cookie

options

Optional cookie attributes

toJSON(): Record<string, 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(): IterableIterator<string>

Returns an iterator of all cookie values in the map.

returns

An iterator for the cookie values

classBun.CryptoHasher

Hardware-accelerated cryptographic hash functions

Used for crypto.createHash()

staticalgorithms: SupportedCryptoAlgorithms[]

List of supported hash algorithms

These are hardware accelerated with BoringSSL

statichash(algorithm: SupportedCryptoAlgorithms, input: BlobOrStringOrBuffer): Buffer

Run the hash over the given data

input

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

constructor(algorithm: SupportedCryptoAlgorithms, hmacKey?: string | TypedArray<ArrayBufferLike>): CryptoHasher

Create a new hasher

algorithm

The algorithm to use. See algorithms for a list of supported algorithms

hmacKey

Optional key for HMAC. Must be a string or TypedArray. If not provided, the hasher will be a non-HMAC hasher.

algorithm: SupportedCryptoAlgorithms

The algorithm chosen to hash the data

byteLength: number

The length of the output hash in bytes

copy(): CryptoHasher

Perform a deep copy of the hasher

digest(encoding: DigestEncoding): string

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

encoding

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

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

Update the hash with data

classBun.CryptoHashInterface<T>

This class only exists in types

statichash(input: BlobOrStringOrBuffer, hashInto?: TypedArray<ArrayBufferLike>): TypedArray

Run the hash over the given data

input

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

hashInto

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

digest(encoding: DigestEncoding): string

Finalize the hash

encoding

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

update(data: BlobOrStringOrBuffer): T

Update the hash with data

VBun.CSRF:
{

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

Generate a CSRF token.

secret

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

options

The options for the token.

returns

The generated token.

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

Verify a CSRF token.

token

The token to verify.

options

The options for the token.

returns

True if the token is valid, false otherwise.

}

Generate and verify CSRF tokens

functionBun.deepEquals(a: any, b: any, strict?: boolean): boolean

Fast deep-equality check two objects.

This also powers expect().toEqual in bun:test

strict

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

functionBun.deflateSync(data: string | ArrayBuffer | Uint8Array<ArrayBufferLike>, options?: ZlibCompressionOptions | LibdeflateCompressionOptions): Uint8Array

Compresses a chunk of data with zlib DEFLATE algorithm.

data

The buffer of data to compress

options

Compression options to use

returns

The output buffer with the compressed data

namespaceBun.dns

DNS Related APIs

VADDRCONFIG: number

VALL: number

VV4MAPPED: number

functiongetCacheStats():
{

cacheHitsCompleted: number

The number of times a cached DNS entry that was already resolved was used.

cacheHitsInflight: number

cacheMisses: number

errors: number

size: number

totalCount: number

}

Experimental API

functionlookup(hostname: string, options?:
{

backend: 'libc' | 'c-ares' | 'system' | 'getaddrinfo'

The DNS resolver implementation to use

Defaults to "c-ares" on Linux and "system" on macOS. This default may change in a future version of Bun if c-ares is not reliable enough.

On macOS, system uses the builtin macOS non-blocking DNS resolution API.

On Linux, system is the same as getaddrinfo.

c-ares is more performant on Linux in some high concurrency situations, but it lacks support support for mDNS (*.local, *.localhost domains) along with some other advanced features. If you run into issues using c-ares, you should try system. If the hostname ends with .local or .localhost, Bun will automatically use system instead of c-ares.

getaddrinfo is the POSIX standard function for blocking DNS resolution. Bun runs it in Bun's thread pool, which is limited to cpus / 2. That means if you run a lot of concurrent DNS lookups, concurrent IO will potentially pause until the DNS lookups are done.

On macOS, it shouldn't be necessary to use "getaddrinfo" because "system" uses the same API underneath (except non-blocking).

On Windows, libuv's non-blocking DNS resolver is used by default, and when specifying backends "system", "libc", or "getaddrinfo". The c-ares backend isn't currently supported on Windows.

family: 0 | 4 | 6 | 'IPv4' | 'IPv6' | 'any'

Limit results to either IPv4, IPv6, or both

flags: number

port: number

socketType: 'udp' | 'tcp'

Limit results to either UDP or TCP

}
): Promise<DNSLookup[]>

Lookup the IP address for a hostname

Uses non-blocking APIs by default

hostname

The hostname to lookup

options

Options for the lookup

Example

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"

functionprefetch(hostname: string): void

Experimental API

Prefetch a hostname.

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

hostname

The hostname to prefetch

VBun.embeddedFiles: ReadonlyArray<Blob>

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.

VBun.enableANSIColors: boolean

Are ANSI colors enabled for stdin and stdout?

Used for console.log

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

functionBun.escapeHTML(input: string | number | boolean | object): string

Escape the following characters in a string:

classBun.EventSourceextendsEventTarget

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

MDN Reference

staticCLOSED: 2

staticCONNECTING: 0

staticOPEN: 1

constructor(url: string | URL, eventSourceInitDict?: EventSourceInit): EventSource

onerror: null | (this: EventSource, ev: Event) => any

onmessage: null | (this: EventSource, ev:
{

prototype: MessageEvent

}
) => any

onopen: null | (this: EventSource, ev: Event) => any

OPEN: 1

readyState: number

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

url: string

Returns the URL providing the event stream.

withCredentials: boolean

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

Not supported in Bun

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

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

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

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

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

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

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

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

MDN Reference

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.

MDN Reference

ref(): void

Keep the event loop alive while connection is open or reconnecting

Not available in browsers

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

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

MDN Reference

unref(): void

Do not keep the event loop alive while connection is open or reconnecting

Not available in browsers

functionBun.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
path

The path to the file (lazily loaded) if the path starts with s3:// it will behave like S3File

classBun.FileSystemRouter

constructor(options:
{

assetPrefix: string

The base path to use when routing

dir: string

The root directory containing the files to route

There is no default value for this option.

fileExtensions: string[]

Limit the pages to those with particular file extensions.

origin: string

style: 'nextjs'

The style of router to use (only "nextjs" supported for now)

}
): FileSystemRouter

Create a new FileSystemRouter.

options

The options to use when creating the router

assetPrefix: string

origin: string

routes: Record<string, string>

style: string

match(input: string | Request | Response): null | MatchedRoute

reload(): void

functionBun.fileURLToPath(url: string | URL): string

Convert a URL to a filesystem path.

url

The URL to convert.

returns

A filesystem path.

functionBun.gc(force: boolean): void

Manually trigger the garbage collector

This does two things:

  1. It tells JavaScriptCore to run the garbage collector
  2. It tells mimalloc to clean up fragmented memory. Mimalloc manages the heap not used in JavaScriptCore.
force

Synchronously run the garbage collector

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

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

constructor(pattern: string): Glob

match(str: string): boolean

Match the glob against a string

scan(optionsOrCwd?: string | GlobScanOptions): AsyncIterableIterator<string>

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

scanSync(optionsOrCwd?: string | GlobScanOptions): IterableIterator<string>

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

functionBun.gunzipSync(data: string | ArrayBuffer | Uint8Array<ArrayBufferLike>, options?: ZlibCompressionOptions | LibdeflateCompressionOptions): Uint8Array

Decompresses a chunk of data with zlib GUNZIP algorithm.

data

The buffer of data to decompress

returns

The output buffer with the decompressed data

functionBun.gzipSync(data: string | ArrayBuffer | Uint8Array<ArrayBufferLike>, options?: ZlibCompressionOptions | LibdeflateCompressionOptions): Uint8Array

Compresses a chunk of data with zlib GZIP algorithm.

data

The buffer of data to compress

options

Compression options to use

returns

The output buffer with the compressed data

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

functionBun.indexOfLine(buffer: ArrayBufferLike | ArrayBufferView<ArrayBufferLike>, 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.

functionBun.inflateSync(data: string | ArrayBuffer | Uint8Array<ArrayBufferLike>, options?: ZlibCompressionOptions | LibdeflateCompressionOptions): Uint8Array

Decompresses a chunk of data with zlib INFLATE algorithm.

data

The buffer of data to decompress

returns

The output buffer with the decompressed data

functionBun.inspect(arg: any, options?: BunInspectOptions): string

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

Supports JSX

arg

The value to inspect

options

Options for the inspection

VBun.inspect.custom: inspect.custom

That can be used to declare custom inspect functions.

functionBun.inspect.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

functionBun.inspect(arg: any, options?: BunInspectOptions): string

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

Supports JSX

arg

The value to inspect

options

Options for the inspection

VBun.inspect.custom: inspect.custom

That can be used to declare custom inspect functions.

functionBun.inspect.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

VBun.isMainThread: boolean

Is the current global scope the main thread?

functionBun.listen<Data=undefined>(options: TCPSocketListenOptions<Data>): TCPSocketListener<Data>

Create a TCP server that listens on a port

VBun.main: string

What script launched Bun?

Absolute file path

classBun.MD4extendsCryptoHashInterface<MD4>

This class only exists in types

staticbyteLength: 16

The number of bytes the hash will produce

statichash(input: BlobOrStringOrBuffer, hashInto?: TypedArray<ArrayBufferLike>): TypedArray

Run the hash over the given data

input

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

hashInto

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

digest(encoding: DigestEncoding): string

Finalize the hash

encoding

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

update(data: BlobOrStringOrBuffer): MD4

Update the hash with data

classBun.MD5extendsCryptoHashInterface<MD5>

This class only exists in types

staticbyteLength: 16

The number of bytes the hash will produce

statichash(input: BlobOrStringOrBuffer, hashInto?: TypedArray<ArrayBufferLike>): TypedArray

Run the hash over the given data

input

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

hashInto

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

digest(encoding: DigestEncoding): string

Finalize the hash

encoding

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

update(data: BlobOrStringOrBuffer): MD5

Update the hash with data

functionBun.mmap(path: PathLike, opts?: MMapOptions): Uint8Array

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

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

functionBun.openInEditor(path: string, options?: EditorOptions): void

Open a file in your local editor. Auto-detects via $VISUAL || $EDITOR

path

path to open

VBun.origin: string

VBun.password: (password: StringOrBuffer, algorithm?: Argon2Algorithm | 'argon2id' | 'argon2d' | 'argon2i' | BCryptAlgorithm | 'bcrypt'): Promise<string>

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.

functionBun.pathToFileURL(path: string): URL

Convert a filesystem path to a file:// URL.

path

The path to convert.

returns

A URL with the file:// scheme.

VBun.peek: Peek

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

VBun.postgres: SQL

SQL client for PostgreSQL

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

encoding

"hex" | "base64" | "base64url"

timestamp

Unix timestamp in milliseconds, defaults to Date.now()

functionBun.readableStreamToArray<T>(stream: ReadableStream<T>): T[] | Promise<T[]>

Consume all data from a ReadableStream until it closes or errors.

stream

The stream to consume

returns

A promise that resolves with the chunks as an array

functionBun.readableStreamToArrayBuffer(stream: ReadableStream<ArrayBufferLike | ArrayBufferView<ArrayBufferLike>>): ArrayBuffer | Promise<ArrayBuffer>

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

stream

The stream to consume.

returns

A promise that resolves with the concatenated chunks or the concatenated chunks as an ArrayBuffer.

functionBun.readableStreamToBlob(stream: ReadableStream): Promise<Blob>

Consume all data from a ReadableStream until it closes or errors.

Concatenate the chunks into a single Blob.

stream

The stream to consume.

returns

A promise that resolves with the concatenated chunks as a Blob.

functionBun.readableStreamToBytes(stream: ReadableStream<ArrayBufferLike | ArrayBufferView<ArrayBufferLike>>): Uint8Array<ArrayBufferLike> | Promise<Uint8Array<ArrayBufferLike>>

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

stream

The stream to consume.

returns

A promise that resolves with the concatenated chunks or the concatenated chunks as a Uint8Array.

functionBun.readableStreamToFormData(stream: ReadableStream<string | Uint8Array<ArrayBufferLike> | Uint8ClampedArray<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Int8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike> | BigInt64Array<ArrayBufferLike> | Float32Array<ArrayBufferLike> | Float64Array<ArrayBufferLike> | DataView<ArrayBufferLike>>, multipartBoundaryExcludingDashes?: string | Uint8Array<ArrayBufferLike> | Uint8ClampedArray<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike> | Int8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike> | BigInt64Array<ArrayBufferLike> | Float32Array<ArrayBufferLike> | Float64Array<ArrayBufferLike> | DataView<ArrayBufferLike>): Promise<FormData>

Consume all data from a ReadableStream until it closes or errors.

Reads the multi-part or URL-encoded form data into a FormData object

stream

The stream to consume.

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.

functionBun.readableStreamToJSON(stream: ReadableStream): Promise<any>

Consume all data from a ReadableStream until it closes or errors.

Concatenate the chunks into a single string and parse as JSON. Chunks must be a TypedArray or an ArrayBuffer. If you need to support chunks of different types, consider readableStreamToBlob.

stream

The stream to consume.

returns

A promise that resolves with the concatenated chunks as a String.

functionBun.readableStreamToText(stream: ReadableStream): Promise<string>

Consume all data from a ReadableStream until it closes or errors.

Concatenate the chunks into a single string. Chunks must be a TypedArray or an ArrayBuffer. If you need to support chunks of different types, consider readableStreamToBlob.

stream

The stream to consume.

returns

A promise that resolves with the concatenated chunks as a String.

VBun.redis: RedisClient

Default Redis client

Connection information populated from one of, in order of preference:

  • process.env.VALKEY_URL
  • process.env.REDIS_URL
  • "valkey://localhost:6379"

classBun.RedisClient

constructor(url?: string, options?: RedisOptions): RedisClient

Creates a new Redis client

url

URL to connect to, defaults to process.env.VALKEY_URL, process.env.REDIS_URL, or "valkey://localhost:6379"

options

Additional options

bufferedAmount: number

Amount of data buffered in bytes

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: string | Blob | ArrayBufferView<ArrayBufferLike>, value: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Append a value to a key

key

The key to append to

value

The value to append

returns

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

bitcount(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

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

key

The key to count bits in

returns

Promise that resolves with the number of bits set to 1

close(): void

Disconnect from the Redis server

connect(): Promise<void>

Connect to the Redis server

returns

A promise that resolves when connected

decr(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Decrement the integer value of a key by one

key

The key to decrement

returns

Promise that resolves with the new value

del(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Delete a key

key

The key to delete

returns

Promise that resolves with the number of keys removed

dump(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

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

key

The key to dump

returns

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

exists(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<boolean>

Determine if a key exists

key

The key to check

returns

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

expire(key: string | Blob | ArrayBufferView<ArrayBufferLike>, seconds: number): Promise<number>

Set a key's time to live in seconds

key

The key to set the expiration for

seconds

The number of seconds until expiration

returns

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

expiretime(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

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

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: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Get the value of a key

key

The key to get

returns

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

getdel(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Get the value of a key and delete the key

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: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Get the value of a key and optionally set its expiration

key

The key to get

returns

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

getset(key: string | Blob | ArrayBufferView<ArrayBufferLike>, value: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Set the value of a key and return its old value

key

The key to set

value

The value to set

returns

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

hgetall(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | Record<string, string>>

Get all the fields and values in a hash

key

The hash key

returns

Promise that resolves with an object containing all fields and values

hincrby(key: string | Blob | ArrayBufferView<ArrayBufferLike>, field: string, increment: string | number): Promise<number>

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

key

The hash key

field

The field to increment

increment

The amount to increment by

returns

Promise that resolves with the new value

hincrbyfloat(key: string | Blob | ArrayBufferView<ArrayBufferLike>, field: string, increment: string | number): Promise<string>

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

key

The hash key

field

The field to increment

increment

The amount to increment by

returns

Promise that resolves with the new value as a string

hkeys(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<string[]>

Get all field names in a hash

key

The hash key

returns

Promise that resolves with an array of field names

hlen(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Get the number of fields in a hash

key

The hash key

returns

Promise that resolves with the number of fields

hmget(key: string | Blob | ArrayBufferView<ArrayBufferLike>, fields: string[]): Promise<null | string[]>

Get the values of all the given hash fields

key

The hash key

fields

The fields to get

returns

Promise that resolves with an array of values

hmset(key: string | Blob | ArrayBufferView<ArrayBufferLike>, fieldValues: string[]): Promise<string>

Set multiple hash fields to multiple values

key

The hash key

fieldValues

An array of alternating field names and values

returns

Promise that resolves with "OK" on success

hvals(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<string[]>

Get all values in a hash

key

The hash key

returns

Promise that resolves with an array of values

incr(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Increment the integer value of a key by one

key

The key to increment

returns

Promise that resolves with the new value

keys(pattern: string): Promise<string[]>

Find all keys matching the given pattern

pattern

The pattern to match

returns

Promise that resolves with an array of matching keys

llen(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Get the length of a list

key

The list key

returns

Promise that resolves with the length of the list

lpop(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Remove and get the first element in a list

key

The list key

returns

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

lpush(key: string | Blob | ArrayBufferView<ArrayBufferLike>, value: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Prepend one or multiple values to a list

key

The list key

value

The value to prepend

returns

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

lpushx(key: string | Blob | ArrayBufferView<ArrayBufferLike>, value: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

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

key

The list key

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

mget(keys: string | Blob | ArrayBufferView<ArrayBufferLike>[]): Promise<null | string[]>

Get the values of all specified keys

keys

The keys to get

returns

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

persist(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Remove the expiration from a key

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

pexpiretime(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

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

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: string | Blob | ArrayBufferView<ArrayBufferLike>, element: string): Promise<number>

Add one or more members to a HyperLogLog

key

The HyperLogLog key

element

The element to add

returns

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

pttl(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Get the time to live for a key in milliseconds

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

rpop(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Remove and get the last element in a list

key

The list key

returns

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

rpush(key: string | Blob | ArrayBufferView<ArrayBufferLike>, value: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Append one or multiple values to a list

key

The list key

value

The value to append

returns

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

rpushx(key: string | Blob | ArrayBufferView<ArrayBufferLike>, value: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

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

key

The list key

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: string | Blob | ArrayBufferView<ArrayBufferLike>, member: string): Promise<number>

Add a member to a set

key

The set key

member

The member to add

returns

Promise that resolves with 1 if the member was added, 0 if it already existed

scard(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Get the number of members in a set

key

The set key

returns

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

send(command: string, args: string[]): Promise<any>

Send a raw command to the Redis server

command

The command to send

args

The arguments to the command

returns

A promise that resolves with the command result

set(key: string | Blob | ArrayBufferView<ArrayBufferLike>, value: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<'OK'>

Set key to hold the string value

key

The key to set

value

The value to set

returns

Promise that resolves with "OK" on success

setnx(key: string | Blob | ArrayBufferView<ArrayBufferLike>, value: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

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

key

The key to set

value

The value to set

returns

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

sismember(key: string | Blob | ArrayBufferView<ArrayBufferLike>, member: string): Promise<boolean>

Check if a value is a member of a set

key

The set key

member

The member to check

returns

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

smembers(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<string[]>

Get all the members in a set

key

The set key

returns

Promise that resolves with an array of all members

spop(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Remove and return a random member from a set

key

The set key

returns

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

srandmember(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Get a random member from a set

key

The set key

returns

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

srem(key: string | Blob | ArrayBufferView<ArrayBufferLike>, member: string): Promise<number>

Remove a member from a set

key

The set key

member

The member to remove

returns

Promise that resolves with 1 if the member was removed, 0 if it didn't exist

strlen(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Get the length of the value stored in a key

key

The key to check

returns

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

ttl(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Get the time to live for a key in seconds

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

zcard(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<number>

Get the number of members in a sorted set

key

The sorted set key

returns

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

zpopmax(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Remove and return members with the highest scores in a sorted set

key

The sorted set key

returns

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

zpopmin(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Remove and return members with the lowest scores in a sorted set

key

The sorted set key

returns

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

zrandmember(key: string | Blob | ArrayBufferView<ArrayBufferLike>): Promise<null | string>

Get one or multiple random members from a sorted set

key

The sorted set key

returns

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

zscore(key: string | Blob | ArrayBufferView<ArrayBufferLike>, member: string): Promise<null | string>

Get the score associated with the given member in a sorted set

key

The sorted set key

member

The member to get the score for

returns

Promise that resolves with the score of the member as a string, or null if the member or key doesn't exist

functionBun.resolve(moduleId: string, parent: string): Promise<string>

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.

functionBun.resolveSync(moduleId: string, parent: string): string

Synchronously resolve a moduleId as though it were imported from parent

On failure, throws a ResolveMessage

VBun.revision: string

The git sha at the time the currently-running version of Bun was compiled

VBun.s3: S3Client

A default instance of S3Client

Pulls credentials from environment variables. Use new Bun.S3Client() if you need to explicitly set credentials.

classBun.S3Client

A configured S3 bucket instance for managing files. The instance is callable to create S3File instances and provides methods for common operations.

staticdelete(path: string, options?: S3Options): Promise<void>

Delete a file from the bucket. Alias for S3Client.unlink.

path

The path to the file in the bucket

options

S3 credentials and configuration options

returns

A promise that resolves when deletion is complete

staticexists(path: string, options?: S3Options): Promise<boolean>

Check if a file exists in the bucket. Uses HEAD request to check existence.

path

The path to the file in the bucket

options

S3 credentials and configuration options

returns

A promise that resolves to true if the file exists, false otherwise

staticfile(path: string, options?: S3Options): S3File

Creates an S3File instance for the given path.

path

The path to the file in the bucket

options

S3 credentials and configuration options

returns

An S3File instance

staticlist(input?: null | S3ListObjectsOptions, options?: Pick<S3Options, 'accessKeyId' | 'secretAccessKey' | 'sessionToken' | 'region' | 'bucket' | 'endpoint'>): Promise<S3ListObjectsResponse>

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.

input

Options for listing objects in the bucket

options

S3 credentials and configuration options

returns

A promise that resolves to the list response

staticpresign(path: string, options?: S3FilePresignOptions): string

Generate a presigned URL for temporary access to a file. Useful for generating upload/download URLs without exposing credentials.

path

The path to the file in the bucket

options

S3 credentials and presigned URL configuration

returns

A presigned URL string

staticsize(path: string, options?: S3Options): Promise<number>

Get the size of a file in bytes. Uses HEAD request to efficiently get size.

path

The path to the file in the bucket

options

S3 credentials and configuration options

returns

A promise that resolves to the file size in bytes

staticstat(path: string, options?: S3Options): Promise<S3Stats>

Get the stat of a file in an S3-compatible storage service.

path

The path to the file in the bucket

options

S3 credentials and configuration options

returns

A promise that resolves to the file stats

Delete a file from the bucket.

path

The path to the file in the bucket

options

S3 credentials and configuration options

returns

A promise that resolves when deletion is complete

staticwrite(path: string, data: string | ArrayBuffer | SharedArrayBuffer | Request | Response | Blob | File | BunFile | ArrayBufferView<ArrayBufferLike> | S3File, options?: S3Options): Promise<number>

Writes data directly to a path in the bucket. Supports strings, buffers, streams, and web API types.

path

The path to the file in the bucket

data

The data to write to the file

options

S3 credentials and configuration options

returns

The number of bytes written

constructor(options?: S3Options): S3Client

Create a new instance of an S3 bucket so that credentials can be managed from a single instance instead of being passed to every method.

options

The default options to use for the S3 client. Can be overriden by passing options to the methods.

returns

delete(path: string, options?: S3Options): Promise<void>

Delete a file from the bucket. Alias for S3Client.unlink.

path

The path to the file in the bucket

options

Additional S3 options to override defaults

returns

A promise that resolves when deletion is complete

exists(path: string, options?: S3Options): Promise<boolean>

Check if a file exists in the bucket. Uses HEAD request to check existence.

path

The path to the file in the bucket

options

Additional S3 options to override defaults

returns

A promise that resolves to true if the file exists, false otherwise

file(path: string, options?: S3Options): S3File

Creates an S3File instance for the given path.

path

The path to the file in the bucket

options

Additional S3 options to override defaults

returns

An S3File instance

list(input?: null | S3ListObjectsOptions, options?: Pick<S3Options, 'accessKeyId' | 'secretAccessKey' | 'sessionToken' | 'region' | 'bucket' | 'endpoint'>): Promise<S3ListObjectsResponse>

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.

input

Options for listing objects in the bucket

options

Additional S3 options to override defaults

returns

A promise that resolves to the list response

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.

path

The path to the file in the bucket

options

Options for generating the presigned URL

returns

A presigned URL string

size(path: string, options?: S3Options): Promise<number>

Get the size of a file in bytes. Uses HEAD request to efficiently get size.

path

The path to the file in the bucket

options

Additional S3 options to override defaults

returns

A promise that resolves to the file size in bytes

stat(path: string, options?: S3Options): Promise<S3Stats>

Get the stat of a file in an S3-compatible storage service.

path

The path to the file in the bucket

options

Additional S3 options to override defaults

returns

A promise that resolves to the file stats

Delete a file from the bucket.

path

The path to the file in the bucket

options

Additional S3 options to override defaults

returns

A promise that resolves when deletion is complete

write(path: string, data: string | ArrayBuffer | SharedArrayBuffer | Request | Response | Blob | File | BunFile | ArrayBufferView<ArrayBufferLike> | S3File, options?: S3Options): Promise<number>

Writes data directly to a path in the bucket. Supports strings, buffers, streams, and web API types.

path

The path to the file in the bucket

data

The data to write to the file

options

Additional S3 options to override defaults

returns

The number of bytes written

VBun.semver:
{

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.

satisfies: (version: StringLike, range: StringLike) => boolean

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

}

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

functionBun.serve<T, R extends { [K in string | number | symbol]: RouteValue<K & string>}>(options: ServeFunctionOptions<T, R> &
{

static: R

}
): Server

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.

options

Server configuration options

functionBun.sha(input: StringOrBuffer, hashInto?: TypedArray<ArrayBufferLike>): TypedArray

input

string, Uint8Array, or ArrayBuffer to hash. Uint8Array or ArrayBuffer will be faster

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

classBun.SHA1extendsCryptoHashInterface<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

staticbyteLength: 20

The number of bytes the hash will produce

statichash(input: BlobOrStringOrBuffer, hashInto?: TypedArray<ArrayBufferLike>): TypedArray

Run the hash over the given data

input

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

hashInto

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

digest(encoding: DigestEncoding): string

Finalize the hash

encoding

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

update(data: BlobOrStringOrBuffer): SHA1

Update the hash with data

classBun.SHA224extendsCryptoHashInterface<SHA224>

This class only exists in types

staticbyteLength: 28

The number of bytes the hash will produce

statichash(input: BlobOrStringOrBuffer, hashInto?: TypedArray<ArrayBufferLike>): TypedArray

Run the hash over the given data

input

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

hashInto

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

digest(encoding: DigestEncoding): string

Finalize the hash

encoding

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

update(data: BlobOrStringOrBuffer): SHA224

Update the hash with data

classBun.SHA256extendsCryptoHashInterface<SHA256>

This class only exists in types

staticbyteLength: 32

The number of bytes the hash will produce

statichash(input: BlobOrStringOrBuffer, hashInto?: TypedArray<ArrayBufferLike>): TypedArray

Run the hash over the given data

input

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

hashInto

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

digest(encoding: DigestEncoding): string

Finalize the hash

encoding

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

update(data: BlobOrStringOrBuffer): SHA256

Update the hash with data

classBun.SHA384extendsCryptoHashInterface<SHA384>

This class only exists in types

staticbyteLength: 48

The number of bytes the hash will produce

statichash(input: BlobOrStringOrBuffer, hashInto?: TypedArray<ArrayBufferLike>): TypedArray

Run the hash over the given data

input

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

hashInto

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

digest(encoding: DigestEncoding): string

Finalize the hash

encoding

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

update(data: BlobOrStringOrBuffer): SHA384

Update the hash with data

classBun.SHA512extendsCryptoHashInterface<SHA512>

This class only exists in types

staticbyteLength: 64

The number of bytes the hash will produce

statichash(input: BlobOrStringOrBuffer, hashInto?: TypedArray<ArrayBufferLike>): TypedArray

Run the hash over the given data

input

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

hashInto

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

digest(encoding: DigestEncoding): string

Finalize the hash

encoding

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

update(data: BlobOrStringOrBuffer): SHA512

Update the hash with data

classBun.SHA512_256extendsCryptoHashInterface<SHA512_256>

See also sha

staticbyteLength: 32

The number of bytes the hash will produce

statichash(input: BlobOrStringOrBuffer, hashInto?: TypedArray<ArrayBufferLike>): TypedArray

Run the hash over the given data

input

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

hashInto

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

digest(encoding: DigestEncoding): string

Finalize the hash

encoding

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

update(data: BlobOrStringOrBuffer): SHA512_256

Update the hash with data

functionBun.shrink(): void

The next time JavaScriptCore is idle, clear unused memory and attempt to reduce the heap size.

functionBun.sleep(ms: number | Date): Promise<void>

Resolve a Promise after milliseconds. This is like setTimeout except it returns a Promise.

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.

functionBun.sleepSync(ms: number): void

Sleep the thread for a given number of milliseconds

This is a blocking function.

Internally, it calls nanosleep(2)

functionBun.spawn<Opts extends OptionsObject<Writable, Readable, Readable>>(options: Opts &
{

cmd: string[]

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

}
): OptionsToSubprocess<Opts>

Spawn a new process

functionBun.spawnSync<Opts extends OptionsObject<Writable, Readable, Readable>>(options: Opts &
{

cmd: string[]

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

onExit: undefined

}
): OptionsToSyncSubprocess<Opts>

Spawn a new process

VBun.sql: SQL

SQL client

VBun.SQL: SQL

The SQL constructor

VBun.stderr: BunFile

Write to stderr

VBun.stdin: BunFile

Read from stdin

This is read-only

VBun.stdout: BunFile

Write to stdout

functionBun.stringWidth(input: string, options?:
{

ambiguousIsNarrow: 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.

}
): 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 terminal
  • Quickly checking if a string contains ANSI escape codes
  • Measuring 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.

input

The string to measure

returns

The width of the string in columns

namespaceBun.TOML

TOML related APIs

functionparse(input: string): object

Parse a TOML string into a JavaScript object.

input

The TOML string to parse

returns

A JavaScript object

classBun.Transpiler

Quickly transpile TypeScript, JSX, or JS to modern JavaScript.

scan(code: StringOrBuffer):
{

exports: string[]

imports: Import[]

}

Get a list of import paths and paths from a TypeScript, JSX, TSX, or JavaScript file.

code

The code to scan

scanImports(code: StringOrBuffer): Import[]

Get a list of import paths from a TypeScript, JSX, TSX, or JavaScript file.

code

The code to scan

transform(code: StringOrBuffer, loader?: JavaScriptLoader): Promise<string>

Transpile code from TypeScript or JSX into valid JavaScript. This function does not resolve imports.

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.

code

The code to transpile

functionBun.udpSocket<DataBinaryType extends keyof BinaryTypeList='buffer'>(options: SocketOptions<DataBinaryType>): Promise<Socket<DataBinaryType>>

Create a UDP socket

options

The options to use when creating the server

VBun.version: string

The current version of Bun

VBun.version_with_sha: string

The current version of Bun with the shortened commit sha of the build

classBun.WebSocketextendsEventTarget

A WebSocket client implementation

staticCLOSED: 3

staticCLOSING: 2

staticCONNECTING: 0

staticOPEN: 1

binaryType: 'arraybuffer' | 'nodebuffer'

The type of binary data being received.

bufferedAmount: number

The number of bytes of data that have been queued using send() but not yet transmitted to the network

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

prototype: MessageEvent

}
) => any

Event handler for message event

onopen: null | (this: WebSocket, ev: Event) => any

Event handler for open event

protocol: string

The protocol selected by the server

readyState: 0 | 1 | 2 | 3

The current state of the connection

url: string

The URL of the WebSocket connection

addEventListener<K 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.

type

A case-sensitive string representing the event type to listen for

listener

The function to be called when the event occurs

options

An options object that specifies characteristics about the event listener

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

Closes the WebSocket connection

code

A numeric value indicating the status code

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.

MDN Reference

ping(data?: string | ArrayBufferLike | ArrayBufferView<ArrayBufferLike>): void

Sends a ping frame to the server

data

Optional data to include in the ping frame

pong(data?: string | ArrayBufferLike | ArrayBufferView<ArrayBufferLike>): void

Sends a pong frame to the server

data

Optional data to include in the pong frame

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

Removes an event listener previously registered with addEventListener()

type

A case-sensitive string representing the event type to remove

listener

The function to remove from the event target

options

An options object that specifies characteristics about the event listener

send(data: string | ArrayBufferLike | ArrayBufferView<ArrayBufferLike>): void

Transmits data to the server

data

The data to send to the server

terminate(): void

Immediately terminates the connection

functionBun.which(command: string, options?:
{

cwd: string

When given a relative path, use this path to join it.

PATH: string

Overrides the PATH environment variable

}
): 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.

command

The name of the executable or script

classBun.WorkerextendsEventTarget, AbstractWorker

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) => any

onmessage: null | (this: Worker, ev:
{

prototype: MessageEvent

}
) => any

onmessageerror: null | (this: Worker, ev:
{

prototype: MessageEvent

}
) => any

threadId: 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.

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

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

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

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

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

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

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

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

MDN Reference

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.

MDN Reference

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

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.

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

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

MDN Reference

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.

functionBun.write(destination: BunFile | S3File | PathLike, input: string | ArrayBufferLike | Blob | TypedArray<ArrayBufferLike> | BlobPart[], options?:
{

createPath: boolean

If true, create the parent directory if it doesn't exist. By default, this is true.

If false, this will throw an error if the directory doesn't exist.

mode: number

If writing to a PathLike, set the permissions of the file.

}
): Promise<number>

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.

destination

The file or file path to write to

input

The data to copy into destination.

returns

A promise that resolves with the number of bytes written.

Type Definitions

interfaceBun.AbstractWorker

onerror: null | (this: AbstractWorker, ev: ErrorEvent) => any

addEventListener<K extends 'error'>(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void

removeEventListener<K extends 'error'>(type: K, listener: (this: AbstractWorker, ev: AbstractWorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void

interfaceBun.AddEventListenerOptionsextendsEventListenerOptions

capture: boolean

once: 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.

typeBun.Architecture='arm' | 'arm64' | 'ia32' | 'mips' | 'mipsel' | 'ppc' | 'ppc64' | 's390' | 's390x' | 'x64'

typeBun.ArrayBufferView<TArrayBuffer extends ArrayBufferLike=ArrayBufferLike>=NodeJS.TypedArray<TArrayBuffer> | DataView<TArrayBuffer>

typeBun.BeforeExitListener=(code: number) => void

typeBun.BlobOrStringOrBuffer=string | NodeJS.TypedArray | ArrayBufferLike | Blob

typeBun.BufferSource=NodeJS.TypedArray | DataView | ArrayBufferLike

interfaceBun.BuildArtifactextendsBlob

A build artifact represents a file that was generated by the bundler

hash: null | string

kind: 'entry-point' | 'chunk' | 'asset' | 'sourcemap' | 'bytecode'

path: string

bytes(): Promise<Uint8Array<ArrayBufferLike>>

formData(): Promise<FormData>

Read the data from the blob as a FormData object.

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

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

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

json(): Promise<any>

Read the data from the blob as a JSON object.

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

slice(start?: number, end?: number, contentType?: string): Blob

text(): Promise<string>

interfaceBun.BuildConfig

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.

Bytecode is currently only supported for CommonJS (format: "cjs").

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

drop: string[]

Drop function calls to matching property accesses.

emitDCEAnnotations: boolean

Force emitting @PURE annotations even if minify.whitespace is true.

entrypoints: string[]

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 entirely
  • A string ending in *: Inlines environment variables that match the given prefix. For example, "MY_PUBLIC_*" will only include env vars starting with "MY_PUBLIC_"

external: string[]

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.

loader: (key: string) => Loader

minify: boolean |
{

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

}

outdir: string

packages: 'external' | 'bundle'

publicPath: string

root: string

sourcemap: boolean | 'external' | 'none' | 'linked' | '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 //# 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 //# sourceMappingURL comment is added to the output file.

true and false are aliases for "inline" and "none", respectively.

splitting: boolean

throw: boolean

When set to true, the returned promise rejects with an AggregateError when a build failure happens. When set to false, the success property of the returned object will be false when a build failure happens. This defaults to true.

interfaceBun.BuildOutput

The output of a build

logs: BuildMessage | ResolveMessage[]

success: boolean

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

typeBun.BunLockFile

Types for bun.lock

typeBun.BunLockFilePackageArray
=[pkg: string, registry: string, info: BunLockFilePackageInfo, integrity: string] | [pkg: string, info: BunLockFilePackageInfo] | [pkg: string] | [pkg: string, info: BunLockFilePackageInfo, bunTag: string] | [pkg: string, info: Pick<BunLockFileBasePackageInfo, 'bin' | 'binDir'>]

typeBun.BunLockFilePackageInfo
=BunLockFileBasePackageInfo &
{

bundled: true

cpu: string | string[]

os: string | string[]

}

interfaceBun.BunMessageEvent<T=any>extendsEvent

A message received by a target object.

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

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

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

currentTarget: null | EventTarget

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

MDN Reference

data: T

Returns the data of the message.

defaultPrevented: boolean

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

MDN Reference

eventPhase: number

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

MDN Reference

isTrusted: boolean

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

MDN Reference

lastEventId: string

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

NONE: 0

origin: string

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

ports: readonly MessagePort[]

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

source: undefined | null

target: null | EventTarget

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

MDN Reference

timeStamp: number

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

MDN Reference

type: string

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

MDN Reference

composedPath(): EventTarget[]

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

MDN Reference

preventDefault(): void

If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.

MDN Reference

stopImmediatePropagation(): void

Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.

MDN Reference

stopPropagation(): void

When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.

MDN Reference

interfaceBun.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 script
  • browser: The plugin will be applied to browser builds
  • node: 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 | Promise<void>

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.

build

A builder object that can be used to register plugin hooks

interfaceBun.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 exports
  • onResolve 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.

(options: T) => ReturnType<T['setup']>;

interfaceBun.BunRequest<T extends string=string>extendsRequest

This Fetch API interface represents a resource request.

MDN Reference

body: null | ReadableStream<Uint8Array<ArrayBufferLike>>

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

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

destination: RequestDestination

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

MDN Reference

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

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

keepalive: boolean

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

MDN Reference

method: string

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

MDN Reference

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

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

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

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

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

url: string

bytes(): Promise<Uint8Array<ArrayBufferLike>>

json(): Promise<any>

text(): Promise<string>

interfaceBun.CloseEventInitextendsEventInit

bubbles: boolean

cancelable: boolean

code: number

composed: boolean

reason: string

wasClean: boolean

typeBun.ColorInput
=
{

a: number

b: number

g: number

r: number

}
| [number, number, number] | [number, number, number, number] | Uint8Array | Uint8ClampedArray | Float32Array | Float64Array | string | number |
{

toString(): string

}

Valid inputs for color

interfaceBun.CookieInit

domain: string

expires: string | number | Date

httpOnly: boolean

maxAge: number

name: string

partitioned: boolean

path: string

Defaults to '/'. To allow the browser to set the path, use an empty string.

sameSite: CookieSameSite

Defaults to lax.

secure: boolean

value: string

typeBun.CookieSameSite='strict' | 'lax' | 'none'

interfaceBun.CookieStoreDeleteOptions

domain: null | string

name: string

path: string

interfaceBun.CookieStoreGetOptions

name: string

url: string

typeBun.CSRFAlgorithm='blake2b256' | 'blake2b512' | 'sha256' | 'sha384' | 'sha512' | 'sha512-256'

interfaceBun.CSRFGenerateOptions

algorithm: 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.

interfaceBun.CSRFVerifyOptions

algorithm: 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.

interfaceBun.CustomEventInit<T=any>extendsEventInit

bubbles: boolean

cancelable: boolean

composed: boolean

typeBun.DigestEncoding='utf8' | 'ucs2' | 'utf16le' | 'latin1' | 'ascii' | 'base64' | 'base64url' | 'hex'

interfaceBun.DirectUnderlyingSource<R=any>

pull: (controller: ReadableStreamDirectController) => void | PromiseLike<void>

type: 'direct'

typeBun.DisconnectListener=() => void

typeBun.DistributedOmit<T, K extends PropertyKey>=T extends T ? Omit<T, K> : never

interfaceBun.DNSLookup

address: string

The IP address of the host as a string in IPv4 or IPv6 format.

family: 4 | 6

ttl: 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.

interfaceBun.EditorOptions

column: number

editor: 'vscode' | 'subl'

line: number

typeBun.Encoding='utf-8' | 'windows-1252' | 'utf-16'

interfaceBun.Env

NODE_ENV: string

TZ: string

Can be used to change the default timezone at runtime

interfaceBun.ErrorEventInitextendsEventInit

bubbles: boolean

cancelable: boolean

colno: number

composed: boolean

error: any

filename: string

lineno: number

message: string

interfaceBun.ErrorLikeextendsError

cause: unknown

The cause of the error.

code: string

errno: number

message: string

name: string

stack: string

syscall: string

interfaceBun.EventInit

bubbles: boolean

cancelable: boolean

composed: boolean

interfaceBun.EventListener

(evt: Event) => void;

typeBun.ExitListener=(code: number) => void

interfaceBun.FdSocketOptions<Data=undefined>extendsSocketOptions<Data>

data: Data

The per-instance data context

fd: number

The file descriptor to connect to

socket: SocketHandler<Data>

Handlers for socket events

tls: TLSOptions

TLS Configuration with which to create the socket

interfaceBun.FetchEventextendsEvent

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

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

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

currentTarget: null | EventTarget

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

MDN Reference

defaultPrevented: boolean

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

MDN Reference

eventPhase: number

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

MDN Reference

isTrusted: boolean

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

MDN Reference

NONE: 0

target: null | EventTarget

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

MDN Reference

timeStamp: number

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

MDN Reference

type: string

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

MDN Reference

url: string

composedPath(): EventTarget[]

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

MDN Reference

preventDefault(): void

If invoked when the cancelable attribute value is true, and while executing a listener for the event with passive set to false, signals to the operation that caused event to be dispatched that it needs to be canceled.

MDN Reference

respondWith(response: Response | Promise<Response>): void

stopImmediatePropagation(): void

Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.

MDN Reference

stopPropagation(): void

When dispatched in a tree, invoking this method prevents event from reaching any objects other than the current object.

MDN Reference

waitUntil(promise: Promise<any>): void

typeBun.FFIFunctionCallable
=Function &
{

__ffi_function_callable: FFIFunctionCallableSymbol

}

interfaceBun.FileBlobextendsBunFile

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

lastModified: number

A UNIX timestamp indicating when the file was last modified.

name: string

The name or path of the file, as specified in the constructor.

bytes(): Promise<Uint8Array<ArrayBufferLike>>

delete(): Promise<void>

Deletes the file (same as unlink)

exists(): Promise<boolean>

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

Read the data from the blob as a FormData object.

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

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

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

json(): Promise<any>

Read the data from the blob as a JSON object.

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

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

begin

start offset in bytes

end

absolute offset in bytes (relative to 0)

contentType

MIME type for the new BunFile

stat(): Promise<Stats>

Provides useful information about the file.

text(): Promise<string>

Deletes the file.

write(data: string | ArrayBuffer | SharedArrayBuffer | Request | Response | BunFile | ArrayBufferView<ArrayBufferLike>, options?:
{

highWaterMark: number

}
): Promise<number>

Write data to the file. This is equivalent to using Bun.write with a BunFile.

data

The data to write.

options

The options to use for the write.

writer(options?:
{

highWaterMark: number

}
): FileSink

Incremental writer for files and pipes.

interfaceBun.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 | Promise<number>

Close the file descriptor. This also flushes the internal buffer.

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

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

Preallocate an internal buffer of this size This can significantly improve performance when the chunk size is small

}
): void

Start the file sink with provided options.

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 | ArrayBufferView<ArrayBufferLike>): number

Write a chunk of data to the file.

If the file descriptor is not writable yet, the data is buffered.

chunk

The data to write

returns

Number of bytes written

interfaceBun.GenericServeOptions

development: boolean |
{

hmr: boolean

Enable Hot Module Replacement for routes (including React Fast Refresh, if React is in use)

}

Render contextual errors? This enables bun's error page

error: (this: Server, error: ErrorLike) => void | Promise<void> | Response | Promise<Response>

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)

interfaceBun.GlobScanOptions

absolute: 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 (.).

Indicates whether to traverse descendants of symbolic link directories.

onlyFiles: boolean

Return only files.

Throw an error when symbolic link is broken

interfaceBun.Hash

adler32: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>) => number

cityHash32: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>) => number

cityHash64: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>, seed?: bigint) => bigint

crc32: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>) => number

murmur32v2: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>, seed?: number) => number

murmur32v3: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>, seed?: number) => number

murmur64v2: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>, seed?: bigint) => bigint

wyhash: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>, seed?: bigint) => bigint

xxHash3: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>, seed?: bigint) => bigint

xxHash32: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>, seed?: number) => number

xxHash64: (data: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>, seed?: bigint) => bigint

typeBun.HeadersInit=string[][] | Record<string, string | ReadonlyArray<string>> | Headers

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

typeBun.HMREvent
=`bun:${HMREventNames}` | string & {}

The event names for the dev server

typeBun.HMREventNames='beforeUpdate' | 'afterUpdate' | 'beforeFullReload' | 'beforePrune' | 'invalidate' | 'error' | 'ws:disconnect' | 'ws:connect'

interfaceBun.HTMLBundle

Used when importing an HTML file at runtime.

index: string

interfaceBun.Import

typeBun.ImportKind='import-statement' | 'require-call' | 'require-resolve' | 'dynamic-import' | 'import-rule' | 'url-token' | 'internal' | 'entry-point-run' | 'entry-point-build'

typeBun.JavaScriptLoader='jsx' | 'js' | 'ts' | 'tsx'

interfaceBun.LibdeflateCompressionOptions

level: 0 | 2 | 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12

library: 'libdeflate'

typeBun.Loader='js' | 'jsx' | 'ts' | 'tsx' | 'json' | 'toml' | 'file' | 'napi' | 'wasm' | 'text' | 'css' | 'html'

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

typeBun.MacroMap=Record<string, Record<string, string>>

This lets you use macros as regular imports

interfaceBun.MatchedRoute

filePath: string

kind: 'exact' | 'catch-all' | 'optional-catch-all' | 'dynamic'

name: string

params: Record<string, string>

A map of the parameters from the route

pathname: string

query: Record<string, string>

src: string

typeBun.MessageEvent<T=any>=Bun.__internal.UseLibDomIfAvailable<'MessageEvent', BunMessageEvent<T>>

interfaceBun.MessageEventInit<T=any>extendsEventInit

bubbles: boolean

cancelable: boolean

composed: boolean

lastEventId: string

origin: string

source: null

typeBun.MessageEventSource=Bun.__internal.UseLibDomIfAvailable<'MessageEventSource', undefined>

typeBun.MessageListener=(message: unknown, sendHandle: unknown) => void

interfaceBun.MMapOptions

shared: 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.

typeBun.MultipleResolveType='resolve' | 'reject'

interfaceBun.NetworkSinkextendsFileSink

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

Finish the upload. This also flushes the internal buffer.

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

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

Preallocate an internal buffer of this size This can significantly improve performance when the chunk size is small

}
): void

Start the file sink with provided options.

options

Configuration options for the file sink

stat(): Promise<Stats>

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 | ArrayBufferView<ArrayBufferLike>): number

Write a chunk of data to the network.

If the network is not writable yet, the data is buffered.

chunk

The data to write

returns

Number of bytes written

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

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

interfaceBun.OnLoadArgs

defer: () => Promise<void>

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

interfaceBun.OnLoadResultObject

exports: Record<string, unknown>

The object to use as the module

loader: 'object'

The loader to use for this file

interfaceBun.OnLoadResultSourceCode

contents: string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView<ArrayBufferLike>

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.

interfaceBun.OnResolveArgs

importer: 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.

typeBun.OnResolveCallback=(args: OnResolveArgs) => OnResolveResult | Promise<OnResolveResult | undefined | null> | undefined | null

interfaceBun.OnResolveResult

external: boolean

namespace: string

The namespace of the destination It will be concatenated with path to form the final import specifier

path: string

The destination of the import

typeBun.OnStartCallback=() => void | Promise<void>

namespaceBun.Password

Hash and verify passwords using argon2 or bcrypt

These are fast APIs that can run in a worker thread if used asynchronously.

interfaceArgon2Algorithm

algorithm: 'argon2id' | 'argon2d' | 'argon2i'

memoryCost: number

Memory cost, which defines the memory usage, given in kibibytes.

timeCost: number

Defines the amount of computation realized and therefore the execution time, given in number of iterations.

interfaceBCryptAlgorithm

algorithm: 'bcrypt'

cost: number

A number between 4 and 31. The default is 10.

typeBun.PathLike=string | NodeJS.TypedArray | ArrayBufferLike | URL

interfaceBun.Peek

(promise: T | Promise<T>) => T | Promise<T>;

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

typeBun.Platform='aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd'

interfaceBun.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 | Promise<OnLoadResult>): this

Create a lazy-loaded virtual module that can be imported or required from other modules

specifier

The module specifier to register the callback for

callback

The function to run when the module is imported or required

Example

returns

this for method chaining

onBeforeParse(constraints: PluginConstraints, callback:
{

external: unknown

napiModule: unknown

symbol: string

}
): this

onLoad(constraints: PluginConstraints, callback: OnLoadCallback): this

Register a callback to load imports with a specific import specifier

constraints

The constraints to apply the plugin to

callback

The callback to handle the import

returns

this for method chaining

onResolve(constraints: PluginConstraints, callback: OnResolveCallback): this

Register a callback to resolve imports matching a filter and/or namespace

constraints

The constraints to apply the plugin to

callback

The callback to handle the import

returns

this for method chaining

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

interfaceBun.PluginConstraints

filter: RegExp

Only apply the plugin when the import specifier matches this regular expression

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.

interfaceBun.ReadableStreamDefaultReadManyResult<T>

done: boolean

size: number

Number of bytes

value: T[]

typeBun.ReadableSubprocess=Subprocess<any, 'pipe', 'pipe'>

Utility type for any process from () with both stdout and stderr set to "pipe"

typeBun.ReadableSyncSubprocess=SyncSubprocess<'pipe', 'pipe'>

Utility type for any process from () with both stdout and stderr set to "pipe"

interfaceBun.RedisOptions

autoReconnect: 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 |
{

ca: string | Buffer<ArrayBufferLike> | string | Buffer<ArrayBufferLike>[]

cert: string | Buffer<ArrayBufferLike>

key: string | Buffer<ArrayBufferLike>

rejectUnauthorized: boolean

}

TLS options Can be a boolean or an object with TLS options

url: string

URL to connect to, defaults to "redis://localhost:6379" Supported protocols: redis://, rediss://, redis+unix://, redis+tls://

typeBun.RejectionHandledListener=(promise: Promise<unknown>) => void

interfaceBun.ReservedSQLextendsSQL

Represents a reserved connection from the connection pool Extends SQL with additional release functionality

(strings: string | TemplateStringsArray, values: any[]) => SQLQuery;

interfaceBun.ResourceUsage

contextSwitches:
{

involuntary: number

Involuntary context switches (context switches initiated by the system scheduler).

voluntary: number

Voluntary context switches (context switches that the process initiated).

}

The number of voluntary and involuntary context switches that the process made.

cpuTime:
{

system: number

System CPU time used by the process, in microseconds.

total: number

Total CPU time used by the process, in microseconds.

user: number

User CPU time used by the process, in microseconds.

}

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

The number of IPC messages received.

sent: number

The number of IPC messages sent.

}

IPC messages sent and received by the process.

ops:
{

in: number

The number of input operations via the file system.

out: number

The number of output operations via the file system.

}

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.

namespaceBun.RouterTypes

typeExtractRouteParams<T>=T extends `${string}:${Param}/${Rest}` ? { [K in Param]: string} & ExtractRouteParams<Rest> : T extends `${string}:${Param}` ? { [K in Param]: string} : T extends `${string}*` ? {} : {}

typeHTTPMethod='GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS'

typeRouteHandler<T extends string>=(req: BunRequest<T>, server: Server) => Response | Promise<Response>

typeRouteHandlerObject<T extends string>

typeRouteHandlerWithWebSocketUpgrade<T extends string>=(req: BunRequest<T>, server: Server) => Response | undefined | void | Promise<Response | undefined | void>

typeRouteValue<T extends string>=Response | false | RouteHandler<T> | RouteHandlerObject<T>

interfaceBun.S3FileextendsBlob

Represents a file in an S3-compatible storage service. Extends the Blob interface for compatibility with web APIs.

bucket: string

The bucket name containing the file.

name: string

The name or path of the file in the bucket.

readable: ReadableStream

Gets a readable stream of the file's content. Useful for processing large files without loading them entirely into memory.

Alias for delete() method. Provided for compatibility with Node.js fs API naming.

bytes(): Promise<Uint8Array<ArrayBufferLike>>

delete(): Promise<void>

Deletes the file from S3.

returns

Promise that resolves when deletion is complete

exists(): Promise<boolean>

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

formData(): Promise<FormData>

Read the data from the blob as a FormData object.

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

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

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

json(): Promise<any>

Read the data from the blob as a JSON object.

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

presign(options?: S3FilePresignOptions): string

Generates a presigned URL for the file. Allows temporary access to the file without exposing credentials.

options

Configuration for the presigned URL

returns

Presigned URL string

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.

begin

Starting byte offset

end

Ending byte offset (exclusive)

contentType

Optional MIME type for the slice

returns

A new S3File representing the specified range

stat(): Promise<S3Stats>

Get the stat of a file in an S3-compatible storage service.

returns

Promise resolving to S3Stat

text(): Promise<string>

write(data: string | ArrayBuffer | SharedArrayBuffer | Request | Response | Blob | BunFile | ArrayBufferView<ArrayBufferLike> | S3File, options?: S3Options): Promise<number>

Uploads data to S3. Supports various input types and automatically handles large files.

data

The data to upload

options

Upload configuration options

returns

Promise resolving to number of bytes written

writer(options?: S3Options): NetworkSink

Creates a writable stream for uploading data. Suitable for large files as it uses multipart upload.

options

Configuration for the upload

returns

A NetworkSink for writing data

interfaceBun.S3FilePresignOptionsextendsS3Options

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.

bucket: string

The S3 bucket name. Defaults to S3_BUCKET or AWS_BUCKET environment variables.

endings: EndingType

endpoint: string

The S3-compatible service endpoint URL. Defaults to S3_ENDPOINT or AWS_ENDPOINT environment variables.

expiresIn: number

Number of seconds until the presigned URL expires.

  • Default: 86400 (1 day)

method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD'

The HTTP method allowed for the presigned URL.

partSize: number

The size of each part in multipart uploads (in bytes).

  • Minimum: 5 MiB
  • Maximum: 5120 MiB
  • Default: 5 MiB

queueSize: number

Number of parts to upload in parallel for multipart uploads.

  • Default: 5
  • Maximum: 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.

retry: number

Number of retry attempts for failed uploads.

  • Default: 3
  • Maximum: 255

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.

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.

type: string

The Content-Type of the file. Automatically set based on file extension when possible.

virtualHostedStyle: boolean

Use virtual hosted style endpoint. default to false, when true if endpoint is informed it will ignore the bucket

interfaceBun.S3ListObjectsOptions

continuationToken: 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.

interfaceBun.S3ListObjectsResponse

commonPrefixes:
{

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'

The algorithm that was used to create a checksum of the object.

checksumType: 'COMPOSITE' | 'FULL_OBJECT'

The checksum type that is used to calculate the object's checksum value.

eTag: string

The entity tag is a hash of the object. The ETag reflects changes only to the contents of an object, not its metadata. The ETag may or may not be an MD5 digest of the object data. Whether or not it is depends on how the object was created and how it is encrypted as described below:

  • Objects created by the PUT Object, POST Object, or Copy operation, or through the AWS Management Console, and are encrypted by SSE-S3 or plaintext, have ETags that are an MD5 digest of their object data.
  • Objects created by the PUT Object, POST Object, or Copy operation, or through the AWS Management Console, and are encrypted by SSE-C or SSE-KMS, have ETags that are not an MD5 digest of their object data.
  • If an object is created by either the Multipart Upload or Part Copy operation, the ETag is not an MD5 digest, regardless of the method of encryption. If an object is larger than 16 MB, the AWS Management Console will upload or copy that object as a Multipart Upload, and therefore the ETag will not be an MD5 digest.

MD5 is not supported by directory buckets.

key: string

The name that you assign to an object. You use the object key to retrieve the object.

lastModified: string

Creation date of the object.

owner:
{

displayName: string

The display name of the owner.

id: string

The ID of the owner.

}

The owner of the object

restoreStatus:
{

isRestoreInProgress: boolean

Specifies whether the object is currently being restored.

restoreExpiryDate: string

Indicates when the restored copy will expire. This value is populated only if the object has already been restored.

}

Specifies the restoration status of an object. Objects in certain storage classes must be restored before they can be retrieved.

size: number

Size in bytes of the object

storageClass: 'STANDARD' | 'DEEP_ARCHIVE' | 'EXPRESS_ONEZONE' | 'GLACIER' | 'GLACIER_IR' | 'INTELLIGENT_TIERING' | 'ONEZONE_IA' | 'OUTPOSTS' | 'REDUCED_REDUNDANCY' | 'SNOW' | 'STANDARD_IA'

The class of storage used to store the object.

}
[]

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.

interfaceBun.S3OptionsextendsBlobPropertyBag

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.

bucket: string

The S3 bucket name. Defaults to S3_BUCKET or AWS_BUCKET environment variables.

endings: EndingType

endpoint: string

The S3-compatible service endpoint URL. Defaults to S3_ENDPOINT or AWS_ENDPOINT environment variables.

partSize: number

The size of each part in multipart uploads (in bytes).

  • Minimum: 5 MiB
  • Maximum: 5120 MiB
  • Default: 5 MiB

queueSize: number

Number of parts to upload in parallel for multipart uploads.

  • Default: 5
  • Maximum: 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.

retry: number

Number of retry attempts for failed uploads.

  • Default: 3
  • Maximum: 255

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.

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.

type: string

The Content-Type of the file. Automatically set based on file extension when possible.

virtualHostedStyle: boolean

Use virtual hosted style endpoint. default to false, when true if endpoint is informed it will ignore the bucket

interfaceBun.S3Stats

etag: string

size: number

type: string

interfaceBun.SavepointSQLextendsSQL

Represents a savepoint within a transaction

(strings: string | TemplateStringsArray, values: any[]) => SQLQuery;

typeBun.Serve<WebSocketDataType=undefined>=ServeOptions | TLSServeOptions | UnixServeOptions | UnixTLSServeOptions | WebSocketServeOptions<WebSocketDataType> | TLSWebSocketServeOptions<WebSocketDataType> | UnixWebSocketServeOptions<WebSocketDataType> | UnixTLSWebSocketServeOptions<WebSocketDataType>

The type of options that can be passed to serve

typeBun.ServeFunctionOptions<T, R extends { [K in keyof R]: RouterTypes.RouteValue<Extract<K, string>>}>
=DistributedOmit<Exclude<Serve<T>, WebSocketServeOptions<T>>, 'fetch'> &
{

fetch: (this: Server, request: Request, server: Server) => Response | Promise<Response>

routes: R

}
| DistributedOmit<Exclude<Serve<T>, WebSocketServeOptions<T>>, 'routes'> &
{

fetch: (this: Server, request: Request, server: Server) => Response | Promise<Response>

routes: never

}
| Omit<WebSocketServeOptions<T>, 'fetch'> &
{

fetch: (this: Server, request: Request, server: Server) => Response | Promise<Response | void | undefined> | void | undefined

routes: { [K in keyof R]: RouterTypes.RouteValueWithWebSocketUpgrade<Extract<K, string>>}

}
| Omit<WebSocketServeOptions<T>, 'fetch'> &
{

fetch: (this: Server, request: Request, server: Server) => Response | Promise<Response | void | undefined> | void | undefined

routes: never

}

The type of options that can be passed to serve, with support for routes and a safer requirement for fetch

interfaceBun.ServeOptionsextendsGenericServeOptions

development: boolean |
{

hmr: boolean

Enable Hot Module Replacement for routes (including React Fast Refresh, if React is in use)

}

Render contextual errors? This enables bun's error page

error: (this: Server, error: ErrorLike) => void | Promise<void> | Response | Promise<Response>

hostname: string

What hostname should the server listen on?

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 the number of seconds to wait before timing out a connection due to inactivity.

Default is 10 seconds.

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.

unix: undefined

If set, the HTTP server will listen on a unix socket instead of a port. (Cannot be used with hostname+port)

fetch(this: Server, request: Request, server: Server): Response | Promise<Response>

Handle HTTP requests

Respond to Request objects with a Response object.

interfaceBun.ServerextendsDisposable

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.

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.

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.

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.

pendingRequests: number

How many requests are in-flight right now?

pendingWebSockets: number

How many ServerWebSockets are in-flight right now?

port: undefined | number

The port the server is listening on.

This will be undefined when the server is listening on a unix socket.

fetch(request: string | Request): Response | Promise<Response>

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 | ArrayBufferView<ArrayBufferLike>, compress?: boolean): number

Send a message to all connected ServerWebSocket subscribed to a topic

topic

The topic to publish to

data

The data to send

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.

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.

reload<T, R extends { [K in string | number | symbol]: RouteValue<K & string>}>(options: ServeFunctionOptions<T, R> &
{

static: R

}
): Server

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.

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.

stop(closeActiveConnections?: boolean): Promise<void>

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.

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.

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.

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<T=undefined>(request: Request, options?:
{

data: T

This value is passed to the ServerWebSocket.data property

headers: HeadersInit

Send any additional headers while upgrading, like cookies

}
): boolean

Upgrade a Request to a ServerWebSocket

request

The Request to upgrade

options

Pass headers or attach data to the ServerWebSocket

returns

true if the upgrade was successful and false if it failed

interfaceBun.ServerWebSocket<T=undefined>

A fast WebSocket designed for servers.

Features:

  • Message compression - Messages can be compressed
  • Backpressure - 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.

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.

data: T

Custom data that you can assign to a client, can be read and written at any time.

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.

remoteAddress: string

The IP address of the client.

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 rejected
  • 1011 means the server encountered an error
  • 1012 means the server is restarting
  • 1013 means the server is too busy or the client is rate-limited
  • 4000 through 4999 are reserved for applications (you can use it!)

To close the connection abruptly, use terminate().

code

The close code to send

reason

The close reason to send

cork<T=unknown>(callback: (ws: ServerWebSocket<T>) => 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.

callback

The callback to run.

isSubscribed(topic: string): boolean

Is the client subscribed to a topic?

topic

The topic name.

ping(data?: string | BufferSource): number

Sends a ping.

data

The data to send

pong(data?: string | BufferSource): number

Sends a pong.

data

The data to send

publish(topic: string, data: string | BufferSource, compress?: boolean): number

Sends a message to subscribers of the topic.

topic

The topic name.

data

The data to send.

compress

Should the data be compressed? If the client does not support compression, this is ignored.

publishBinary(topic: string, data: BufferSource, compress?: boolean): number

Sends a binary message to subscribers of the topic.

topic

The topic name.

data

The data to send.

compress

Should the data be compressed? If the client does not support compression, this is ignored.

publishText(topic: string, data: string, compress?: boolean): number

Sends a text message to subscribers of the topic.

topic

The topic name.

data

The data to send.

compress

Should the data be compressed? If the client does not support compression, this is ignored.

send(data: string | BufferSource, compress?: boolean): number

Sends a message to the client.

data

The data to send.

compress

Should the data be compressed? If the client does not support compression, this is ignored.

sendBinary(data: BufferSource, compress?: boolean): number

Sends a binary message to the client.

data

The data to send.

compress

Should the data be compressed? If the client does not support compression, this is ignored.

sendText(data: string, compress?: boolean): number

Sends a text message to the client.

data

The data to send.

compress

Should the data be compressed? If the client does not support compression, this is ignored.

subscribe(topic: string): void

Subscribes a client to the topic.

topic

The topic name.

terminate(): void

Abruptly close the connection.

To gracefully close the connection, use close().

unsubscribe(topic: string): void

Unsubscribes a client to the topic.

topic

The topic name.

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

typeBun.ShellExpression
=
{

toString(): string

}
| ShellExpression[] | string |
{

raw: string

}
| Subprocess | SpawnOptions.Readable | SpawnOptions.Writable | ReadableStream

typeBun.SignalsListener=(signal: NodeJS.Signals) => void

interfaceBun.Socket<Data=undefined>extendsDisposable

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.

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.

bytesWritten: number

The number of bytes written to the socket.

data: Data

The data context for the socket.

listener: SocketListener<undefined>

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.

localAddress: string

localFamily: 'IPv4' | 'IPv6'

localPort: number

local port connected to the socket

readyState: 'open' | 'closed' | 'closing'

remoteAddress: string

Remote IP address connected to the socket

remoteFamily: 'IPv4' | 'IPv6'

remotePort: number

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

Like Socket.write except it includes a TCP FIN packet

Use it to send your last message and close the connection.

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:
 <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
    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>

length

number of bytes to retrieve from keying material

label
context

Optionally provide a context.

returns

requested bytes of the keying material

flush(): void

Flush any buffered data to the socket

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

getSharedSigalgs(): string[]

returns

List of signature algorithms shared between the server and the client in the order of decreasing preference.

getTLSFinishedMessage(): undefined | Buffer<ArrayBufferLike>

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

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

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.

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(handler: SocketHandler): 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.

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

enable

Default: false

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.

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

noDelay

Default: true

returns

true if is able to setNoDelay and false if it fails.

shutdown(halfClose?: boolean): void

Shutdown writes to a socket

This makes the socket a half-closed socket. It can still receive data.

This calls shutdown(2) internally

terminate(): void

Forcefully close the socket. The other end may not receive all data, and the socket will be closed immediately.

This passes SO_LINGER with l_onoff set to 1 and l_linger set to 0 and then calls close(2).

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.

write(data: string | BufferSource, byteOffset?: number, byteLength?: number): number

Write data to the socket

data

The data to write to the socket

byteOffset

The offset in the buffer to start writing from (defaults to 0)

byteLength

The number of bytes to write (defaults to the length of the buffer)

When passed a string, byteOffset and byteLength refer to the UTF-8 offset, not the string character offset.

This is unbuffered as of Bun v0.2.2. That means individual write() calls will be slow. In the future, Bun will buffer writes and flush them at the end of the tick, when the event loop is idle, or sooner if the buffer is full.

interfaceBun.SocketAddress

address: string

The IP address of the client.

family: 'IPv4' | 'IPv6'

The IP family ("IPv4" or "IPv6").

port: number

The port of the client.

interfaceBun.SocketHandler<Data=unknown, DataBinaryType extends BinaryType='buffer'>

binaryType: unknown

Choose what ArrayBufferView is returned in the SocketHandler.data callback.

close(socket: Socket<Data>, error?: Error): void | Promise<void>

connectError(socket: Socket<Data>, error: Error): void | Promise<void>

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: Socket<Data>, data: BinaryTypeList[DataBinaryType]): void | Promise<void>

drain(socket: Socket<Data>): void | Promise<void>

end(socket: Socket<Data>): void | Promise<void>

When the socket has been shutdown from the other end, this function is called. This is a TCP FIN packet.

error(socket: Socket<Data>, error: Error): void | Promise<void>

handshake(socket: Socket<Data>, success: boolean, authorizationError: null | Error): void

When handshake is completed, this functions is called.

success

Indicates if the server authorized despite the authorizationError.

authorizationError

Certificate Authorization Error or null.

open(socket: Socket<Data>): void | Promise<void>

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: Socket<Data>): void | Promise<void>

Called when a message times out.

interfaceBun.SocketListener<Data=undefined>extendsDisposable

ref(): void

reload(options: Pick<Partial<SocketOptions<unknown>>, 'socket'>): void

stop(closeActiveConnections?: boolean): void

unref(): void

interfaceBun.SocketOptions<Data=unknown>

data: Data

The per-instance data context

socket: SocketHandler<Data>

Handlers for socket events

namespaceBun.SpawnOptions

interfaceOptionsObject<In extends Writable=Writable, Out extends Readable=Readable, Err extends Readable=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()

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

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

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 process
  • ArrayBufferView: 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 process
  • ArrayBufferView, Blob: The process will read from the buffer
  • number: The process will read from the file descriptor

stdio: [In, Out, Err]

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 process
  • ArrayBufferView, 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 process
  • ArrayBufferView: 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 process
  • ArrayBufferView: 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).

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: Subprocess<In, Out, Err>): 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 recieve 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.

subprocess

The Subprocess that sent the message

onExit(subprocess: Subprocess<In, Out, Err>, exitCode: null | number, signalCode: null | number, error?: ErrorLike): void | Promise<void>

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.

error

If an error occurred in the call to waitpid2, this will be the error.

typeOptionsToSubprocess<Opts extends OptionsObject>=Opts extends OptionsObject<In, Out, Err> ? Subprocess<Writable extends In ? 'ignore' : In, Readable extends Out ? 'pipe' : Out, Readable extends Err ? 'inherit' : Err> : Subprocess<Writable, Readable, Readable>

typeOptionsToSyncSubprocess<Opts extends OptionsObject>=Opts extends OptionsObject<any, Out, Err> ? SyncSubprocess<Readable extends Out ? 'pipe' : Out, Readable extends Err ? 'pipe' : Err> : SyncSubprocess<Readable, Readable>

typeReadable='pipe' | 'inherit' | 'ignore' | null | undefined | BunFile | ArrayBufferView | number

Option for stdout/stderr

typeReadableIO=ReadableStream<Uint8Array> | number | undefined

typeReadableToIO<X extends Readable>=X extends 'pipe' | undefined ? ReadableStream<Uint8Array> : X extends BunFile | ArrayBufferView | number ? number : undefined

typeReadableToSyncIO<X extends Readable>=X extends 'pipe' | undefined ? Buffer : undefined

typeWritable='pipe' | 'inherit' | 'ignore' | null | undefined | BunFile | ArrayBufferView | number | ReadableStream | Blob | Response | Request

Option for stdin

typeWritableIO=FileSink | number | undefined

typeWritableToIO<X extends Writable>=X extends 'pipe' ? FileSink : X extends BunFile | ArrayBufferView | Blob | Request | Response | number ? number : undefined

interfaceBun.SQL

Main SQL client interface providing connection and transaction management

(strings: string | TemplateStringsArray, values: any[]) => SQLQuery;

typeBun.SQLOptions

Configuration options for SQL client connection and behavior

interfaceBun.SQLQueryextendsPromise<any>

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

active: boolean

Indicates if the query is currently executing

cancelled: boolean

Indicates if the query has been cancelled

cancel(): SQLQuery

Cancels the executing query

catch<TResult=never>(onrejected?: null | (reason: any) => TResult | PromiseLike<TResult>): Promise<any>

Attaches a callback for only the rejection of the Promise.

onrejected

The callback to execute when the Promise is rejected.

returns

A Promise for the completion of the callback.

execute(): SQLQuery

Executes the query

finally(onfinally?: null | () => void): Promise<any>

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

onfinally

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

returns

A Promise for the completion of the callback.

raw(): SQLQuery

Returns the raw query result

simple(): SQLQuery

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

then<TResult1=any, TResult2=never>(onfulfilled?: null | (value: any) => TResult1 | PromiseLike<TResult1>, onrejected?: null | (reason: any) => TResult2 | PromiseLike<TResult2>): Promise<TResult1 | TResult2>

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

onfulfilled

The callback to execute when the Promise is resolved.

onrejected

The callback to execute when the Promise is rejected.

returns

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

values(): SQLQuery

Returns only the values from the query result

typeBun.SQLSavepointContextCallback=(sql: SavepointSQL) => Promise<any> | SQLQuery[]

Callback function type for savepoint contexts

typeBun.SQLTransactionContextCallback=(sql: TransactionSQL) => Promise<any> | SQLQuery[]

Callback function type for transaction contexts

typeBun.StringLike
=string |
{

toString(): string

}

typeBun.StringOrBuffer=string | NodeJS.TypedArray | ArrayBufferLike

interfaceBun.Subprocess<In extends SpawnOptions.Writable=SpawnOptions.Writable, Out extends SpawnOptions.Readable=SpawnOptions.Readable, Err extends SpawnOptions.Readable=SpawnOptions.Readable>extendsAsyncDisposable

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)

exitCode: null | number

Synchronously get the exit code of the process

If the process hasn't exited yet, this will return null

exited: Promise<number>

The exit code of the process

The promise will resolve when the process exits

killed: boolean

Has the process exited?

pid: number

The process ID of the child process

readable: ReadableToIO<Out>

This returns the same value as Subprocess.stdout

It exists for compatibility with ReadableStream.pipeThrough

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.

[Symbol.asyncDispose](): PromiseLike<void>

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

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.

typeBun.SupportedCryptoAlgorithms='blake2b256' | 'blake2b512' | 'md4' | 'md5' | 'ripemd160' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512' | 'sha512-224' | 'sha512-256' | 'sha3-224' | 'sha3-256' | 'sha3-384' | 'sha3-512' | 'shake128' | 'shake256'

interfaceBun.SyncSubprocess<Out 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: number

pid: number

resourceUsage: ResourceUsage

Get the resource usage information of the process (max RSS, CPU time, etc)

signalCode: string

success: boolean

interfaceBun.SystemErrorextendsError

cause: unknown

The cause of the error.

code: string

errno: number

message: string

name: string

path: string

stack: string

syscall: string

typeBun.Target='bun' | 'node' | 'browser'

interfaceBun.TCPSocketextendsSocket

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.

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.

bytesWritten: number

The number of bytes written to the socket.

data: undefined

The data context for the socket.

listener: SocketListener<undefined>

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.

localAddress: string

localFamily: 'IPv4' | 'IPv6'

localPort: number

local port connected to the socket

readyState: 'open' | 'closed' | 'closing'

remoteAddress: string

Remote IP address connected to the socket

remoteFamily: 'IPv4' | 'IPv6'

remotePort: number

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

Like Socket.write except it includes a TCP FIN packet

Use it to send your last message and close the connection.

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:
 <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
    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>

length

number of bytes to retrieve from keying material

label
context

Optionally provide a context.

returns

requested bytes of the keying material

flush(): void

Flush any buffered data to the socket

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

getSharedSigalgs(): string[]

returns

List of signature algorithms shared between the server and the client in the order of decreasing preference.

getTLSFinishedMessage(): undefined | Buffer<ArrayBufferLike>

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

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

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.

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(handler: SocketHandler): 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.

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

enable

Default: false

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.

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

noDelay

Default: true

returns

true if is able to setNoDelay and false if it fails.

shutdown(halfClose?: boolean): void

Shutdown writes to a socket

This makes the socket a half-closed socket. It can still receive data.

This calls shutdown(2) internally

terminate(): void

Forcefully close the socket. The other end may not receive all data, and the socket will be closed immediately.

This passes SO_LINGER with l_onoff set to 1 and l_linger set to 0 and then calls close(2).

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.

write(data: string | BufferSource, byteOffset?: number, byteLength?: number): number

Write data to the socket

data

The data to write to the socket

byteOffset

The offset in the buffer to start writing from (defaults to 0)

byteLength

The number of bytes to write (defaults to the length of the buffer)

When passed a string, byteOffset and byteLength refer to the UTF-8 offset, not the string character offset.

This is unbuffered as of Bun v0.2.2. That means individual write() calls will be slow. In the future, Bun will buffer writes and flush them at the end of the tick, when the event loop is idle, or sooner if the buffer is full.

interfaceBun.TCPSocketConnectOptions<Data=undefined>extendsSocketOptions<Data>

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 end
  • The local side can continue sending data even after the remote side has closed
  • The 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 connect to

port: number

The port to connect to

socket: SocketHandler<Data>

Handlers for socket events

tls: boolean

TLS Configuration with which to create the socket

interfaceBun.TCPSocketListener<Data=unknown>extendsSocketListener<Data>

hostname: string

port: number

ref(): void

reload(options: Pick<Partial<SocketOptions<unknown>>, 'socket'>): void

stop(closeActiveConnections?: boolean): void

unref(): void

interfaceBun.TCPSocketListenOptions<Data=undefined>extendsSocketOptions<Data>

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 end
  • The local side can continue sending data even after the remote side has closed
  • The 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: SocketHandler<Data>

Handlers for socket events

tls: TLSOptions

The TLS configuration object with which to create the server

typeBun.TimerHandler=(args: any[]) => void

interfaceBun.TLSOptions

Options for TLS connections

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

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

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

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

dhParamsFile: string

File path to a .pem file custom Diffie Helman parameters

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

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

lowMemoryMode: boolean

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

passphrase: string

Passphrase for the TLS key

rejectUnauthorized: boolean

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

requestCert: boolean

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

Default is false.

secureOptions: number

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

serverName: string

Explicitly set a server name

interfaceBun.TLSSocketextendsSocket

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.

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.

bytesWritten: number

The number of bytes written to the socket.

data: undefined

The data context for the socket.

listener: SocketListener<undefined>

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.

localAddress: string

localFamily: 'IPv4' | 'IPv6'

localPort: number

local port connected to the socket

readyState: 'open' | 'closed' | 'closing'

remoteAddress: string

Remote IP address connected to the socket

remoteFamily: 'IPv4' | 'IPv6'

remotePort: number

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

Like Socket.write except it includes a TCP FIN packet

Use it to send your last message and close the connection.

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:
 <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
    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>

length

number of bytes to retrieve from keying material

label
context

Optionally provide a context.

returns

requested bytes of the keying material

flush(): void

Flush any buffered data to the socket

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

getSharedSigalgs(): string[]

returns

List of signature algorithms shared between the server and the client in the order of decreasing preference.

getTLSFinishedMessage(): undefined | Buffer<ArrayBufferLike>

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

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

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.

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(handler: SocketHandler): 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.

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

enable

Default: false

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.

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

noDelay

Default: true

returns

true if is able to setNoDelay and false if it fails.

shutdown(halfClose?: boolean): void

Shutdown writes to a socket

This makes the socket a half-closed socket. It can still receive data.

This calls shutdown(2) internally

terminate(): void

Forcefully close the socket. The other end may not receive all data, and the socket will be closed immediately.

This passes SO_LINGER with l_onoff set to 1 and l_linger set to 0 and then calls close(2).

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.

write(data: string | BufferSource, byteOffset?: number, byteLength?: number): number

Write data to the socket

data

The data to write to the socket

byteOffset

The offset in the buffer to start writing from (defaults to 0)

byteLength

The number of bytes to write (defaults to the length of the buffer)

When passed a string, byteOffset and byteLength refer to the UTF-8 offset, not the string character offset.

This is unbuffered as of Bun v0.2.2. That means individual write() calls will be slow. In the future, Bun will buffer writes and flush them at the end of the tick, when the event loop is idle, or sooner if the buffer is full.

interfaceBun.TransactionSQLextendsSQL

Represents a client within a transaction context Extends SQL with savepoint functionality

(strings: string | TemplateStringsArray, values: any[]) => SQLQuery;

interfaceBun.TransformerFlushCallback<O>

(controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;

interfaceBun.TransformerTransformCallback<I, O>

(chunk: I, controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;

interfaceBun.TranspilerOptions

autoImportJSX: boolean

deadCodeElimination: 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: Record<string, string>

Replace key with value. Value must be a JSON string.

exports:
{

eliminate: string[]

replace: Record<string, string>

}

inline: boolean

This does two things (and possibly more in the future):

  1. 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.
  2. 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!

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

minifyWhitespace: boolean

Experimental

Minify whitespace and comments from the output.

treeShaking: boolean

tsconfig: 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.

interfaceBun.TSConfig

tsconfig.json options supported by Bun

compilerOptions:
{

baseUrl: string

importsNotUsedAsValues: 'error' | 'preserve' | 'remove'

jsx: 'preserve' | 'react' | 'react-jsx' | 'react-jsxdev'

"preserve" is not supported yet

jsxFactory: string

jsxFragmentFactory: string

jsxImportSource: string

moduleSuffixes: any

moduleSuffixes is not supported yet

paths: Record<string, string[]>

useDefineForClassFields: boolean

}

extends: string

namespaceBun.udp

interfaceBaseUDPSocket

closed: boolean

hostname: string

port: number

close(): void

ref(): void

unref(): void

interfaceConnectedSocket<DataBinaryType extends BinaryType>extendsBaseUDPSocket

closed: boolean

hostname: string

port: number

close(): void

ref(): void

reload(handler: ConnectedSocketHandler<DataBinaryType>): void

send(data: Data): boolean

sendMany(packets: readonly Data[]): number

unref(): void

interfaceConnectedSocketHandler<DataBinaryType extends BinaryType>

data(socket: ConnectedSocket<DataBinaryType>, data: BinaryTypeList[DataBinaryType], port: number, address: string): void | Promise<void>

drain(socket: ConnectedSocket<DataBinaryType>): void | Promise<void>

error(socket: ConnectedSocket<DataBinaryType>, error: Error): void | Promise<void>

interfaceConnectSocketOptions<DataBinaryType extends BinaryType>

interfaceSocket<DataBinaryType extends BinaryType>extendsBaseUDPSocket

closed: boolean

hostname: string

port: number

close(): void

ref(): void

reload(handler: SocketHandler<DataBinaryType>): void

send(data: Data, port: number, address: string): boolean

sendMany(packets: readonly number | Data[]): number

unref(): void

interfaceSocketHandler<DataBinaryType extends BinaryType>

data(socket: Socket<DataBinaryType>, data: BinaryTypeList[DataBinaryType], port: number, address: string): void | Promise<void>

drain(socket: Socket<DataBinaryType>): void | Promise<void>

error(socket: Socket<DataBinaryType>, error: Error): void | Promise<void>

typeData=string | ArrayBufferView | ArrayBufferLike

typeBun.UncaughtExceptionOrigin='uncaughtException' | 'unhandledRejection'

interfaceBun.UnderlyingSinkAbortCallback

(reason?: any) => void | PromiseLike<void>;

interfaceBun.UnderlyingSinkCloseCallback

() => void | PromiseLike<void>;

interfaceBun.UnderlyingSinkWriteCallback<W>

(chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike<void>;

interfaceBun.UnderlyingSourceCancelCallback

(reason?: any) => void | PromiseLike<void>;

interfaceBun.UnderlyingSourcePullCallback<R>

(controller: ReadableStreamController<R>) => void | PromiseLike<void>;

typeBun.UnhandledRejectionListener=(reason: unknown, promise: Promise<unknown>) => void

Most of the time the unhandledRejection will be an Error, but this should not be relied upon as anything can be thrown/rejected, it is therefore unsafe to assume that the value is an Error.

interfaceBun.UnixServeOptionsextendsGenericServeOptions

development: boolean |
{

hmr: boolean

Enable Hot Module Replacement for routes (including React Fast Refresh, if React is in use)

}

Render contextual errors? This enables bun's error page

error: (this: Server, error: ErrorLike) => void | Promise<void> | Response | Promise<Response>

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)

unix: string

If set, the HTTP server will listen on a unix socket instead of a port. (Cannot be used with hostname+port)

fetch(this: Server, request: Request, server: Server): Response | Promise<Response>

Handle HTTP requests

Respond to Request objects with a Response object.

interfaceBun.UnixSocketListener<Data>extendsSocketListener<Data>

unix: string

ref(): void

reload(options: Pick<Partial<SocketOptions<unknown>>, 'socket'>): void

stop(closeActiveConnections?: boolean): void

unref(): void

interfaceBun.UnixSocketOptions<Data=undefined>extendsSocketOptions<Data>

data: Data

The per-instance data context

socket: SocketHandler<Data>

Handlers for socket events

tls: TLSOptions

TLS Configuration with which to create the socket

unix: string

The unix socket to listen on or connect to

interfaceBun.UnixWebSocketServeOptions<WebSocketDataType=undefined>extendsGenericServeOptions

development: boolean |
{

hmr: boolean

Enable Hot Module Replacement for routes (including React Fast Refresh, if React is in use)

}

Render contextual errors? This enables bun's error page

error: (this: Server, error: ErrorLike) => void | Promise<void> | Response | Promise<Response>

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)

unix: string

If set, the HTTP server will listen on a unix socket instead of a port. (Cannot be used with hostname+port)

websocket: WebSocketHandler<WebSocketDataType>

Enable websockets with Bun.serve

For simpler type safety, see Bun.websocket

fetch(this: Server, request: Request, server: Server): undefined | Response | Promise<undefined | Response>

Handle HTTP requests or upgrade them to a ServerWebSocket

Respond to Request objects with a Response object.

interfaceBun.Unsafe

arrayBufferToString(buffer: ArrayBufferLike | Uint8Array<ArrayBufferLike>): 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.

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

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

  • 0: default, disable
  • 1: asynchronously call the garbage collector more often
  • 2: 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

mimallocDump(): void

Dump the mimalloc heap to the console

typeBun.WarningListener=(warning: Error) => void

namespaceBun.WebAssembly

interfaceCompileErrorextendsError

cause: unknown

The cause of the error.

message: string

name: string

stack: string

interfaceGlobalDescriptor<T extends ValueType=ValueType>

mutable: boolean

interfaceLinkErrorextendsError

cause: unknown

The cause of the error.

message: string

name: string

stack: string

interfaceMemoryDescriptor

initial: number

maximum: number

shared: boolean

interfaceRuntimeErrorextendsError

cause: unknown

The cause of the error.

message: string

name: string

stack: string

interfaceTable

get(index: number): any

grow(delta: number, value?: any): number

set(index: number, value?: any): void

interfaceValueTypeMap

anyfunc: Function

f32: number

f64: number

i32: number

i64: bigint

v128: never

typeExports=Record<string, ExportValue>

typeImportExportKind='function' | 'global' | 'memory' | 'table'

typeImports=Record<string, ModuleImports>

typeModuleImports=Record<string, ImportValue>

typeTableKind='anyfunc' | 'externref'

typeBun.WebSocketCompressor='disable' | 'shared' | 'dedicated' | '3KB' | '4KB' | '8KB' | '16KB' | '32KB' | '64KB' | '128KB' | '256KB'

Compression options for WebSocket messages.

interfaceBun.WebSocketHandler<T=undefined>

Create a server-side ServerWebSocket handler for use with Bun.serve

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.

Default is false.

idleTimeout: number

Sets the the number of seconds to wait before timing out a connection due to no messages or pings.

Default is 2 minutes, or 120 in seconds.

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

Sets the compression level.

decompress: boolean | WebSocketCompressor

Sets the decompression level.

}

Sets the compression level for messages, for clients that supports it. By default, compression is disabled.

Default is false.

publishToSelf: boolean

Should ws.publish() also send a message to ws (itself), if it is subscribed?

Default is false.

sendPings: boolean

Should the server automatically send and respond to pings to clients?

Default is true.

close(ws: ServerWebSocket<T>, code: number, reason: string): void | Promise<void>

Called when a connection is closed.

ws

The websocket that was closed

code

The close code

reason

The close reason

drain(ws: ServerWebSocket<T>): void | Promise<void>

Called when a connection was previously under backpressure, meaning it had too many queued messages, but is now ready to receive more data.

ws

The websocket that is ready for more data

message(ws: ServerWebSocket<T>, message: string | Buffer<ArrayBufferLike>): void | Promise<void>

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

The websocket that sent the message

message

The message received

open(ws: ServerWebSocket<T>): void | Promise<void>

Called when a connection is opened.

ws

The websocket that was opened

ping(ws: ServerWebSocket<T>, data: Buffer): void | Promise<void>

Called when a ping is sent.

ws

The websocket that received the ping

data

The data sent with the ping

pong(ws: ServerWebSocket<T>, data: Buffer): void | Promise<void>

Called when a pong is received.

ws

The websocket that received the ping

data

The data sent with the ping

typeBun.WebSocketOptionsProtocolsOrProtocol
=
{

protocols: string | string[]

Protocols to use for the WebSocket connection

}
|
{

protocol: string

Protocol to use for the WebSocket connection

}

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

interfaceBun.WebSocketServeOptions<WebSocketDataType=undefined>extendsGenericServeOptions

development: boolean |
{

hmr: boolean

Enable Hot Module Replacement for routes (including React Fast Refresh, if React is in use)

}

Render contextual errors? This enables bun's error page

error: (this: Server, error: ErrorLike) => void | Promise<void> | Response | Promise<Response>

hostname: string

What hostname should the server listen on?

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)

port: string | number

What port should the server listen on?

websocket: WebSocketHandler<WebSocketDataType>

Enable websockets with Bun.serve

For simpler type safety, see Bun.websocket

fetch(this: Server, request: Request, server: Server): undefined | void | Response | Promise<undefined | void | Response>

Handle HTTP requests or upgrade them to a ServerWebSocket

Respond to Request objects with a Response object.

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

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

name: string

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

preload: string | string[]

An array of module specifiers to preload in the worker.

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

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

ref: boolean

When true, the worker will keep the parent thread alive until the worker is terminated or unref'd. When false, the worker will not keep the parent thread alive.

By default, this is false.

smol: boolean

Use less memory, but make the worker slower.

Internally, this sets the heap size configuration in JavaScriptCore to be the small heap instead of the large heap.

type: WorkerType

In Bun, this does nothing.

typeBun.WorkerType='classic' | 'module'

typeBun.WritableSubprocess=Subprocess<'pipe', any, any>

Utility type for any process from () with stdin set to "pipe"

interfaceBun.ZlibCompressionOptions

Compression options for Bun.deflateSync and Bun.gzipSync

level: 0 | 2 | 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -1

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 compression
  • A value of 1 gives least compression, fastest speed
  • A value of 9 gives best compression, slowest speed

library: 'zlib'

memLevel: 2 | 1 | 3 | 4 | 5 | 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 predictor
  • Z_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.