blog.dopana

返回

你手上有一个 Node.js 项目,跑得好好的。团队想试试 Bun,因为启动更快、测试运行器内置、装依赖只要几秒钟。

然后你打开第一个文件,发现到处都是这样的代码:

src/config.ts
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const configPath = path.join(__dirname, "config.json");
const raw = fs.readFileSync(configPath, "utf8");
ts

一个念头立刻冒出来:「这些是不是都得重写一遍?」

简短的回答是 不用 —— 而这正是理解 Bun 设计理念最关键的一点。Bun 不是另一个星球,它只是同一个星球上多背了一个更大的工具箱。

10 秒速查表#

Node.jsBun 的替代方案要重写吗?
node:fsBun.file()、Bun.write()、Bun.$只有简单的文件内容读写才需要
node:pathpath / node:path不要 —— 原样保留就好
node:urlURL、URLSearchParams(Web API)只有你确实想要 Web API 时才换
node:child_processBun.$、Bun.spawn可选,跑 shell 命令时收益明显

心智模型:只是工具箱更大,不是换了工具箱#

用一个比喻就能把整件事讲清楚。

想象一间木工房。Node.js 给你一条工具腰带,上面挂着锤子、锯子和螺丝刀。这时 Bun 出现了,说:「这是更好的锤子、电动锯和激光测距仪 —— 顺便一提,旧的锤子照样用得好好的。」

有了新工具,并不意味着你 必须 换掉旧工具。它意味着你多了一种选择:当新工具真的能让代码更清晰时,你再用它。

Bun 的兼容层是刻意做得很深的。node:fs、node:path、node:url、node:http 以及数百个其他模块,在 Bun 上的语义和 Node 完全一致。这正是重点所在:绝大部分现有 Node 代码可以一行不改地跑起来。

[!TIP] 把 Bun 原生 API 当成升级路径,而不是迁移义务。你可以一个文件一个文件地替换,在代码真正变清晰的时候再动手。

1. node:fs → Bun.file() 与 Bun.write()#

基础替换#

Node.js
// Node
import fs from "node:fs";

const text = fs.readFileSync("file.txt", "utf8");
fs.writeFileSync("file.txt", "hello");
ts
Bun
// Bun
const text = await Bun.file("file.txt").text();
await Bun.write("file.txt", "hello");
ts

思路就这么简单:Bun.file(path) 给你一个文件句柄(严格来说是 BunFile,它实现了标准的 Blob 接口),Bun.write(destination, data) 则把任意数据写到磁盘上。

判断文件是否存在#

const exists = await Bun.file("file.txt").exists();
ts

比 Node 里那套 try { fs.accessSync(p) } catch { false } 的怪写法清爽多了。

[!WARNING] Bun.file() 是惰性的 —— 仅仅创建句柄并不会碰磁盘,文件不存在也不会抛错。不存在的文件会报告 size === 0、type === "text/plain;charset=utf-8"。只有你真正去读它时才会报错(ENOENT: no such file or directory)。所以当你关心文件是否存在时,请使用 .exists(),不要把 Bun.file() 当成校验手段。

读取 JSON#

const data = await Bun.file("config.json").json();
ts

不用再写 JSON.parse(fs.readFileSync(...)) 了,.json() 直接给你解析好的对象。

BunFile 还能做什么#

const file = Bun.file("data.bin");

await file.text();         // string
await file.json();         // 解析后的 JSON
await file.arrayBuffer();  // ArrayBuffer
await file.bytes();        // Uint8Array
file.stream();             // ReadableStream
await file.exists();       // boolean
await file.delete();       // 删除文件
ts

因为 BunFile 就是 一个 Blob,你可以直接把它交给 fetch、Response 或任何接受二进制数据的 API。

写入#

Bun.write() 是一把多用途工具。目标可以是路径、file:// URL 或 BunFile;内容可以是字符串、Blob、ArrayBuffer、类型化数组,甚至一个 Response 的 body。

await Bun.write("output.txt", "plain text");
await Bun.write("output.txt", new Uint8Array([1, 2, 3]));

