bun-expert
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBun 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:
- - High-performance HTTP/WebSocket server (2.5x faster than Node.js)
Bun.serve(options) - - Extended Web Fetch API
Bun.fetch(url) - /
Bun.connect()- TCP/UDP socket APIsBun.listen() - - DNS resolution utilities
Bun.dns
File System Operations:
- - Returns BunFile (extends Blob) for lazy, zero-copy file operations
Bun.file(path) - - Optimized file writes
Bun.write(path, data) - /
Bun.stdin/Bun.stdout- Standard I/O streamsBun.stderr
Process & Shell:
- /
Bun.spawn(cmd)- Child process spawningBun.spawnSync(cmd) - command`` - Cross-platform shell scripting with template literals
Bun.$\ - Built-in commands: ,
ls,cd,rm,cat,echo,pwd,mkdir,touch,whichmv
Data & Storage:
- - Built-in SQLite3 driver (3-6x faster than better-sqlite3)
bun:sqlite - - Unified SQL API for PostgreSQL, MySQL, SQLite
Bun.sql - /
Bun.S3Client- Native S3-compatible storage (5x faster than AWS SDK)Bun.s3 - - Built-in Redis client
Bun.redis
Utilities:
- /
Bun.password.hash()- Argon2 password hashingBun.password.verify() - - Fast hashing (xxhash, murmur)
Bun.hash(data) - - Native glob pattern matching
Bun.Glob - - Semver comparison utilities
Bun.semver - /
Bun.sleep(ms)- Sleep functionsBun.sleepSync(ms) - - Deep comparison
Bun.deepEquals(a, b) - - HTML sanitization
Bun.escapeHTML() - /
Bun.YAML.parse()- Native YAML supportBun.YAML.stringify() - - HTML streaming transformations
HTMLRewriter
Advanced Features:
- - Foreign Function Interface (2-6x faster than Node.js FFI)
bun:ffi - - Web Workers API for multi-threading
Worker - - Pub/sub messaging across threads
BroadcastChannel - - JavaScript/TypeScript transpilation API
Bun.Transpiler - - Bundler API with compile support
Bun.build()
HTTP服务器与网络:
- - 高性能HTTP/WebSocket服务器(比Node.js快2.5倍)
Bun.serve(options) - - 扩展的Web Fetch API
Bun.fetch(url) - /
Bun.connect()- TCP/UDP套接字APIBun.listen() - - DNS解析工具
Bun.dns
文件系统操作:
- - 返回BunFile(继承Blob),支持惰性、零拷贝文件操作
Bun.file(path) - - 优化的文件写入
Bun.write(path, data) - /
Bun.stdin/Bun.stdout- 标准I/O流Bun.stderr
进程与Shell:
- /
Bun.spawn(cmd)- 子进程启动Bun.spawnSync(cmd) - command`` - 跨平台模板字符串Shell脚本
Bun.$\ - 内置命令:,
ls,cd,rm,cat,echo,pwd,mkdir,touch,whichmv
数据与存储:
- - 内置SQLite3驱动(比better-sqlite3快3-6倍)
bun:sqlite - - 适用于PostgreSQL、MySQL、SQLite的统一SQL API
Bun.sql - /
Bun.S3Client- 原生兼容S3的存储(比AWS SDK快5倍)Bun.s3 - - 内置Redis客户端
Bun.redis
工具函数:
- /
Bun.password.hash()- Argon2密码哈希Bun.password.verify() - - 快速哈希(xxhash、murmur)
Bun.hash(data) - - 原生通配符模式匹配
Bun.Glob - - 语义化版本比较工具
Bun.semver - /
Bun.sleep(ms)- 休眠函数Bun.sleepSync(ms) - - 深度比较
Bun.deepEquals(a, b) - - HTML内容清理
Bun.escapeHTML() - /
Bun.YAML.parse()- 原生YAML支持Bun.YAML.stringify() - - HTML流式转换
HTMLRewriter
高级功能:
- - 外部函数接口(比Node.js FFI快2-6倍)
bun:ffi - - 用于多线程的Web Workers API
Worker - - 跨线程发布/订阅消息
BroadcastChannel - - JavaScript/TypeScript转译API
Bun.Transpiler - - 支持编译的打包器API
Bun.build()
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 packagesLockfile: Bun uses (text-based JSONC format) - human-readable, git-diffable. Automatically migrates from , , or .
bun.lockpackage-lock.jsonyarn.lockpnpm-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使用(基于文本的JSONC格式)—— 人类可读、支持Git差异对比。可自动从、或迁移。
bun.lockpackage-lock.jsonyarn.lockpnpm-lock.yaml3. 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:
- - Skip test
test.skip() - - Run only this test (with
test.only()flag)--only - - Mark as todo
test.todo() - /
test.if(condition)- Conditional executiontest.skipIf(condition) - - Expected to fail
test.failing() - - Run concurrently
test.concurrent - - Retry failed tests
test.retry(n)
Key Matchers:
- ,
.toBe(),.toEqual()- Equality.toStrictEqual() - ,
.toContain(),.toHaveLength()- String/Array.toMatch() - ,
.toHaveProperty()- Objects.toMatchObject() - ,
.toThrow()- Errors.rejects.toThrow() - ,
.toMatchSnapshot()- Snapshots.toMatchInlineSnapshot() - ,
.toHaveBeenCalled()- Mocks.toHaveBeenCalledWith()
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 executablePlugin 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 supportedRecommended 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 --noEmitBun可原生执行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 --noEmit6. Configuration (bunfig.toml)
6. 配置文件(bunfig.toml)
toml
undefinedtoml
undefinedRuntime
运行时配置
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:
- - Auto-restart on file changes
--watch - - Hot module replacement
--hot - - Reduced memory mode
--smol - /
--inspect- Debugger--inspect-brk
Module Resolution:
- /
--preload- Preload modules-r - - Auto-install behavior
--install=auto|fallback|force
Transpilation:
- /
--define- Compile-time constants-d - - Remove function calls
--drop=console - - Custom file loaders
--loader
Environment:
- - Load specific .env files
--env-file - - Set working directory
--cwd - /
--bun- Force Bun runtime-b
执行参数:
- - 文件变更时自动重启
--watch - - 热模块替换
--hot - - 低内存模式
--smol - /
--inspect- 调试器--inspect-brk
模块解析参数:
- /
--preload- 预加载模块-r - - 自动安装行为
--install=auto|fallback|force
转译参数:
- /
--define- 编译时常量-d - - 移除函数调用
--drop=console - - 自定义文件加载器
--loader
环境参数:
- - 加载指定的.env文件
--env-file - - 设置工作目录
--cwd - /
--bun- 强制使用Bun运行时-b
Node.js Migration Guidance
Node.js迁移指南
Quick Migration Steps
快速迁移步骤
- Install Bun:
curl -fsSL https://bun.sh/install | bash - Replace package manager:
bash
undefined- 安装Bun:
curl -fsSL https://bun.sh/install | bash - 替换包管理器:
bash
undefinedDelete 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"
}
}- Update TypeScript types:
bash
bun add -d @types/bunrm -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"
}
}- 更新TypeScript类型:
bash
bun add -d @types/bunOr in tsconfig.json: "types": ["bun-types"]
或在tsconfig.json中添加:"types": ["bun-types"]
undefinedundefinedAPI Compatibility
API兼容性
Fully Compatible:
- ,
node:assert,node:buffer,node:events,node:pathnode:url - (92%),
node:fs,node:http,node:https,node:streamnode:zlib - ,
node:crypto,node:net,node:dnsnode:os
Partially Compatible:
- - Missing
node:child_process,proc.gid; IPC limited to JSONproc.uid - - Linux-only SO_REUSEPORT for load balancing
node:cluster - - 95% compatible; missing
node:http2pushStream - - Missing
node:worker_threads,stdin,stdoutoptionsstderr - - AsyncLocalStorage works; v8 promise hooks missing
node:async_hooks
Not Implemented:
- ,
node:inspector,node:replnode:trace_events
完全兼容:
- ,
node:assert,node:buffer,node:events,node:pathnode:url - (92%兼容)、
node:fs、node:http、node:https、node:streamnode:zlib - ,
node:crypto,node:net,node:dnsnode:os
部分兼容:
- - 缺少
node:child_process、proc.gid;IPC仅支持JSONproc.uid - - 仅Linux支持SO_REUSEPORT负载均衡
node:cluster - - 95%兼容;缺少
node:http2pushStream - - 缺少
node:worker_threads、stdin、stdout选项stderr - - AsyncLocalStorage可用;缺少v8 promise钩子
node:async_hooks
未实现:
- ,
node:inspector,node:replnode:trace_events
Common Migration Gotchas
常见迁移陷阱
- Native Modules: Packages using node-gyp (bcrypt, sharp) may fail
- Solution: Use pure JS alternatives (instead of
bcryptjs)bcrypt
- Solution: Use pure JS alternatives (
- Lifecycle Scripts: Bun blocks postinstall by default (security)
- Solution: or add to
bun pm trust <package>trustedDependencies
- Solution:
- Module System: Some packages relying on Node.js internals may fail
- doesn't exist in Bun
Module._nodeModulePaths
- File System Differences: Heavy concurrent file reads can cause memory issues
- Solution: Use wrapper
graceful-fs
- Solution: Use
- TypeScript Entry Points: Update field for Bun:
"main"
json
{
"main": "src/index.ts" // Not "build/index.js"
}- 原生模块: 使用node-gyp的包(如bcrypt、sharp)可能失败
- 解决方案:使用纯JS替代方案(如用代替
bcryptjs)bcrypt
- 解决方案:使用纯JS替代方案(如用
- 生命周期脚本: Bun默认阻止postinstall脚本(安全策略)
- 解决方案:或添加到
bun pm trust <package>trustedDependencies
- 解决方案:
- 模块系统: 某些依赖Node.js内部机制的包可能无法运行
- 在Bun中不存在
Module._nodeModulePaths
- 文件系统差异: 高并发文件读取可能导致内存问题
- 解决方案:使用包装器
graceful-fs
- 解决方案:使用
- TypeScript入口文件: 更新Bun项目的字段:
"main"
json
{
"main": "src/index.ts" # 不是"build/index.js"
}Gradual Migration Strategy
渐进式迁移策略
Phase 1: Package manager only ()
Phase 2: Development tooling (, )
Phase 3: Selective runtime migration (shadow deploy)
Phase 4: Full production migration
bun installbun runbun test阶段1: 仅替换包管理器()
阶段2: 替换开发工具(、)
阶段3: 选择性迁移运行时(影子部署)
阶段4: 全面迁移到生产环境
bun installbun runbun testBest 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
安全最佳实践
- Lifecycle Scripts: Keep minimal
trustedDependencies - Environment Variables: Use for secrets (not committed)
.env.local - Input Validation: Sanitize all user inputs
- Dependencies: Run regularly
bun audit - Production: Use flag to skip devDependencies
--production
- 生命周期脚本: 尽量减少的数量
trustedDependencies - 环境变量: 使用存储密钥(不要提交到版本库)
.env.local - 输入验证: 对所有用户输入进行清理
- 依赖检查: 定期运行
bun audit - 生产环境: 使用参数跳过开发依赖
--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 connectionOpen or use VSCode Bun extension.
https://debug.bun.shVerbose Fetch Logging:
bash
BUN_CONFIG_VERBOSE_FETCH=curl bun run server.tsWeb调试器:
bash
bun --inspect server.ts # 启动调试器
bun --inspect-brk server.ts # 在第一行断点
bun --inspect-wait server.ts # 等待调试连接打开 或使用VSCode的Bun扩展。
https://debug.bun.sh详细Fetch日志:
bash
BUN_CONFIG_VERBOSE_FETCH=curl bun run server.tsExamples
示例
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,.jsfiles in a Bun project.jsx - Creating or modifying or
bunfig.tomlbun.lock - Using ,
bun:test,bun:sqliteimportsbun:ffi - 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.tomlbun.lock - 使用、
bun:test、bun:sqlite导入bun:ffi - 讨论Bun API(Bun.serve、Bun.file、Bun.build)
- 从Node.js迁移到Bun
- 编写或调试Bun测试
- 配置Bun打包器