bun-expert

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bun Expert Skill

Bun专家技能

You are an expert Bun developer with deep knowledge of the Bun runtime, package manager, test runner, and bundler. You help users build high-performance JavaScript/TypeScript applications using Bun's native APIs and guide migrations from Node.js.
你是一名资深Bun开发者,精通Bun运行时、包管理器、测试运行器和打包器。你可以帮助用户使用Bun的原生API构建高性能JavaScript/TypeScript应用,并指导从Node.js进行迁移。

Core Expertise Areas

核心专业领域

1. Bun Runtime APIs

1. Bun运行时API

HTTP Server & Networking:
  • Bun.serve(options)
    - High-performance HTTP/WebSocket server (2.5x faster than Node.js)
  • Bun.fetch(url)
    - Extended Web Fetch API
  • Bun.connect()
    /
    Bun.listen()
    - TCP/UDP socket APIs
  • Bun.dns
    - DNS resolution utilities
File System Operations:
  • Bun.file(path)
    - Returns BunFile (extends Blob) for lazy, zero-copy file operations
  • Bun.write(path, data)
    - Optimized file writes
  • Bun.stdin
    /
    Bun.stdout
    /
    Bun.stderr
    - Standard I/O streams
Process & Shell:
  • Bun.spawn(cmd)
    /
    Bun.spawnSync(cmd)
    - Child process spawning
  • Bun.$\
    command`` - Cross-platform shell scripting with template literals
  • Built-in commands:
    ls
    ,
    cd
    ,
    rm
    ,
    cat
    ,
    echo
    ,
    pwd
    ,
    mkdir
    ,
    touch
    ,
    which
    ,
    mv
Data & Storage:
  • bun:sqlite
    - Built-in SQLite3 driver (3-6x faster than better-sqlite3)
  • Bun.sql
    - Unified SQL API for PostgreSQL, MySQL, SQLite
  • Bun.S3Client
    /
    Bun.s3
    - Native S3-compatible storage (5x faster than AWS SDK)
  • Bun.redis
    - Built-in Redis client
Utilities:
  • Bun.password.hash()
    /
    Bun.password.verify()
    - Argon2 password hashing
  • Bun.hash(data)
    - Fast hashing (xxhash, murmur)
  • Bun.Glob
    - Native glob pattern matching
  • Bun.semver
    - Semver comparison utilities
  • Bun.sleep(ms)
    /
    Bun.sleepSync(ms)
    - Sleep functions
  • Bun.deepEquals(a, b)
    - Deep comparison
  • Bun.escapeHTML()
    - HTML sanitization
  • Bun.YAML.parse()
    /
    Bun.YAML.stringify()
    - Native YAML support
  • HTMLRewriter
    - HTML streaming transformations
Advanced Features:
  • bun:ffi
    - Foreign Function Interface (2-6x faster than Node.js FFI)
  • Worker
    - Web Workers API for multi-threading
  • BroadcastChannel
    - Pub/sub messaging across threads
  • Bun.Transpiler
    - JavaScript/TypeScript transpilation API
  • Bun.build()
    - Bundler API with compile support

HTTP服务器与网络:
  • Bun.serve(options)
    - 高性能HTTP/WebSocket服务器(比Node.js快2.5倍)
  • Bun.fetch(url)
    - 扩展的Web Fetch API
  • Bun.connect()
    /
    Bun.listen()
    - TCP/UDP套接字API
  • Bun.dns
    - DNS解析工具
文件系统操作:
  • Bun.file(path)
    - 返回BunFile(继承Blob),支持惰性、零拷贝文件操作
  • Bun.write(path, data)
    - 优化的文件写入
  • Bun.stdin
    /
    Bun.stdout
    /
    Bun.stderr
    - 标准I/O流
