Bun

Essential Bun commands, APIs, and patterns for the fast all-in-one JavaScript runtime.

cli
bunjavascripttypescriptruntimebundlerpackage-manager

Installation

# macOS/Linux
curl -fsSL https://bun.sh/install | bash

# Homebrew
brew install oven-sh/bun/bun

# npm
npm install -g bun

# Windows (experimental)
powershell -c "irm bun.sh/install.ps1 | iex"

Bun vs npm Commands

TaskBunnpm
Initialize projectbun initnpm init
Install dependenciesbun installnpm install
Add packagebun add <pkg>npm install <pkg>
Add dev dependencybun add -d <pkg>npm install -D <pkg>
Add global packagebun add -g <pkg>npm install -g <pkg>
Remove packagebun remove <pkg>npm uninstall <pkg>
Update packagesbun updatenpm update
Run scriptbun run <script>npm run <script>
Execute binarybunx <cmd>npx <cmd>
Run testsbun testnpm test
List packagesbun pm lsnpm ls

Updating Bun

# Update to latest version
bun upgrade

# Update to specific version
bun upgrade --version 1.0.0

# Update to canary (nightly) build
bun upgrade --canary

Running Scripts

# Run a TypeScript/JavaScript file
bun run script.ts

# Run directly (shorthand)
bun script.ts

# Watch mode
bun --watch script.ts

# Hot reload mode
bun --hot script.ts

# Run with environment file
bun --env-file=.env script.ts

Package Management

# Initialize new project
bun init

# Install all dependencies
bun install

# Add a package
bun add express

# Add dev dependency
bun add -d typescript

# Add global package
bun add -g typescript

# Remove a package
bun remove express

# Update packages
bun update

# List installed packages
bun pm ls

Running Scripts (package.json)

# Run a script from package.json
bun run dev
bun run build

# Shorthand (without 'run')
bun dev
bun build

# Run binaries from node_modules
bunx tsc --init
bunx prisma migrate dev

Built-in Bundler

# Bundle a file
bun build ./src/index.ts --outdir ./dist

# Bundle with minification
bun build ./src/index.ts --outdir ./dist --minify

# Bundle for browser
bun build ./src/index.ts --outdir ./dist --target browser

# Bundle for Node.js
bun build ./src/index.ts --outdir ./dist --target node

# Create single executable
bun build ./src/index.ts --compile --outfile myapp

HTTP Server

// Simple server using Bun.serve
Bun.serve({
  port: 3000,
  fetch(req) {
    return new Response("Hello, World!");
  },
});

// With routing
Bun.serve({
  port: 3000,
  fetch(req) {
    const url = new URL(req.url);
    
    if (url.pathname === "/api") {
      return Response.json({ message: "Hello" });
    }
    
    if (url.pathname === "/") {
      return new Response("Welcome!");
    }
    
    return new Response("Not Found", { status: 404 });
  },
});

// With WebSocket support
Bun.serve({
  port: 3000,
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return new Response("HTTP request");
  },
  websocket: {
    message(ws, message) {
      ws.send(`Echo: ${message}`);
    },
  },
});

File System

// Read file
const text = await Bun.file("file.txt").text();
const json = await Bun.file("data.json").json();
const bytes = await Bun.file("file.bin").arrayBuffer();

// Write file
await Bun.write("file.txt", "Hello, World!");
await Bun.write("data.json", JSON.stringify({ name: "Bun" }));

// Check if file exists
const file = Bun.file("file.txt");
const exists = await file.exists();

// Get file info
const file = Bun.file("file.txt");
console.log(file.size, file.type);

// Copy file
await Bun.write("copy.txt", Bun.file("original.txt"));

Environment Variables

// Access environment variables
const apiKey = Bun.env.API_KEY;
const nodeEnv = process.env.NODE_ENV;

// Using .env file (automatic)
// Bun automatically loads .env files

Testing

// test.ts
import { expect, test, describe, beforeEach } from "bun:test";

test("basic test", () => {
  expect(1 + 1).toBe(2);
});

describe("group", () => {
  beforeEach(() => {
    // Setup
  });

  test("nested test", () => {
    expect("hello").toContain("ell");
  });
});

// Async test
test("async test", async () => {
  const response = await fetch("https://api.example.com");
  expect(response.ok).toBe(true);
});
# Run tests
bun test

# Run specific test file
bun test test.ts

# Watch mode
bun test --watch

# With coverage
bun test --coverage

SQLite Database

import { Database } from "bun:sqlite";

// Open database
const db = new Database("mydb.sqlite");

// Create table
db.run(`
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    email TEXT UNIQUE
  )
`);

// Insert data
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
insert.run("John", "john@example.com");

// Query data
const query = db.prepare("SELECT * FROM users WHERE name = ?");
const user = query.get("John");
const allUsers = query.all("John");

// Close database
db.close();

Password Hashing

// Hash password
const password = "supersecure";
const hash = await Bun.password.hash(password);

// Verify password
const isValid = await Bun.password.verify(password, hash);

// With options
const hash = await Bun.password.hash(password, {
  algorithm: "argon2id",
  memoryCost: 65536,
  timeCost: 2,
});

Spawning Processes

// Simple spawn
const proc = Bun.spawn(["echo", "Hello"]);
const output = await new Response(proc.stdout).text();

// With options
const proc = Bun.spawn(["ls", "-la"], {
  cwd: "/path/to/dir",
  env: { ...process.env, MY_VAR: "value" },
  stdout: "pipe",
  stderr: "pipe",
});

// Wait for completion
await proc.exited;
console.log(proc.exitCode);

// Synchronous spawn
const result = Bun.spawnSync(["echo", "Hello"]);
console.log(result.stdout.toString());

bunfig.toml Configuration

# bunfig.toml

[install]
# Registry URL
registry = "https://registry.npmjs.org"

# Install peer dependencies
peer = true

# Lockfile settings
lockfile = true

[run]
# Silent mode
silent = false

[test]
# Test settings
coverage = true
coverageDir = "coverage"

TypeScript Support

// Bun supports TypeScript out of the box
// No configuration needed!

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "John",
  age: 30,
};

// JSX also works out of the box
const element = <div>Hello, World!</div>;

Fetch API

// GET request
const response = await fetch("https://api.example.com/data");
const data = await response.json();

// POST request
const response = await fetch("https://api.example.com/data", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Bun" }),
});

// Streaming response
const response = await fetch("https://api.example.com/stream");
for await (const chunk of response.body!) {
  console.log(chunk);
}

Globals

// Bun-specific globals
Bun.version;        // Bun version
Bun.revision;       // Git SHA
Bun.main;           // Entry point path
Bun.cwd();          // Current working directory
Bun.sleep(1000);    // Sleep for 1 second
Bun.sleepSync(1000); // Sync sleep

// Generate random data
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);

// UUID
const uuid = crypto.randomUUID();