bun-runtime
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBun Runtime APIs
Bun 运行时API
Use this skill when working with Bun's runtime environment, including file system operations, HTTP servers, environment variables, and Bun-specific APIs.
当你使用Bun运行时环境时可以使用本教程,涉及的场景包括文件系统操作、HTTP服务器、环境变量以及Bun专属API。
Key Concepts
核心概念
Bun Globals
Bun全局API
Bun provides several global APIs that are optimized for performance:
- - Fast file reading with automatic content-type detection
Bun.file() - - High-performance file writing
Bun.write() - - Ultra-fast HTTP server
Bun.serve() - - Type-safe environment variables
Bun.env - - Shell command execution with template literals
Bun.$
Bun提供了多个经过性能优化的全局API:
- - 支持自动内容类型检测的高速文件读取
Bun.file() - - 高性能文件写入
Bun.write() - - 超高速HTTP服务器
Bun.serve() - - 类型安全的环境变量
Bun.env - - 支持模板字面量的Shell命令执行
Bun.$
File I/O
文件I/O
Bun's file APIs are significantly faster than Node.js equivalents:
typescript
// Reading files
const file = Bun.file("./data.json");
const text = await file.text();
const json = await file.json();
const arrayBuffer = await file.arrayBuffer();
// Writing files
await Bun.write("output.txt", "Hello, Bun!");
await Bun.write("data.json", { key: "value" });
// Streaming large files
const file = Bun.file("large-file.txt");
const stream = file.stream();Bun的文件API比Node.js对应的API速度快得多:
typescript
// Reading files
const file = Bun.file("./data.json");
const text = await file.text();
const json = await file.json();
const arrayBuffer = await file.arrayBuffer();
// Writing files
await Bun.write("output.txt", "Hello, Bun!");
await Bun.write("data.json", { key: "value" });
// Streaming large files
const file = Bun.file("large-file.txt");
const stream = file.stream();HTTP Server
HTTP服务器
Bun.serve() provides exceptional performance:
typescript
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/") {
return new Response("Hello, Bun!");
}
if (url.pathname === "/api/data") {
return Response.json({ message: "Fast API response" });
}
return new Response("Not Found", { status: 404 });
},
});Bun.serve() 拥有极为出色的性能:
typescript
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/") {
return new Response("Hello, Bun!");
}
if (url.pathname === "/api/data") {
return Response.json({ message: "Fast API response" });
}
return new Response("Not Found", { status: 404 });
},
});WebSocket Support
WebSocket支持
Built-in WebSocket support without external dependencies:
typescript
Bun.serve({
port: 3000,
fetch(req, server) {
if (server.upgrade(req)) {
return; // WebSocket upgrade successful
}
return new Response("Expected WebSocket connection", { status: 400 });
},
websocket: {
message(ws, message) {
console.log("Received:", message);
ws.send(`Echo: ${message}`);
},
open(ws) {
console.log("Client connected");
},
close(ws) {
console.log("Client disconnected");
},
},
});无需外部依赖的内置WebSocket支持:
typescript
Bun.serve({
port: 3000,
fetch(req, server) {
if (server.upgrade(req)) {
return; // WebSocket upgrade successful
}
return new Response("Expected WebSocket connection", { status: 400 });
},
websocket: {
message(ws, message) {
console.log("Received:", message);
ws.send(`Echo: ${message}`);
},
open(ws) {
console.log("Client connected");
},
close(ws) {
console.log("Client disconnected");
},
},
});Best Practices
最佳实践
Use Native APIs
使用原生API
Prefer Bun's native APIs over Node.js equivalents for better performance:
typescript
// Good - Use Bun.file()
const data = await Bun.file("./data.json").json();
// Avoid - Don't use fs from Node.js when Bun alternatives exist
import fs from "fs/promises";
const data = JSON.parse(await fs.readFile("./data.json", "utf-8"));优先使用Bun原生API而非Node.js对应的API,以获得更好的性能:
typescript
// Good - Use Bun.file()
const data = await Bun.file("./data.json").json();
// Avoid - Don't use fs from Node.js when Bun alternatives exist
import fs from "fs/promises";
const data = JSON.parse(await fs.readFile("./data.json", "utf-8"));Type Safety with Environment Variables
环境变量类型安全
Use type-safe environment variable access:
typescript
// Good - Type-safe access
const apiKey = Bun.env.API_KEY;
// Also valid - process.env works but Bun.env is preferred
const port = process.env.PORT ?? "3000";使用类型安全的方式访问环境变量:
typescript
// Good - Type-safe access
const apiKey = Bun.env.API_KEY;
// Also valid - process.env works but Bun.env is preferred
const port = process.env.PORT ?? "3000";Efficient Shell Commands
高效Shell命令
Use for shell command execution:
Bun.$typescript
// Execute shell commands safely
import { $ } from "bun";
const output = await $`ls -la`.text();
const gitBranch = await $`git branch --show-current`.text();
// With error handling
try {
await $`npm run build`;
} catch (error) {
console.error("Build failed:", error);
}使用执行Shell命令:
Bun.$typescript
// Execute shell commands safely
import { $ } from "bun";
const output = await $`ls -la`.text();
const gitBranch = await $`git branch --show-current`.text();
// With error handling
try {
await $`npm run build`;
} catch (error) {
console.error("Build failed:", error);
}Password Hashing
密码哈希
Use built-in password hashing:
typescript
const password = "super-secret";
// Hash a password
const hash = await Bun.password.hash(password);
// Verify a password
const isMatch = await Bun.password.verify(password, hash);使用内置的密码哈希能力:
typescript
const password = "super-secret";
// Hash a password
const hash = await Bun.password.hash(password);
// Verify a password
const isMatch = await Bun.password.verify(password, hash);Common Patterns
常用模式
API Server with JSON
基于JSON的API服务器
typescript
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/api/users") {
return Response.json(users);
}
if (url.pathname.startsWith("/api/users/")) {
const id = parseInt(url.pathname.split("/")[3]);
const user = users.find((u) => u.id === id);
if (!user) {
return Response.json({ error: "User not found" }, { status: 404 });
}
return Response.json(user);
}
return Response.json({ error: "Not found" }, { status: 404 });
},
});typescript
interface User {
id: number;
name: string;
}
const users: User[] = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === "/api/users") {
return Response.json(users);
}
if (url.pathname.startsWith("/api/users/")) {
const id = parseInt(url.pathname.split("/")[3]);
const user = users.find((u) => u.id === id);
if (!user) {
return Response.json({ error: "User not found" }, { status: 404 });
}
return Response.json(user);
}
return Response.json({ error: "Not found" }, { status: 404 });
},
});File Upload Handler
文件上传处理程序
typescript
Bun.serve({
port: 3000,
async fetch(req) {
if (req.method === "POST" && new URL(req.url).pathname === "/upload") {
const formData = await req.formData();
const file = formData.get("file") as File;
if (!file) {
return Response.json({ error: "No file provided" }, { status: 400 });
}
await Bun.write(`./uploads/${file.name}`, file);
return Response.json({
message: "File uploaded successfully",
filename: file.name,
size: file.size,
});
}
return new Response("Method not allowed", { status: 405 });
},
});typescript
Bun.serve({
port: 3000,
async fetch(req) {
if (req.method === "POST" && new URL(req.url).pathname === "/upload") {
const formData = await req.formData();
const file = formData.get("file") as File;
if (!file) {
return Response.json({ error: "No file provided" }, { status: 400 });
}
await Bun.write(`./uploads/${file.name}`, file);
return Response.json({
message: "File uploaded successfully",
filename: file.name,
size: file.size,
});
}
return new Response("Method not allowed", { status: 405 });
},
});Reading Configuration Files
读取配置文件
typescript
// Read and parse JSON config
const config = await Bun.file("./config.json").json();
// Read TOML (Bun has built-in TOML support)
const tomlConfig = await Bun.file("./config.toml").text();
// Read environment-specific config
const env = Bun.env.NODE_ENV ?? "development";
const envConfig = await Bun.file(`./config.${env}.json`).json();typescript
// Read and parse JSON config
const config = await Bun.file("./config.json").json();
// Read TOML (Bun has built-in TOML support)
const tomlConfig = await Bun.file("./config.toml").text();
// Read environment-specific config
const env = Bun.env.NODE_ENV ?? "development";
const envConfig = await Bun.file(`./config.${env}.json`).json();Anti-Patterns
反模式
Don't Mix Node.js and Bun APIs Unnecessarily
不要无理由混用Node.js和Bun API
typescript
// Bad - Mixing APIs without reason
import fs from "fs/promises";
const data1 = await fs.readFile("file1.txt", "utf-8");
const data2 = await Bun.file("file2.txt").text();
// Good - Use consistent APIs
const data1 = await Bun.file("file1.txt").text();
const data2 = await Bun.file("file2.txt").text();typescript
// Bad - Mixing APIs without reason
import fs from "fs/promises";
const data1 = await fs.readFile("file1.txt", "utf-8");
const data2 = await Bun.file("file2.txt").text();
// Good - Use consistent APIs
const data1 = await Bun.file("file1.txt").text();
const data2 = await Bun.file("file2.txt").text();Don't Ignore Error Handling
不要忽略错误处理
typescript
// Bad - No error handling
const data = await Bun.file("./might-not-exist.json").json();
// Good - Proper error handling
try {
const file = Bun.file("./might-not-exist.json");
if (await file.exists()) {
const data = await file.json();
} else {
console.error("File not found");
}
} catch (error) {
console.error("Failed to read file:", error);
}typescript
// Bad - No error handling
const data = await Bun.file("./might-not-exist.json").json();
// Good - Proper error handling
try {
const file = Bun.file("./might-not-exist.json");
if (await file.exists()) {
const data = await file.json();
} else {
console.error("File not found");
}
} catch (error) {
console.error("Failed to read file:", error);
}Don't Block the Event Loop
不要阻塞事件循环
typescript
// Bad - Synchronous file reading blocks
import fs from "fs";
const data = fs.readFileSync("large-file.txt", "utf-8");
// Good - Async operations
const data = await Bun.file("large-file.txt").text();typescript
// Bad - Synchronous file reading blocks
import fs from "fs";
const data = fs.readFileSync("large-file.txt", "utf-8");
// Good - Async operations
const data = await Bun.file("large-file.txt").text();Related Skills
相关技能
- bun-testing: Testing Bun applications with built-in test runner
- bun-bundler: Building and bundling with Bun's fast bundler
- bun-package-manager: Managing dependencies with Bun's package manager
- bun-testing: 使用内置测试运行器测试Bun应用
- bun-bundler: 使用Bun的高速打包工具进行构建和打包
- bun-package-manager: 使用Bun的包管理器管理依赖