Skip to content

Este fragmento lee un archivo del disco usando Bun.file(). Esto devuelve una instancia BunFile, que se puede pasar directamente al constructor new Response.

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

El Content-Type se lee del archivo y se establece automáticamente en la Response.

ts
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

Juntando todo con Bun.serve().

ts
// servidor de archivos estáticos
Bun.serve({
  async fetch(req) {
    const path = new URL(req.url).pathname;
    const file = Bun.file(path);
    return new Response(file);
  },
});

Consulta Documentación > API > File I/O para documentación completa de Bun.write().

Bun por www.bunjs.com.cn editar