Bun - Ultra-fast JavaScript Runtime
Bun is a modern JavaScript runtime like Node.js, but it's designed to be much faster and more efficient.
GitHub
https://github.com/oven-sh/bun
What is Bun?
Bun is a drop-in replacement for Node.js that includes:
All in a single executable!
Key Features
1. Lightning Fast
2. All-in-One
3. Modern Features
4. Developer Experience
Installation
macOS & Linux
ash
curl -fsSL https://bun.sh/install | bash
Windows
ash
powershell -c "irm bun.sh/install.ps1|iex"
Using npm
ash
npm install -g bun
Quick Start
Hello World
javascript
// server.js
Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello Bun!");
},
});
console.log("Listening on http://localhost:3000");
Run it:
ash
bun run server.js
Package Manager
Install Packages
ash
Install dependencies
bun install
Add package
bun add react
Add dev dependency
bun add -D typescript
Remove package
bun remove react
Speed Comparison
| Operation | Bun | npm/pnpm | Speedup |
|-----------|-----|----------|---------|
| Install 1000 packages | 1.2s | 15s | 12x |
| Install 1 package | 0.02s | 1.2s | 60x |
| Run script | 0.03s | 0.8s | 27x |
Web Server
Basic HTTP Server
javascript
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!" });
}
return new Response("Not Found", { status: 404 });
},
});
File Serving
javascript
Bun.serve({
port: 3000,
async fetch(req) {
const url = new URL(req.url);
const file = Bun.file(.);
return new Response(file);
},
});
WebSocket Support
javascript
Bun.serve({
port: 3000,
fetch(req, server) {
const success = server.upgrade(req);
if (success) return undefined;
return new Response("Upgrade failed", { status: 500 });
},
websocket: {
message(ws, message) {
ws.send(message);
},
open(ws) {
ws.send("Connected!");
},
},
});
TypeScript Support
Native TypeScript
ypescript
// app.ts
interface User {
name: string;
email: string;
}
async function getUser(id: number): Promise {
const response = await fetch(/api/users/);
return response.json();
}
console.log(await getUser(1));
Run TypeScript directly:
ash
bun run app.ts
No s-node or sconfig.json needed!
Testing
Built-in Test Runner
ypescript
// math.test.ts
import { expect, test } from "bun:test";
test("addition", () => {
expect(1 + 2).toBe(3);
});
test("async", async () => {
const result = await Promise.resolve(42);
expect(result).toBe(42);
});
Run tests:
ash
bun test
Bundling
Simple Bundle
javascript
// bundle.js
export const greet = (name: string) => Hello, !;
ash
bun build bundle.js --outdir ./dist
Bundle for Browser
ash
bun build app.ts --outdir ./dist --target browser
Bundle for Node
ash
bun build app.ts --outdir ./dist --target node
Database Support
SQLite
ypescript
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite");
// Create table
db.query("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)").run();
// Insert
db.query("INSERT INTO users (name) VALUES (?)").run("Alice");
// Query
const users = db.query("SELECT * FROM users").all();
console.log(users);
PostgreSQL
ypescript
import postgres from "postgres";
const sql = postgres("postgres://user:password@localhost/db");
const users = await sql\SELECT * FROM users\;
console.log(users);
File Operations
Read File
ypescript
import { readFile } from "bun:fs";
const text = await readFile("hello.txt", "utf-8");
console.log(text);
Write File
ypescript
import { writeFile } from "bun:fs";
await writeFile("hello.txt", "Hello Bun!");
Read JSON
ypescript
import { readFileSync } from "bun:fs";
const data = JSON.parse(readFileSync("data.json", "utf-8"));
Comparison
| Feature | Bun | Node.js | Deno |
|---------|-----|---------|------|
| Startup Speed | 4x faster | Baseline | 2x faster |
| Package Manager | Built-in | npm | Built-in |
| TypeScript | Native | Requires setup | Native |
| Bundler | Built-in | Webpack | Built-in |
| Test Runner | Built-in | Jest | Built-in |
Framework Support
Express Alternative
ypescript
import { Elysia } from "elysia";
const app = new Elysia()
.get("/", () => "Hello Bun!")
.post("/api/users", ({ body }) => {
return { created: body };
})
.listen(3000);
React/Next.js
ash
Use Bun with Next.js
bun install next react react-dom
bun run dev
Performance Benchmarks
HTTP Server
| Runtime | Requests/sec |
|---------|-------------|
| Bun | 100,000 |
| Node.js (Express) | 25,000 |
| Deno | 80,000 |
File I/O
| Operation | Bun | Node.js |
|-----------|-----|---------|
| Read 1GB file | 0.8s | 2.5s |
| Write 1GB file | 0.9s | 3.1s |
| Copy 1GB file | 0.6s | 1.8s |
Why Bun?
Use Cases
Migration from Node.js
Easy Migration
ash
Replace node with bun
Replace npm with bun install
Replace node_modules with bun.lockb
That's it!
Compatibility
Learning Resources
Summary
Bun represents the future of JavaScript tooling. It's faster, simpler, and more efficient than traditional Node.js setups. If you're building JavaScript applications, Bun should definitely be on your radar.
Rating: 猸愨瓙猸愨瓙猸?
Best for: Web servers, APIs, CLI tools
Learning curve: 猸?(if you know Node.js)
Performance: 猸愨瓙猸愨瓙猸?
💬 评论区 (0)
暂无评论,快来抢沙发吧!