執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

讀取檔案到 ArrayBuffer

Bun.file() 函式接受一個路徑並傳回一個 BunFile 例項。BunFile 擴充套件了 Blob,因此你可以以各種格式延遲讀取檔案。使用 .arrayBuffer() 將檔案讀取為 ArrayBuffer。

index.ts
const path = "/path/to/package.json";
const file = Bun.file(path);

const buffer = await file.arrayBuffer();

使用型別化陣列(例如 Int8Array)讀取 ArrayBuffer 的二進位制內容。對於 Uint8Array,請使用 .bytes()。

index.ts
const buffer = await file.arrayBuffer();
const bytes = new Int8Array(buffer);

bytes[0];
bytes.length;

有關在 Bun 中使用型別化陣列的更多資訊,請參閱型別化陣列。