Bun Runtime Guide — Fast JavaScript Runtime and Toolkit
Bun is an all-in-one JavaScript runtime and toolkit designed for speed — it replaces Node.js, npm, npx, Jest, and even SQLite drivers with a single executable that’s 4x faster at package installation and starts scripts in milliseconds.
What You’ll Learn
- Running JavaScript and TypeScript with Bun’s native runtime
- Using
bun installas a faster npm replacement - Writing and running tests with
bun test - Reading and writing files with the
Bun.fileAPI - Working with the built-in SQLite database
- Comparing Bun with Node.js and Deno
Why Bun Matters
Node.js is the standard JavaScript runtime but has accumulated years of technical debt — slow package resolution, convoluted module systems, and a test ecosystem that requires separate tools. Bun rewrites everything from scratch in Zig, achieving 4x faster package installs, instant script starts, and built-in tooling (bundler, test runner, package manager) that Node.js needs separate libraries for. DodaZIP’s CI pipeline switched to Bun and reduced package install from 45 seconds to 8 seconds — cutting total CI time by half.
flowchart LR
A[JavaScript & TypeScript Basics] --> B[Bun]
B --> C[Runtime]
B --> D[Package Manager]
B --> E[Test Runner]
B --> F[Bun.file & SQLite]
C --> G[TypeScript / JSX]
D --> H[npm Compatibility]
E --> I[Jest-Compatible API]
style B fill:#f9f9f9,color:#000
Core Concepts
Installation and Running Scripts
# Install Bun
curl -fsSL https://bun.sh/install | bash
# Run a JavaScript file
bun run index.ts # TypeScript works natively — no ts-node needed
# Output: Runs at startup in ~2ms vs Node's ~30ms
# Watch mode (dev servers, hot reload)
bun --watch server.tsOutput: Bun starts scripts in single-digit milliseconds. It transpiles TypeScript, JSX, and even TSX on the fly with zero configuration. No tsconfig.json required for basic TypeScript execution.
Package Manager — bun install
# Uses your existing package.json — no migration needed
bun install
# bun.lockb replaces package-lock.json or yarn.lock
# 4x faster than npm install, 2x faster than yarn
# Add dependencies
bun add express zod
bun add -D typescript @types/node
# Remove dependencies
bun remove lodash
# Run scripts
bun run dev
bun run build
# Global packages (replaces npx)
bun x create-react-app my-appOutput: bun install downloads packages ~4x faster than npm by using a global module cache and parallel downloads. The generated bun.lockb is a binary format that reads faster than JSON/YAML lockfiles.
Testing with bun test
Bun has a built-in Jest-compatible test runner:
// math.test.ts — no test library imports needed
import { describe, expect, test } from "bun:test";
function add(a, b) {
return a + b;
}
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero");
return a / b;
}
describe("add", () => {
test("adds positive numbers", () => {
expect(add(2, 3)).toBe(5);
});
test("adds negative numbers", () => {
expect(add(-1, -1)).toBe(-2);
});
});
describe("divide", () => {
test("divides correctly", () => {
expect(divide(10, 2)).toBe(5);
});
test("throws on division by zero", () => {
expect(() => divide(1, 0)).toThrow("Cannot divide by zero");
});
});# Run tests
bun test
# Output:
# bun test v1.0.0
# math.test.ts:
# ✓ add > adds positive numbers
# ✓ add > adds negative numbers
# ✓ divide > divides correctly
# ✓ divide > throws on division by zero
# 4 pass, 0 fail, 0 skip
# Ran in 12msOutput: Tests run in milliseconds. Bun uses the same describe/expect/test API as Jest, so existing test suites often work without changes. Mocking and snapshots are also supported.
Bun.file API
import { Bun } from "bun";
// Read file
const file = Bun.file("data.json");
const text = await file.text(); // "{\"name\": \"Alice\"}"
const json = await file.json(); // { name: "Alice" }
const bytes = await file.arrayBuffer(); // Buffer for binary data
console.log(file.size); // File size in bytes
console.log(file.type); // MIME type (e.g., "application/json")
console.log(file.exists()); // true or false
// Write file
await Bun.write("output.txt", "Hello, Bun!");
await Bun.write("data.json", JSON.stringify({ name: "Bob" }));Output: Bun.file handles all file operations with a clean, modern API. No need for fs.readFileSync or fs.promises.readFile. It handles encoding, MIME types, and large files efficiently with streaming under the hood.
Built-in SQLite
import { Database } from "bun:sqlite";
// Create or open a database
const db = new Database("app.db");
// Create a table
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)
`);
// Insert data
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
insert.run("Alice", "alice@example.com");
insert.run("Bob", "bob@example.com");
// Query with parameterized statements
const query = db.prepare("SELECT * FROM users WHERE email = ?");
const user = query.get("alice@example.com");
console.log(user);
// { id: 1, name: "Alice", email: "alice@example.com" }
// Query all rows
const allUsers = db.prepare("SELECT * FROM users").all();
console.log(allUsers);
// [{ id: 1, name: "Alice", ... }, { id: 2, name: "Bob", ... }]
db.close();Output: Bun’s built-in SQLite is faster than better-sqlite3 and requires no npm install. Queries are compiled once and executed efficiently. It’s perfect for local data, caching, and prototypes.
Bun vs Node.js vs Deno
| Feature | Bun | Node.js | Deno |
|---|---|---|---|
| Startup time | ~2ms | ~30ms | ~15ms |
| Package manager | Built-in (fast) | npm (slow) | Import from URL |
| TypeScript | Native | Via ts-node | Native |
| Test runner | Built-in | Third-party | Built-in |
| SQLite | Built-in | Third-party | No |
| Bun.file | Built-in | fs module | Deno.readTextFile |
Common Mistakes
Expecting full Node.js compatibility: Bun aims for Node.js compatibility but doesn’t implement every internal API. Test your app thoroughly before migrating production workloads.
Not running
bun installafter migrating from npm: Bun’s lockfile format is different. Always deletenode_modulesandpackage-lock.jsonthen runbun installfresh.Using
process.envbefore Bun environment variables are loaded: Bun loads env vars on first access. Access them inside your app, not during module initialization, to ensure they’re populated.Ignoring SQLite concurrency limits: Bun’s SQLite is single-writer. Multiple concurrent writes cause
SQLITE_BUSYerrors. Use WAL mode for better concurrency.Assuming
bun testsupports every Jest feature: Bun implements most of Jest’s API but not all (e.g., custom reporters). Check compatibility before migrating large test suites.
Practice Questions
How fast is Bun compared to Node.js for script startup? Answer: Bun starts scripts in ~2ms vs Node.js ~30ms, making it ~15x faster for cold starts — important for CLI tools and serverless functions.
What tools does Bun replace? Answer: Bun replaces Node.js (runtime), npm (package manager), npx (package runner), Jest (test runner), and ts-node (TypeScript runner) with a single executable.
How do you run TypeScript with Bun? Answer: Directly — just run
bun run script.ts. Bun transpiles TypeScript natively with no configuration or tsconfig.json required.What is the advantage of Bun’s built-in SQLite? Answer: Zero dependencies, faster than better-sqlite3, and consistent API across platforms. No npm install needed for database functionality.
Challenge
Build a CLI note-taking app with Bun: use Bun.file for JSON storage, bun:sqlite for note indexing, implement CRUD commands (add, list, search, delete), write tests with bun test, and publish as a global CLI with bun build --compile.
FAQ
Try It Yourself
curl -fsSL https://bun.sh/install | bash
# Run TypeScript directly
echo 'console.log("Hello from Bun!");' > hello.ts
bun run hello.ts
# Compare speed
time node -e "console.log('Node')"
time bun -e "console.log('Bun')"
# Build a small HTTP server
bun -e "
import { serve } from 'bun';
serve({
fetch(req) { return new Response('Hello!'); },
port: 3000,
});
console.log('Server at http://localhost:3000');
"What’s Next
| Topic | Description |
|---|---|
| TypeScript runs natively on Bun | |
| Compare Bun with the classic runtime |
Related topics: JavaScript, TypeScript, Node.js, SQLite
What’s Next
Congratulations on completing this Bun tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro