🌐 Bun.serve - HTTP 服务
高性能 HTTP 服务器,支持 WebSocket。
typescript
// 基础 HTTP 服务
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/api") {
return Response.json({ message: "Hello API" });
}
return new Response("Hello World");
},
});
WebSocket 支持
typescript
Bun.serve({
fetch(req, server) {
// 升级为 WebSocket
if (server.upgrade(req)) {
return; // 升级成功
}
return new Response("WebSocket only");
},
websocket: {
open(ws) {
ws.send("Welcome!");
},
message(ws, msg) {
ws.send(`Echo: ${msg}`);
},
close(ws) {
console.log("Client disconnected");
},
},
});
📄 Bun.file - 文件操作
高性能文件读取,支持流式处理。
typescript
// 读取文件
const file = Bun.file("./data.json");
const content = await file.text();
const json = await file.json();
// 写入文件
await Bun.write("./output.txt", "Hello, Bun!");
await Bun.write("./data.json", JSON.stringify(data));
// 流式读取
const stream = file.stream();
for await (const chunk of stream) {
console.log(chunk);
}
// 文件信息
const stats = await file.stat();
console.log(stats.size, stats.mtime);
🔄 Bun.spawn - 子进程
typescript
// 同步执行
const result = Bun.spawnSync(["echo", "Hello"]);
console.log(result.stdout.toString());
// 异步执行
const proc = Bun.spawn(["npm", "install"], {
cwd: "./my-project",
stdout: "pipe",
});
// 读取输出
const text = await new Response(proc.stdout).text();
// 等待完成
await proc.exited;
🔧 全局 API
| API | 说明 |
|---|---|
Bun.env | 环境变量(自动加载 .env) |
Bun.argv | 命令行参数 |
Bun.version | Bun 版本 |
Bun.cwd() | 当前工作目录 |
Bun.main | 入口文件路径 |
Bun.inspect() | 格式化输出 |
typescript
// 环境变量
console.log(Bun.env.NODE_ENV);
console.log(Bun.env.DATABASE_URL);
// 命令行参数
console.log(Bun.argv); // ["bun", "run", "script.ts", "arg1"]
// 入口文件
console.log(Bun.main); // 当前执行的文件
⚡ Shell API
跨平台 bash 风格 shell 脚本。
typescript
// 使用 Bun.$
const $ = Bun.$;
// 执行命令
await $`echo "Hello"`;
// 捕获输出
const text = await $`ls -la`.text();
const lines = await $`cat file.txt`.lines();
// 管道
await $`cat input.txt | grep "error" > errors.txt`;