Bun

指南HTTP

使用 Bun 將檔案串流為 HTTP 回應

此程式碼片段使用 Bun.file() 從磁碟讀取檔案。這會傳回一個 BunFile 執行個體,它可以直接傳遞給 new Response 建構函式。

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

Content-Type 會從檔案中讀取並自動設定在 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

將其與 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);
  },
});

請參閱 文件 > API > 檔案 I/O 以取得 Bun.write() 的完整文件。