Bun-native Alternatives to node:fs, node:path, node:url
A practical map from node:fs, node:path and node:url to Bun-native APIs like Bun.file(), Bun.write() and Bun.$ — plus when to just keep Node.
You have a Node.js codebase. It works. Your team wants to try Bun because startup is faster, the test runner is built in, and installing dependencies takes seconds instead of minutes.
Then you open the first file and see this everywhere:
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");tsThe question pops up immediately: “Do I have to rewrite all of this?”
The short answer is no — and that is the most important thing to understand about Bun’s design. Bun is not a different planet. It is the same planet with a bigger toolbox.
The 10-second answer#
| Node.js | Bun alternative | Should you rewrite? |
|---|---|---|
node:fs | Bun.file(), Bun.write(), Bun.$ | Only for simple read/write of file contents |
node:path | path / node:path | No — keep it as-is |
node:url | URL, URLSearchParams (Web APIs) | Only when you actually want the Web API |
node:child_process | Bun.$, Bun.spawn | Optional, nice win for shell commands |
The mental model: a bigger toolbox, not a different toolbox#
Here is the analogy that makes this whole topic easy.
Imagine a carpenter’s workshop. Node.js gives you a tool belt with a hammer, a saw, and a screwdriver. Bun shows up and says: “Here is a better hammer, a power saw, and a laser level — and by the way, I still support the old hammer perfectly well.”
A new tool does not mean you must replace the old one. It means you now have a choice, and you should use the new tool when it genuinely makes your code simpler.
Bun’s compatibility layer is deliberately deep. node:fs, node:path, node:url, node:http and hundreds of other modules run on Bun with the same semantics as Node. That is the whole point: most existing Node code runs unchanged.
[!TIP] Treat Bun-native APIs as an upgrade path, not a migration requirement. You can adopt them one file at a time, whenever it makes the code better.
1. node:fs → Bun.file() and Bun.write()#
The basic swap#
// Node
import fs from "node:fs";
const text = fs.readFileSync("file.txt", "utf8");
fs.writeFileSync("file.txt", "hello");ts// Bun
const text = await Bun.file("file.txt").text();
await Bun.write("file.txt", "hello");tsThat is the whole idea: Bun.file(path) gives you a file handle (technically a BunFile, which implements the standard Blob interface), and Bun.write(destination, data) writes anything to disk.
Checking existence#
const exists = await Bun.file("file.txt").exists();tsThis is much nicer than the Node dance of try { fs.accessSync(p) } catch { false }.
[!WARNING]
Bun.file()is lazy — creating the handle never touches the disk and never throws, even if the file does not exist. A missing file reportssize === 0andtype === "text/plain;charset=utf-8". The error only appears when you actually read it (ENOENT: no such file or directory). So use.exists()when you care about presence, and do not treatBun.file()as a validation step.
Reading JSON#
const data = await Bun.file("config.json").json();tsNo JSON.parse(fs.readFileSync(...)) ceremony. .json() parses it for you.
Everything else a BunFile can do#
const file = Bun.file("data.bin");
await file.text(); // string
await file.json(); // parsed JSON
await file.arrayBuffer(); // ArrayBuffer
await file.bytes(); // Uint8Array
file.stream(); // ReadableStream
await file.exists(); // boolean
await file.delete(); // remove the filetsBecause a BunFile is a Blob, it can go straight into fetch, Response, or any API that accepts binary data.
Writing#
Bun.write() is a multi-tool. The destination can be a path, a file:// URL, or a BunFile; the payload can be a string, a Blob, an ArrayBuffer, a typed array, or even a Response body.
await Bun.write("output.txt", "plain text");
await Bun.write("output.txt", new Uint8Array([1, 2, 3]));
// Copy a file — Bun picks the fastest syscall for the platform
await Bun.write(Bun.file("copy.txt"), Bun.file("input.txt"));
// Download straight to disk
const response = await fetch("https://bun.com");
await Bun.write("index.html", response);
// Pipe a file to stdout
await Bun.write(Bun.stdout, Bun.file("input.txt"));tsBun.write() resolves with the number of bytes written, which is handy for logging:
const bytes = await Bun.write("output.txt", "hello");
console.log(`wrote ${bytes} bytes`); // wrote 5 bytestsIncremental writes with FileSink#
When a file is too big to hold in memory, use the 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(); // flush + closets[!NOTE] One behavioural difference worth knowing:
Bun.write()creates missing parent directories automatically, while Node’sfs.writeFileSync()throwsENOENTif the directory does not exist. Verified on Bun 1.4.3 —Bun.write("a/b/c.txt", "x")succeeds and createsa/b/for you.
What node:fs still owns#
Bun.file() covers file contents. It does not cover the filesystem. For these, keep node:fs — Bun’s implementation of it is fast:
import { mkdir, readdir, stat } from "node:fs/promises";
// Create a directory tree
await mkdir("build/output", { recursive: true });
// List files
const entries = await readdir(import.meta.dir, { recursive: true });
// Metadata
const info = await stat("package.json");
console.log(info.size, info.mtime);tsBun’s own documentation says it plainly: for operations they don’t cover, such as mkdir or readdir, use Bun’s nearly complete implementation of the node:fs module.
And the shell escape hatch: Bun.$#
Reading and writing files is not the only I/O your code does. Sometimes you want to run a command:
// Node
import { execSync } from "node:child_process";
execSync("git rev-parse HEAD");ts// Bun
import { $ } from "bun";
const hash = await $`git rev-parse HEAD`.text();tsBun.$ is a cross-platform, bash-like shell implemented in Rust. It is not a wrapper around /bin/sh — it is a re-implementation that runs inside the Bun process, which means it behaves the same on Windows, macOS and Linux.
await $`ls -la`.quiet(); // no output
await $`echo "hi"`.text(); // "hi\n"
await $`cat package.json`.json(); // parsed JSON
for await (const line of $`cat list.txt`.lines()) { /* ... */ }tsAnd a security detail that matters: interpolated values are escaped by default, so user input cannot break out of the command.
const userInput = "my-file.txt; rm -rf /";
await $`ls ${userInput}`; // ls receives ONE literal argument, not two commandstsFor full process control (stdin/stdout piping, env vars, exit codes), use 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);ts2. node:path → just keep it#
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);tsThere is no advantage to replacing node:path in Bun:
- It is pure string logic — no I/O, no runtime magic.
- It is platform-aware (Windows separators, drive letters, UNC paths).
- Bun implements it completely and passes Node’s own test suite for it.
- Replacing it with manual string concatenation would be a downgrade, not an upgrade.
The one Bun-specific convenience is knowing where this file lives:
import.meta.dir; // "/a/b" — absolute path of this file's directory
import.meta.path; // "/a/b/c.ts" — absolute path of this filetsCompare that with process.cwd(), which is where the command was run — not where the code lives. import.meta.dir is the Bun answer to the classic “how do I find a file next to my module?” problem.
[!NOTE] Node.js caught up: since Node 20.11 / 21.2,
import.meta.dirnameandimport.meta.filenameare standard too. So if you want code that runs on both runtimes,import.meta.dirnameis the portable spelling andimport.meta.diris the Bun-only one.
3. node:url → prefer the standard Web APIs#
The URL class is not a Bun invention — it is a Web standard, available in browsers, Node, Deno, Bun, workers, everything.
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"tsURLSearchParams is the ergonomic way to build query strings:
const params = new URLSearchParams({ page: "2", q: "bun runtime" });
console.log(`https://api.example.com/search?${params}`);tsFor the very common “turn my module URL into a filesystem path” case, Node needs a helper:
import { fileURLToPath } from "node:url";
const filename = fileURLToPath(import.meta.url);tsIn Bun you usually do not need the helper at all:
const filename = import.meta.path;
const dirname = import.meta.dir;tsfileURLToPath() still works in Bun (via node:url) and is still the right tool when you are converting an arbitrary file:// URL, not just import.meta.url:
const localPath = fileURLToPath(new URL("../config/app.json", import.meta.url));tsShould you rewrite? A decision tree#
A migration recipe that does not hurt#
- Do nothing first. Change
nodetobunin your Dockerfile/CI and run the test suite. Most code passes untouched. - Replace the boilerplate, not the logic. Swap
fs.readFileSync+JSON.parseforawait Bun.file(p).json(); that is a readability win, not a rewrite. - Introduce
Bun.$for shell-outs that are currentlyexecSyncstrings — you get escaping and cross-platform behaviour for free. - Leave
node:pathandnode:urlalone unless you specifically want the WebURLAPI. - Keep
node:fsfor directory and permission work — Bun’snode:fsis fast, and it will not go away.
Gotchas worth remembering#
Bun.file()never throws on a missing file. It is a promise, not a check. Use.exists().Bun.write()returns the byte count, and it creates parent directories for you.Bun.file()works with a path, a file descriptor, or afile://URL:Bun.file(new URL(import.meta.url)).import.meta.path/import.meta.dirare Bun-only;import.meta.urlis the portable one.node:fssynchronous APIs still work in Bun. They are fast. “Async everywhere” is a style choice, not a requirement.- Do not use
Bun.file()for directories — it is for file contents only.
TL;DR#
If your goal is Bun compatibility, do not rewrite everything:
node:fs → Bun.file / Bun.write when you want Bun-native APIs
node:path → keep node:path
node:url → URL / URLSearchParams, or keep node:url where neededtextBun is designed to run a lot of existing Node.js code unchanged. Use the Bun-native APIs where they make the code clearer, and leave the rest alone.
References#
- Bun Documentation — File I/O ↗
- Bun Documentation — Shell ↗
- Bun Documentation — Node.js Compatibility ↗
- Bun Documentation —
import.meta.dir↗ - Bun API Reference —
Bun.write()↗ - Node.js Documentation —
node:path↗ - Node.js Documentation —
node:url↗ - Node.js Documentation —
import.meta.dirname↗ - MDN —
URL↗