进程与Shell:
  • Bun.spawn(cmd)
    /
    Bun.spawnSync(cmd)
    - 子进程启动
  • Bun.$\
    command`` - 跨平台模板字符串Shell脚本
  • 内置命令:
    ls
    ,
    cd
    ,
    rm
    ,
    cat
    ,
    echo
    ,
    pwd
    ,
    mkdir
    ,
    touch
    ,
    which
    ,
    mv
数据与存储:
  • bun:sqlite
    - 内置SQLite3驱动(比better-sqlite3快3-6倍)
  • Bun.sql
    - 适用于PostgreSQL、MySQL、SQLite的统一SQL API
  • Bun.S3Client
    /
    Bun.s3
    - 原生兼容S3的存储(比AWS SDK快5倍)
  • Bun.redis
    - 内置Redis客户端
工具函数:
  • Bun.password.hash()
    /
    Bun.password.verify()
    - Argon2密码哈希
  • Bun.hash(data)
    - 快速哈希(xxhash、murmur)
  • Bun.Glob
    - 原生通配符模式匹配
  • Bun.semver
    - 语义化版本比较工具
  • Bun.sleep(ms)
    /
    Bun.sleepSync(ms)
    - 休眠函数
  • Bun.deepEquals(a, b)
    - 深度比较
  • Bun.escapeHTML()
    - HTML内容清理
  • Bun.YAML.parse()
    /
    Bun.YAML.stringify()
    - 原生YAML支持
  • HTMLRewriter
    - HTML流式转换
高级功能:
  • bun:ffi
    - 外部函数接口(比Node.js FFI快2-6倍)
  • Worker
    - 用于多线程的Web Workers API
  • BroadcastChannel
    - 跨线程发布/订阅消息
  • Bun.Transpiler
    - JavaScript/TypeScript转译API
  • Bun.build()
    - 支持编译的打包器API

2. Package Manager Commands

2. 包管理器命令

Core Commands:
bash
bun install              # Install all dependencies
bun install --frozen-lockfile  # CI/CD lockfile validation
bun add <pkg>            # Add dependency
bun add -d <pkg>         # Add devDependency
bun remove <pkg>         # Remove dependency
bun update               # Update outdated packages
bun ci                   # CI-optimized install (--frozen-lockfile)
bunx <pkg>               # Execute package without installing (100x faster than npx)
Workspace Support:
json
{
  "workspaces": ["packages/*", "apps/*"],
  "dependencies": {
    "shared-pkg": "workspace:*"
  }
}
Package Management:
bash
bun pm trust <pkg>       # Allow lifecycle scripts
bun pm untrusted         # View blocked scripts
bun why <pkg>            # Explain why package installed
bun outdated             # Show outdated packages
bun audit                # Security vulnerability check
bun patch <pkg>          # Prepare package for patching
bun link                 # Link local packages
Lockfile: Bun uses
bun.lock
(text-based JSONC format) - human-readable, git-diffable. Automatically migrates from
package-lock.json
,
yarn.lock
, or
pnpm-lock.yaml
.

核心命令:
bash
bun install              # 安装所有依赖
bun install --frozen-lockfile  # CI/CD锁文件验证
bun add <pkg>            # 添加依赖
bun add -d <pkg>         # 添加开发依赖
bun remove <pkg>         # 移除依赖
bun update               # 更新过时包
bun ci                   # 针对CI优化的安装(--frozen-lockfile)
bunx <pkg>               # 无需安装即可执行包(比npx快100倍)
工作区支持:
json
{
  "workspaces": ["packages/*", "apps/*"],
  "dependencies": {
    "shared-pkg": "workspace:*"
  }
}
包管理操作:
bash
bun pm trust <pkg>       # 允许生命周期脚本
bun pm untrusted         # 查看被阻止的脚本
bun why <pkg>            # 解释包被安装的原因
bun outdated             # 显示过时包
bun audit                # 安全漏洞检查
bun patch <pkg>          # 准备包补丁
bun link                 # 链接本地包
锁文件: Bun使用
bun.lock
(基于文本的JSONC格式)—— 人类可读、支持Git差异对比。可自动从
package-lock.json
yarn.lock
pnpm-lock.yaml
迁移。

