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

相关推荐
java小白小3 分钟前
SpringBoot(05):Spring Data JPA——用面向对象的方式操作数据库
后端
juejin9985 分钟前
Claude Code Lab-2(上):自然语言查库助手
后端
java小白小11 分钟前
SpringBoot(06):多数据源配置——一个项目连多个库怎么做
后端
程序员cxuan1 小时前
Codex 会把磁盘给烧了?完整复盘来了!
人工智能·后端·程序员
禅思院2 小时前
前端部署“三层漏斗”完全指南:从CI/CD到自动回滚的工程化实战【开题】
前端·架构·前端框架
ClouGence2 小时前
Oracle 数据同步为什么会出现数据不一致?长事务是常被忽略的原因
数据库·后端·oracle
快乐肚皮2 小时前
深入理解Loop Engineering
前端·后端
风骏时光牛马3 小时前
VHDL十大经典基础功能设计实例代码合集
前端
小兔崽子去哪了3 小时前
Vue3 + Pinia 集成 IGV.js 实现 BAM 文件在线浏览
javascript·vue.js·后端
hunterandroid3 小时前
Notification 通知:从基础到渠道适配
前端