Bun คือ All-in-One JavaScript toolkit ที่รวม Runtime, Bundler, Test runner, และ Package manager ไว้ในตัวเดียว สร้างด้วยภาษา Zig และใช้ JavaScriptCore engine (เดียวกับ Safari) แทน V8 ที่ Node.js ใช้ ทำให้เร็วกว่า Node.js ในเกือบทุกด้าน ตั้งแต่การ Start process, ติดตั้ง Package, Build, ไปจนถึงการ Run test
Bun ถูกสร้างโดย Jarred Sumner โดยเริ่มพัฒนาในปี 2021 และเปิดตัว v1.0 ในเดือนกันยายน 2023 เป้าหมายของ Bun คือการเป็น Drop-in replacement ของ Node.js ที่เร็วกว่าและง่ายกว่า โดยรวมเครื่องมือทุกอย่างที่ JavaScript developer ต้องใช้ไว้ในที่เดียว
Bun Architecture — JavaScriptCore + Zig
Bun เลือกใช้สถาปัตยกรรมที่แตกต่างจาก Node.js และ Deno อย่างสิ้นเชิง:
| Component | Bun | Node.js | Deno |
|---|---|---|---|
| JS Engine | JavaScriptCore (WebKit/Safari) | V8 (Chrome) | V8 (Chrome) |
| Implementation Language | Zig + C++ | C++ + JavaScript | Rust + TypeScript |
| Event Loop | Custom (Zig-based) | libuv | Tokio (Rust) |
| TypeScript | Native transpilation (ไม่ต้อง tsc) | ต้องใช้ ts-node/tsx | Native transpilation |
| JSX | Native transpilation | ต้องใช้ Babel/esbuild | ต้อง configure |
| Package Manager | Built-in (bun install) | npm (แยกต่างหาก) | URL imports + npm: |
| Bundler | Built-in (bun build) | ต้องใช้ webpack/esbuild/Vite | ไม่มี built-in |
| Test Runner | Built-in (bun test) | ต้องใช้ Jest/Vitest | Built-in (Deno.test) |
ทำไม JavaScriptCore ถึงเร็ว? JavaScriptCore (JSC) มี Startup time ที่เร็วกว่า V8 อย่างมาก เพราะ JSC ถูกออกแบบมาสำหรับ Mobile (Safari) ที่ต้อง Start เร็ว ขณะที่ V8 ถูกออกแบบสำหรับ Long-running processes (Chrome) ที่เน้น Peak performance มากกว่า Startup
ทำไม Zig? Zig เป็นภาษา Systems programming ที่ให้ Control ระดับต่ำเหมือน C/C++ แต่ปลอดภัยกว่าและเขียนง่ายกว่า Zig ไม่มี Garbage collector และไม่มี Hidden allocations ทำให้ Bun สามารถ Control memory ได้ 100% ส่งผลให้ Performance สูงและ Memory usage ต่ำ
Bun vs Node.js vs Deno — Deep Comparison
Speed Benchmarks
# Bun vs Node.js Performance (typical benchmarks)
# ================================================
# Test | Bun | Node.js | Speedup
# ----------------------- | -------- | -------- | -------
# Startup time | 7ms | 35ms | 5x
# bun install (cold) | 1.2s | 12s | 10x
# bun install (cached) | 0.3s | 3.5s | 11x
# HTTP server (req/sec) | 250,000 | 100,000 | 2.5x
# FFI call overhead | 3ns | 48ns | 16x
# TypeScript transpile | 0ms | 200ms+ | Instant
# bun test (1000 tests) | 0.8s | 8s | 10x
# bun build (bundle) | 0.3s | 2.5s | 8x
# JSON parse (large) | 12ms | 45ms | 3.7x
# WebSocket messages/sec | 1.6M | 400K | 4x
หมายเหตุ: Benchmarks เป็นค่าประมาณจาก Official benchmarks และ Community tests ผลลัพธ์จริงขึ้นอยู่กับ Workload, Hardware และ Configuration
Bun as Runtime
# ติดตั้ง Bun
curl -fsSL https://bun.sh/install | bash
# หรือ Windows:
powershell -c "irm bun.sh/install.ps1 | iex"
# ตรวจสอบเวอร์ชัน
bun --version # 1.x.x
# Run JavaScript/TypeScript โดยตรง (ไม่ต้อง tsc!)
bun run index.ts
bun run server.js
# Run with watch mode (auto-restart เมื่อ file เปลี่ยน)
bun --watch run index.ts
# Run script จาก package.json
bun run dev
bun run build
Bun รองรับ TypeScript และ JSX ได้ทันทีโดยไม่ต้อง Configure อะไร ไม่ต้องติดตั้ง ts-node ไม่ต้อง tsconfig.json (แต่รองรับถ้ามี) แค่เขียน .ts แล้ว bun run file.ts ได้เลย
Bun as Bundler — vs esbuild vs webpack
# Bundle JavaScript/TypeScript
bun build ./src/index.ts --outdir ./dist
# Bundle สำหรับ Browser
bun build ./src/app.tsx --outdir ./dist --target browser
# Bundle เป็น Single file
bun build ./src/index.ts --outfile ./dist/bundle.js
# Minify
bun build ./src/index.ts --outdir ./dist --minify
# Source maps
bun build ./src/index.ts --outdir ./dist --sourcemap=external
# Bundle with external dependencies
bun build ./src/index.ts --outdir ./dist --external react --external react-dom
# Watch mode
bun build ./src/index.ts --outdir ./dist --watch
| Feature | Bun Bundler | esbuild | webpack |
|---|---|---|---|
| Speed | เร็วมาก (Zig) | เร็วมาก (Go) | ช้า (JavaScript) |
| Tree Shaking | รองรับ | รองรับ | รองรับ |
| Code Splitting | รองรับ | รองรับ | รองรับ (ดีที่สุด) |
| CSS | รองรับ | รองรับ | รองรับ (ผ่าน Loader) |
| Plugin System | Bun Plugin API | esbuild Plugin API | Loader + Plugin (มากที่สุด) |
| Config | bunfig.toml หรือ CLI flags | JS/CLI | webpack.config.js (ซับซ้อน) |
| Ecosystem | กำลังเติบโต | ดี | ใหญ่ที่สุด |
Bun as Test Runner — vs Jest vs Vitest
// math.test.ts — Bun test (Jest-compatible API!)
import { expect, test, describe, beforeAll, afterAll } from "bun:test";
describe("Math operations", () => {
test("addition", () => {
expect(1 + 1).toBe(2);
});
test("multiplication", () => {
expect(3 * 4).toBe(12);
});
test("async operation", async () => {
const result = await fetchData();
expect(result).toBeDefined();
expect(result.status).toBe("ok");
});
test("snapshot", () => {
const obj = { name: "Bun", version: "1.0" };
expect(obj).toMatchSnapshot();
});
test("mock function", () => {
const fn = jest.fn(); // Bun รองรับ jest.fn()!
fn("hello");
expect(fn).toHaveBeenCalledWith("hello");
});
});
// Run: bun test
// Run specific file: bun test math.test.ts
// Run with coverage: bun test --coverage
// Run with watch: bun test --watch
Bun test runner ใช้ API เดียวกับ Jest ทำให้ Migrate จาก Jest มาได้ง่าย แค่เปลี่ยนจาก npx jest เป็น bun test Tests ส่วนใหญ่ทำงานได้ทันทีโดยไม่ต้องแก้ Code
Bun as Package Manager — vs npm vs pnpm
# ติดตั้ง Dependencies (เร็วกว่า npm 10x+)
bun install # อ่านจาก package.json
bun add express # เพิ่ม dependency
bun add -d typescript # เพิ่ม devDependency
bun remove express # ลบ dependency
bun update # Update dependencies
# Global install
bun add -g typescript
# lockfile
# Bun ใช้ bun.lockb (binary format — เร็วกว่า JSON/YAML)
# สามารถ Export เป็น yarn.lock ได้:
bun install --yarn
| Feature | bun install | npm install | pnpm install |
|---|---|---|---|
| Cold install speed | ~1-2s | ~10-15s | ~5-8s |
| Cached install | ~0.3s | ~3-5s | ~1-2s |
| Lockfile format | Binary (bun.lockb) | JSON (package-lock.json) | YAML (pnpm-lock.yaml) |
| Disk usage | Standard node_modules | Standard node_modules | Content-addressable store (ดีที่สุด) |
| Workspace support | รองรับ | รองรับ | รองรับ (ดีที่สุด) |
| npm compatibility | สูงมาก | 100% | สูงมาก |
Built-in SQLite
// Bun มี SQLite driver ในตัว (ไม่ต้อง npm install!)
import { Database } from "bun:sqlite";
const db = new Database("myapp.db");
// สร้าง Table
db.run(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
// Insert
const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
insert.run("Bom", "bom@example.com");
// Select
const users = db.prepare("SELECT * FROM users").all();
console.log(users);
// [{ id: 1, name: "Bom", email: "bom@example.com", created_at: "2026-04-11 ..." }]
// Transaction
const insertMany = db.transaction((users) => {
const stmt = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
for (const user of users) stmt.run(user.name, user.email);
});
insertMany([
{ name: "Alice", email: "alice@example.com" },
{ name: "Bob", email: "bob@example.com" },
]);
Built-in S3 Client
// Bun 1.2+ มี S3 client ในตัว
import { S3Client } from "bun";
const s3 = new S3Client({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: "ap-southeast-1",
});
// Upload file
const file = Bun.file("./image.jpg");
await s3.write("my-bucket/image.jpg", file);
// Download file
const data = await s3.file("my-bucket/image.jpg").arrayBuffer();
// ทำงานกับ S3-compatible storage (MinIO, R2, etc.)
const r2 = new S3Client({
accessKeyId: process.env.R2_ACCESS_KEY,
secretAccessKey: process.env.R2_SECRET_KEY,
endpoint: "https://account.r2.cloudflarestorage.com",
});
Bun Shell
// Bun Shell — Run shell commands ใน JavaScript
import { $ } from "bun";
// Simple command
const result = await $`ls -la`;
console.log(result.text());
// With variables (safe from injection)
const dir = "/tmp";
await $`ls ${dir}`;
// Pipe
const count = await $`cat file.txt | wc -l`.text();
// Redirect
await $`echo "hello" > output.txt`;
// Error handling
try {
await $`command-that-doesnt-exist`;
} catch (e) {
console.error("Command failed:", e.exitCode);
}
// Cross-platform — ทำงานบน Windows, macOS, Linux!
Bun.serve() — HTTP Server
// HTTP server ที่เร็วที่สุดใน JavaScript ecosystem
const server = Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/") {
return new Response("Hello from Bun!", {
headers: { "Content-Type": "text/plain" },
});
}
if (url.pathname === "/json") {
return Response.json({ message: "Hello", timestamp: Date.now() });
}
if (url.pathname === "/html") {
return new Response("Hello Bun!
", {
headers: { "Content-Type": "text/html" },
});
}
return new Response("Not Found", { status: 404 });
},
});
console.log(`Server running at http://localhost:${server.port}`);
// Benchmark: Bun.serve() handles 250,000+ req/sec
// Node.js http.createServer: ~100,000 req/sec
WebSocket in Bun
// Built-in WebSocket server (ไม่ต้อง ws package!)
Bun.serve({
port: 3000,
fetch(req, server) {
// Upgrade HTTP to WebSocket
if (server.upgrade(req)) return;
return new Response("Upgrade failed", { status: 500 });
},
websocket: {
open(ws) {
console.log("Client connected");
ws.subscribe("chat"); // PubSub built-in!
},
message(ws, message) {
console.log(`Received: ${message}`);
ws.publish("chat", `Echo: ${message}`); // Broadcast to all
},
close(ws) {
console.log("Client disconnected");
ws.unsubscribe("chat");
},
},
});
// Benchmark: Bun WebSocket handles 1.6M messages/sec
// ws (Node.js): ~400K messages/sec
Bun + Hono / Elysia Frameworks
// Hono — Lightweight web framework (works with Bun, Node, Deno, Cloudflare)
import { Hono } from "hono";
const app = new Hono();
app.get("/", (c) => c.text("Hello Hono + Bun!"));
app.get("/json", (c) => c.json({ message: "fast" }));
app.post("/users", async (c) => {
const body = await c.req.json();
return c.json({ created: body }, 201);
});
export default app; // Bun จะ Serve อัตโนมัติ
// -----------------------------------------------
// Elysia — Bun-native framework (เร็วที่สุด!)
import { Elysia } from "elysia";
const app = new Elysia()
.get("/", () => "Hello Elysia!")
.get("/user/:id", ({ params: { id } }) => `User ${id}`)
.post("/users", ({ body }) => body, {
body: { name: String, email: String } // Built-in validation!
})
.listen(3000);
console.log(`Elysia running at http://localhost:${app.server?.port}`);
Bun + React / Next.js
# ใช้ Bun กับ Next.js
bunx create-next-app@latest my-app
cd my-app
bun install
bun run dev # เริ่ม Dev server ด้วย Bun
# ใช้ Bun กับ Vite + React
bun create vite my-react-app --template react-ts
cd my-react-app
bun install
bun run dev
# Bun ทำงานเป็น Package manager + Script runner
# Next.js/Vite ยังใช้ Node.js runtime ภายใน (บางส่วน)
# แต่ bun install + bun run dev เร็วกว่ามาก
Bun Compatibility กับ Node.js Ecosystem
Bun ตั้งเป้าเป็น Drop-in replacement ของ Node.js สิ่งที่ Compatible:
Node.js APIs ที่รองรับ: fs, path, os, crypto, http, https, net, stream, events, buffer, url, querystring, child_process, worker_threads, util, assert, zlib, dns, tls และอื่นๆ อีกมาก
npm Packages ที่ทำงานได้: Express, Fastify, Koa, Socket.io, Prisma, TypeORM, Drizzle, React, Vue, Angular, Next.js, Nuxt, Svelte, Tailwind, และ npm packages อีกเกือบทั้งหมด
สิ่งที่ยังมี Gaps (ปี 2026): บาง Native addons (C++ addons) อาจไม่ทำงาน, VM module ยังไม่สมบูรณ์, Inspector/Debugger protocol ยังต่างจาก Node.js บ้าง, บาง Edge cases ของ Node.js stream ยังไม่ 100%
Bun in Docker
# Dockerfile สำหรับ Bun
FROM oven/bun:1 AS base
WORKDIR /app
# Install dependencies
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile --production
# Copy source
COPY . .
# Build (ถ้าต้อง bundle)
RUN bun build ./src/index.ts --outdir ./dist --target bun
# Production image
FROM oven/bun:1-slim
WORKDIR /app
COPY --from=base /app/dist ./dist
COPY --from=base /app/node_modules ./node_modules
COPY --from=base /app/package.json ./
EXPOSE 3000
CMD ["bun", "run", "dist/index.js"]
# Image size: ~150MB (vs Node.js Alpine ~180MB)
Bun for Production — Stability Status
| Feature | Stability (2026) | Production Ready? |
|---|---|---|
| Runtime (bun run) | Stable | ใช้ได้ |
| Package Manager (bun install) | Stable | ใช้ได้ |
| Test Runner (bun test) | Stable | ใช้ได้ |
| Bundler (bun build) | Stable | ใช้ได้ (แต่ Plugin ecosystem ยังเล็ก) |
| HTTP Server (Bun.serve) | Stable | ใช้ได้ |
| WebSocket | Stable | ใช้ได้ |
| SQLite | Stable | ใช้ได้ |
| Node.js compatibility | ~95%+ | ทดสอบก่อนใช้ |
| Windows support | Stable (ตั้งแต่ v1.1) | ใช้ได้ |
Limitations & Edge Cases
1. Node.js compatibility ยังไม่ 100%: Native C++ addons บางตัวไม่ทำงาน (ต้อง Compile ใหม่สำหรับ Bun) ถ้า Project พึ่งพา Node.js-specific features มาก อาจพบปัญหา
2. Ecosystem ยังเล็กกว่า Node.js: Bun-specific packages ยังน้อย ส่วนใหญ่ใช้ npm packages ซึ่งทำงานได้ดี แต่บาง Edge cases อาจพบ Bug
3. Debugging: Chrome DevTools protocol ยังไม่ 100% เหมือน Node.js ถ้า Debug complex issues อาจยากกว่า
4. Production track record: Node.js มี Production track record มากกว่า 15 ปี Bun ยังค่อนข้างใหม่ (v1.0 ออกปลายปี 2023) แม้จะ Stable แล้ว แต่บาง Enterprise ยังรอดูอยู่
คำแนะนำ: สำหรับ Projects ใหม่ ลอง Bun ได้เลย สำหรับ Existing projects ทดสอบ Compatibility ก่อน Migrate เริ่มจากใช้ bun install (Package manager) ก่อน ซึ่ง Drop-in ได้ง่ายที่สุด แล้วค่อยๆ ขยายไปใช้ Runtime และ Test runner
สรุป
Bun เป็น Game changer ของ JavaScript ecosystem ด้วยการรวม Runtime + Bundler + Test runner + Package manager ไว้ในตัวเดียว พร้อม Performance ที่เร็วกว่า Node.js 2-10 เท่าในเกือบทุกด้าน Native TypeScript/JSX support ทำให้ไม่ต้อง Configure อะไร Built-in SQLite, S3, Shell ลดการพึ่งพา Third-party packages
ในปี 2026 Bun เข้าสู่ช่วง Mature แล้ว Compatibility กับ Node.js ecosystem สูงมาก ใช้งานจริงใน Production ได้ สำหรับ JavaScript developer ที่ต้องการ Speed และ Simplicity Bun คือคำตอบที่น่าลองมากที่สุดในตอนนี้
