Bun is a fast all-in-one JavaScript runtime that includes a bundler, test runner, and package manager. It is 3-4x faster than Node.js for many operations.
Installation
curl -fsSL https://bun.sh/install | bash
Running JavaScript
bun run index.ts # Direct TypeScript execution
bun run index.js # JavaScript
bun run index.jsx # JSX support built-in
HTTP Server
const server = Bun.serve({
port: 3000,
async fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/api/hello") {
return Response.json({ message: "Hello from Bun!" });
}
if (url.pathname === "/api/posts" && req.method === "POST") {
const body = await req.json();
return Response.json({ created: body }, { status: 201 });
}
return new Response("Not Found", { status: 404 });
}
});
console.log(`Server running at ${server.url}`);
File I/O
// Read file
const content = await Bun.file("data.json").text();
const data = JSON.parse(content);
// Write file
await Bun.write("output.json", JSON.stringify(data, null, 2));
// Stream large files
const file = Bun.file("large.csv");
const stream = file.stream();
Package Manager (faster than npm)
bun install # Install dependencies
bun add express # Add package
bun add -d vitest # Dev dependency
bun remove lodash # Remove
bun update # Update all
Test Runner
// math.test.ts
import { expect, test, describe } from "bun:test";
describe("math", () => {
test("addition", () => {
expect(2 + 2).toBe(4);
});
test("async", async () => {
const result = await fetchData();
expect(result).toBeDefined();
});
});
bun test
bun test --coverage
SQLite (Built-in)
import { Database } from "bun:sqlite";
const db = new Database("app.db");
db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)");
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
insert.run("Alex", "alex@dev.com");
const users = db.prepare("SELECT * FROM users").all();
console.log(users);
Bundler
bun build ./src/index.ts --outdir ./dist --target browser --minify
Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)