# 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"
| Task | Bun | npm |
|---|
| Initialize project | bun init | npm init |
| Install dependencies | bun install | npm install |
| Add package | bun add <pkg> | npm install <pkg> |
| Add dev dependency | bun add -d <pkg> | npm install -D <pkg> |
| Add global package | bun add -g <pkg> | npm install -g <pkg> |
| Remove package | bun remove <pkg> | npm uninstall <pkg> |
| Update packages | bun update | npm update |
| Run script | bun run <script> | npm run <script> |
| Execute binary | bunx <cmd> | npx <cmd> |
| Run tests | bun test | npm test |
| List packages | bun pm ls | npm ls |
# Update to latest version
bun upgrade
# Update to specific version
bun upgrade --version 1.0.0
# Update to canary (nightly) build
bun upgrade --canary
# 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
# 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
# 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
# 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
// 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}`);
},
},
});
// 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"));
// Access environment variables
const apiKey = Bun.env.API_KEY;
const nodeEnv = process.env.NODE_ENV;
// Using .env file (automatic)
// Bun automatically loads .env files
// 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
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();
// 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,
});
// 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
[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"
// 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>;
// 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);
}
// 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();