Skip to content

Este snippet lê um arquivo do disco usando Bun.file(). Isso retorna uma instância BunFile, que pode ser passada diretamente para o construtor new Response.

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

O Content-Type é lido do arquivo e automaticamente definido na 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 tudo com Bun.serve().

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

Veja Docs > API > File I/O para documentação completa de Bun.write().

Bun by www.bunjs.com.cn edit