Skip to main content

Stream a file as an HTTP Response

还没翻译译自英文(bun.com)本页 5 段都还没译

Bun.file() accepts a path and returns a lazily-loaded BunFile instance, which you can pass directly to the new Response constructor.

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

Bun determines the Content-Type from the file extension and sets it on the Response.

new Response(Bun.file("./package.json")).headers.get("Content-Type");
// => application/json;charset=utf-8

new Response(Bun.file("./test.txt")).headers.get("Content-Type");
// => text/plain;charset=utf-8

new Response(Bun.file("./index.tsx")).headers.get("Content-Type");
// => text/javascript;charset=utf-8

new Response(Bun.file("./img.png")).headers.get("Content-Type");
// => image/png

Putting it all together with Bun.serve().

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

See Bun.write().

Traducción © 2026 fanyi.dev · Original © 2026 the Bun project (LICENSE.md names no copyright holder) (MIT)