| name | bun |
| description | Fast, modern JavaScript runtime and toolkit. IMPORTANT: This is Bun, NOT Node.js. Use Bun-specific APIs below. Do NOT use Node.js APIs like require(), process, fs (use Bun.file() instead). |
Bun 是面向现代 JavaScript 生态的全新运行时,定位为 Node.js 的替代方案,基于 JavaScriptCore 引擎和 Zig 语言编写。请使用 Bun 特有的 API,不要使用 Node.js 的写法。
Quick Start
curl -fsSL https://bun.sh/install | bash
bun run index.ts
bun install
bun test
Key Features
- Native TypeScript: 直接运行 .ts/.tsx 文件,无需转译
- Built-in Tools: 包管理器、测试、打包工具内置
- Node.js Compatible: 兼容大部分 Node.js 生态
- Web APIs: 原生 fetch, WebSocket, ReadableStream
- Bun.serve(): 高性能 HTTP 服务
- Bun.file(): 简化文件操作
- Bun.password: 原生密码哈希(argon2)
- bun:test: 零配置测试框架
Module Import/Export
重要: Bun 默认使用 ES 模块,兼容 CommonJS,无需额外配置。
import fs from 'fs/promises';
export const foo = 'bar';
import App from './App.tsx';
const fs = require('fs');
module.exports = { foo: 'bar' };
const fs = require('fs');
Global Objects
重要: Bun 有自己的全局对象,优先使用 Bun 特有的写法。
console.log(import.meta.dir);
console.log(import.meta.file);
console.log(Bun.env.NODE_ENV);
console.log(Bun.version);
console.log(Bun.memoryUsage());
console.log(process.env.NODE_ENV);
console.log(process.pid);
const bytes = crypto.randomBytes(32);
HTTP Server (最核心差异)
重要: 使用 Bun.serve() 而非 http.createServer()。
Bun.serve({
port: 3000,
fetch(req) {
return new Response('Hello Bun', {
headers: { 'Content-Type': 'text/plain' }
});
}
});
Bun.serve({
port: 3000,
fetch(req) {
if (req.headers.get('upgrade') === 'websocket') {
const ws = new WebSocket(req);
ws.on('message', (data) => console.log('Message:', data));
return ws;
}
return new Response('Hello Bun');
}
});
File Operations
重要: 使用 Bun.file() 和 Bun.write() 而非 fs 模块。
const file = Bun.file('./test.txt');
const text = await file.text();
const json = await file.json();
const buffer = = await file.arrayBuffer();
await Bun.write('./test.txt', 'Hello Bun');
await Bun.write('./test.json', { name: 'Bun' });
import { readdir, mkdir } from 'node:fs/promises';
const files = await readdir(import.meta.dir);
await mkdir('./newDir', { recursive: true });
Cryptography
重要: 使用 Bun.password 和 Bun.hash 而非第三方库。
const hash = await Bun.password.hash('123456');
const isMatch = await Bun.password.verify('123456', hash);
const hash1 = Bun.hash('test');
const hash2 = Bun.hash.sha256('test');
Environment Variables
重要: Bun 自动读取 .env,使用 Bun.env 而非 dotenv。
console.log(Bun.env.DB_URL);
console.log(Bun.env.PORT);
console.log(process.env.DB_URL);
declare module "bun" {
interface Env {
DB_URL: string;
PORT: string;
}
}
Bun.env.DB_URL;
Package Manager
bun install axios
bun run start
bunx cowsay "Hello"
Testing
重要: 使用 bun:test 而非 Jest/Vitest。
import { test, expect } from 'bun:test';
test('1 + 1 = 2', () => {
expect(1 + 1).toBe(2);
});
Common Patterns
Running TypeScript
interface User {
id: number;
name: string;
}
const user: User = { id: 1, name: 'John' };
console.log(user);
bun run app.ts
SQLite
const db = new Bun.Database('my.db');
const users = db.query('SELECT * FROM users').all();
Migration Checklist
| Node.js | Bun | Notes |
|---|
require() | import | 默认 ESM |
__dirname | import.meta.dir | |
fs.readFile | Bun.file().text() | 更简洁 |
http.createServer | Bun.serve() | 性能更好 |
bcrypt | Bun.password | 内置 |
dotenv | Bun.env | 自动读取 |
Jest | bun:test | 零配置 |
npm | bun | 速度更快 |
Key Points
- 使用 Bun API: 优先使用
Bun.serve(), Bun.file(), Bun.write(), Bun.password, Bun.hash
- 使用 import: 默认 ES 模块,直接
import 而非 require
- 使用 import.meta.dir: 获取当前目录
- 使用 Bun.env: 访问环境变量,自动读取 .env
- 使用 bun:test: 内置测试框架
- 使用 bun: 包管理和运行脚本
Resources