Bun 提供了许多 Node.js 原生没有的专属 API

0 阅读1分钟

Bun 提供了许多 Node.js 原生没有的专属 API:

| API | 功能 | | :-- | :-- | | Bun.serve | HTTP/WebSocket 服务器 | | Bun.file / Bun.write | 文件操作 | | Bun.$ | Shell 命令 | | Bun.build | 打包器 | | Bun.Transpiler | TypeScript/JSX 转译器 | | Bun.password | 密码哈希与验证 | | Bun.Glob | 文件模式匹配 | | Bun.Cookie / Bun.CookieMap | Cookie 解析与序列化 | | Bun.S3Client | S3 客户端 | | Bun.Cron | 定时任务 | | HTMLRewriter | 流式 HTML 解析与转换 | | Bun.sleep / Bun.peek / Bun.deepEquals 等 | 实用工具函数 |

创建 HTTP/WebSocket 服务器:Bun.serve

Bun.serve({
  fetch(req) {
    return new Response("Hello, Bun!");
  },
  port: 3000,
});
console.log("Server running on http://localhost:3000");

获取文件对象:Bun.file

const file = Bun.file("example.txt");
console.log(await file.text());

高性能写入文件/响应:Bun.write

await Bun.write("output.txt""Hello Bun!");
console.log("写入完成");

标准输入/输出/错误:Bun.stdin / Bun.stdout / Bun.stderr

const input = await Bun.stdin.text();
Bun.stdout.write("你输入了: " + input);
Bun.stderr.write("这是一条错误消息");

衍生子进程:Bun.spawn / Bun.spawnSync

const proc = Bun.spawn(["echo""hello"]);
await proc.exited;
console.log(await new Response(proc.stdout).text());

const result = Bun.spawnSync(["echo""world"]);
console.log(result.stdout.toString());

执行 Shell 命令:Bun.$

const output = await $`echo Hello from Bun`;
console.log(output.text());

创建 TCP 服务器:Bun.listen

const server = Bun.listen({
  hostname: "localhost",
  port: 8080,
  socket: {
    data(socket, data) {
      socket.write(data);
    },
  },
});
console.log("TCP server listening on", server.port);

创建 TCP 客户端:Bun.connect

const socket = await Bun.connect({
  hostname: "example.com",
  port: 80,
  socket: {
    data(socket, data) {
      console.log(data.toString());
      socket.end();
    },
  },
});
socket.write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");

创建 UDP 套接字:Bun.udpSocket

const socket = await Bun.udpSocket({
  port: 41234,
  socket: {
    data(socket, buf, port, addr) {
      console.log(`收到来自 ${addr}:${port}:`, buf.toString());
    },
  },
});
socket.send("hello", 41234, "127.0.0.1");

DNS 查询工具:Bun.dns

const result = await Bun.dns.lookup("bun.sh");
console.log(result.address);

打包代码:Bun.build

const result = await Bun.build({
  entrypoints: ["./src/index.ts"],
  outdir: "./dist",
});
if (!result.success) console.error(result.logs);

转译 TypeScript/JSX:Bun.Transpiler

const transpiler = new Bun.Transpiler();
const code = `const x: number = 42;`;
const output = transpiler.transformSync(code);
console.log(output);

密码哈希与验证:Bun.password

const password = "mySecret123";
const hash = await Bun.password.hash(password);
console.log(hash);
const isValid = await Bun.password.verify(password, hash);
console.log(isValid);

快速哈希:Bun.hash / Bun.CryptoHasher

console.log(Bun.hash("hello"));

const hasher = new Bun.CryptoHasher("sha256");
hasher.update("hello");
console.log(hasher.digest("hex"));

文件模式匹配:Bun.Glob

const glob = new Bun.Glob("*.js");
for await (const file of glob.scan(".")) {
  console.log(file);
}

Cookie 解析与序列化:Bun.Cookie / Bun.CookieMap

const cookieMap = new Bun.CookieMap("name=Alice; age=20");
console.log(cookieMap.get("name"));
const setCookie = Bun.Cookie.serialize("token""abc123", { maxAge: 3600 });
console.log(setCookie);

S3 客户端:Bun.S3Client

const client = new Bun.S3Client({
  accessKeyId: "YOUR_KEY",
  secretAccessKey: "YOUR_SECRET",
  region: "us-east-1",
});
await client.write("my-bucket""file.txt""Hello S3");
const data = await client.file("my-bucket""file.txt").text();
console.log(data);

定时任务调度器:Bun.Cron(v1.3.11)

const cron = new Bun.Cron({
  pattern: "* * * * *",
  handler() {
    console.log("每分钟执行一次");
  },
});
cron.start();

流式 HTML 解析与转换:HTMLRewriter

const rewriter = new HTMLRewriter()
  .on("a", {
    element(el) {
      el.setAttribute("target""_blank");
    },
  });
const html = `<a href="https://bun.sh">Bun</a>`;
const output = rewriter.transform(html);
console.log(await output.text());

运行时信息:Bun.version / Bun.revision / Bun.env / Bun.main

console.log("Bun版本:", Bun.version);
console.log("Git提交:", Bun.revision);
console.log("环境变量PATH:", Bun.env.PATH);
console.log("入口文件:", Bun.main);

延迟等待:Bun.sleep / Bun.sleepSync

await Bun.sleep(1000);
Bun.sleepSync(500);
console.log("醒来");

提前查看 Promise 状态:Bun.peek

const promise = Promise.resolve(42);
console.log(Bun.peek(promise));
const stillPending = new Promise(() => {});
console.log(Bun.peek(stillPending));

查找可执行文件路径:Bun.which

const nodePath = Bun.which("node");
console.log(nodePath);

深度比较对象:Bun.deepEquals

const obj1 = { a: { b: 1 } };
const obj2 = { a: { b: 1 } };
console.log(Bun.deepEquals(obj1, obj2));

高精度纳秒时间:Bun.nanoseconds

const start = Bun.nanoseconds();
await Bun.sleep(100);
const end = Bun.nanoseconds();
console.log(`耗时 ${end - start} 纳秒`);

格式化输出对象:Bun.inspect

const obj = { a: 1, b: [2, 3] };
console.log(Bun.inspect(obj, { depth: 2 }));

手动触发垃圾回收:Bun.gc(需 --expose-gc 标志)

bun --expose-gc script.ts
if (Bun.gc) {
  Bun.gc();
  console.log("GC 已执行");
}

以上所有 API 中,只有 Bun.Cron 的版本号大于 1.3,因此单独标注为 Bun.Cron(v1.3.11)。其余均不显示版本。每个 API 都附有简洁的功能描述和可直接运行的示例代码。