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

相关推荐
Csvn4 小时前
TypeScript 大型项目架构:从单体 tsconfig 到分层可扩展的工程
前端
Bs_MoneyMagnet5 小时前
基于springboot+vue的心理咨询预约与随访平台的设计与实现 源码+文档
vue.js·spring boot·后端·spring·毕业设计·旅游·计算机毕业设计
计算机魔术师5 小时前
Dario Amodei 发文呼吁为前沿 AI 降速并提出三点计划
前端
计算机魔术师6 小时前
OpenAI的AI代理偷偷给RubyGems下毒,我们却毫无察觉
前端
甲维斯6 小时前
0代码,0建模,3句话开发一个3D游戏!
前端·游戏·游戏开发
IT_陈寒6 小时前
Vue的响应式更新把我坑惨了,原来问题出在这
前端·人工智能·后端
tingke6 小时前
别再堆 AGENTS.md 了:前端团队的 Agent 上下文分层落地指南
前端
李明卫杭州7 小时前
React 复合事件系统对比解析
前端·javascript·react.js
陌シ未央ゞ7 小时前
基于BM25算法和RRF实现的混合索引(java版)
人工智能·spring boot·后端·算法
第五页的你7 小时前
SpringBoot基础设施配置(Redis序列化,JJWT新版)
后端