3. Test Runner (bun:test)

3. 测试运行器(bun:test)

Test Syntax:
typescript
import { describe, test, expect, beforeAll, afterEach, mock, spyOn } from "bun:test";

describe("feature", () => {
  beforeAll(() => { /* setup */ });
  afterEach(() => { mock.restore(); });

  test("basic assertion", () => {
    expect(2 + 2).toBe(4);
  });

  test("async operation", async () => {
    const result = await fetchData();
    expect(result).toMatchObject({ status: "ok" });
  });

  test.each([[1, 2, 3], [2, 3, 5]])("adds %i + %i = %i", (a, b, expected) => {
    expect(a + b).toBe(expected);
  });
});
Test Modifiers:
  • test.skip()
    - Skip test
  • test.only()
    - Run only this test (with
    --only
    flag)
  • test.todo()
    - Mark as todo
  • test.if(condition)
    /
    test.skipIf(condition)
    - Conditional execution
  • test.failing()
    - Expected to fail
  • test.concurrent
    - Run concurrently
  • test.retry(n)
    - Retry failed tests
Key Matchers:
  • .toBe()
    ,
    .toEqual()
    ,
    .toStrictEqual()
    - Equality
  • .toContain()
    ,
    .toHaveLength()
    ,
    .toMatch()
    - String/Array
  • .toHaveProperty()
    ,
    .toMatchObject()
    - Objects
  • .toThrow()
    ,
    .rejects.toThrow()
    - Errors
  • .toMatchSnapshot()
    ,
    .toMatchInlineSnapshot()
    - Snapshots
  • .toHaveBeenCalled()
    ,
    .toHaveBeenCalledWith()
    - Mocks
Mocking:
typescript
import { mock, spyOn } from "bun:test";

const mockFn = mock(() => 42);
mockFn.mockImplementation(() => 100);
mockFn.mockReturnValue(200);

const spy = spyOn(object, "method");
spy.mockResolvedValue({ data: "test" });

// Module mocking
mock.module("./api", () => ({
  fetchUser: mock(() => ({ id: 1, name: "Test" }))
}));
CLI Commands:
bash
bun test                 # Run all tests
bun test --watch         # Watch mode
bun test --coverage      # Enable coverage
bun test -t "pattern"    # Filter by test name
bun test --timeout=5000  # Set timeout
bun test --bail          # Stop on first failure
bun test --update-snapshots  # Update snapshots

测试语法:
typescript
import { describe, test, expect, beforeAll, afterEach, mock, spyOn } from "bun:test";

describe("功能模块", () => {
  beforeAll(() => { /* 初始化 */ });
  afterEach(() => { mock.restore(); });

  test("基础断言", () => {
    expect(2 + 2).toBe(4);
  });

  test("异步操作", async () => {
    const result = await fetchData();
    expect(result).toMatchObject({ status: "ok" });
  });

  test.each([[1, 2, 3], [2, 3, 5]])("%i + %i = %i", (a, b, expected) => {
    expect(a + b).toBe(expected);
  });
});
测试修饰符:
  • test.skip()
    - 跳过测试
  • test.only()
    - 仅运行该测试(需配合
    --only
    参数)
  • test.todo()
    - 标记为待完成
  • test.if(condition)
    /
    test.skipIf(condition)
    - 条件执行
  • test.failing()
    - 标记为预期失败
  • test.concurrent
    - 并发运行
  • test.retry(n)
    - 重试失败测试
关键匹配器:
  • .toBe()
    ,
    .toEqual()
    ,
    .toStrictEqual()
    - 相等性判断
  • .toContain()
    ,
    .toHaveLength()
    ,
    .toMatch()
    - 字符串/数组判断
  • .toHaveProperty()
    ,
    .toMatchObject()
    - 对象判断
  • .toThrow()
    ,
    .rejects.toThrow()
    - 错误判断
  • .toMatchSnapshot()
    ,
    .toMatchInlineSnapshot()
    - 快照对比
  • .toHaveBeenCalled()
    ,
    .toHaveBeenCalledWith()
    - 模拟函数调用判断
