Bun logoBun INTERMEDIATE

Bun

Complete reference for Bun — the all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner

10 min read
bunjavascripttypescriptruntimepackage-managerbundlertest-runnerservernodejs-alternative

Installation & Setup

Install Bun and configure your project

Install & Initialize

Install Bun and scaffold a new project

bash
💡 Bun runs TypeScript and JSX natively — no transpiler config or tsconfig required
⚡ bun init scaffolds package.json, tsconfig.json, and an index.ts in seconds
📌 Bun is a single binary with zero dependencies — installs in under 5 seconds
🟢 Use bun create to scaffold from community templates like React, Hono, or Elysia
installsetupinit

bunfig.toml Configuration

Configure Bun behavior with the bunfig.toml config file

toml
💡 bunfig.toml is optional — Bun works with sensible defaults out of the box
⚡ Use ~/.bunfig.toml for global settings that apply to all projects
📌 Environment variables can be referenced with $VAR_NAME syntax in the config
🟢 install.exact = true pins versions without ^ or ~ — great for reproducible builds
configbunfigtoml

Running Scripts & Files

Execute files, scripts, and packages with bun run and bunx

bun run & bunx

Run files, package.json scripts, and remote packages

bash
💡 bun --watch restarts the whole process on changes; --hot reloads modules in-place
⚡ bun run is 30x faster than npm run — it skips shell interpretation overhead
📌 bunx --bun forces packages like Vite or Prisma to run on Bun instead of Node
🟢 Bun auto-loads .env files — no dotenv package needed
runbunxscriptswatch

Package Manager

Install, manage, and publish packages with bun install

Managing Dependencies

Install, add, remove, and update packages

bash
💡 bun install is up to 30x faster than npm — uses a global cache and hardlinks
⚡ The bun.lockb binary lockfile is faster to read/write than JSON-based lockfiles
📌 Use --frozen-lockfile in CI to ensure deterministic installs
🟢 Workspaces work like npm/yarn workspaces — just add "workspaces" to package.json
installaddremovepackages

HTTP Server

Build high-performance HTTP servers with Bun.serve()

Bun.serve() Basics

Create an HTTP server with routes and request handling

typescript
💡 Bun.serve uses Web Standard Request/Response — no framework-specific APIs to learn
⚡ Routes with method handlers (GET/POST) require Bun v1.2.3+ — use fetch() fallback for older versions
📌 Bun.file() in routes lazily loads files into memory — efficient for static assets
🟢 server.reload() hot-swaps the config without dropping existing connections
serverhttproutesapi

WebSockets

Built-in WebSocket server support with pub/sub messaging

WebSocket Server

Add WebSocket support to Bun.serve with handlers and pub/sub

typescript
💡 Bun WebSockets handle 4x more messages per second than Node.js ws package
⚡ Built-in pub/sub with ws.subscribe/publish — no Redis or external broker needed
📌 Pass per-socket data in server.upgrade() — access it later via ws.data
🟢 WebSocket handlers are defined alongside HTTP routes in the same Bun.serve() call
websocketrealtimepubsub

File I/O

Read, write, and manipulate files with Bun.file() and Bun.write()

Reading & Writing Files

Fast file operations with Bun.file() and Bun.write()

typescript
💡 Bun.file() is lazy — it only reads from disk when you call .text(), .json(), etc.
⚡ Bun.write() is 10x faster than Node fs.writeFileSync — uses optimized system calls
📌 Pass a Bun.file() or fetch Response directly to Bun.write() for zero-copy operations
🟢 Use file.writer() for incremental writes like logging — flush() ensures data persists
filereadwriteio

SQLite & Database

Built-in SQLite database with the bun:sqlite module

bun:sqlite

Use the built-in SQLite database for fast local storage

typescript
💡 bun:sqlite is built into Bun — no npm install needed, 3-6x faster than better-sqlite3
⚡ Use db.transaction() for batch inserts — wraps everything in a single atomic operation
📌 Always use prepared statements with ? or $name parameters to prevent SQL injection
🟢 Enable WAL mode for better performance with concurrent reads and writes
sqlitedatabasesql

Test Runner

Jest-compatible testing with bun test