// 复制文件 —— Bun 会挑选当前平台上最快的系统调用
await Bun.write(Bun.file("copy.txt"), Bun.file("input.txt"));

// 直接下载到磁盘
const response = await fetch("https://bun.com");
await Bun.write("index.html", response);

// 把文件内容输出到 stdout
await Bun.write(Bun.stdout, Bun.file("input.txt"));
ts

Bun.write() 返回写入的字节数,拿来打日志很方便:

const bytes = await Bun.write("output.txt", "hello");
console.log(`wrote ${bytes} bytes`); // wrote 5 bytes
ts

用 FileSink 增量写入#

文件大到装不进内存时,用 writer:

const writer = Bun.file("output.txt").writer();

writer.write("it was the best of times\n");
writer.write("it was the worst of times\n");

await writer.end(); // 刷盘并关闭
ts

[!NOTE] 有一处行为差异值得记住:Bun.write() 会自动创建缺失的父目录,而 Node 的 fs.writeFileSync() 在父目录不存在时会抛 ENOENT。已在 Bun 1.4.3 上验证:Bun.write("a/b/c.txt", "x") 会成功,并顺带创建 a/b/。

node:fs 仍然负责的部分#

Bun.file() 处理的是文件内容,不是文件系统本身。下面这些操作请继续使用 node:fs —— Bun 的实现很快:

src/scan.ts
import { mkdir, readdir, stat } from "node:fs/promises";

// 创建目录树
await mkdir("build/output", { recursive: true });

// 列出文件
const entries = await readdir(import.meta.dir, { recursive: true });

// 读取元信息
const info = await stat("package.json");
console.log(info.size, info.mtime);
ts

Bun 官方文档写得很直白:for operations they don’t cover, such as mkdir or readdir, use Bun’s nearly complete implementation of the node:fs module.

顺带一提:Bun.$ 跑 shell 命令#

文件读写并不构成代码里的全部 I/O,有时候你需要执行一条命令:

Node.js
// Node
import { execSync } from "node:child_process";
execSync("git rev-parse HEAD");
ts
Bun
// Bun
import { $ } from "bun";

const hash = await $`git rev-parse HEAD`.text();
ts

Bun.$ 是一个用 Rust 实现的、跨平台的类 bash shell。它不是 /bin/sh 的包装器,而是跑在 Bun 进程内的重新实现,因此在 Windows、macOS、Linux 上行为一致。

await $`ls -la`.quiet();                       // 不输出任何内容
await $`echo "hi"`.text();                     // "hi\n"
await $`cat package.json`.json();              // 解析后的 JSON
for await (const line of $`cat list.txt`.lines()) { /* ... */ }
ts

还有一个很关键的安全细节:插值的值默认会被转义,用户输入无法逃逸成额外的命令。

const userInput = "my-file.txt; rm -rf /";
await $`ls ${userInput}`; // ls 收到的是一个字面量参数,而不是两条命令
ts

需要完全掌控进程时(stdin/stdout 管道、环境变量、退出码),用 Bun.spawn:

const proc = Bun.spawn(["echo", "hello"], { stdout: "pipe" });
const output = await new Response(proc.stdout).text();
await proc.exited;
console.log(output, proc.exitCode);
ts

2. node:path → 原样保留#

import path from "node:path";

const file = path.join("src", "index.ts");
const dir = path.dirname(file);
const ext = path.extname(file);
const abs = path.resolve(file);
ts

在 Bun 里替换 node:path 没有任何好处:

  • 它只是字符串处理,不涉及 I/O,也没有什么运行时魔法。
  • 它是跨平台感知的(Windows 分隔符、盘符、UNC 路径)。
  • Bun 完整实现了它,并且通过了 Node 自己的测试套件。
  • 手动拼接字符串是降级,不是升级。

Bun 特有的便利只有一点:知道这个文件住在哪。

import.meta.dir;  // "/a/b"      — 当前文件所在目录的绝对路径
import.meta.path; // "/a/b/c.ts" — 当前文件的绝对路径
ts

