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.
Functions 49
- Bun.$()
Runs a shell command with the Bun Shell.
- Bun.allocUnsafe()
Allocate a new
Uint8Arraywithout zeroing the bytes. - Bun.build()
Bundles JavaScript, TypeScript, CSS, HTML and other supported files into optimized outputs.
- Bun.color()
Converts a color to a different format
- Bun.concatArrayBuffers()
Concatenate an array of typed arrays into a single
ArrayBuffer. - Bun.connect()
Create a TCP client that connects to a server
- Bun.deepEquals()
Fast deep-equality check two objects.
- Bun.deepMatch()
Returns true if all properties in the subset exist in the other and have equal values.
- Bun.deflateSync()
Compresses a chunk of data with the
zlibDEFLATE algorithm. - Bun.escapeHTML()
Escape the following characters in a string.
- Bun.file()
Blobpowered by the fastest system calls available for operating on files. - Bun.fileURLToPath()
Convert a URL to a filesystem path.
- Bun.gc()
Manually trigger the garbage collector
- Bun.generateHeapSnapshot()
Generates a heap snapshot in JavaScriptCore's format.
- Bun.gunzipSync()
Decompresses a chunk of data with the
zlibGUNZIP algorithm. - Bun.gzipSync()
Compresses a chunk of data with the
zlibGZIP algorithm. - Bun.indexOfLine()
Find the index of a newline character in potentially ill-formed UTF-8 text.
- Bun.inflateSync()
Decompresses a chunk of data with the
zlibINFLATE algorithm. - Bun.inspect()
Pretty-prints an object to a
string, the same as console.log - Bun.listen()
Create a TCP server that listens on a port
- Bun.mmap()
Open a file as a live-updating
Uint8Arraywithout copying memory - Bun.nanoseconds()
Returns the number of nanoseconds since the process was started, measured with a high-resolution monotonic system timer.
- Bun.openInEditor()
Open a file in your local editor.
- Bun.pathToFileURL()
Convert a filesystem path to a file:// URL.
- Bun.peek()
Extract the value from the Promise in the same tick of the event loop
- Bun.randomUUIDv5()
Generate a UUIDv5, a name-based UUID derived from the SHA-1 hash of a namespace UUID and a name.
- Bun.randomUUIDv7()
Generate a UUIDv7, a sequential ID based on the current timestamp with a random component.
- Bun.readableStreamToArray()
Consume all data from a ReadableStream until it closes or errors.
- Bun.readableStreamToArrayBuffer()
Consume all data from a ReadableStream until it closes or errors, concatenating the chunks into a single ArrayBuffer.
- Bun.readableStreamToFormData()
Consume all data from a ReadableStream until it closes or errors.
- Bun.resolve()
Resolve a
moduleIdas though it were imported fromparent - Bun.resolveSync()
Synchronously resolve a
moduleIdas though it were imported fromparent - Bun.serve()
Bun.serve starts a high-performance HTTP server with built-in routing.
- Bun.sha()
Hash
inputusing SHA-2 512/256 - Bun.sleep()
Returns a
Promisethat resolves after the given number of milliseconds, or at the given Date. - Bun.sleepSync()
Block the thread for a given number of milliseconds.
- Bun.sliceAnsi()
Slice a string by visible column width, preserving ANSI escape codes.
- Bun.spawn()
Spawn a new process
- Bun.spawnSync()
Synchronously spawn a new process
- Bun.stringWidth()
Get the column count of a string as it would be displayed in a terminal.
- Bun.stripANSI()
Remove ANSI escape codes from a string.
- Bun.udpSocket()
Create a UDP socket
- Bun.which()
Find the path to an executable, like the
whichcommand in your terminal. - Bun.wrapAnsi()
Wrap a string to fit within the specified column width, preserving ANSI escape codes.
- Bun.write()
Use the fastest syscalls available to copy from
inputintodestination. - Bun.zstdCompress()
Compresses a chunk of data with the Zstandard (zstd) compression algorithm.
- Bun.zstdCompressSync()
Compresses a chunk of data with the Zstandard (zstd) compression algorithm.
- Bun.zstdDecompress()
Decompresses a chunk of data with the Zstandard (zstd) decompression algorithm.
- Bun.zstdDecompressSync()
Decompresses a chunk of data with the Zstandard (zstd) decompression algorithm.
Classes 26
- class Bun.Archive
Create and extract tar archives, with optional gzip compression.
- class Bun.ArrayBufferSink
Fast incremental writer that becomes an ArrayBuffer on end().
- class Bun.Cookie
A single HTTP cookie: its name, value, and attributes.
- class Bun.CookieMap
A Map-like collection of cookies.
- class Bun.CryptoHasher
Hardware-accelerated cryptographic hash functions
- class Bun.CryptoHashInterface
This class only exists in types
- class Bun.EventSource
EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.
- class Bun.FileSystemRouter
Resolve routes against a directory of files using Next.js-style (
pagesdirectory) conventions. - class Bun.Glob
Match files using glob patterns).
- class Bun.Image
Decode, transform and re-encode images.
- class Bun.MD4
This class only exists in types
- class Bun.MD5
This class only exists in types
- class Bun.RedisClient
- class Bun.S3Client
A configured S3 bucket instance for managing files.
- class Bun.SHA1
This is not the default because it's not cryptographically secure and it's slower than SHA512
- class Bun.SHA224
This class only exists in types
- class Bun.SHA256
This class only exists in types
- class Bun.SHA384
This class only exists in types
- class Bun.SHA512
This class only exists in types
- class Bun.SHA512_256
See also sha
- class Bun.SQL
SQL client.
- class Bun.Terminal
A pseudo-terminal (PTY) for spawning interactive terminal programs.
- class Bun.Transpiler
Quickly transpile TypeScript, JSX, or JS to modern JavaScript.
- class Bun.WebSocket
A WebSocket client implementation
- class Bun.WebView
A headless browser view for automation.
- class Bun.Worker
EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.
Interfaces 118
- interface AbstractWorker
- interface AbstractWorkerEventMap
- interface AddEventListenerOptions
- interface ArchiveExtractOptions
Options for extracting archive contents.
- interface ArchiveOptions
Options for creating an Archive instance.
- interface BinaryTypeList
- interface BuildArtifact
A file generated by the bundler.
- interface BuildConfig
- interface BuildMetafile
Build metadata: every input and output file, its size, and the imports between them.
- interface BuildOutput
The output of a build
- interface BunFile
Blobpowered by the fastest system calls available for operating on files. - interface BunInspectOptions
Options for
Bun.inspect - interface BunMessageEvent
A message received by a target object.
- interface BunPlugin
A Bun plugin.
- interface BunRegisterPlugin
Extend Bun's module resolution and loading behavior
- interface BunRequest
This Fetch API interface represents a resource request.
- interface CloseEventInit
- interface CompileBuildOptions
- interface CookieInit
- interface CookieStoreDeleteOptions
- interface CookieStoreGetOptions
- interface CronController
Controller object passed to the
scheduled()handler when a cron job fires. - interface CronJob
A handle to an in-process cron job returned by Bun.cron when called with a callback.
- interface CronOptions
Options for the in-process Bun.cron callback overload and Bun.cron.parse.
- interface CSRFGenerateOptions
- interface CSRFVerifyOptions
- interface CustomEventInit
- interface DirectUnderlyingSource
- interface DNSLookup
- interface EditorOptions
- interface Env
- interface ErrorEventInit
- interface ErrorLike
- interface EventInit
- interface EventListener
- interface EventListenerObject
- interface EventListenerOptions
- interface EventMap
- interface EventSourceEventMap
- interface FdSocketOptions
- interface FetchEvent
An event which takes place in the DOM.
- interface FileBlob
Blobpowered by the fastest system calls available for operating on files. - interface FileSink
Fast incremental writer for files and pipes.
- interface GenericTransformStream
- interface GlobScanOptions
- interface Hash
- interface HeapSnapshot
JavaScriptCore engine's internal heap snapshot format
- interface HTMLBundle
The result of importing an HTML file, at runtime or at build time.
- interface Import
- interface LibdeflateCompressionOptions
- interface MatchedRoute
- interface MessageEventInit
- interface MMapOptions
- interface NetworkSink
Fast incremental writer for files and pipes.
- interface OnLoadArgs
- interface OnLoadResultObject
- interface OnLoadResultSourceCode
- interface OnResolveArgs
- interface OnResolveResult
- interface PluginBuilder
The builder object passed to
Bun.plugin - interface PluginConstraints
- interface ReadableStreamDefaultReadManyResult
- interface RedisOptions
- interface ReservedSQL
A connection reserved from the pool with SQL.reserve.
- interface ResourceUsage
- interface S3File
Represents a file in an S3-compatible storage service.
- interface S3FilePresignOptions
Options for generating presigned URLs
- interface S3ListObjectsOptions
- interface S3ListObjectsResponse
- interface S3Options
Configuration options for S3 operations
- interface S3Stats
- interface SavepointSQL
The client passed to TransactionSQL.savepoint callbacks; queries run within that savepoint
- interface Server
HTTP & HTTPS Server
- interface ServerWebSocket
A fast WebSocket designed for servers.
- interface SliceAnsiOptions
- interface Socket
A TCP or TLS socket connection.
- interface SocketAddress
- interface SocketHandler
- interface SocketListener
- interface SocketOptions
- interface SQLArrayParameter
An array parameter created by SQL.array
- interface StringWidthOptions
- interface StructuredSerializeOptions
- interface Subprocess
A process created by Bun.spawn.
- interface SyncSubprocess
A process created by Bun.spawnSync.
- interface SystemError
An
Errorfrom a failed system call, with optionalerrno,code, - interface TCPSocket
A TCP or TLS socket connection.
- interface TCPSocketConnectOptions
- interface TCPSocketListener
- interface TCPSocketListenOptions
- interface TerminalOptions
Options for creating a pseudo-terminal (PTY).
- interface TLSOptions
Options for TLS connections
- interface TLSSocket
A TCP or TLS socket connection.
- interface TLSUpgradeOptions
- interface TransactionSQL
The client passed to transaction callbacks (SQL.begin,
- interface TransformerFlushCallback
- interface TransformerStartCallback
- interface TransformerTransformCallback
- interface TranspilerOptions
- interface TSConfig
tsconfig.json options supported by Bun
- interface UnderlyingSink
- interface UnderlyingSinkAbortCallback
- interface UnderlyingSinkCloseCallback
- interface UnderlyingSinkStartCallback
- interface UnderlyingSinkWriteCallback
- interface UnderlyingSource
- interface UnderlyingSourceCancelCallback
- interface UnderlyingSourcePullCallback
- interface UnderlyingSourceStartCallback
- interface UnixSocketListener
- interface UnixSocketOptions
- interface WebSocketEventMap
- interface WebSocketHandler
Server-side ServerWebSocket event handlers for Bun.serve
- interface WhichOptions
- interface WorkerEventMap
- interface WorkerOptions
Bun's Web Worker constructor supports some extra options on top of the API browsers have.
- interface WrapAnsiOptions
- interface ZlibCompressionOptions
Compression options for
Bun.deflateSyncandBun.gzipSync
Types 79
- type $
- type ArchiveCompression
Compression format for archive output.
- type ArchiveInput
Input data for creating an archive.
- type ArrayBufferView
- type ArrayType
- type BeforeExitListener
- type BinaryType
- type BlobOrStringOrBuffer
- type BlobPart
- type BodyInit
- type BufferSource
- type BunLockFile
The structure of Bun's lockfile,
bun.lock - type BunLockFileBasePackageInfo
- type BunLockFilePackageArray
- type BunLockFilePackageInfo
- type BunLockFileWorkspacePackage
- type ColorInput
Valid inputs for color
- type CompressionFormat
Extends the standard web formats with
brotliandzstdsupport. - type CookieSameSite
- type CronWithAutocomplete
A cron schedule: a 5-field expression (
minute hour day month weekday) or a nickname. - type CSRFAlgorithm
- type DigestEncoding
- type DisconnectListener
- type DOMHighResTimeStamp
- type Encoding
- type EventListenerOrEventListenerObject
- type ExitListener
- type FFIFunctionCallable
- type FormDataEntryValue
- type HeadersInit
- type HMREvent
Event names accepted by
import.meta.hot.on()andimport.meta.hot.off() - type HMREventNames
- type ImportKind
- type JavaScriptLoader
- type Loader
https://bun.com/docs/bundler/loaders
- type MacroMap
Use macros as regular imports.
- type MaybePromise
- type MessageEvent
- type MessageEventSource
- type MessageListener
- type MultipleResolveType
- type NullSubprocess
Utility type for any process from () with stdin, stdout, stderr all set to
nullor similar. - type NullSyncSubprocess
Utility type for any process from () with both stdout and stderr set to
nullor similar - type OnBeforeParseCallback
- type OnEndCallback
- type OnLoadCallback
- type OnLoadResult
- type OnResolveCallback
- type OnStartCallback
- type PathLike
- type PipedSubprocess
Utility type for any process from () with stdin, stdout, stderr all set to
"pipe". - type ReadableStreamController
- type ReadableStreamDefaultReadResult
- type ReadableStreamReader
- type ReadableSubprocess
Utility type for any process from () with both stdout and stderr set to
"pipe" - type ReadableSyncSubprocess
Utility type for any process from () with both stdout and stderr set to
"pipe" - type RejectionHandledListener
- type ServerWebSocketSendStatus
A status that represents the outcome of a sent message.
- type ShellExpression
- type SignalsListener
- type StringLike
- type StringOrBuffer
- type SupportedCryptoAlgorithms
- type Target
- type TimerHandler
- type Transferable
- type UncaughtExceptionOrigin
- type WarningListener
- type WebSocketCompressor
Compression options for WebSocket messages.
- type WebSocketOptions
Constructor options for the
Bun.WebSocketclient - type WebSocketOptionsCompression
- type WebSocketOptionsHeaders
- type WebSocketOptionsProtocolsOrProtocol
- type WebSocketOptionsProxy
- type WebSocketOptionsTLS
- type WebSocketReadyState
The connection state of a WebSocket.
- type WorkerType
- type WritableSubprocess
Utility type for any process from () with stdin set to
"pipe" - type XMLHttpRequestBodyInit
Variables 22
- const Bun.argv
The raw arguments passed to the process, including flags passed to Bun.
- const Bun.cron
Schedule cron jobs.
- const Bun.embeddedFiles
A list of files embedded into the standalone executable, lexicographically sorted by name.
- const Bun.enableANSIColors
Whether ANSI colors are enabled for stdin and stdout
- const Bun.env
The environment variables of the process
- const Bun.fetch
- const Bun.hash
Hash a string or array buffer using Wyhash
- const Bun.isMainThread
Whether the current global scope is the main thread
- const Bun.isStandaloneExecutable
truewhen the current process is a standalone executable produced by - const Bun.main
Absolute path of the script that launched Bun
- const Bun.password
Hash and verify passwords using argon2 or bcrypt.
- const Bun.plugin
- const Bun.redis
Default Redis client
- const Bun.revision
The git sha at the time the currently-running version of Bun was compiled
- const Bun.s3
A default instance of S3Client
- const Bun.secrets
Securely store and retrieve sensitive credentials using the operating system's native credential storage.
- const Bun.sql
The default SQL client, configured from environment variables such as
- const Bun.stderr
Write to stderr
- const Bun.stdin
Read from stdin
- const Bun.stdout
Write to stdout
- const Bun.version
The current version of Bun
- const Bun.version_with_sha
The current version of Bun with the shortened commit sha of the build
Namespaces 25
- namespace Bun.$
- namespace Bun.Build
- namespace Bun.CSRF
Generate and verify CSRF tokens
- namespace Bun.dns
DNS-related APIs
- namespace Bun.Image
- namespace Bun.inspect
- namespace Bun.JSON5
JSON5 related APIs
- namespace Bun.JSONC
JSONC related APIs
- namespace Bun.JSONL
JSONL (JSON Lines) related APIs.
- namespace Bun.markdown
Markdown related APIs.
- namespace Bun.Password
Hash and verify passwords using argon2 or bcrypt
- namespace Bun.peek
- namespace Bun.RedisClient
- namespace Bun.Security
Security scanner declarations for
bun install - namespace Bun.semver
Bun.semver parses and compares version numbers.
- namespace Bun.Serve
- namespace Bun.Spawn
- namespace Bun.SQL
- namespace Bun.TOML
TOML related APIs
- namespace Bun.udp
- namespace Bun.unsafe
- namespace Bun.WebAssembly
- namespace Bun.WebView
- namespace Bun.XML
XML related APIs
- namespace Bun.YAML
YAML related APIs