Bun and File System
×


Bun and File System

108

📁 Introduction to Bun and File System

Working with files is a fundamental part of backend development — from reading configuration files to saving uploaded content. The good news? Bun makes file system operations blazingly fast and developer-friendly. In this blog, you'll learn how to use Bun and File System APIs for reading, writing, and managing files efficiently using its modern JavaScript-based syntax.

🛠️ Using Bun’s Built-in File System API

Bun provides full support for the Node.js fs module, but it also introduces enhancements for better speed. You can use both the synchronous and asynchronous methods provided via fs or Bun's built-ins.

import { readFileSync, writeFileSync } from 'fs';

// Reading a file synchronously
const content = readFileSync('./data.txt', 'utf-8');
console.log(content);

// Writing to a file synchronously
writeFileSync('./output.txt', 'Hello from Bun!');

📄 Reading Files Asynchronously

Bun is built on top of JavaScript promises, making async operations natural and clean:

import { readFile } from 'fs/promises';

const content = await readFile('./data.txt', 'utf-8');
console.log(content);

Using async I/O is preferred in web servers to avoid blocking operations during file access.

📝 Writing Files with Bun

Whether you're saving logs, exporting JSON, or storing uploaded data, Bun’s file write methods are fast and reliable:

import { writeFile } from 'fs/promises';

const data = 'Bun is fast!';
await writeFile('./bun-speed.txt', data);

You can even write JSON:

const user = { name: 'Aditya', role: 'Developer' };
await writeFile('./user.json', JSON.stringify(user, null, 2));

🧹 Checking, Deleting, and Managing Files

Need to check if a file exists or delete it? Bun supports all file system utilities:

import { existsSync, unlinkSync } from 'fs';

if (existsSync('./old-file.txt')) {
  unlinkSync('./old-file.txt');
  console.log('File deleted');
}

📂 Working with Directories

Want to read files from a folder or create a directory? Here’s how:

import { readdirSync, mkdirSync } from 'fs';

mkdirSync('./uploads', { recursive: true });
const files = readdirSync('./uploads');

console.log('Files:', files);

You can also read directory contents asynchronously:

import { readdir } from 'fs/promises';

const files = await readdir('./logs');
console.log(files);

🪄 Bun Specific Enhancements

Bun provides a modern global function: Bun.file(path) which simplifies file access with a nice interface.

const file = Bun.file('./info.txt');
const text = await file.text();
console.log(text);

You can also get the binary buffer or JSON from the file:

const buffer = await file.arrayBuffer();
const jsonData = await Bun.file('./data.json').json();

📦 Real-World Use Case: Serve Static Files

Let’s build a simple static file server using Bun that returns HTML content from the file system:

import { serve } from 'bun';

serve({
  port: 3000,
  async fetch(req) {
    const html = await Bun.file('./index.html').text();
    return new Response(html, {
      headers: { 'Content-Type': 'text/html' }
    });
  }
});

Open http://localhost:3000 in your browser, and it will render your static HTML page served directly via Bun’s FS API.

🚨 Error Handling in File Operations

Always wrap file operations in try/catch to avoid crashing your app:

try {
  const data = await Bun.file('./config.json').json();
  console.log(data);
} catch (err) {
  console.error('Failed to read file:', err);
}

✅ Final Thoughts

Bun offers a fast, flexible, and developer-friendly way to interact with the file system. Whether you're reading config files, storing logs, or serving static content, Bun’s FS capabilities give you speed and simplicity with modern JavaScript syntax.

Now that you've got a solid understanding of how Bun and File System work together, you're ready to build blazing-fast backends with clean file handling. 🚀



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat