Bun运行时Skill bun-runtime

这个技能用于在Bun运行时环境中工作,包括文件系统操作、HTTP服务器、环境变量和Bun特有的API,特别适用于高性能JavaScript/TypeScript应用程序开发。关键词:Bun, JavaScript, TypeScript, 运行时, API, 文件I/O, HTTP服务器, 环境变量, 性能优化, 后端开发。

后端开发 0 次安装 0 次浏览 更新于 3/25/2026

名称: bun运行时 用户可调用: false 描述: 使用时与Bun的运行时API一起工作,包括文件I/O、HTTP服务器和本地API。涵盖在Bun快速运行时环境中执行现代JavaScript/TypeScript。 允许的工具:

  • Read
  • Write
  • Edit
  • Bash
  • Grep
  • Glob

Bun 运行时 APIs

使用此技能时与Bun的运行时环境一起工作,包括文件系统操作、HTTP服务器、环境变量和Bun特有的API。

关键概念

Bun 全局变量

Bun提供了几个针对性能优化的全局API:

  • Bun.file() - 带有自动内容类型检测的快速文件读取
  • Bun.write() - 高性能文件写入
  • Bun.serve() - 超快速HTTP服务器
  • Bun.env - 类型安全的环境变量
  • Bun.$ - 使用模板字面量的Shell命令执行

文件 I/O

Bun的文件API比Node.js的等效API快得多:

// 读取文件
const file = Bun.file("./data.json");
const text = await file.text();
const json = await file.json();
const arrayBuffer = await file.arrayBuffer();

// 写入文件
await Bun.write("output.txt", "Hello, Bun!");
await Bun.write("data.json", { key: "value" });

// 流式处理大文件
const file = Bun.file("large-file.txt");
const stream = file.stream();

HTTP 服务器

Bun.serve() 提供卓越的性能:

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 支持

内置WebSocket支持,无需外部依赖:

Bun.serve({
  port: 3000,
  fetch(req, server) {
    if (server.upgrade(req)) {
      return; // WebSocket 升级成功
    }
    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");
    },
  },
});

最佳实践

使用原生 API

优先使用Bun的原生API而非Node.js的等效API以获得更好的性能:

// 好 - 使用 Bun.file()
const data = await Bun.file("./data.json").json();

// 避免 - 当存在Bun替代方案时,不要使用Node.js的fs
import fs from "fs/promises";
const data = JSON.parse(await fs.readFile("./data.json", "utf-8"));

环境变量的类型安全

使用类型安全的环境变量访问:

// 好 - 类型安全访问
const apiKey = Bun.env.API_KEY;

// 也有效 - process.env 可用,但Bun.env是首选
const port = process.env.PORT ?? "3000";

高效的 Shell 命令

使用 Bun.$ 执行Shell命令:

// 安全地执行Shell命令
import { $ } from "bun";

const output = await $`ls -la`.text();
const gitBranch = await $`git branch --show-current`.text();

// 带错误处理
try {
  await $`npm run build`;
} catch (error) {
  console.error("Build failed:", error);
}

密码哈希

使用内置的密码哈希:

const password = "super-secret";

// 哈希密码
const hash = await Bun.password.hash(password);

// 验证密码
const isMatch = await Bun.password.verify(password, hash);

常见模式

带有 JSON 的 API 服务器

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 });
  },
});

文件上传处理程序

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 });
  },
});

读取配置文件

// 读取和解析JSON配置
const config = await Bun.file("./config.json").json();

// 读取TOML(Bun有内置TOML支持)
const tomlConfig = await Bun.file("./config.toml").text();

// 读取环境特定的配置
const env = Bun.env.NODE_ENV ?? "development";
const envConfig = await Bun.file(`./config.${env}.json`).json();

反模式

不要不必要地混合 Node.js 和 Bun APIs

// 坏 - 无理由混合API
import fs from "fs/promises";
const data1 = await fs.readFile("file1.txt", "utf-8");
const data2 = await Bun.file("file2.txt").text();

// 好 - 使用一致的API
const data1 = await Bun.file("file1.txt").text();
const data2 = await Bun.file("file2.txt").text();

不要忽略错误处理

// 坏 - 没有错误处理
const data = await Bun.file("./might-not-exist.json").json();

// 好 - 适当的错误处理
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);
}

不要阻塞事件循环

// 坏 - 同步文件读取阻塞
import fs from "fs";
const data = fs.readFileSync("large-file.txt", "utf-8");

// 好 - 异步操作
const data = await Bun.file("large-file.txt").text();

相关技能

  • bun-testing: 使用内置测试运行器测试Bun应用程序
  • bun-bundler: 使用Bun的快速打包器进行构建和打包
  • bun-package-manager: 使用Bun的包管理器管理依赖项