Bun.file() & Bun.write(): Linux io_uring and Darwin kqueue Syscalls
- Last updated
- Prerequisites:
- Node.js `fs/promises`
- Linux kernel syscalls (`read`, `write`, `io_uring`)
- bun
- file-io
- io_uring
- syscalls
- bun-file
- bun-write
- performance
Read at your depth
The practical view
`Bun.file(path)` creates a lazy `BunFile` reference extending the Web `Blob` standard. It does not read the file until you ask: `await file.text()`, `await file.json()`, `await file.arrayBuffer()`, or `file.stream()`. `Bun.write(destination, data)` writes strings, buffers, `Blob`s, or even pipes one `BunFile` directly into another with maximum speed.
The same idea in other frameworks
`import fs from 'node:fs/promises'; const text = await fs.readFile('file.txt', 'utf8');``const text = await Deno.readTextFile('file.txt');``const text = await Bun.file('file.txt').text();``const blob = new Blob([...]); await blob.text();`Legacy vs modern
Node.js fs.readFile vs Bun.file() Lazy Zero-Copy
Node reads entire buffers into V8 memory; `Bun.file()` creates lazy references and pipes directly to HTTP responses.
const buffer = await fs.readFile(path); res.send(buffer); // ❌ Copies bytes into V8 heapreturn new Response(Bun.file('./large-video.mp4')); // ✅ NEW: Zero-copy kernel sendfileInterview gotchas
Context
Interviewers test your knowledge of lazy evaluation in Bun's file system API.
The mechanical answer
`Bun.file('test.txt')` is completely **lazy and synchronous**: it does *not* touch the disk, open a file descriptor, or read any bytes. It simply creates a lightweight `BunFile` object holding the path. The disk is only accessed when an explicit method like `.text()`, `.arrayBuffer()`, `.stream()`, or `Bun.write()` is called.
Trap
Do not `await Bun.file('test.txt')`; `Bun.file` is not a Promise.
Context
Checks knowledge of OS-level file copy optimizations.
The mechanical answer
When copying a file (`await Bun.write('dest.txt', Bun.file('src.txt'))`), Bun uses OS-level copy-on-write syscalls: **`copy_file_range`** on Linux (or `reflink` on Btrfs/XFS) and **`clonefile`** on macOS APFS. The filesystem creates a copy instantly without reading or writing data bytes through user-space memory.
Trap
Copying files via `Bun.write(dest, Bun.file(src))` is instantaneous on APFS/CoW filesystems because it only copies filesystem metadata.