README 提供四合一工具链;本页聚焦脚本内部的全局 Bun API(无需 import,直接可用,仅当用 bun 运行时存在)。
Bun.file / Bun.write — 文件 IO
const file = Bun.file("data.json");
await file.exists(); // boolean
const data = await file.json(); // 自动按扩展名推断:.json()/.text()/.arrayBuffer()/.stream()
await Bun.write("out.txt", "hello"); // 可写 string / Uint8Array / Blob / Response / URL
await Bun.write("copy.png", Bun.file("a.png")); // 文件复制Bun.$ — 内置 Shell(Bun Shell)
import { $ } from "bun";
const branch = await $`git branch --show-current`.text(); // 捕获输出为字符串
await $`ls src/*.ts`.quiet(); // 抑制 stdout
$`echo ${userInput}`; // 模板变量自动转义,防注入
import { Glob } from "bun";
for await (const f of new Glob("**/*.ts").scan(".")) console.log(f); // 内置 globBun.serve — HTTP Server
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("ok"); // 标准 Web Fetch API
},
});
console.log(server.url);支持静态路由(routes: { "/": req => Response })、hot reload、idleTimeout。
环境与杂项
| API | 用途 |
|---|---|
Bun.env.X | 等价 process.env.X |
Bun.main | 入口文件路径 |
Bun.version | Bun 版本号 |
Bun.deepEquals(a, b) | 深度比较(含循环引用) |
Bun.nanoseconds() | 高精度时间戳 |
Bun.hash() | wyhash 哈希,另有 Bun.hashXX() / Murmur64v3 / CityHash32 / CRC32 |
Bun.password.hash/verify | 内置 argon2 / bcrypt |
Bun.s3() | S3 兼容存储客户端 |
bun:sqlite | 内置 SQLite(new Database("x.db")) |
bun:test | 内置测试框架的 describe/test/expect |
Bun.spawn(["cmd"]) | 子进程(比 shell 更可控) |
Bun.build() | JS API 方式打包(等价 bun build CLI) |
注意
- 这些 API 只在
bun运行时可用;用node跑会直接ReferenceError,跨运行时脚本需做能力检测 - TS/JSX 原生执行,无需配置
Bun.$模板变量自动转义,但拼接成路径的参数仍需自行校验- 配置文件为
bunfig.toml(运行时/安装/测试各节配置)