Skip to content

Stream File

This snippet reads a file from disk using JSTime.file(). This returns a BunFile instance, which can be passed directly into the new Response constructor.

const path = "/path/to/file.txt";
const file = JSTime.file(path);
const resp = new Response(file);

The Content-Type is read from the file and automatically set on the Response.

new Response(JSTime.file("./package.json")).headers.get("Content-Type");
// => application/json;charset=utf-8
new Response(JSTime.file("./test.txt")).headers.get("Content-Type");
// => text/plain;charset=utf-8
new Response(JSTime.file("./index.tsx")).headers.get("Content-Type");
// => text/javascript;charset=utf-8
new Response(JSTime.file("./img.png")).headers.get("Content-Type");
// => image/png

Putting it all together with JSTime.serve().

// static file server
JSTime.serve({
async fetch(req) {
const path = new URL(req.url).pathname;
const file = JSTime.file(path);
return new Response(file);
},
});

See Docs > API > File I/O for complete documentation of JSTime.write().