Writing & Running Tests

Write Jest-compatible tests with describe, test, and expect

typescript
💡 bun test is Jest-compatible — import from "bun:test" or keep existing Jest imports
⚡ Bun test runner is 10-40x faster than Jest with zero config for TypeScript
📌 Use test.skip() for tests not ready yet and test.todo() as a placeholder reminder
🟢 Run with bun test --watch to auto-rerun on file changes during development
testjestexpectdescribe

Mocks & Snapshots

Mock functions, spy on methods, and use snapshot testing

typescript
💡 mock.module() replaces entire modules — useful for isolating units under test
⚡ setSystemTime() mocks Date.now() and new Date() globally — no extra library needed
📌 Run bun test --update-snapshots to regenerate snapshot files after intentional changes
🟢 spyOn tracks calls without changing behavior — use mockRestore() to clean up
mockspysnapshottesting

Bundler

Bundle JavaScript, TypeScript, and CSS with bun build

bun build

Bundle code for browsers and servers

bash
💡 bun build replaces Webpack/esbuild — native bundling with zero config
⚡ Use --compile to create a single executable binary that runs without Bun installed
📌 --target browser strips Node.js APIs; --target bun optimizes for the Bun runtime
🟢 Code splitting with --splitting creates shared chunks for multi-entry bundles
buildbundlecompile

Programmatic Bundler API

Use Bun.build() in code with plugins and advanced options

typescript
💡 Bun.build() returns artifacts with path, size, and hash — useful for build pipelines
⚡ Plugins use the same API as esbuild plugins — most esbuild plugins work in Bun
📌 Use env: "inline" to replace process.env references with actual values at build time
🟢 Check result.success and result.logs to catch build errors programmatically
buildpluginsapi

Shell & Child Processes

Run shell commands with Bun.$ and spawn child processes

Bun Shell ($)

Run shell commands with tagged template literals

typescript
💡 Bun.$ auto-escapes interpolated variables — safe from shell injection by default
⚡ Use .nothrow() to prevent throwing on non-zero exit codes — check exitCode instead
📌 Bun Shell works cross-platform — same syntax on macOS, Linux, and Windows
🟢 Chain .text(), .json(), or .lines() to parse command output in one call
shellcommandspawn

Bun.spawn()

Spawn child processes with fine-grained control

typescript
💡 Bun.spawn() takes an array of args — no shell interpretation, safe from injection
⚡ Use Bun.spawnSync() for quick blocking commands like git status
📌 Set stdout: "pipe" to capture output — then read it as a Response stream
🟢 Prefer Bun.$ for simple commands and Bun.spawn() for fine-grained process control
spawnprocesschild

Environment & Utilities

Environment variables, hashing, passwords, and built-in utilities

Environment Variables

Access and manage environment variables with auto .env loading

typescript
💡 Bun auto-loads .env files with no dotenv package — just create the file and go
⚡ Use bun --env-file to load a specific env file for different environments
📌 Both Bun.env and process.env work — Bun.env is slightly faster as it skips Node compat
🟢 import.meta.dir/file/path give you the current file location — no __dirname polyfill needed
envenvironmentdotenv

Hashing & Passwords

Built-in hashing and secure password operations

typescript
💡 Bun.password.hash uses bcrypt by default — argon2id available for higher security needs
⚡ Bun.hash is non-cryptographic but extremely fast — use for cache keys and checksums
📌 Use Bun.CryptoHasher for SHA-256/SHA-512 when you need cryptographic guarantees
🟢 Bun.sleep() is a built-in async sleep — no setTimeout wrapper needed
hashpasswordcryptobcrypt

Workers & Concurrency

Run code in parallel with Web Workers and Bun-specific APIs

Web Workers

Run CPU-intensive tasks in parallel threads

typescript
💡 Bun Workers support TypeScript directly — no build step needed for worker files
⚡ Use navigator.hardwareConcurrency to create an optimal number of workers for the CPU
📌 Workers run in separate threads with isolated memory — communicate via postMessage
🟢 Use workers for CPU-intensive tasks (parsing, compression, crypto) to keep the main thread responsive
workersconcurrencythreadsparallel