bun
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBun
Bun
All-in-one JavaScript/TypeScript toolkit: runtime, package manager, test runner, bundler.
一站式JavaScript/TypeScript工具包:包含运行时、包管理器、测试运行器、打包工具。
Quick Navigation
快速导航
| Topic | Reference |
|---|---|
| Package Manager | |
| Project Setup | |
| Development | |
| Module System | |
| TypeScript & JSX | |
| Configuration | |
| HTTP Server | |
| WebSockets | |
| File I/O | |
| SQLite | |
| S3 Storage | |
| Redis | |
| Low-Level Network | |
| Fetch API | |
| Shell Scripts | |
| Spawn Process | |
| Workers | |
| Native FFI | |
| C/C++ Compile | |
| Transpiler | |
| Plugins | |
| FS Router | |
| Environment Vars | |
| Utilities | |
| Node.js Compat | |
| 主题 | 参考文档 |
|---|---|
| 包管理器 | |
| 项目初始化 | |
| 开发指南 | |
| 模块系统 | |
| TypeScript & JSX | |
| 配置文件 | |
| HTTP服务器 | |
| WebSockets | |
| 文件I/O | |
| SQLite | |
| S3存储 | |
| Redis | |
| 底层网络 | |
| Fetch API | |
| Shell脚本 | |
| 进程启动 | |
| 工作线程 | |
| 原生FFI | |
| C/C++编译 | |
| 转译器 | |
| 插件 | |
| 文件系统路由 | |
| 环境变量 | |
| 实用工具 | |
| Node.js兼容性 | |
When to Use Bun
Bun 的适用场景
- Running TypeScript/JSX without build step
- Fast HTTP server with native routing
- SQLite database (embedded, no deps)
- WebSocket server/client
- S3-compatible storage (AWS, R2, MinIO)
- Redis caching/pub-sub
- Cross-platform shell scripts
- Markdown parsing (v1.3.8+)
- Native library calls via FFI
- 无需构建步骤直接运行TypeScript/JSX
- 带有原生路由的高性能HTTP服务器
- SQLite数据库(嵌入式,无依赖)
- WebSocket服务器/客户端
- 兼容S3的存储服务(AWS、R2、MinIO)
- Redis缓存/发布订阅
- 跨平台Shell脚本
- Markdown解析(v1.3.8+)
- 通过FFI调用原生库
Core Advantages
核心优势
- 4x faster startup than Node.js
- Native TypeScript/JSX — no tsconfig needed
- ESM + CommonJS — both work seamlessly
- Web APIs built-in — fetch, WebSocket, etc.
- 30x faster installs than npm
- 启动速度比Node.js快4倍
- 原生支持TypeScript/JSX — 无需tsconfig配置
- ESM + CommonJS — 两者无缝兼容
- 内置Web API — fetch、WebSocket等
- 安装速度比npm快30倍
Quick Start
快速开始
bash
undefinedbash
undefinedRun TypeScript directly
Run TypeScript directly
bun run index.ts
bun run index.ts
Install packages
Install packages
bun install
bun install
Run package.json script
Run package.json script
bun run dev
bun run dev
Execute package binary
Execute package binary
bunx cowsay "Hello"
bunx cowsay "Hello"
Run tests
Run tests
bun test
bun test
Build for production
Build for production
bun build ./index.ts --outdir ./dist
bun build ./index.ts --outdir ./dist
Bundle analysis for LLMs (v1.3.8+)
Bundle analysis for LLMs (v1.3.8+)
bun build ./index.ts --metafile-md --outdir ./dist
undefinedbun build ./index.ts --metafile-md --outdir ./dist
undefinedCritical Rules
重要规则
| Don't | Do |
|---|---|
| |
| |
| |
| |
| Built-in |
| 不推荐做法 | 推荐做法 |
|---|---|
| |
| |
| |
| |
| 内置.env支持 |
Essential Recipes
核心使用示例
HTTP Server
HTTP服务器
ts
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/api/data") {
return Response.json({ ok: true });
}
return new Response("Not Found", { status: 404 });
},
});ts
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/api/data") {
return Response.json({ ok: true });
}
return new Response("Not Found", { status: 404 });
},
});File Operations
文件操作
ts
// Read
const content = await Bun.file("data.txt").text();
// Write
await Bun.write("output.txt", "Hello World");
// JSON
const config = await Bun.file("config.json").json();ts
// Read
const content = await Bun.file("data.txt").text();
// Write
await Bun.write("output.txt", "Hello World");
// JSON
const config = await Bun.file("config.json").json();SQLite
SQLite
ts
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)");
const insert = db.prepare("INSERT INTO users (name) VALUES (?)");
insert.run("Alice");
const users = db.query("SELECT * FROM users").all();ts
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)");
const insert = db.prepare("INSERT INTO users (name) VALUES (?)");
insert.run("Alice");
const users = db.query("SELECT * FROM users").all();WebSocket Server
WebSocket服务器
ts
Bun.serve({
fetch(req, server) {
if (server.upgrade(req)) return;
return new Response("Upgrade failed", { status: 400 });
},
websocket: {
message(ws, message) {
ws.send(`Echo: ${message}`);
},
},
});ts
Bun.serve({
fetch(req, server) {
if (server.upgrade(req)) return;
return new Response("Upgrade failed", { status: 400 });
},
websocket: {
message(ws, message) {
ws.send(`Echo: ${message}`);
},
},
});Shell Commands
Shell命令
ts
import { $ } from "bun";
// Simple command
const files = await $`ls -la`.text();
// With variables (auto-escaped)
const name = "my file.txt";
await $`cat ${name}`;
// Piping
await $`cat data.csv | grep "pattern" | wc -l`;ts
import { $ } from "bun";
// Simple command
const files = await $`ls -la`.text();
// With variables (auto-escaped)
const name = "my file.txt";
await $`cat ${name}`;
// Piping
await $`cat data.csv | grep "pattern" | wc -l`;S3 Storage
S3存储
ts
import { s3 } from "bun";
// Upload
await s3.file("uploads/doc.pdf").write(data);
// Download
const content = await s3.file("uploads/doc.pdf").text();
// Presigned URL
const url = s3.presign("uploads/doc.pdf", { expiresIn: 3600 });ts
import { s3 } from "bun";
// Upload
await s3.file("uploads/doc.pdf").write(data);
// Download
const content = await s3.file("uploads/doc.pdf").text();
// Presigned URL
const url = s3.presign("uploads/doc.pdf", { expiresIn: 3600 });Redis
Redis
ts
import { redis } from "bun";
await redis.set("key", "value");
const value = await redis.get("key");
await redis.expire("key", 3600);ts
import { redis } from "bun";
await redis.set("key", "value");
const value = await redis.get("key");
await redis.expire("key", 3600);Testing
测试
ts
import { expect, test, describe } from "bun:test";
describe("math", () => {
test("2 + 2 = 4", () => {
expect(2 + 2).toBe(4);
});
});ts
import { expect, test, describe } from "bun:test";
describe("math", () => {
test("2 + 2 = 4", () => {
expect(2 + 2).toBe(4);
});
});Configuration (bunfig.toml)
配置文件(bunfig.toml)
toml
[run]
watch = true
[install]
registry = "https://registry.npmjs.org"
[test]
coverage = truetoml
[run]
watch = true
[install]
registry = "https://registry.npmjs.org"
[test]
coverage = trueEnvironment Variables
环境变量
bash
undefinedbash
undefined.env files loaded automatically
.env files loaded automatically
DATABASE_URL=postgres://localhost/mydb
```ts
// Access
Bun.env.DATABASE_URL;
process.env.DATABASE_URL;
import.meta.env.DATABASE_URL;DATABASE_URL=postgres://localhost/mydb
```ts
// Access
Bun.env.DATABASE_URL;
process.env.DATABASE_URL;
import.meta.env.DATABASE_URL;