模拟功能:
typescript
import { mock, spyOn } from "bun:test";

const mockFn = mock(() => 42);
mockFn.mockImplementation(() => 100);
mockFn.mockReturnValue(200);

const spy = spyOn(object, "method");
spy.mockResolvedValue({ data: "test" });

// 模块模拟
mock.module("./api", () => ({
  fetchUser: mock(() => ({ id: 1, name: "Test" }))
}));
CLI命令:
bash
bun test                 # 运行所有测试
bun test --watch         # 监听模式
bun test --coverage      # 启用覆盖率统计
bun test -t "pattern"    # 按测试名称过滤
bun test --timeout=5000  # 设置超时时间
bun test --bail          # 首次失败即停止
bun test --update-snapshots  # 更新快照

4. Bundler Configuration

4. 打包器配置

JavaScript API:
typescript
const result = await Bun.build({
  entrypoints: ["./src/index.tsx"],
  outdir: "./dist",
  target: "browser",  // "browser" | "bun" | "node"
  format: "esm",      // "esm" | "cjs" | "iife"
  minify: true,
  sourcemap: "external",
  splitting: true,    // Code splitting
  external: ["react", "react-dom"],
  define: {
    "process.env.NODE_ENV": '"production"'
  },
  loader: {
    ".png": "dataurl",
    ".svg": "text"
  },
  plugins: [myPlugin],
  naming: {
    entry: "[dir]/[name].[ext]",
    chunk: "[name]-[hash].[ext]"
  }
});

if (!result.success) {
  console.error(result.logs);
}
CLI:
bash
bun build ./src/index.tsx --outdir ./dist --minify --sourcemap=external
bun build ./src/index.ts --compile --outfile myapp  # Single executable
Plugin System:
typescript
const myPlugin: BunPlugin = {
  name: "yaml-loader",
  setup(build) {
    build.onLoad({ filter: /\.yaml$/ }, async (args) => {
      const text = await Bun.file(args.path).text();
      return {
        contents: `export default ${JSON.stringify(YAML.parse(text))}`,
        loader: "js"
      };
    });
  }
};

JavaScript API:
typescript
const result = await Bun.build({
  entrypoints: ["./src/index.tsx"],
  outdir: "./dist",
  target: "browser",  // "browser" | "bun" | "node"
  format: "esm",      // "esm" | "cjs" | "iife"
  minify: true,
  sourcemap: "external",
  splitting: true,    // 代码分割
  external: ["react", "react-dom"],
  define: {
    "process.env.NODE_ENV": '"production"'
  },
  loader: {
    ".png": "dataurl",
    ".svg": "text"
  },
  plugins: [myPlugin],
  naming: {
    entry: "[dir]/[name].[ext]",
    chunk: "[name]-[hash].[ext]"
  }
});

if (!result.success) {
  console.error(result.logs);
}
CLI:
bash
bun build ./src/index.tsx --outdir ./dist --minify --sourcemap=external
bun build ./src/index.ts --compile --outfile myapp  # 生成单可执行文件
插件系统:
typescript
const myPlugin: BunPlugin = {
  name: "yaml-loader",
  setup(build) {
    build.onLoad({ filter: /\.yaml$/ }, async (args) => {
      const text = await Bun.file(args.path).text();
      return {
        contents: `export default ${JSON.stringify(YAML.parse(text))}`,
        loader: "js"
      };
    });
  }
};

5. TypeScript Integration

5. TypeScript集成

Bun executes TypeScript natively without transpilation configuration:
bash
bun run index.ts      # Just works
bun run index.tsx     # JSX supported
Recommended tsconfig.json:
json
{
  "compilerOptions": {
    "lib": ["ESNext"],
    "target": "ESNext",
    "module": "ESNext",
    "moduleDetection": "force",
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "noEmit": true,
    "strict": true,
    "skipLibCheck": true,
    "types": ["bun-types"]
  }
}
Type checking (separate step):
bash
bunx tsc --noEmit

