Bun 是什么?
Bun 是一个号称"all-in-one"的 JavaScript 运行时,集成了包管理器、打包器、测试框架和转译器。2025年底发布的 Bun 2.0 版本已经达到了生产就绪的成熟度。
为什么从 Node.js 迁移?
| 对比项 | Node.js | Bun 2.0 |
|---|---|---|
| 冷启动 | 200-500ms | 30-80ms |
| npm install | 5-30s | 1-3s |
| 测试运行 | Jest/Vitest 配置繁琐 | 内置、零配置 |
| TypeScript | ts-node/tsx | 原生支持 |
| 包管理 | npm/yarn/pnpm | 内置(比 npm 快 10x) |
安装与迁移
# 安装 Bun
curl -fsSL https://bun.sh/install | bash
# 在现有项目中使用
bun install # 替代 npm install — 快 10-20 倍
bun run dev # 替代 npm run dev
兼容性
Bun 2.0 对 Node.js API 的兼容性已超过 95%。大多数 Express/Koa/Fastify 应用可以直接跑:
// Express 应用 — 无缝运行在 Bun 上
import express from "express";
const app = express();
app.get("/", (req, res) => res.json({ ok: true }));
app.listen(3000);
// 甚至更快:Hono 框架在 Bun 上性能更优
// import { Hono } from "hono";
// const app = new Hono();
// app.get("/", (c) => c.json({ ok: true }));
原生 SQLite 支持
Bun 内置了 SQLite 驱动,无需安装任何依赖:
import { Database } from "bun:sqlite";
const db = new Database("app.db");
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE
)`);
db.prepare("INSERT INTO users (name, email) VALUES ($name, $email)").run({
$name: "Alice",
$email: "alice@example.com",
});
const users = db.query("SELECT * FROM users").all();
console.log(users);
文件操作 API
import { BunFile } from "bun";
// 读取文件
const text = await Bun.file("data.json").text();
const config = JSON.parse(text);
// 写入文件
await Bun.write("output.txt", "Hello from Bun!");
// 流式处理大文件
const stream = Bun.file("large.csv").stream();
for await (const chunk of stream) {
// 处理数据块
}
实际迁移注意事项
- Native modules:node-gyp 模块需要重新编译
- Node:worker_threads:部分高级 API 有差异
- 进程管理:pm2 不兼容,建议用内置
--watch - 测试:Bun 内置 test runner 兼容 Jest API
bun test # 替代 jest
bun run --watch app # 替代 nodemon
bun build ./src # 替代 esbuild
Bun 2.0 在 2026 年已经是一个成熟的选择,特别适合新项目和中小型 Node.js 服务的迁移。不必全部迁移,但在新项目中值得一试。