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 都附有简洁的功能描述和可直接运行的示例代码。

相关推荐
Mh12 小时前
别再只会 `find` 了:Map 在前端业务里的真实用法
前端·javascript
陈随易12 小时前
FFmpeg 9.0 发布,代号 Lei,音视频处理再升级
前端·后端·程序员
爱丶狸13 小时前
Grafana_Zabbix_ImageRenderer_部署与前端操作手册
linux·前端·zabbix·grafana·kylin
凌虚15 小时前
面向 MySQL 用户的 PostgreSQL 快速上手指南
数据库·后端·架构
用户0595401744615 小时前
把AI对话记忆存储测试从手工改成Playwright+pytest,覆盖率从20%提到96%,回归时间缩短90%
前端·css
kyriewen16 小时前
别再这样写TypeScript了——Code Review中最常见的8个反模式
前端·javascript·typescript
名字还没想好☜16 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
午安~婉16 小时前
GitHub Token/ GitHub Stats统计显示图异常
前端·github·vercel·github token
码云之上16 小时前
AI Agent 工程化总览篇:从 Prompt 到 Harness
前端·人工智能
2501_9269783316 小时前
以说明书 DNA 为模板——完整 AGI 的结构图景
前端·人工智能·经验分享·笔记·ai写作