Runtime APIs
Read and write files
Use Bun.file and Bun.write to load and save text or JSON with small Web API-compatible primitives.
9 minute lesson
Bun.file() creates a reference to a file. It does not read the contents immediately.
Create settings.json:
{
"siteName": "Bun Notes",
"itemsPerPage": 20
}
Read it with:
type Settings = {
siteName: string
itemsPerPage: number
}
const file = Bun.file('settings.json')
const settings = await file.json() as Settings
console.log(settings.siteName)
A BunFile follows the Web Blob interface. You can read it as text, JSON, bytes, an array buffer, or a stream.
Check whether a file exists before reading optional data:
const file = Bun.file('settings.json')
if (await file.exists()) {
console.log(await file.text())
}
Write a file
Bun.write() accepts a destination and some data:
const settings = {
siteName: 'Bun Notes',
itemsPerPage: 30,
}
await Bun.write(
'settings.json',
JSON.stringify(settings, null, 2),
)
The returned promise resolves to the number of bytes written.
You can also copy one file into another:
await Bun.write('settings.backup.json', Bun.file('settings.json'))
Use node:fs for directory operations such as mkdir() and readdir(). Bun implements those Node.js APIs, while Bun.file() and Bun.write() cover the common file-content path.
Lesson completed