Bun 打包与运行 — 用 Zig 写的极速 JavaScript 运行时,替代 Node.js + npm¶
一句话说明¶
Bun 是一个全能 JavaScript 工具箱:运行时(替代 Node.js)+ 包管理(替代 npm/pnpm)+ 打包器(替代 esbuild)+ 测试框架,全部用 Zig/C++ 编写,速度比 Node.js 快 3-5 倍。当前版本 v1.3.x。
安装与配置¶
# Linux/macOS 安装(一行命令)
curl -fsSL https://bun.sh/install | bash
# Windows(PowerShell)
powershell -c "irm bun.sh/install.ps1 | iex"
# 通过 npm 安装
npm install -g bun
# 验证安装
bun --version # 查看版本号
# 升级 Bun 自身
bun upgrade
# 项目初始化(类似 npm init)
bun init # 交互式创建项目
bun init -y # 跳过问答,用默认配置
核心用法¶
# ── 包管理(替代 npm/yarn/pnpm)──
bun install # 安装 package.json 中所有依赖(比 npm 快 25x)
bun add react # 安装包(相当于 npm install react)
bun add -d typescript # 安装开发依赖(-d 等于 --dev)
bun remove react # 卸载包
bun update # 更新所有依赖
# ── 运行脚本 ──
bun run dev # 运行 package.json 中的 dev 脚本
bun run src/index.ts # 直接运行 TypeScript 文件(无需编译!)
bun src/index.ts # 简写形式
# ── 执行一次性命令 ──
bunx create-react-app # 相当于 npx,临时下载并执行包
// src/server.ts — 用 Bun 内置 API 创建 HTTP 服务器
const server = Bun.serve({
port: 3000, // 监听端口
hostname: '0.0.0.0', // 监听所有网络接口
fetch(req: Request): Response { // 每个请求都会调用此函数
const url = new URL(req.url); // 解析 URL
if (url.pathname === '/health') { // 健康检查接口
return new Response('OK', { status: 200 });
}
return new Response('Hello from Bun!'); // 默认响应
},
});
console.log(`服务器运行在 http://localhost:${server.port}`);
实战案例¶
// ── 用 Bun 处理生信数据文件 ──
// 1. 读取大型 FASTQ 文件(Bun 的文件 API)
const file = Bun.file('/data/reads.fastq'); // 创建文件引用(不立即读取)
const text = await file.text(); // 读取全部内容为字符串
console.log('文件大小:', file.size, 'bytes'); // 获取文件大小
// 2. 流式处理大文件(推荐处理几 GB 的 FASTQ)
async function countReads(filePath: string): Promise<number> {
let count = 0; // 读段计数
const file = Bun.file(filePath);
const text = await file.text();
for (const line of text.split('\n')) {
if (line.startsWith('@')) count++; // FASTQ 的读段以 @ 开头
}
return count;
}
// 3. 写入文件
await Bun.write('/results/output.txt', '分析结果\n'); // 写入字符串
// 4. 执行 shell 命令(替代 child_process)
const result = await Bun.$`fastqc /data/sample.fastq --outdir /results`;
// Bun.$ 是内置的 shell 模板字符串,类似 zx
console.log('FastQC 完成:', result.exitCode);
// 5. 并行处理多个文件
const samples = ['S1.fastq', 'S2.fastq', 'S3.fastq'];
await Promise.all( // 并行执行
samples.map(s => Bun.$`fastqc /data/${s} --outdir /results`)
);
# ── Bun 内置测试框架 ──
bun test # 运行所有测试(查找 *.test.ts 文件)
bun test --watch # 监听模式
bun test --parallel # 并行运行(v1.3 新增)
bun test --shard 1/3 # 分片测试(在 CI 中分布到多个节点)
bun test --coverage # 代码覆盖率报告
// sum.test.ts — Bun 测试语法(兼容 Jest/Vitest API)
import { expect, test, describe } from 'bun:test'; // 使用 bun:test 模块
describe('基因计数工具', () => {
test('正确统计 FASTQ 读段数', () => {
const mockContent = '@read1\nATCG\n+\nIIII\n@read2\nGCTA\n+\nHHHH\n';
const count = mockContent.split('\n').filter(l => l.startsWith('@')).length;
expect(count).toBe(2); // 应有 2 条读段
});
});
常见报错与解决¶
| 报错 | 原因 | 解决方法 |
|---|---|---|
bun: command not found | 安装路径未加入 PATH | 重开终端,或执行 source ~/.bashrc |
Cannot find module | 依赖未安装 | 运行 bun install |
Bun.$ 命令执行失败 | 命令不存在或路径错误 | 检查命令是否在 PATH 中 |
| 内存使用高于预期 | 文件太大全量读取 | 改用流式处理,或用 Bun.file().stream() |
| TypeScript 路径别名不生效 | tsconfig.json 的 paths 未配置 | 在 tsconfig 中添加 paths 并重启 |
速查表¶
# 包管理
bun install # 安装全部依赖
bun add <pkg> # 添加包
bun add -d <pkg> # 添加开发依赖
bun remove <pkg> # 删除包
bun update # 更新所有包
# 运行
bun run <script> # 运行 npm script
bun <file.ts> # 直接运行 TS 文件
bunx <cmd> # 临时执行包命令
# 构建(打包为单文件)
bun build src/index.ts --outdir dist # 打包输出
bun build src/index.ts --target bun # 打包为 Bun 可执行文件
bun build src/index.ts --minify # 压缩输出
# 测试
bun test # 运行测试
bun test --watch # 监听模式
bun test --coverage # 覆盖率
# 官方文档:https://bun.sh/docs