用 Bun 写后端:Bun.serve、bun:sqlite 与 bun test
MrSmy Lv5

Bun 1.1(2024 年 4 月)补上 Windows 支持后,我开始把一些内部服务真的用 Bun 写。这篇是一个完整的小服务(带认证、SQLite 存储、WebSocket 推送、测试),重点是真实的代码是什么样的,以及哪里不舒服。

项目结构

1
2
3
4
5
6
7
8
9
10
11
tiny-api/
├── src/
│ ├── index.ts # 入口
│ ├── routes/
│ │ ├── auth.ts
│ │ └── todos.ts
│ ├── db.ts
│ └── ws.ts
├── src/**/*.test.ts
├── .env
└── package.json

package.json 极简:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"name": "tiny-api",
"scripts": {
"dev": "bun --hot src/index.ts",
"start": "bun src/index.ts",
"test": "bun test",
"build": "bun build --compile src/index.ts --outfile tiny-api"
},
"devDependencies": {
"@types/bun": "^1.1.0",
"typescript": "^5.4.0"
}
}

零运行时依赖。HTTP 服务、SQLite、JWT 签名、密码哈希、测试全在 Bun 里。

Bun.serve:路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// src/index.ts
import { authRoutes } from './routes/auth'
import { todoRoutes } from './routes/todos'
import { openSocket } from './ws'

type Handler = (req: Request, ctx: { params: Record<string, string> }) => Response | Promise<Response>

const routes: Array<{ method: string; pattern: RegExp; keys: string[]; handler: Handler }> = []

function route(method: string, path: string, handler: Handler) {
// /todos/:id → /\/todos\/([^/]+)/
const keys: string[] = []
const pattern = new RegExp(
'^' + path.replace(/:(\w+)/g, (_, k) => { keys.push(k); return '([^/]+)' }) + '$'
)
routes.push({ method, pattern, keys, handler })
}

// 注册
for (const r of [...authRoutes, ...todoRoutes]) route(r.method, r.path, r.handler)

const server = Bun.serve({
port: Number(Bun.env.PORT ?? 3000),
async fetch(req) {
const url = new URL(req.url)

// WebSocket 升级
if (url.pathname === '/ws') {
const ok = server.upgrade(req)
return ok ? undefined : new Response('Upgrade failed', { status: 400 })
}

if (url.pathname === '/api/todos' && req.method === 'GET') {
return todoRoutes.find((r) => r.path === '/api/todos' && r.method === 'GET')!.handler(req, { params: {} })
}

for (const r of routes) {
if (r.method !== req.method) continue
const m = url.pathname.match(r.pattern)
if (!m) continue
const params = Object.fromEntries(r.keys.map((k, i) => [k, decodeURIComponent(m[i + 1])]))
return r.handler(req, { params })
}

return new Response('Not Found', { status: 404 })
},
websocket: {
open: openSocket,
message(ws, msg) { /* ... */ },
},
error(err) {
console.error(err)
return Response.json({ error: 'internal' }, { status: 500 })
},
})

console.log(`listening on ${server.port}`)

不用 Express 时,路由要自己写(上面这个 40 行)。如果不想自己写,可以用 Hono——它在 Bun 上跑得比 Express 好得多:

1
2
3
4
5
6
7
import { Hono } from 'hono'

const app = new Hono()
app.get('/api/todos', async (c) => {
const rows = db.query('SELECT * FROM todos').all()
return c.json(rows)
})

Hono 是”零依赖 + 基于 Request/Response”,和 Bun 的设计对齐。Express 在 Bun 上能跑,但它的 req/res 是 Node 的对象模型,要经过兼容层,性能会打折扣。

bun:sqlite:同步但很快

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/db.ts
import { Database } from 'bun:sqlite'

export const db = new Database('data/app.db', { create: true })

db.run(`
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA foreign_keys = ON;

CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS todos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id),
title TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE INDEX IF NOT EXISTS idx_todos_user ON todos(user_id, done);
`)

注意 db.run 可以一次执行多条语句——这在 better-sqlite3 里要拆开。

查询:

