Bun

指南讀取檔案

使用 Bun 讀取檔案至 Uint8Array

Bun.file() 函式接受路徑並傳回 BunFile 執行個體。BunFile 類別延伸 Blob,並允許您以各種格式延遲讀取檔案。

若要將檔案讀取至 Uint8Array 執行個體,請使用 .arrayBuffer()BunFile 的內容作為 ArrayBuffer 擷取,然後傳遞至 Uint8Array 建構函式。

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

const arrBuffer = await file.arrayBuffer();
const byteArray = new Uint8Array(arrBuffer);

byteArray[0]; // first byteArray
byteArray.length; // length of byteArray

參閱 API > 二進制資料 > 型化陣列 以取得更多關於在 Bun 中使用 Uint8Array 和其他二進制資料格式的資訊。