tools 工具 Bun JavaScript 运行时 Bun 是一个全能型 JavaScript/TypeScript 运行时,集成了包管理器、打包器、测试框架于一体,启动速度比 Node.js 快数倍,已被 Anthropic 收购用于加速 Claude Code 开发。
核心知识点 知识点 说明 工具定位 JavaScript/TypeScript 全能运行时 最新版本 v1.3.11(内置 Postgres/MySQL/Redis 支持) 开发语言 Zig + JavaScriptCore 引擎 核心优势 启动极快、内置工具链、Node.js 兼容 内置功能 包管理、打包、测试、数据库客户端 与 Anthropic 2025.12 被 Anthropic 收购,用于 Claude Code
安装配置 # 安装 Bun
curl -fsSL https://bun.sh/install | bash # 一键安装
bun --version # 验证版本
# 或用 npm 安装
npm install -g bun
基本使用 1. 项目初始化和包管理 bun init # 初始化项目(生成 package.json)
bun add express # 添加依赖(比 npm install 快得多)
bun add -d typescript # 添加开发依赖
bun install # 安装所有依赖
bun remove express # 移除依赖
2. 运行脚本 bun run index.ts # 直接运行 TypeScript(无需编译)
bun run index.js # 运行 JavaScript
bun --hot run server.ts # 热重载模式
3. Web 服务器 // server.ts
const server = Bun . serve ({
port : 3000 , // 端口
fetch ( req ) { // 请求处理函数
const url = new URL ( req . url );
if ( url . pathname === "/api/hello" ) {
return Response . json ({ message : "Hello from Bun!" });
}
return new Response ( "Not Found" , { status : 404 });
},
});
console . log ( `服务器运行在 http://localhost: ${ server . port } ` );
4. 文件操作 // Bun 内置的文件 API(比 Node.js fs 更简洁)
const file = Bun . file ( "data.txt" ); // 引用文件
const text = await file . text (); // 读取文本
const json = await Bun . file ( "data.json" ). json (); // 读取 JSON
// 写入文件
await Bun . write ( "output.txt" , "Hello Bun!" ); // 写入文本
await Bun . write ( "data.json" , JSON . stringify ({ key : "value" }));
5. 测试 // test.ts(Bun 内置测试框架)
import { expect , test , describe } from "bun:test" ;
describe ( "BMI 计算" , () => {
test ( "正常计算" , () => {
const bmi = 75 / ( 1.75 * 1.75 );
expect ( bmi ). toBeCloseTo ( 24.49 , 1 );
});
test ( "超重判断" , () => {
expect ( 28.5 > 25 ). toBe ( true );
});
});
高级用法 内置数据库支持(v1.2+) // PostgreSQL(内置,无需安装额外包)
import { SQL } from "bun" ;
const sql = new SQL ( "postgres://user:pass@localhost/db" );
const users = await sql `SELECT * FROM users WHERE age > ${ 25 } ` ;
// SQLite(内置)
import { Database } from "bun:sqlite" ;
const db = new Database ( "mydb.sqlite" );
db . run ( "CREATE TABLE IF NOT EXISTS samples (id TEXT, bmi REAL)" );
db . run ( "INSERT INTO samples VALUES (?, ?)" , [ "T2D_001" , 28.5 ]);
const rows = db . query ( "SELECT * FROM samples" ). all ();
常见报错与解决 报错信息 原因 解决方法 bun: command not found未安装或未加到 PATH 重新安装并 source ~/.bashrc Node.js 模块不兼容 部分 native addon 不支持 查看 Bun 兼容性列表 EACCES permission denied权限不足 不要用 sudo 安装
速查表 # ===== Bun 速查表 =====
# 安装
curl -fsSL https://bun.sh/install | bash
# 项目管理
bun init # 初始化
bun add pkg # 添加依赖
bun install # 安装依赖
bun remove pkg # 移除依赖
# 运行
bun run file.ts # 运行文件
bun --hot run server.ts # 热重载
# 测试
bun test # 运行测试
# 打包
bun build ./src/index.ts --outdir ./dist
# 对比 Node.js
# bun install 比 npm install 快 25 倍
# bun run 比 node 启动快 4 倍
# bun test 比 jest 快 5-10 倍