1
2
3
4
5
6
7
8
9
// 单条
const user = db.query('SELECT * FROM users WHERE email = ?').get(email)

// 多条
const todos = db.query('SELECT * FROM todos WHERE user_id = ? ORDER BY id DESC').all(userId)

// 语句复用(预编译,性能关键)
const insertTodo = db.prepare('INSERT INTO todos (user_id, title) VALUES (?, ?) RETURNING *')
const created = insertTodo.get(userId, title)

get() / all() 是同步的。这看起来”反直觉”(在 Node 里同步 IO 是禁忌),但 SQLite 是本地文件,同步调用的开销只有几十微秒,比 await 的微任务调度还便宜。

better-sqlite3 也是这个思路,而 Bun 的实现比它快 3-5 倍(不用跨 native addon 边界)。

坑:db.query() 每次都创建 statement,高频调用要缓存:

1
2
3
4
5
const queries = {
findUser: db.query('SELECT * FROM users WHERE email = ?'),
insertTodo: db.prepare('INSERT INTO todos (user_id, title) VALUES (?, ?) RETURNING *'),
listTodos: db.query('SELECT * FROM todos WHERE user_id = ? ORDER BY id DESC'),
}

query 和 prepare 在 Bun 里是同义的(都返回 Statement),官方在 1.1 之后统一了这两个名字。

密码与 JWT

没有内置 bcrypt(那是 native addon)。用 Argon2 的 WASM 版本或者 Bun.password:

1
2
3
4
5
6
7
8
// Bun 内置的密码哈希(用 argon2id 或 bcrypt)
const hash = await Bun.password.hash(password, {
algorithm: 'argon2id',
memoryCost: 65536, // 64MB
timeCost: 3,
})

const valid = await Bun.password.verify(password, hash)

这是 1.1 引入的,基于 BoringSSL 的实现。比装 bcrypt 再编译省事太多。

JWT:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 用 Web Crypto(全局可用,不需要 jsonwebtoken)
async function signJwt(payload: object, secret: string): Promise<string> {
const header = { alg: 'HS256', typ: 'JWT' }
const enc = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64url')

const data = `${enc(header)}.${enc(payload)}`
const key = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
)
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(data))
return `${data}.${Buffer.from(sig).toString('base64url')}`
}

crypto.subtle 是 Web 标准,Bun 和 Node 18+ 都有。不需要 jsonwebtoken 这个包(它有历史漏洞,比如算法混淆)。

认证中间件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// src/routes/auth.ts
export const authRoutes = [
{
method: 'POST',
path: '/api/auth/register',
handler: async (req: Request) => {
const { email, password } = await req.json()

if (!email || typeof password !== 'string' || password.length < 8) {
return Response.json({ error: '参数不合法' }, { status: 400 })
}

const exists = db.query('SELECT id FROM users WHERE email = ?').get(email)
if (exists) return Response.json({ error: '邮箱已注册' }, { status: 409 })

const hash = await Bun.password.hash(password, { algorithm: 'argon2id' })
const user = db
.prepare('INSERT INTO users (email, password) VALUES (?, ?) RETURNING id, email')
.get(email, hash) as { id: number; email: string }

return Response.json({ user }, { status: 201 })
},
},
{
method: 'POST',
path: '/api/auth/login',
handler: async (req: Request) => {
const { email, password } = await req.json()
const user = db.query('SELECT * FROM users WHERE email = ?').get(email) as any

// 统一错误信息,避免枚举用户
if (!user || !(await Bun.password.verify(password, user.password))) {
return Response.json({ error: '邮箱或密码错误' }, { status: 401 })
}

const token = await signJwt(
{ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 },
Bun.env.JWT_SECRET!
)
return Response.json({ token })
},
},
]

export async function requireAuth(req: Request): Promise<{ userId: number } | null> {
const header = req.headers.get('authorization')
if (!header?.startsWith('Bearer ')) return null

try {
const payload = await verifyJwt(header.slice(7), Bun.env.JWT_SECRET!)
return { userId: (payload as any).sub }
} catch {
return null
}
}

**Bun.env 自动读 .env**——不需要 dotenv。这是 Bun 的另一个”少一个依赖”的地方。