对比一下 process.cwd() —— 那是命令执行的位置,不是代码所在的位置。import.meta.dir 正是 Bun 对「怎么找到和我这个模块放在一起的文件」这个经典问题的答案。

[!NOTE] Node.js 也跟上了:从 Node 20.11 / 21.2 开始,import.meta.dirname 和 import.meta.filename 已成为标准。所以如果你想要同时跑在两个运行时上的代码,import.meta.dirname 才是可移植的写法,import.meta.dir 是 Bun 专属的。

3. node:url → 优先使用标准 Web API#

URL 类不是 Bun 的发明 —— 它是 Web 标准,浏览器、Node、Deno、Bun、Worker 全都有。

const url = new URL("https://example.com/foo?bar=baz");

console.log(url.pathname);              // "/foo"
console.log(url.searchParams.get("bar")); // "baz"
console.log(url.host);                  // "example.com"
ts

拼接查询字符串时,URLSearchParams 是最顺手的做法:

const params = new URLSearchParams({ page: "2", q: "bun runtime" });
console.log(`https://api.example.com/search?${params}`);
ts

对于非常常见的「把模块 URL 转成磁盘路径」场景,Node 需要一个辅助函数:

Node.js
import { fileURLToPath } from "node:url";

const filename = fileURLToPath(import.meta.url);
ts

在 Bun 里通常连辅助函数都不需要:

Bun
const filename = import.meta.path;
const dirname = import.meta.dir;
ts

fileURLToPath() 在 Bun 中依然可用(通过 node:url),而且当你需要转换的是任意 file:// URL(而不只是 import.meta.url)时,它依然是正确的工具:

const localPath = fileURLToPath(new URL("../config/app.json", import.meta.url));
ts

到底该不该重写?决策树#

node:fs是否: 目录、权限、软链接node:pathnode:url是否: 模块路径你在 Bun 项目里 import 了一个node: 模块是哪个模块?只是读写文件内容吗?使用 Bun.file() 和 Bun.write()继续使用 node:fs继续使用 node:path重写没有任何收益需要 Web 的 URL API 吗?使用 URL 和URLSearchParams使用 import.meta.path 和import.meta.dir

一套不痛的迁移步骤#

  1. 先什么都别做。 把 Dockerfile/CI 里的 node 换成 bun,跑一遍测试。大部分代码原样通过。
  2. 换掉样板代码,而不是换掉逻辑。 把 fs.readFileSync + JSON.parse 换成 await Bun.file(p).json() —— 这是可读性的提升,不是重写。
  3. 把 execSync 字符串换成 Bun.$。 转义和跨平台行为全都免费得到。
  4. 除非你真的想要 Web 的 URL API,否则别动 node:path 和 node:url。
  5. 目录和权限相关的操作继续用 node:fs。 Bun 的 node:fs 很快,也不会消失。

值得记住的坑#

  • Bun.file() 遇到缺失的文件永远不抛错。它是一个承诺,不是一个检查。请用 .exists()。
  • Bun.write() 返回字节数,并且在缺少父目录时会自动创建。
  • Bun.file() 接受路径、文件描述符或 file:// URL:Bun.file(new URL(import.meta.url))。
  • import.meta.path / import.meta.dir 是 Bun 专属的;import.meta.url 才是可移植的那个。
  • node:fs 的同步 API 在 Bun 里照常可用,而且很快。「全都用 async」是一种风格选择,不是硬性要求。
  • 不要用 Bun.file() 处理目录 —— 它只面向文件内容。

TL;DR#

如果你的目标是兼容 Bun,不要重写一切:

node:fs   → 想要 Bun 原生 API 时用 Bun.file / Bun.write
node:path → 保留 node:path
node:url  → 用 URL / URLSearchParams,或者在需要时保留 node:url
text

Bun 的设计目标就是让大量现有 Node.js 代码原封不动地跑起来。在 Bun 原生 API 能让代码更清晰的地方用它们,其余部分保持原样。

参考资料#