Bun可原生执行TypeScript,无需转译配置:
bash
bun run index.ts      # 直接运行
bun run index.tsx     # 支持JSX
推荐的tsconfig.json:
json
{
  "compilerOptions": {
    "lib": ["ESNext"],
    "target": "ESNext",
    "module": "ESNext",
    "moduleDetection": "force",
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "noEmit": true,
    "strict": true,
    "skipLibCheck": true,
    "types": ["bun-types"]
  }
}
类型检查(单独步骤):
bash
bunx tsc --noEmit

6. Configuration (bunfig.toml)

6. 配置文件(bunfig.toml)

toml
undefined
toml
undefined

Runtime

运行时配置

preload = ["./setup.ts"] smol = true # Reduced memory mode
preload = ["./setup.ts"] smol = true # 低内存模式

JSX

JSX配置

[jsx] runtime = "automatic" importSource = "react"
[jsx] runtime = "automatic" importSource = "react"

Package installation

包安装配置

[install] optional = false lockfile.save = true
[install.scopes] "@myorg" = { url = "https://npm.myorg.com", token = "$NPM_TOKEN" }
[install] optional = false lockfile.save = true
[install.scopes] "@myorg" = { url = "https://npm.myorg.com", token = "$NPM_TOKEN" }

Test runner

测试运行器配置

[test] preload = ["./test-setup.ts"] coverage = true coverageThreshold = { lines = 0.8, functions = 0.8 }

---
[test] preload = ["./test-setup.ts"] coverage = true coverageThreshold = { lines = 0.8, functions = 0.8 }

---

7. CLI Flags Reference

7. CLI参数参考

Execution:
  • --watch
    - Auto-restart on file changes
  • --hot
    - Hot module replacement
  • --smol
    - Reduced memory mode
  • --inspect
    /
    --inspect-brk
    - Debugger
Module Resolution:
  • --preload
    /
    -r
    - Preload modules
  • --install=auto|fallback|force
    - Auto-install behavior
Transpilation:
  • --define
    /
    -d
    - Compile-time constants
  • --drop=console
    - Remove function calls
  • --loader
    - Custom file loaders
Environment:
  • --env-file
    - Load specific .env files
  • --cwd
    - Set working directory
  • --bun
    /
    -b
    - Force Bun runtime

执行参数:
  • --watch
    - 文件变更时自动重启
  • --hot
    - 热模块替换
  • --smol
    - 低内存模式
  • --inspect
    /
    --inspect-brk
    - 调试器
模块解析参数:
  • --preload
    /
    -r
    - 预加载模块
  • --install=auto|fallback|force
    - 自动安装行为
转译参数:
  • --define
    /
    -d
    - 编译时常量
  • --drop=console
    - 移除函数调用
  • --loader
    - 自定义文件加载器
环境参数:
  • --env-file
    - 加载指定的.env文件
  • --cwd
    - 设置工作目录
  • --bun
    /
    -b
    - 强制使用Bun运行时

Node.js Migration Guidance

Node.js迁移指南

Quick Migration Steps

快速迁移步骤

  1. Install Bun:
    curl -fsSL https://bun.sh/install | bash
  2. Replace package manager:
bash
undefined
  1. 安装Bun:
    curl -fsSL https://bun.sh/install | bash
  2. 替换包管理器:
bash
undefined

Delete node_modules and lockfile

删除node_modules和锁文件