WebSocket

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/ws.ts
type Client = { ws: ServerWebSocket<{ userId: number }>; userId: number }
const clients = new Set<Client>()

export function openSocket(ws: ServerWebSocket<{ userId: number }>) {
clients.add({ ws, userId: ws.data.userId })
}

export function broadcast(userId: number, event: unknown) {
const msg = JSON.stringify(event)
for (const c of clients) {
if (c.userId === userId) c.ws.send(msg)
}
}

export function removeSocket(ws: ServerWebSocket) {
for (const c of clients) {
if (c.ws === ws) clients.delete(c)
}
}

升级时带认证:

1
2
3
4
5
6
7
8
if (url.pathname === '/ws') {
const token = url.searchParams.get('token')
const auth = token ? await verifyJwt(token, Bun.env.JWT_SECRET!) : null
if (!auth) return new Response('unauthorized', { status: 401 })

const ok = server.upgrade(req, { data: { userId: (auth as any).sub } })
return ok ? undefined : new Response('Upgrade failed', { status: 400 })
}

server.upgrade 是 Bun 的 API,data 会挂到 ws.data 上。比 ws 库的 WebSocketServer 少一层事件绑定。

测试

1
2
3
4
5
6
// src/routes/auth.test.ts
import { test, expect, beforeEach, afterAll } from 'bun:test'
import { Database } from 'bun:sqlite'

// 用内存库测,不污染开发数据
// 注意:db 是模块级单例,要用 preload 或者在测试里替换

这里有个实际问题:**db.ts 里 new Database('data/app.db') 是模块级副作用**,测试会写到真实文件。

解法 1:环境变量控制。

1
2
3
4
5
// src/db.ts
export const db = new Database(
Bun.env.NODE_ENV === 'test' ? ':memory:' : 'data/app.db',
{ create: true }
)

解法 2:导出一个工厂,生产代码用单例。

1
2
3
4
5
6
7
export function createDb(path = 'data/app.db') {
const db = new Database(path, { create: true })
migrate(db)
return db
}

export const db = createDb(Bun.env.DB_PATH ?? 'data/app.db')

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { test, expect } from 'bun:test'
import { createApp } from '../app'

test('注册 → 登录 → 创建 todo', async () => {
const app = createApp({ db: createDb(':memory:') }) // 每次全新

const reg = await app.request('/api/auth/register', {
method: 'POST',
body: JSON.stringify({ email: 'a@b.com', password: 'password123' }),
})
expect(reg.status).toBe(201)

const login = await app.request('/api/auth/login', {
method: 'POST',
body: JSON.stringify({ email: 'a@b.com', password: 'password123' }),
})
const { token } = await login.json()
expect(token).toBeString()

const create = await app.request('/api/todos', {
method: 'POST',
headers: { authorization: `Bearer ${token}` },
body: JSON.stringify({ title: '写代码' }),
})
expect(create.status).toBe(201)

const list = await app.request('/api/todos', {
headers: { authorization: `Bearer ${token}` },
})
expect((await list.json()).length).toBe(1)
})

关键设计:把路由封装成 createApp({ db }),接受注入的 db。这样测试可以完全隔离,而且不需要起真实端口(app.request() 直接调用 handler)。

如果 Bun.serve 的 fetch 是内联在入口文件里的,就没法这样测。这是”为了可测试性调整结构”的典型例子。

bun test 的速度:

1
2
3
bun test v1.1.x
3 pass, 0 fail
Ran 3 tests across 1 files. [38.00ms]

38ms。同样的测试在 Jest + ts-jest 下要 4 秒。

热重载

1
bun --hot src/index.ts

--hot 的语义是”保留进程状态,替换模块”。对比 --watch(重启进程):

--watch --hot
行为 重启整个进程 替换修改的模块
内存状态 丢失 保留
适合 大部分后端 需要保留连接/缓存时

但 --hot 有风险:

1
2
// 模块顶层建的连接
const db = new Database('app.db') // 热更新后旧连接没关

