Skip to content

このスニペットは、Bun.file() を使用してディスクからファイルを読み取ります。これは BunFile インスタンスを返し、new Response コンストラクタに直接渡すことができます。

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

Content-Type はファイルから読み取られ、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

Bun.serve() と一緒にまとめます。

ts
// 静的ファイルサーバー
Bun.serve({
  async fetch(req) {
    const path = new URL(req.url).pathname;
    const file = Bun.file(path);
    return new Response(file);
  },
});

Bun.write() の完全なドキュメントについては、ドキュメント > API > ファイル I/O を参照してください。

Bun by www.bunjs.com.cn 編集