Skip to content

Dieses Snippet liest eine Datei von der Festplatte mit Bun.file(). Dies gibt eine BunFile-Instanz zurück, die direkt in den new Response-Konstruktor übergeben werden kann.

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

Der Content-Type wird aus der Datei gelesen und automatisch auf der Response gesetzt.

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

Alles zusammen mit Bun.serve().

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

Siehe Docs > API > File I/O für vollständige Dokumentation von Bun.write().

Bun von www.bunjs.com.cn bearbeitet