模块被替换时,旧的副作用(定时器、连接、监听器)不会自动清理。Bun 支持 import.meta.hot.dispose(),但要自己写:

1
2
3
4
5
6
if (import.meta.hot) {
import.meta.hot.dispose(() => {
server.stop()
db.close()
})
}

**我们的实践:开发用 --watch(更接近生产行为),只在调 UI 时用 --hot**。

打包成单文件

1
bun build --compile src/index.ts --outfile tiny-api

产物是一个可执行文件(约 60MB,含 Bun 运行时)。部署:

1
2
scp tiny-api server:/opt/app/
ssh server '/opt/app/tiny-api'

不需要 Node、不需要 node_modules、不需要 Docker。这对”小服务”是巨大的运维简化。

Docker 里也能用:

1
2
3
4
5
6
7
8
9
10
11
12
13
FROM oven/bun:1.1-alpine AS build
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile
COPY . .
RUN bun build --compile src/index.ts --outfile app

FROM alpine:3.20
RUN apk add --no-cache ca-certificates
WORKDIR /app
COPY --from=build /app/app .
EXPOSE 3000
CMD ["./app"]

镜像约 80MB(主要是 60MB 的二进制)。

不舒服的地方

1. 错误堆栈不友好

1
2
error: Cannot find module "./routes/todos"
at /app/src/index.ts:3:1

只显示一行,没有 node_modules 的调用链上下文。Node 的堆栈信息量大得多。

2. 某些包的兼容性还是问题

我们踩到的:

  • pino 的 AsyncLocalStorage 用法在 Bun 下 requestId 偶尔丢失
  • @sentry/node 的 auto-instrumentation 不工作(依赖 async_hooks)
  • drizzle-orm 的 sqlite driver 优先用 better-sqlite3,要用 bun:sqlite 得换 driver

3. 类型定义不全

@types/bun 覆盖了大部分,但 Bun.serve 的泛型推导在某些组合下会退化成 any。

4. import.meta.env 不存在

Vite 风格的环境变量在 Bun 里是 Bun.env 或者 process.env。跨运行时共享代码时要注意。

5. 监控生态薄弱

Node 的 APM(New Relic、Datadog、Sentry)都基于 async_hooks + require('module') 的 hook。Bun 的支持程度不一,出问题时很难排查。

最终选用的场景

这个小服务我们用了三个月,结论:

方面 评价
开发速度 ✅ 明显更快(少装 20 个包)
性能 ✅ 够用(单机 2 万 QPS 的简单接口)
稳定性 ✅ 三个月零 downtime
可观测性 ⚠️ 只有 console.log + 自己打的日志
部署 ✅ 单文件,最省事
团队接受度 ⚠️ 有人抱怨调试不方便

适合的内部服务画像:接口简单、数据量小(SQLite 够)、不需要复杂 APM、团队 1-2 人维护。

不适合的:核心交易、需要精细监控、多人长期维护。

小结

用 Bun 写生产服务的实际感受:

能力 成熟度(2024-05)
HTTP 服务 ✅ 生产可用
SQLite ✅ 生产可用
密码哈希 / JWT ✅ 够用
WebSocket ✅ 生产可用
测试 ✅ 很好
单文件编译 ✅ 杀手功能
可观测性生态 ❌ 短板
复杂框架兼容 ⚠️ 看运气

一个横向的结论:Bun 把一个”简单后端”的依赖从 30 个降到 0 个。这个价值在”小服务”上极其明显——不用管 package.json 里的版本冲突,不用管 node-gyp 编译失败,不用管 dotenv 加载顺序。

代价是”遇到问题时你没有社区答案”。用 Express 遇到问题,Stack Overflow 上有 500 个答案;用 Bun 遇到问题,只能翻 GitHub issue。

这个取舍在”内部工具”和”核心系统”之间的答案是不同的。

  • 本文标题:用 Bun 写后端:Bun.serve、bun:sqlite 与 bun test
  • 本文作者:MrSmy
  • 创建时间:2024-05-19 20:36:00
  • 本文链接:https://fengyang.live/2024/05/19/用Bun写后端:Bun.serve、bun-sqlite与bun test/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!