How to Use Files in Bun JS

Bun comes with its own modules for handling file read and writes. Let’s whip up a simple server that allows us to see this in action.

Read an HTML File with Bun

Initialise a new server and paste in the following code to your index.ts file:

const server = Bun.serve({
  port: 3000,
  async fetch(req) {
    const url = new URL(req.url);

    if (url.pathname === "/")
      return new Response(Bun.file("index.html"), {
        headers: {
          "Content-Type": "text/html",
        },
      });

    return new Response("404 Not Found", { status: 404 });
  },
});

console.log(`Server running at http://localhost:${server.port}`);

This will read an index.html file off disk and return a bun response to the caller. Let’s create a simple html file in the project root:

<!DOCTYPE <em>html</em>>
<html>
  <head>
    <meta <em>charset</em>="utf-8" />
    <title>Hello World of bun</title>
  </head>
  <body>
    Bun is sooper fast!
  </body>
</html>

Go ahead and run your server with

bun index.ts

If you navigate to localhost:3000 you should see the index.html response returned and rendered.

Bun JS and Json Files

Bun includes support for reading JSON files natively. Create a server.json file in your project root folder and paste in some JSON:

{
  "production": false,
  "version": "0.1alpha"
}

Now in your index.ts file you can log that file anywhere you please:

const serverDeets = Bun.file("server.json")
console.log(await serverDeets.json())

Note that the file API is asynchronous and that you need to call the file type as a function, in this case .json(). From there you can select properties from the file in the usual manner, eg:

console.log((await serverDeets.json()).version)

Be aware that if your file doesn’t exist you will get an error that stops your server. It also outputs that error to the endpoint being requested (including the code surrounding it!).

I’m not sure if that only happens in the development phase but I sure hope it doesn’t happen in production – otherwise that’s a security hole! Imagine if a private key is stored in code and gets output in that error log! (Don’t judge me, we all do it from time to time thinking we can ‘refactor’ later… 😉

Leave a Comment