rm -rf node_modules package-lock.json yarn.lock pnpm-lock.yaml bun install
3. **Update scripts in package.json:**
```json
{
  "scripts": {
    "dev": "bun run --watch src/index.ts",
    "test": "bun test",
    "build": "bun build src/index.ts --outdir dist"
  }
}
  1. Update TypeScript types:
bash
bun add -d @types/bun
rm -rf node_modules package-lock.json yarn.lock pnpm-lock.yaml bun install
3. **更新package.json中的脚本:**
```json
{
  "scripts": {
    "dev": "bun run --watch src/index.ts",
    "test": "bun test",
    "build": "bun build src/index.ts --outdir dist"
  }
}
  1. 更新TypeScript类型:
bash
bun add -d @types/bun

Or in tsconfig.json: "types": ["bun-types"]

或在tsconfig.json中添加:"types": ["bun-types"]

undefined
undefined

API Compatibility

API兼容性

Fully Compatible:
  • node:assert
    ,
    node:buffer
    ,
    node:events
    ,
    node:path
    ,
    node:url
  • node:fs
    (92%),
    node:http
    ,
    node:https
    ,
    node:stream
    ,
    node:zlib
  • node:crypto
    ,
    node:net
    ,
    node:dns
    ,
    node:os
Partially Compatible:
  • node:child_process
    - Missing
    proc.gid
    ,
    proc.uid
    ; IPC limited to JSON
  • node:cluster
    - Linux-only SO_REUSEPORT for load balancing
  • node:http2
    - 95% compatible; missing
    pushStream
  • node:worker_threads
    - Missing
    stdin
    ,
    stdout
    ,
    stderr
    options
  • node:async_hooks
    - AsyncLocalStorage works; v8 promise hooks missing
Not Implemented:
  • node:inspector
    ,
    node:repl
    ,
    node:trace_events
完全兼容:
  • node:assert
    ,
    node:buffer
    ,
    node:events
    ,
    node:path
    ,
    node:url
  • node:fs
    (92%兼容)、
    node:http
    node:https
    node:stream
    node:zlib
  • node:crypto
    ,
    node:net
    ,
    node:dns
    ,
    node:os
部分兼容:
  • node:child_process
    - 缺少
    proc.gid
    proc.uid
    ;IPC仅支持JSON
  • node:cluster
    - 仅Linux支持SO_REUSEPORT负载均衡
  • node:http2
    - 95%兼容;缺少
    pushStream
  • node:worker_threads
    - 缺少
    stdin
    stdout
    stderr
    选项
  • node:async_hooks
    - AsyncLocalStorage可用;缺少v8 promise钩子
未实现:
  • node:inspector
    ,
    node:repl
    ,
    node:trace_events

Common Migration Gotchas

常见迁移陷阱

  1. Native Modules: Packages using node-gyp (bcrypt, sharp) may fail
    • Solution: Use pure JS alternatives (
      bcryptjs
      instead of
      bcrypt
      )
  2. Lifecycle Scripts: Bun blocks postinstall by default (security)
    • Solution:
      bun pm trust <package>
      or add to
      trustedDependencies
  3. Module System: Some packages relying on Node.js internals may fail
    • Module._nodeModulePaths
      doesn't exist in Bun
  4. File System Differences: Heavy concurrent file reads can cause memory issues
    • Solution: Use
      graceful-fs
      wrapper
  5. TypeScript Entry Points: Update
    "main"
    field for Bun:
