Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท File I/O, SQLite and Data

Bun.file and Bun.write: Fast File I/O

Read and write files with Bun.file and Bun.write: lazy BunFile objects, text, json, bytes and streams, incremental writers, directories with node:fs and safe path handling.

Bun supports the whole node:fs API, but it also has two small, fast functions of its own: Bun.file() to read and Bun.write() to write. They follow web standards (a BunFile is a Blob), they take advantage of operating-system shortcuts such as copy-on-write and sendfile, and the code is shorter than the Node equivalent. This lesson covers them and where node:fs is still the right tool.

Bun is not available on the site, so the Bun calls are read-only. The runnable blocks use a small Node fs wrapper with the same method names so you can try the flow. It is a stand-in, not Bun.

Bun.file: a lazy reference

Bun.file(path) does not read anything. It returns a BunFile, a lightweight reference to a path. Work happens when you call a reader.

TypeScript
const file = Bun.file("./notes.txt");

console.log(file.size);   // bytes (a number, read from disk metadata)
console.log(file.type);   // MIME type guessed from the extension: "text/plain;charset=utf-8"
console.log(file.name);   // "./notes.txt"

const text = await file.text();           // string
const bytes = await file.bytes();         // Uint8Array
const buffer = await file.arrayBuffer();  // ArrayBuffer
const stream = file.stream();             // ReadableStream
const data = await Bun.file("./package.json").json(); // parsed JSON

await file.exists() tells you whether the file is there. Reading a missing file rejects with an ENOENT error, so check first or catch it. file.slice(start, end) returns a new BunFile for a byte range, which is perfect for reading the header of a large file without loading the rest:

TypeScript
const header = await Bun.file("./big.log").slice(0, 100).text();

Because BunFile extends Blob, you can hand it to new Response(file), FormData, fetch bodies or new File([...]) directly.

Bun.write: write anything to a path

Bun.write(destination, data) writes and resolves to the number of bytes. The destination is a path string, a URL, a BunFile, or Bun.stdout/Bun.stderr. The data can be a string, Blob, BunFile, ArrayBuffer, typed array or a Response.

TypeScript
await Bun.write("./out/hello.txt", "Hello!\n");                 // string
await Bun.write("./out/data.json", JSON.stringify({ a: 1 }));   // JSON text
await Bun.write("./out/copy.bin", Bun.file("./in/source.bin"));  // copy a file fast
await Bun.write(Bun.stdout, "printed with no console.log\n");   // to the terminal

const res = await fetch("https://example.com/logo.png");
await Bun.write("./out/logo.png", res);                          // download straight to disk

Parent folders are created for you. Existing files are overwritten. Bun.write is the one-line way to save an HTTP download, an upload File, or a generated report, and none of these load an unneeded copy of the data into JavaScript memory. Appending is not an option of Bun.write: use a writer(), below, or node:fs's appendFile.

Incremental writing with file.writer()

When you produce output over time (logs, a big CSV), open a FileSink. It buffers writes and flushes in large blocks.

TypeScript
const out = Bun.file("./out/report.csv").writer();
out.write("id,name\n");
for (let i = 1; i <= 1_000_000; i++) {
  out.write(`${i},user${i}\n`);
}
await out.end(); // flush and close

Call out.flush() to force data to disk at a chosen moment, and out.end() when done. Use a highWaterMark (.writer({ highWaterMark: 1024 * 1024 })) to tune the buffer size.

Standard input and output

Bun.stdin, Bun.stdout and Bun.stderr are BunFiles too:

TypeScript
const input = await Bun.stdin.text();            // everything piped in: echo hi | bun run script.ts
for await (const chunk of Bun.stdin.stream()) {  // or process it in pieces
  process.stdout.write(chunk);
}

For interactive prompts, the global prompt("Name?") and console iteration (for await (const line of console) { ... }) read lines.

Try the flow

This stand-in implements file() and write() over Node's fs in a temporary folder. The method names match Bun's, so the logic carries over.

Node.js A Bun.file / Bun.write style wrapper (Node stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Directories and metadata: use node:fs

Bun deliberately has no Bun.readdir. Directory work uses the standard modules, which Bun implements natively:

TypeScript
import { readdir, mkdir, rm, rename, stat } from "node:fs/promises";
import { join } from "node:path";

await mkdir("./data/cache", { recursive: true });

const entries = await readdir("./data", { withFileTypes: true });
for (const e of entries) {
  console.log(e.isDirectory() ? "dir " : "file", e.name);
}

const info = await stat("./data/cache");
console.log(info.mtime, info.isDirectory());

await rename("./data/old.txt", "./data/new.txt");
await rm("./data/cache", { recursive: true, force: true });

Also handy: Bun.Glob to match patterns, fs.watch for changes and fs.promises.appendFile for appends.

TypeScript
const glob = new Bun.Glob("**/*.ts");
for await (const path of glob.scan({ cwd: "./src" })) {
  console.log(path); // paths relative to ./src
}

Paths that survive any working directory

Relative paths such as "./notes.txt" resolve against the current working directory of the process, which changes depending on where the command is run. To anchor a path to the source file, use the Bun-provided module variables:

TypeScript
import { join } from "node:path";

console.log(import.meta.dir);   // folder of this file
console.log(import.meta.file);  // file name of this module
console.log(import.meta.path);  // full path of this module

const dataFile = Bun.file(join(import.meta.dir, "data", "users.json"));

(__dirname and __filename also work in Bun, even in ES modules.) Use import.meta.main to run code only when the file is the entry point, not when it is imported.

Serving user-chosen files safely

If the file name comes from a request, resolve and check it, so that ../../etc/passwd cannot escape your folder.

Node.js Blocking path traversal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Bun.file('./a.txt') do on its own?

    BunFile is a lazy handle, much like a Blob.
  2. 2. What does Bun.write resolve to?

    It resolves with the byte count, and creates missing parent folders.
  3. 3. How do you append lines to a growing log efficiently?

    Bun.write overwrites. A FileSink buffers many writes; appendFile adds to the end.
  4. 4. Which value gives the folder of the current module regardless of the working directory?

    import.meta.dir is tied to the file; process.cwd() depends on where you launched Bun.

Summary

  • Bun.file(path) is a lazy Blob: .text(), .json(), .bytes(), .stream(), .exists(), .size, .slice().
  • Bun.write(dest, data) writes strings, blobs, files, buffers and Response bodies and returns the byte count; it overwrites and creates parents.
  • file.writer() gives a buffered FileSink for incremental output.
  • Directories, renames and deletes use node:fs; Bun.Glob matches patterns.
  • Anchor paths with import.meta.dir and validate user-supplied names.

Next: SQLite with bun:sqlite