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

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

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

获取文件对象:Bun.file

bash 复制代码
const file = Bun.file("example.txt");
console.log(await file.text());

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

bash 复制代码
await Bun.write("output.txt", "Hello Bun!");
console.log("写入完成");

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

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

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

bash 复制代码
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.$

bash 复制代码
const output = await $`echo Hello from Bun`;
console.log(output.text());

创建 TCP 服务器:Bun.listen

bash 复制代码
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

bash 复制代码
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

bash 复制代码
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

bash 复制代码
const result = await Bun.dns.lookup("bun.sh");
console.log(result.address);

打包代码:Bun.build

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

转译 TypeScript/JSX:Bun.Transpiler

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

密码哈希与验证:Bun.password

bash 复制代码
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

bash 复制代码
console.log(Bun.hash("hello"));

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

文件模式匹配:Bun.Glob

bash 复制代码
const glob = new Bun.Glob("*.js");
for await (const file of glob.scan(".")) {
  console.log(file);
}
bash 复制代码
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

bash 复制代码
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)

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

流式 HTML 解析与转换:HTMLRewriter

bash 复制代码
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

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

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

bash 复制代码
await Bun.sleep(1000);
Bun.sleepSync(500);
console.log("醒来");

提前查看 Promise 状态:Bun.peek

bash 复制代码
const promise = Promise.resolve(42);
console.log(Bun.peek(promise));
const stillPending = new Promise(() => {});
console.log(Bun.peek(stillPending));

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

bash 复制代码
const nodePath = Bun.which("node");
console.log(nodePath);

深度比较对象:Bun.deepEquals

bash 复制代码
const obj1 = { a: { b: 1 } };
const obj2 = { a: { b: 1 } };
console.log(Bun.deepEquals(obj1, obj2));

高精度纳秒时间:Bun.nanoseconds

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

格式化输出对象:Bun.inspect

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

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

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

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

相关推荐
翼帆42 分钟前
我用 AI 复刻了 CodeTank,重温代码坦克
前端·javascript·开源·ai编程·游戏开发·codetank
考虑考虑43 分钟前
zookeeper认证
后端·zookeeper
有趣的老凌1 小时前
学习MarkDown笔记
前端
掘金者阿豪1 小时前
数据库选型到底应该看什么?从业务需求到技术架构的实践分析
前端·后端
苍何2 小时前
豆包终于想通了...
后端
AAA修煤气灶刘哥2 小时前
Agent 都能干活了,软件还需要那么多按钮吗?
人工智能·后端·架构
未秃头的程序猿2 小时前
给新模块加了个 @MapperScan,启动崩了,最后发现跟 MapperScan 没关系
java·后端·mybatis
苍何2 小时前
不用 Opus5.5 ,即梦也能出爆款 vibe 视频了
后端
徐小夕2 小时前
万字拆解:零向量库、无模型微调,SAG2 凭什么刷新多跳问答 SOTA
前端·vue.js·github
SimonKing2 小时前
WorkBuddy又推出新的限免模型(Hy4 flash)了,羊毛可以薅起来了
java·后端·程序员