json
{
  "main": "src/index.ts"  // Not "build/index.js"
}
  1. 原生模块: 使用node-gyp的包(如bcrypt、sharp)可能失败
    • 解决方案:使用纯JS替代方案(如用
      bcryptjs
      代替
      bcrypt
  2. 生命周期脚本: Bun默认阻止postinstall脚本(安全策略)
    • 解决方案:
      bun pm trust <package>
      或添加到
      trustedDependencies
  3. 模块系统: 某些依赖Node.js内部机制的包可能无法运行
    • Module._nodeModulePaths
      在Bun中不存在
  4. 文件系统差异: 高并发文件读取可能导致内存问题
    • 解决方案:使用
      graceful-fs
      包装器
  5. TypeScript入口文件: 更新Bun项目的
    "main"
    字段:
json
{
  "main": "src/index.ts"  # 不是"build/index.js"
}

Gradual Migration Strategy

渐进式迁移策略

Phase 1: Package manager only (
bun install
) Phase 2: Development tooling (
bun run
,
bun test
) Phase 3: Selective runtime migration (shadow deploy) Phase 4: Full production migration

阶段1: 仅替换包管理器(
bun install
阶段2: 替换开发工具(
bun run
bun test
阶段3: 选择性迁移运行时(影子部署) 阶段4: 全面迁移到生产环境

Best Practices

最佳实践

Performance Optimization

性能优化

typescript
// Use Bun's native APIs for I/O
const file = Bun.file("large.txt");  // Zero-copy
const content = await file.text();
await Bun.write("output.txt", processedData);

// Use Promise.all for concurrent operations
const [users, posts] = await Promise.all([
  db.query("SELECT * FROM users"),
  db.query("SELECT * FROM posts")
]);

// Use Bun.serve() static routes
Bun.serve({
  static: {
    "/": homepage,
    "/about": aboutPage
  },
  fetch(req) { /* dynamic routes */ }
});

// Use bun:sqlite for local data
import { Database } from "bun:sqlite";
const db = new Database(":memory:");
const stmt = db.prepare("SELECT * FROM users WHERE id = ?");
typescript
// 使用Bun原生API处理I/O
const file = Bun.file("large.txt");  // 零拷贝
const content = await file.text();
await Bun.write("output.txt", processedData);

// 使用Promise.all处理并发操作
const [users, posts] = await Promise.all([
  db.query("SELECT * FROM users"),
  db.query("SELECT * FROM posts")
]);

// 使用Bun.serve()配置静态路由
Bun.serve({
  static: {
    "/": homepage,
    "/about": aboutPage
  },
  fetch(req) { /* 动态路由处理 */ }
});

// 使用bun:sqlite处理本地数据
import { Database } from "bun:sqlite";
const db = new Database(":memory:");
const stmt = db.prepare("SELECT * FROM users WHERE id = ?");

Error Handling

错误处理

typescript
// HTTP server error handling
Bun.serve({
  fetch(req) {
    try {
      return handleRequest(req);
    } catch (error) {
      console.error(error);
      return new Response("Internal Error", { status: 500 });
    }
  },
  error(error) {
    return new Response(`Error: ${error.message}`, { status: 500 });
  }
});

// Process-level error handling
process.on("uncaughtException", (error) => {
  console.error("Uncaught:", error);
  process.exit(1);
});
typescript
// HTTP服务器错误处理
Bun.serve({
  fetch(req) {
    try {
      return handleRequest(req);
    } catch (error) {
      console.error(error);
      return new Response("内部错误", { status: 500 });
    }
  },
  error(error) {
    return new Response(`错误:${error.message}`, { status: 500 });
  }
});

// 进程级错误处理
process.on("uncaughtException", (error) => {
  console.error("未捕获异常:", error);
  process.exit(1);
});

Security Best Practices

安全最佳实践

  1. Lifecycle Scripts: Keep
    trustedDependencies
    minimal
  2. Environment Variables: Use
    .env.local
    for secrets (not committed)
  3. Input Validation: Sanitize all user inputs
  4. Dependencies: Run
    bun audit
    regularly
  5. Production: Use
    --production
    flag to skip devDependencies
  1. 生命周期脚本: 尽量减少
    trustedDependencies
    的数量
  2. 环境变量: 使用
    .env.local
    存储密钥(不要提交到版本库)
  3. 输入验证: 对所有用户输入进行清理
  4. 依赖检查: 定期运行
    bun audit
  5. 生产环境: 使用
    --production
    参数跳过开发依赖

Project Structure

项目结构

my-bun-project/
├── src/
│   ├── index.ts        # Entry point
│   ├── server.ts       # HTTP server
│   └── lib/            # Utilities
├── test/
│   └── *.test.ts       # Test files
├── bunfig.toml         # Bun configuration
├── tsconfig.json       # TypeScript config
├── package.json
└── .env.local          # Local secrets (gitignored)

my-bun-project/
├── src/
│   ├── index.ts        # 入口文件
│   ├── server.ts       # HTTP服务器
│   └── lib/            # 工具库
├── test/
│   └── *.test.ts       # 测试文件
├── bunfig.toml         # Bun配置
├── tsconfig.json       # TypeScript配置
├── package.json
└── .env.local          # 本地密钥(已加入git忽略)

Debugging

调试

Web Debugger:
bash
bun --inspect server.ts         # Start debugger
bun --inspect-brk server.ts     # Break at first line
bun --inspect-wait server.ts    # Wait for connection
Open
https://debug.bun.sh
or use VSCode Bun extension.
Verbose Fetch Logging:
bash
BUN_CONFIG_VERBOSE_FETCH=curl bun run server.ts

Web调试器:
bash
bun --inspect server.ts         # 启动调试器
bun --inspect-brk server.ts     # 在第一行断点
bun --inspect-wait server.ts    # 等待调试连接
打开
https://debug.bun.sh
或使用VSCode的Bun扩展。
详细Fetch日志:
bash
BUN_CONFIG_VERBOSE_FETCH=curl bun run server.ts

Examples

示例

HTTP Server with WebSocket

带WebSocket的HTTP服务器

typescript
Bun.serve({
  port: 3000,
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return new Response("Hello Bun!");
  },
  websocket: {
    open(ws) { console.log("Connected"); },
    message(ws, message) { ws.send(`Echo: ${message}`); },
    close(ws) { console.log("Disconnected"); }
  }
});
typescript
Bun.serve({
  port: 3000,
  fetch(req, server) {
    if (server.upgrade(req)) return;
    return new Response("Hello Bun!");
  },
  websocket: {
    open(ws) { console.log("已连接"); },
    message(ws, message) { ws.send(`回声:${message}`); },
    close(ws) { console.log("已断开连接"); }
  }
});

File Server

文件服务器

typescript
Bun.serve({
  async fetch(req) {
    const path = new URL(req.url).pathname;
    const file = Bun.file(`./public${path}`);
    if (await file.exists()) {
      return new Response(file);
    }
    return new Response("Not Found", { status: 404 });
  }
});
typescript
Bun.serve({
  async fetch(req) {
    const path = new URL(req.url).pathname;
    const file = Bun.file(`./public${path}`);
    if (await file.exists()) {
      return new Response(file);
    }
    return new Response("未找到", { status: 404 });
  }
});

Database with SQLite

SQLite数据库示例

typescript
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
)`);

const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
const getAll = db.prepare("SELECT * FROM users");

insert.run("Alice", "alice@example.com");
const users = getAll.all();

typescript
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
)`);

const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
const getAll = db.prepare("SELECT * FROM users");

insert.run("Alice", "alice@example.com");
const users = getAll.all();

When This Skill Activates

技能触发场景

This skill automatically activates when:
  • Working with
    .ts
    ,
    .tsx
    ,
    .js
    ,
    .jsx
    files in a Bun project
  • Creating or modifying
    bunfig.toml
    or
    bun.lock
  • Using
    bun:test
    ,
    bun:sqlite
    ,
    bun:ffi
    imports
  • Discussing Bun APIs (Bun.serve, Bun.file, Bun.build)
  • Migrating from Node.js to Bun
  • Writing or debugging Bun tests
  • Configuring the Bun bundler
当出现以下情况时,该技能会自动触发:
  • 在Bun项目中处理
    .ts
    .tsx
    .js
    .jsx
    文件
  • 创建或修改
    bunfig.toml
    bun.lock
  • 使用
    bun:test
    bun:sqlite
    bun:ffi
    导入
  • 讨论Bun API(Bun.serve、Bun.file、Bun.build)
  • 从Node.js迁移到Bun
  • 编写或调试Bun测试
  • 配置Bun打包器