bun-api
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBun Runtime API
Bun Runtime API
Bun runs TypeScript natively — no compilation, no , no build step. Run any file directly with . Use Bun's native APIs instead of Node.js equivalents — they're faster, more ergonomic, and require no additional dependencies.
tscts-node.tsbun file.tsCritical: In a Bun project (has , , , or in devDependencies), always use Bun to run scripts (, not ) and prefer Bun-native APIs over Node.js equivalents. Mixing runtimes causes subtle bugs and unnecessary retries.
bun.lockbun.lockbbunfig.toml@types/bunbun file.tsnode file.tsVerified against Bun v1.3.14 (2026-05-28).
Bun原生支持TypeScript运行——无需编译、无需、无需构建步骤。直接使用运行任意文件。使用Bun的原生API替代Node.js等效API——它们更快、更符合人体工程学,且无需额外依赖。
tscts-nodebun file.ts.ts关键提示:在Bun项目(包含、、或开发依赖中的)中,始终使用Bun运行脚本(,而非),并优先选择Bun原生API而非Node.js等效API。混合运行时会导致难以察觉的Bug和不必要的重试。
bun.lockbun.lockbbunfig.toml@types/bunbun file.tsnode file.ts已针对Bun v1.3.14验证(2026-05-28)。
When to Use
使用场景
- Scripts for generating files, parsing data, running migrations
- File processing and transformation pipelines
- Shell scripting and automation
- Database operations with SQLite ()
bun:sqlite - Database queries via connection URL -- project has in
DATABASE_URLor environment (PostgreSQL, MySQL, SQLite via.env)Bun.sql() - S3 storage operations -- project has or uses S3-compatible storage (
AWS_ACCESS_KEY_ID)Bun.s3 - Redis/Valkey caching and pub/sub -- project has or
REDIS_URL(VALKEY_URL)Bun.redis - Any scripting task in a Bun project
- 用于生成文件、解析数据、运行迁移的脚本
- 文件处理与转换流水线
- Shell脚本与自动化
- 使用SQLite的数据库操作()
bun:sqlite - 通过连接URL进行数据库查询——项目在或环境变量中配置了
.env(PostgreSQL、MySQL、通过DATABASE_URL连接的SQLite)Bun.sql() - S3存储操作——项目配置了或使用兼容S3的存储(
AWS_ACCESS_KEY_ID)Bun.s3 - Redis/Valkey缓存与发布订阅——项目配置了或
REDIS_URL(VALKEY_URL)Bun.redis - Bun项目中的任何脚本任务
HTTP Server (Bun.serve)
HTTP服务器(Bun.serve)
Built-in HTTP server — replaces Express, Fastify, or .
http.createServertypescript
const server = Bun.serve({
port: 3000,
fetch(req: Request): Response | Promise<Response> {
const url = new URL(req.url)
if (url.pathname === '/api/health') {
return Response.json({ status: 'ok' })
}
if (url.pathname === '/api/data' && req.method === 'POST') {
const body = await req.json()
return Response.json({ received: body })
}
return new Response('Not Found', { status: 404 })
},
error(error: Error): Response {
return new Response(`Error: ${error.message}`, { status: 500 })
},
})
console.log(`Listening on ${server.url}`)Key methods: , (hot-swap handler), , (WebSocket).
server.stop()server.reload()server.requestIP(req)server.upgrade(req)Reference: Seefor TLS, WebSocket upgrade, streaming responses, static file serving, and full server API.references/http-server.md
内置HTTP服务器——替代Express、Fastify或。
http.createServertypescript
const server = Bun.serve({
port: 3000,
fetch(req: Request): Response | Promise<Response> {
const url = new URL(req.url)
if (url.pathname === '/api/health') {
return Response.json({ status: 'ok' })
}
if (url.pathname === '/api/data' && req.method === 'POST') {
const body = await req.json()
return Response.json({ received: body })
}
return new Response('Not Found', { status: 404 })
},
error(error: Error): Response {
return new Response(`Error: ${error.message}`, { status: 500 })
},
})
console.log(`Listening on ${server.url}`)核心方法:、(热替换处理器)、、(WebSocket)。
server.stop()server.reload()server.requestIP(req)server.upgrade(req)参考文档:查看获取TLS、WebSocket升级、流式响应、静态文件服务及完整服务器API的详细信息。references/http-server.md
TCP / UDP Sockets
TCP / UDP套接字
Raw sockets for non-HTTP protocols -- / for TCP, for UDP, plus the built-in client and .
Bun.listen()Bun.connect()Bun.udpSocket()WebSocketfetch()typescript
const server = Bun.listen({
hostname: '127.0.0.1',
port: 8080,
socket: {
open(socket) { socket.write('welcome\n') },
data(socket, data) { /* Buffer */ },
},
})Reference: Seefor TCP/UDP handlers, Unix sockets, the WebSocket client (references/networking.md), andws+unix://transport options (HTTP/2, HTTP/3, proxies, system CA).fetch()
用于非HTTP协议的原始套接字——TCP使用 / ,UDP使用,此外还有内置的客户端和。
Bun.listen()Bun.connect()Bun.udpSocket()WebSocketfetch()typescript
const server = Bun.listen({
hostname: '127.0.0.1',
port: 8080,
socket: {
open(socket) { socket.write('welcome\n') },
data(socket, data) { /* Buffer */ },
},
})参考文档:查看获取TCP/UDP处理器、Unix套接字、WebSocket客户端(references/networking.md)以及ws+unix://传输选项(HTTP/2、HTTP/3、代理、系统CA)的详细信息。fetch()
File I/O
文件I/O
Reading Files
读取文件
typescript
// Create a BunFile reference (lazy, no read yet)
const file = Bun.file('path/to/file.txt')
// Read contents
const text = await file.text() // string
const json = await file.json() // parsed JSON
const bytes = await file.arrayBuffer() // ArrayBuffer
const stream = file.stream() // ReadableStream
const blob = await file.blob() // Blob
// File metadata
file.size // Size in bytes
file.type // MIME type (auto-detected)
file.name // File path
await file.exists() // Boolean
// Read from URL
const remote = Bun.file('https://example.com/data.json')typescript
// 创建BunFile引用(惰性加载,尚未读取)
const file = Bun.file('path/to/file.txt')
// 读取内容
const text = await file.text() // 字符串
const json = await file.json() // 解析后的JSON
const bytes = await file.arrayBuffer() // ArrayBuffer
const stream = file.stream() // ReadableStream
const blob = await file.blob() // Blob
// 文件元数据
file.size // 字节大小
file.type // MIME类型(自动检测)
file.name // 文件路径
await file.exists() // 布尔值
// 从URL读取
const remote = Bun.file('https://example.com/data.json')Writing Files
写入文件
typescript
// Write string
await Bun.write('output.txt', 'content')
// Write from BunFile (efficient copy)
await Bun.write('copy.txt', Bun.file('original.txt'))
// Write JSON
await Bun.write('data.json', JSON.stringify(data, null, 2))
// Write Uint8Array / ArrayBuffer
await Bun.write('binary.dat', new Uint8Array([1, 2, 3]))
// Write Response body
await Bun.write('page.html', await fetch('https://example.com'))
// Write to stdout
await Bun.write(Bun.stdout, 'Hello\n')typescript
// 写入字符串
await Bun.write('output.txt', 'content')
// 从BunFile写入(高效复制)
await Bun.write('copy.txt', Bun.file('original.txt'))
// 写入JSON
await Bun.write('data.json', JSON.stringify(data, null, 2))
// 写入Uint8Array / ArrayBuffer
await Bun.write('binary.dat', new Uint8Array([1, 2, 3]))
// 写入Response主体
await Bun.write('page.html', await fetch('https://example.com'))
// 写入标准输出
await Bun.write(Bun.stdout, 'Hello\n')Stdio
标准输入输出
typescript
Bun.stdin // BunFile for stdin
Bun.stdout // BunFile for stdout
Bun.stderr // BunFile for stderr
// Read all of stdin
const input = await Bun.stdin.text()
// Stream stdin line by line
for await (const chunk of Bun.stdin.stream()) {
// process chunk (Uint8Array)
}typescript
Bun.stdin // 对应标准输入的BunFile
Bun.stdout // 对应标准输出的BunFile
Bun.stderr // 对应标准错误的BunFile
// 读取全部标准输入
const input = await Bun.stdin.text()
// 逐行流式读取标准输入
for await (const chunk of Bun.stdin.stream()) {
// 处理chunk(Uint8Array)
}Common Patterns
常见模式
typescript
// JSON transform
const data = await Bun.file('input.json').json()
data.version = '2.0.0'
await Bun.write('output.json', JSON.stringify(data, null, 2))
// File generation from template
const template = await Bun.file('template.html').text()
const output = template.replace('{{title}}', 'My Page')
await Bun.write('index.html', output)
// Check if file exists before reading
const file = Bun.file('config.json')
if (await file.exists()) {
const config = await file.json()
}Reference: Seefor BunFile interface, write overloads, streaming, MIME detection, and file watching.references/file-io.md
typescript
// JSON转换
const data = await Bun.file('input.json').json()
data.version = '2.0.0'
await Bun.write('output.json', JSON.stringify(data, null, 2))
// 从模板生成文件
const template = await Bun.file('template.html').text()
const output = template.replace('{{title}}', 'My Page')
await Bun.write('index.html', output)
// 读取前检查文件是否存在
const file = Bun.file('config.json')
if (await file.exists()) {
const config = await file.json()
}参考文档:查看获取BunFile接口、写入重载、流式处理、MIME检测及文件监听的详细信息。references/file-io.md
Shell and Process Execution
Shell与进程执行
Bun.$ (Tagged Template Shell)
Bun.$(模板字符串Shell)
The primary way to run shell commands. Returns a promise with output.
typescript
import { $ } from 'bun'
// Basic execution
const result = await $`ls -la`
console.log(result.text()) // stdout as string
// With interpolation (auto-escaped)
const dir = 'my folder'
await $`ls ${dir}` // Safe: "my folder" is properly quoted
// Output methods
const output = await $`echo hello`
output.text() // "hello\n"
output.json() // Parse stdout as JSON
output.lines() // string[] (splits on newlines)
output.bytes() // Uint8Array
output.blob() // Blob
output.exitCode // number
output.stderr // Buffer
// Piping
await $`cat file.txt | grep pattern | wc -l`
// Quiet mode (suppress stdout)
await $`npm install`.quiet()
// No-throw mode (don't throw on non-zero exit)
const result = await $`command-that-might-fail`.nothrow()
if (result.exitCode !== 0) {
console.error('Failed:', result.stderr.toString())
}
// Combined
await $`risky-command`.quiet().nothrow()
// Environment variables
await $`echo $HOME`.env({ HOME: '/custom' })
// Working directory
await $`ls`.cwd('/tmp')
// Redirect to file
await $`echo hello > output.txt`
await $`cat < input.txt`
// Pipe between commands
const input = Buffer.from('hello')
await $`cat`.stdin(input)运行Shell命令的主要方式。返回包含输出的Promise。
typescript
import { $ } from 'bun'
// 基础执行
const result = await $`ls -la`
console.log(result.text()) // 标准输出转为字符串
// 插值(自动转义)
const dir = 'my folder'
await $`ls ${dir}` // 安全:"my folder"会被正确引用
// 输出方法
const output = await $`echo hello`
output.text() // "hello\n"
output.json() // 将标准输出解析为JSON
output.lines() // 字符串数组(按换行分割)
output.bytes() // Uint8Array
output.blob() // Blob
output.exitCode // 数字
output.stderr // Buffer
// 管道
await $`cat file.txt | grep pattern | wc -l`
// 静默模式(抑制标准输出)
await $`npm install`.quiet()
// 不抛出异常模式(非零退出码时不抛出)
const result = await $`command-that-might-fail`.nothrow()
if (result.exitCode !== 0) {
console.error('Failed:', result.stderr.toString())
}
// 组合使用
await $`risky-command`.quiet().nothrow()
// 环境变量
await $`echo $HOME`.env({ HOME: '/custom' })
// 工作目录
await $`ls`.cwd('/tmp')
// 重定向到文件
await $`echo hello > output.txt`
await $`cat < input.txt`
// 命令间管道
const input = Buffer.from('hello')
await $`cat`.stdin(input)Bun.spawn (Lower-Level)
Bun.spawn(底层API)
For more control over process execution.
typescript
const proc = Bun.spawn(['command', 'arg1', 'arg2'], {
cwd: '/path',
env: { ...process.env, CUSTOM: 'value' },
stdin: 'pipe', // 'pipe' | 'inherit' | 'ignore' | BunFile | Blob | Response
stdout: 'pipe', // 'pipe' | 'inherit' | 'ignore' | BunFile
stderr: 'pipe', // 'pipe' | 'inherit' | 'ignore' | BunFile
onExit(proc, exitCode, signalCode, error) {
// Called when process exits
},
})
// Write to stdin
proc.stdin.write('input data')
proc.stdin.end()
// Read stdout
const output = await new Response(proc.stdout).text()
// Wait for completion
await proc.exited // Promise<number> (exit code)
// Kill
proc.kill() // SIGTERM
proc.kill('SIGKILL') // Specific signal用于更精细地控制进程执行。
typescript
const proc = Bun.spawn(['command', 'arg1', 'arg2'], {
cwd: '/path',
env: { ...process.env, CUSTOM: 'value' },
stdin: 'pipe', // 'pipe' | 'inherit' | 'ignore' | BunFile | Blob | Response
stdout: 'pipe', // 'pipe' | 'inherit' | 'ignore' | BunFile
stderr: 'pipe', // 'pipe' | 'inherit' | 'ignore' | BunFile
onExit(proc, exitCode, signalCode, error) {
// 进程退出时调用
},
})
// 写入标准输入
proc.stdin.write('input data')
proc.stdin.end()
// 读取标准输出
const output = await new Response(proc.stdout).text()
// 等待进程完成
await proc.exited // Promise<number>(退出码)
// 终止进程
proc.kill() // SIGTERM
proc.kill('SIGKILL') // 指定信号Bun.spawnSync (Synchronous)
Bun.spawnSync(同步执行)
typescript
const result = Bun.spawnSync(['command', 'arg1'], {
cwd: '/path',
env: { ...process.env },
})
result.exitCode // number
result.stdout // Buffer
result.stderr // Buffer
result.success // booleanReference: Seefor complete $ API, spawn options, IPC, and signal handling.references/shell-and-process.md
typescript
const result = Bun.spawnSync(['command', 'arg1'], {
cwd: '/path',
env: { ...process.env },
})
result.exitCode // 数字
result.stdout // Buffer
result.stderr // Buffer
result.success // 布尔值参考文档:查看获取完整的$ API、spawn选项、IPC及信号处理的详细信息。references/shell-and-process.md
Glob Pattern Matching
Glob模式匹配
typescript
const glob = new Bun.Glob('**/*.ts')
// Async iteration
for await (const path of glob.scan({ cwd: './src', onlyFiles: true })) {
console.log(path)
}
// Sync iteration
for (const path of glob.scanSync('./src')) {
console.log(path)
}
// Test if a path matches
glob.match('src/index.ts') // true
glob.match('README.md') // false
// Scan options
glob.scan({
cwd: './src', // Directory to scan (default: '.')
dot: false, // Include dotfiles (default: false)
onlyFiles: true, // Skip directories (default: true)
absolute: false, // Return absolute paths (default: false)
followSymlinks: false, // Follow symlinks (default: false)
})typescript
const glob = new Bun.Glob('**/*.ts')
// 异步迭代
for await (const path of glob.scan({ cwd: './src', onlyFiles: true })) {
console.log(path)
}
// 同步迭代
for (const path of glob.scanSync('./src')) {
console.log(path)
}
// 测试路径是否匹配
glob.match('src/index.ts') // true
glob.match('README.md') // false
// 扫描选项
glob.scan({
cwd: './src', // 扫描目录(默认:'.')
dot: false, // 包含点文件(默认:false)
onlyFiles: true, // 跳过目录(默认:true)
absolute: false, // 返回绝对路径(默认:false)
followSymlinks: false, // 跟随符号链接(默认:false)
})Environment and Arguments
环境变量与参数
typescript
Bun.env.NODE_ENV // Environment variable (same as process.env)
Bun.env.DATABASE_URL // Typed access
Bun.argv // string[] — [bunPath, scriptPath, ...args]
// Equivalent: process.argv
Bun.main // Absolute path to the entry point script
import.meta.dir // Directory of current file
import.meta.file // Filename of current file
import.meta.path // Full path of current file
import.meta.dirname // Same as import.meta.dir (Node.js compat)
import.meta.filename // Same as import.meta.path (Node.js compat)typescript
Bun.env.NODE_ENV // 环境变量(与process.env相同)
Bun.env.DATABASE_URL // 类型化访问
Bun.argv // 字符串数组 — [bunPath, scriptPath, ...args]
// 等效于:process.argv
Bun.main // 入口脚本的绝对路径
import.meta.dir // 当前文件所在目录
import.meta.file // 当前文件名
import.meta.path // 当前文件的完整路径
import.meta.dirname // 与import.meta.dir相同(Node.js兼容)
import.meta.filename // 与import.meta.path相同(Node.js兼容)SQL Client (Bun.sql) -- PostgreSQL, MySQL, SQLite
SQL客户端(Bun.sql)——PostgreSQL、MySQL、SQLite
Built-in SQL client for querying databases via connection URL. Zero dependencies, tagged template literals, automatic prepared statements, connection pooling. Use when the project has in or environment.
DATABASE_URL.envtypescript
import { sql, SQL } from "bun"
// Default instance -- auto-connects using DATABASE_URL from environment
const users = await sql`SELECT * FROM users WHERE active = ${true} LIMIT ${10}`
// Explicit connection
const db = new SQL("postgres://user:pass@localhost:5432/mydb")
const results = await db`SELECT * FROM users`
// MySQL
const mysql = new SQL("mysql://user:pass@localhost:3306/mydb")内置SQL客户端,通过连接URL查询数据库。零依赖、模板字符串语法、自动预编译语句、连接池。适用于项目在或环境变量中配置了的场景。
.envDATABASE_URLtypescript
import { sql, SQL } from "bun"
// 默认实例——自动使用环境中的DATABASE_URL连接
const users = await sql`SELECT * FROM users WHERE active = ${true} LIMIT ${10}`
// 显式连接
const db = new SQL("postgres://user:pass@localhost:5432/mydb")
const results = await db`SELECT * FROM users`
// MySQL
const mysql = new SQL("mysql://user:pass@localhost:3306/mydb")Insert / Update with Object Helpers
使用对象助手进行插入/更新
typescript
const user = { name: "Alice", email: "alice@example.com" }
// Insert -- expands object to (column1, column2) VALUES (val1, val2)
const [newUser] = await sql`INSERT INTO users ${sql(user)} RETURNING *`
// Bulk insert
await sql`INSERT INTO users ${sql([user1, user2, user3])}`
// Update -- expands to SET column1 = val1, column2 = val2
await sql`UPDATE users SET ${sql(updates)} WHERE id = ${userId}`typescript
const user = { name: "Alice", email: "alice@example.com" }
// 插入——将对象展开为(column1, column2) VALUES (val1, val2)
const [newUser] = await sql`INSERT INTO users ${sql(user)} RETURNING *`
// 批量插入
await sql`INSERT INTO users ${sql([user1, user2, user3])}`
// 更新——将对象展开为SET column1 = val1, column2 = val2
await sql`UPDATE users SET ${sql(updates)} WHERE id = ${userId}`Transactions
事务
typescript
await sql.begin(async (tx) => {
const [user] = await tx`INSERT INTO users (name) VALUES (${"Alice"}) RETURNING *`
await tx`INSERT INTO audit_log (action, user_id) VALUES ('created', ${user.id})`
})
// Auto-committed on success, rolled back on errorReference: Seefor connection options, pool management, savepoints, MySQL specifics, and prepared statement configuration.references/sql-client.md
typescript
await sql.begin(async (tx) => {
const [user] = await tx`INSERT INTO users (name) VALUES (${"Alice"}) RETURNING *`
await tx`INSERT INTO audit_log (action, user_id) VALUES ('created', ${user.id})`
})
// 成功时自动提交,出错时自动回滚参考文档:查看获取连接选项、池管理、保存点、MySQL特性及预编译语句配置的详细信息。references/sql-client.md
S3 Client (Bun.s3)
S3客户端(Bun.s3)
Built-in S3 client with Web standard Blob API. Zero dependencies, works with any S3-compatible service (AWS S3, Cloudflare R2, MinIO, etc.). Use when the project has or S3-compatible credentials in environment.
AWS_ACCESS_KEY_IDtypescript
import { s3, write } from "bun"
// Reads credentials from AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, etc.
const file = s3.file("data.json") // Lazy reference, no network yet
// Read from S3
const data = await file.json() // Download and parse JSON
const text = await file.text() // Download as string
const stream = file.stream() // ReadableStream
// Upload to S3
await write(s3.file("output.json"), JSON.stringify(data))
// Presigned URLs (synchronous, no network request)
const url = s3.presign("report.pdf", {
expiresIn: 3600, // 1 hour
method: "PUT", // For uploads
acl: "public-read",
})
// Delete
await file.delete()Reference: Seefor custom S3Client, presign options, multipart upload, and serving from Bun.serve.references/s3-client.md
内置S3客户端,基于Web标准Blob API。零依赖,兼容所有S3兼容服务(AWS S3、Cloudflare R2、MinIO等)。适用于项目在环境变量中配置了或S3兼容凭证的场景。
AWS_ACCESS_KEY_IDtypescript
import { s3, write } from "bun"
// 从AWS_ACCESS_KEY_ID、AWS_SECRET_ACCESS_KEY等读取凭证
const file = s3.file("data.json") // 惰性引用,尚未发起网络请求
// 从S3读取
const data = await file.json() // 下载并解析JSON
const text = await file.text() // 下载为字符串
const stream = file.stream() // ReadableStream
// 上传到S3
await write(s3.file("output.json"), JSON.stringify(data))
// 预签名URL(同步,无需网络请求)
const url = s3.presign("report.pdf", {
expiresIn: 3600, // 1小时
method: "PUT", // 用于上传
acl: "public-read",
})
// 删除
await file.delete()参考文档:查看获取自定义S3Client、预签名选项、分块上传及通过Bun.serve提供服务的详细信息。references/s3-client.md
Redis Client (Bun.redis)
Redis客户端(Bun.redis)
Built-in Redis/Valkey client with zero dependencies. Use when the project has or in environment.
REDIS_URLVALKEY_URLtypescript
import { redis, RedisClient } from "bun"
// Default client -- reads REDIS_URL from environment
await redis.set("key", "value")
const value = await redis.get("key") // "value" | null
// With expiration
await redis.set("session", "data", "EX", 3600)
// Counter operations
await redis.incr("counter")
await redis.incrby("counter", 5)
// Hash operations
await redis.hset("user:1", "name", "Alice", "email", "alice@example.com")
await redis.hget("user:1", "name") // "Alice"
// Custom client
const client = new RedisClient("redis://user:pass@host:6379")Reference: Seefor all commands (strings, hashes, lists, sets, sorted sets), pub/sub, pipelines, and common patterns.references/redis-client.md
内置Redis/Valkey客户端,零依赖。适用于项目在环境变量中配置了或的场景。
REDIS_URLVALKEY_URLtypescript
import { redis, RedisClient } from "bun"
// 默认客户端——从环境中读取REDIS_URL
await redis.set("key", "value")
const value = await redis.get("key") // "value" | null
// 设置过期时间
await redis.set("session", "data", "EX", 3600)
// 计数器操作
await redis.incr("counter")
await redis.incrby("counter", 5)
// Hash操作
await redis.hset("user:1", "name", "Alice", "email", "alice@example.com")
await redis.hget("user:1", "name") // "Alice"
// 自定义客户端
const client = new RedisClient("redis://user:pass@host:6379")参考文档:查看获取所有命令(字符串、哈希、列表、集合、有序集合)、发布订阅、管道及常见模式的详细信息。references/redis-client.md
Archive (Bun.Archive)
归档(Bun.Archive)
Create and extract tarballs with optional gzip compression.
typescript
// Create archive
const archive = new Bun.Archive({
"hello.txt": "Hello, World!",
"config.json": JSON.stringify({ key: "value" }),
})
await Bun.write("archive.tar", archive)
// With gzip compression
const compressed = new Bun.Archive(
{ "hello.txt": "Hello, World!" },
{ compress: "gzip", level: 9 }
)
await Bun.write("archive.tar.gz", compressed)
// Extract (auto-detects gzip)
const tarball = await Bun.file("archive.tar.gz").bytes()
const extracted = new Bun.Archive(tarball)创建和解压tar包,支持可选gzip压缩。
typescript
// 创建归档
const archive = new Bun.Archive({
"hello.txt": "Hello, World!",
"config.json": JSON.stringify({ key: "value" }),
})
await Bun.write("archive.tar", archive)
// 带gzip压缩
const compressed = new Bun.Archive(
{ "hello.txt": "Hello, World!" },
{ compress: "gzip", level: 9 }
)
await Bun.write("archive.tar.gz", compressed)
// 解压(自动检测gzip)
const tarball = await Bun.file("archive.tar.gz").bytes()
const extracted = new Bun.Archive(tarball)JSONC (JSON with Comments)
JSONC(带注释的JSON)
Parse JSON with comments and trailing commas -- replaces or packages.
jsonc-parserjson5typescript
import { JSONC } from "bun"
const config = JSONC.parse(`{
// Database config
"host": "localhost",
"port": 5432, // default port
}`)Bun automatically uses JSONC parsing for , , , and . files can be imported directly: .
tsconfig.jsonjsconfig.jsonpackage.jsonbun.lock.jsoncimport config from "./config.jsonc"解析带注释和尾随逗号的JSON——替代或包。
jsonc-parserjson5typescript
import { JSONC } from "bun"
const config = JSONC.parse(`{
// 数据库配置
"host": "localhost",
"port": 5432, // 默认端口
}`)Bun会自动对、、和使用JSONC解析。文件可直接导入:。
tsconfig.jsonjsconfig.jsonpackage.jsonbun.lock.jsoncimport config from "./config.jsonc"Additional Parsing and Utilities (v1.3+)
额外解析与工具类(v1.3+)
typescript
import { JSON5, JSONL, markdown, cron } from "bun"
// JSON5 -- superset of JSON (comments, unquoted keys, trailing commas)
const config = JSON5.parse(`{ unquoted: 'value', /* comment */ }`)
// JSONL -- newline-delimited JSON
const records = JSONL.parse('{"a":1}\n{"a":2}\n')
// Markdown -- built-in CommonMark parser (replaces marked, remark, etc.)
const html = markdown.html("# Title\n\n**Bold** text.")
const ansi = markdown.ansi("# Title") // ANSI terminal output (v1.3.12+)
// Cron -- in-process scheduler + expression parser
const job = cron("0 9 * * 1-5", runReport) // scheduler (v1.3.12+)
const next = cron.parse("0 9 * * 1-5") // next run as ISO string
// ANSI-aware string utilities (replace wrap-ansi, slice-ansi npm packages)
const coloredText = "\x1b[31mHello, World!\x1b[0m"
Bun.wrapAnsi(coloredText, 80) // Wrap to column width
Bun.sliceAnsi(coloredText, 0, 5) // Grapheme-aware sliceReference: Seefor full details on all parsing and utility APIs.references/utilities.md
typescript
import { JSON5, JSONL, markdown, cron } from "bun"
// JSON5——JSON的超集(支持注释、未引号键、尾随逗号)
const config = JSON5.parse(`{ unquoted: 'value', /* comment */ }`)
// JSONL——换行分隔的JSON
const records = JSONL.parse('{"a":1}\n{"a":2}\n')
// Markdown——内置CommonMark解析器(替代marked、remark等)
const html = markdown.html("# Title\n\n**Bold** text.")
const ansi = markdown.ansi("# Title") // ANSI终端输出(v1.3.12+)
// Cron——进程内调度器+表达式解析器
const job = cron("0 9 * * 1-5", runReport) // 调度器(v1.3.12+)
const next = cron.parse("0 9 * * 1-5") // 下次运行时间的ISO字符串
// 支持ANSI的字符串工具类(替代wrap-ansi、slice-ansi npm包)
const coloredText = "\x1b[31mHello, World!\x1b[0m"
Bun.wrapAnsi(coloredText, 80) // 按列宽换行
Bun.sliceAnsi(coloredText, 0, 5) // 基于 grapheme 的切片参考文档:查看获取所有解析与工具API的完整细节。references/utilities.md
SQLite (bun:sqlite)
SQLite(bun:sqlite)
Built-in SQLite3 with zero dependencies. For embedded/local databases -- file-based or in-memory.
typescript
import { Database } from 'bun:sqlite'
// Open database
const db = new Database('mydb.sqlite')
const db = new Database(':memory:') // In-memory
// Enable WAL mode (recommended)
db.exec('PRAGMA journal_mode = WAL')
// Execute statements
db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)')
// Prepared statements
const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)')
insert.run('Alice', 'alice@example.com')
// Query
const select = db.prepare('SELECT * FROM users WHERE name = ?')
const user = select.get('Alice') // Single row or null
const users = select.all('Alice') // All matching rows
// Named parameters
const stmt = db.prepare('SELECT * FROM users WHERE name = $name')
stmt.get({ $name: 'Alice' })
// Transactions
const insertMany = db.transaction((users) => {
for (const user of users) {
insert.run(user.name, user.email)
}
})
insertMany([
{ name: 'Bob', email: 'bob@example.com' },
{ name: 'Carol', email: 'carol@example.com' },
])
// Close
db.close()Reference: Seefor Database constructor, Statement API, transactions, and column types.references/sqlite-and-data.md
内置SQLite3,零依赖。适用于嵌入式/本地数据库——基于文件或内存。
typescript
import { Database } from 'bun:sqlite'
// 打开数据库
const db = new Database('mydb.sqlite')
const db = new Database(':memory:') // 内存数据库
// 启用WAL模式(推荐)
db.exec('PRAGMA journal_mode = WAL')
// 执行语句
db.exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)')
// 预编译语句
const insert = db.prepare('INSERT INTO users (name, email) VALUES (?, ?)')
insert.run('Alice', 'alice@example.com')
// 查询
const select = db.prepare('SELECT * FROM users WHERE name = ?')
const user = select.get('Alice') // 单行或null
const users = select.all('Alice') // 所有匹配行
// 命名参数
const stmt = db.prepare('SELECT * FROM users WHERE name = $name')
stmt.get({ $name: 'Alice' })
// 事务
const insertMany = db.transaction((users) => {
for (const user of users) {
insert.run(user.name, user.email)
}
})
insertMany([
{ name: 'Bob', email: 'bob@example.com' },
{ name: 'Carol', email: 'carol@example.com' },
])
// 关闭数据库
db.close()参考文档:查看获取Database构造函数、Statement API、事务及列类型的详细信息。references/sqlite-and-data.md
Hashing and Passwords
哈希与密码
typescript
// Non-cryptographic (fast, for hash tables/checksums)
Bun.hash('input') // number (wyhash, fastest)
Bun.hash.crc32('input') // CRC32
// Cryptographic
new Bun.CryptoHasher('sha256').update('data').digest('hex')
// Password hashing (async, bcrypt by default)
const hash = await Bun.password.hash('password')
const hash = await Bun.password.hash('password', { algorithm: 'argon2id' })
const valid = await Bun.password.verify('password', hash)Reference: Seefor all hash algorithms, CryptoHasher streaming API, and password hashing options (bcrypt vs argon2id, cost parameters).references/hashing.md
typescript
// 非加密哈希(快速,用于哈希表/校验和)
Bun.hash('input') // 数字(wyhash,最快)
Bun.hash.crc32('input') // CRC32
// 加密哈希
new Bun.CryptoHasher('sha256').update('data').digest('hex')
// 密码哈希(异步,默认bcrypt)
const hash = await Bun.password.hash('password')
const hash = await Bun.password.hash('password', { algorithm: 'argon2id' })
const valid = await Bun.password.verify('password', hash)参考文档:查看获取所有哈希算法、CryptoHasher流式API及密码哈希选项(bcrypt vs argon2id、成本参数)的详细信息。references/hashing.md
Compression
压缩
typescript
// Gzip
const compressed = Bun.gzipSync(data) // Uint8Array → Uint8Array
const decompressed = Bun.gunzipSync(compressed)
// Deflate
const compressed = Bun.deflateSync(data)
const decompressed = Bun.inflateSync(compressed)
// Zstandard (zstd)
const compressed = Bun.zstdCompressSync(data)
const decompressed = Bun.zstdDecompressSync(compressed)
// With options
Bun.gzipSync(data, { level: 9, memLevel: 9 })
Bun.deflateSync(data, { level: 6 })
Bun.zstdCompressSync(data, { level: 3 })All compression functions accept and return .
Uint8Array | string | ArrayBufferUint8Arraytypescript
// Gzip
const compressed = Bun.gzipSync(data) // Uint8Array → Uint8Array
const decompressed = Bun.gunzipSync(compressed)
// Deflate
const compressed = Bun.deflateSync(data)
const decompressed = Bun.inflateSync(compressed)
// Zstandard (zstd)
const compressed = Bun.zstdCompressSync(data)
const decompressed = Bun.zstdDecompressSync(compressed)
// 带选项
Bun.gzipSync(data, { level: 9, memLevel: 9 })
Bun.deflateSync(data, { level: 6 })
Bun.zstdCompressSync(data, { level: 3 })所有压缩函数接受并返回。
Uint8Array | string | ArrayBufferUint8ArrayUtilities
工具类
typescript
// Which (find binary in PATH)
Bun.which('node') // '/usr/local/bin/node' or null
Bun.which('bun', { PATH: '/custom/bin' })
// Inspect (like console.log formatting)
Bun.inspect(obj) // string
Bun.inspect(obj, { depth: 4, colors: true })
// Module resolution
Bun.resolveSync('./module', '/from/dir') // Resolved absolute path
// Deep equality
Bun.deepEquals(a, b) // boolean (structural equality)
Bun.deepEquals(a, b, true) // Strict (differentiates 0 and -0)
// Sleep
await Bun.sleep(1000) // ms
await Bun.sleep(Bun.nanoseconds() + 1e9) // Until timestamp
// Timing
Bun.nanoseconds() // High-resolution timer (bigint)
// UUID
Bun.randomUUIDv7() // Time-ordered UUID v7
// String width (for terminal column alignment)
Bun.stringWidth('hello') // 5
Bun.stringWidth('你好') // 4 (CJK double-width)
// Peek at a promise without awaiting
const value = Bun.peek(promise) // Returns value if resolved, promise if pending
// Color detection
Bun.color('red', 'css') // 'rgb(255, 0, 0)'
Bun.color('#ff0000', 'ansi') // ANSI escape code
Bun.color('hsl(0, 100%, 50%)', 'number') // 0xff0000Reference: Seefor complete utility function signatures and examples.references/utilities.md
typescript
// Which(在PATH中查找二进制文件)
Bun.which('node') // '/usr/local/bin/node' 或 null
Bun.which('bun', { PATH: '/custom/bin' })
// Inspect(类似console.log的格式化)
Bun.inspect(obj) // 字符串
Bun.inspect(obj, { depth: 4, colors: true })
// 模块解析
Bun.resolveSync('./module', '/from/dir') // 解析后的绝对路径
// 深度相等
Bun.deepEquals(a, b) // 布尔值(结构相等)
Bun.deepEquals(a, b, true) // 严格模式(区分0和-0)
// 休眠
await Bun.sleep(1000) // 毫秒
await Bun.sleep(Bun.nanoseconds() + 1e9) // 直到指定时间戳
// 计时
Bun.nanoseconds() // 高分辨率计时器(bigint)
// UUID
Bun.randomUUIDv7() // 时间排序的UUID v7
// 字符串宽度(用于终端列对齐)
Bun.stringWidth('hello') // 5
Bun.stringWidth('你好') // 4(CJK双宽度)
// 无需await即可查看Promise状态
const value = Bun.peek(promise) // 已解析则返回值,pending则返回promise
// 颜色转换
Bun.color('red', 'css') // 'rgb(255, 0, 0)'
Bun.color('#ff0000', 'ansi') // ANSI转义码
Bun.color('hsl(0, 100%, 50%)', 'number') // 0xff0000参考文档:查看获取完整工具函数签名及示例。references/utilities.md
Semver (Bun.semver)
Semver(Bun.semver)
Built-in semver operations — replaces the npm package.
semvertypescript
// Check if a version satisfies a range
Bun.semver.satisfies('1.2.3', '^1.0.0') // true
Bun.semver.satisfies('2.0.0', '>=1.0 <2.0') // false
Bun.semver.satisfies('1.0.0-beta', '*') // false (pre-release excluded by default)
// Sort versions (returns -1, 0, or 1)
Bun.semver.order('1.0.0', '2.0.0') // -1 (a < b)
Bun.semver.order('2.0.0', '1.0.0') // 1 (a > b)
Bun.semver.order('1.0.0', '1.0.0') // 0 (equal)
// Sort an array of versions
const versions = ['3.0.0', '1.2.0', '2.1.0']
versions.sort(Bun.semver.order) // ['1.2.0', '2.1.0', '3.0.0']内置语义化版本操作——替代 npm包。
semvertypescript
// 检查版本是否满足范围
Bun.semver.satisfies('1.2.3', '^1.0.0') // true
Bun.semver.satisfies('2.0.0', '>=1.0 <2.0') // false
Bun.semver.satisfies('1.0.0-beta', '*') // false(默认排除预发布版本)
// 版本排序(返回-1、0或1)
Bun.semver.order('1.0.0', '2.0.0') // -1(a < b)
Bun.semver.order('2.0.0', '1.0.0') // 1 (a > b)
Bun.semver.order('1.0.0', '1.0.0') // 0 (相等)
// 对版本数组排序
const versions = ['3.0.0', '1.2.0', '2.1.0']
versions.sort(Bun.semver.order) // ['1.2.0', '2.1.0', '3.0.0']Serialization (bun:jsc)
序列化(bun:jsc)
Binary structured clone for efficient serialization.
typescript
import { serialize, deserialize } from 'bun:jsc'
const data = { key: 'value', nested: [1, 2, 3] }
const bytes = serialize(data) // Uint8Array
const restored = deserialize(bytes) // Original structureFaster than / for complex objects. Supports types JSON doesn't: , , , , , etc.
JSON.stringifyJSON.parseDateRegExpMapSetArrayBuffer用于高效序列化的二进制结构化克隆。
typescript
import { serialize, deserialize } from 'bun:jsc'
const data = { key: 'value', nested: [1, 2, 3] }
const bytes = serialize(data) // Uint8Array
const restored = deserialize(bytes) // 原始结构对于复杂对象,比/更快。支持JSON不支持的类型:、、、、等。
JSON.stringifyJSON.parseDateRegExpMapSetArrayBufferImage Processing (Bun.Image)
图像处理(Bun.Image)
Built-in image decode/transform/encode (v1.3.14+) — replaces and . Supports JPEG, PNG, WebP, GIF, BMP, HEIC, AVIF, TIFF.
sharpjimptypescript
const thumb = await Bun.file('upload.jpg')
.image()
.resize(400, 400, { fit: 'cover' })
.webp({ quality: 82 })
.bytes()
const { width, height, format } = await new Bun.Image(buffer).metadata()
const blur = await Bun.file('hero.jpg').image().placeholder() // thumbhash data URLReference: Seefor transforms, output formats, and metadata.references/image.md
内置图像解码/转换/编码(v1.3.14+)——替代和。支持JPEG、PNG、WebP、GIF、BMP、HEIC、AVIF、TIFF。
sharpjimptypescript
const thumb = await Bun.file('upload.jpg')
.image()
.resize(400, 400, { fit: 'cover' })
.webp({ quality: 82 })
.bytes()
const { width, height, format } = await new Bun.Image(buffer).metadata()
const blur = await Bun.file('hero.jpg').image().placeholder() // thumbhash数据URL参考文档:查看获取转换操作、输出格式及元数据的详细信息。references/image.md
Browser Automation (Bun.WebView)
浏览器自动化(Bun.WebView)
Headless browser automation (v1.3.12+) — navigate, click, type, run JS, and screenshot without Playwright or Puppeteer (WebKit on macOS, Chrome backend elsewhere).
typescript
await using view = new Bun.WebView({ width: 1280, height: 720 })
await view.navigate('https://bun.sh')
const title = await view.evaluate('document.title')
await Bun.write('page.png', await view.screenshot())Reference: Seefor the full method list and CDP access.references/webview.md
无头浏览器自动化(v1.3.12+)——无需Playwright或Puppeteer即可实现导航、点击、输入、运行JS及截图(macOS使用WebKit,其他平台使用Chrome后端)。
typescript
await using view = new Bun.WebView({ width: 1280, height: 720 })
await view.navigate('https://bun.sh')
const title = await view.evaluate('document.title')
await Bun.write('page.png', await view.screenshot())参考文档:查看获取完整方法列表及CDP访问方式。references/webview.md
Script Patterns
脚本模式
CLI Script Template
CLI脚本模板
typescript
#!/usr/bin/env bun
const args = Bun.argv.slice(2)
const command = args[0]
switch (command) {
case 'generate':
await generate(args.slice(1))
break
case 'process':
await process(args.slice(1))
break
default:
console.log('Usage: script <generate|process> [args]')
process.exit(1)
}typescript
#!/usr/bin/env bun
const args = Bun.argv.slice(2)
const command = args[0]
switch (command) {
case 'generate':
await generate(args.slice(1))
break
case 'process':
await process(args.slice(1))
break
default:
console.log('Usage: script <generate|process> [args]')
process.exit(1)
}File Generator
文件生成器
typescript
const glob = new Bun.Glob('**/*.schema.json')
for await (const path of glob.scan('./schemas')) {
const schema = await Bun.file(`./schemas/${path}`).json()
const code = generateTypeScript(schema)
const outPath = path.replace('.schema.json', '.ts')
await Bun.write(`./generated/${outPath}`, code)
}typescript
const glob = new Bun.Glob('**/*.schema.json')
for await (const path of glob.scan('./schemas')) {
const schema = await Bun.file(`./schemas/${path}`).json()
const code = generateTypeScript(schema)
const outPath = path.replace('.schema.json', '.ts')
await Bun.write(`./generated/${outPath}`, code)
}Data Pipeline
数据流水线
typescript
import { $ } from 'bun'
import { Database } from 'bun:sqlite'
// Fetch data
const data = await $`curl -s https://api.example.com/data`.json()
// Process and store
const db = new Database('output.sqlite')
db.exec('CREATE TABLE IF NOT EXISTS items (id TEXT PRIMARY KEY, value TEXT)')
const insert = db.prepare('INSERT OR REPLACE INTO items (id, value) VALUES (?, ?)')
const batch = db.transaction((items) => {
for (const item of items) {
insert.run(item.id, JSON.stringify(item))
}
})
batch(data.items)
db.close()typescript
import { $ } from 'bun'
import { Database } from 'bun:sqlite'
// 获取数据
const data = await $`curl -s https://api.example.com/data`.json()
// 处理并存储
const db = new Database('output.sqlite')
db.exec('CREATE TABLE IF NOT EXISTS items (id TEXT PRIMARY KEY, value TEXT)')
const insert = db.prepare('INSERT OR REPLACE INTO items (id, value) VALUES (?, ?)')
const batch = db.transaction((items) => {
for (const item of items) {
insert.run(item.id, JSON.stringify(item))
}
})
batch(data.items)
db.close()Best Practices
最佳实践
- Prefer +
Bun.file()overBun.write()/fs.readFilefs.writeFile - Use for shell commands instead of
Bun.$child_process - Use for PostgreSQL/MySQL when
Bun.sql()is available -- zero-dependency, connection pooling, tagged templatesDATABASE_URL - Use for embedded/local SQLite databases instead of external packages
bun:sqlite - Use instead of
Bun.Globnpm packageglob - Use instead of
Bun.CryptoHashercrypto.createHash - Use instead of
Bun.password/bcryptnpm packagesargon2 - Use /
Bun.gzipSyncinstead ofBun.zstdCompressSynczlib - Use for environment variables (same as
Bun.envbut typed)process.env - Use instead of
import.meta.dir(or__dirnamefor Node compat)import.meta.dirname - Use instead of
Bun.which()npm packagewhich - Use instead of
Bun.s3for S3 operations@aws-sdk/client-s3 - Use instead of
Bun.redisorioredisnpm packagesredis - Use instead of
Bun.Archiveortarnpm packages for tarballsarchiver - Use instead of
JSONC.parse()packagejsonc-parser - Use instead of
JSON5.parse()packagejson5 - Use instead of manual newline splitting for JSON Lines
JSONL.parse() - Use /
markdown.html()instead ofmarkdown.ansi(),marked, orremarkpackagesmarkdown-it - Use instead of
Bun.wrapAnsi()npm packagewrap-ansi - Use instead of
Bun.sliceAnsi()npm packageslice-ansi - Use instead of
Bun.Imageorsharpfor image processingjimp
- 优先使用+
Bun.file()而非Bun.write()/fs.readFilefs.writeFile - 使用执行Shell命令而非
Bun.$child_process - 当可用时使用
DATABASE_URL连接PostgreSQL/MySQL——零依赖、连接池、模板字符串语法Bun.sql() - 使用连接嵌入式/本地SQLite数据库而非外部包
bun:sqlite - 使用而非
Bun.Globnpm包glob - 使用而非
Bun.CryptoHashercrypto.createHash - 使用而非
Bun.password/bcryptnpm包argon2 - 使用/
Bun.gzipSync而非Bun.zstdCompressSynczlib - 使用获取环境变量(与
Bun.env相同但支持类型化)process.env - 使用而非
import.meta.dir(或使用__dirname实现Node.js兼容)import.meta.dirname - 使用而非
Bun.which()npm包which - 使用操作S3存储而非
Bun.s3@aws-sdk/client-s3 - 使用操作Redis/Valkey而非
Bun.redis或ioredisnpm包redis - 使用处理tar包而非
Bun.Archive或tarnpm包archiver - 使用而非
JSONC.parse()包jsonc-parser - 使用而非
JSON5.parse()包json5 - 使用处理JSON Lines而非手动按换行分割
JSONL.parse() - 使用/
markdown.html()解析Markdown而非markdown.ansi()、marked或remark包markdown-it - 使用而非
Bun.wrapAnsi()npm包wrap-ansi - 使用而非
Bun.sliceAnsi()npm包slice-ansi - 使用处理图像而非
Bun.Image或sharpjimp