Skip to content

Uint8Array 創建 ReadableStream 的天真方法是使用 ReadableStream 構造函數並將整個數組作為單個塊入隊。對於較大的塊,這可能不理想,因為它實際上並沒有"流式"傳輸數據。

ts
const arr = new Uint8Array(64);
const stream = new ReadableStream({
  start(controller) {
    controller.enqueue(arr);
    controller.close();
  },
});

要以較小的塊流式傳輸數據,首先從 Uint8Array 創建 Blob 實例。然後使用 Blob.stream() 方法創建一個 ReadableStream,以指定的大小分塊流式傳輸數據。

ts
const arr = new Uint8Array(64);
const blob = new Blob([arr]);
const stream = blob.stream();

可以通過向 .stream() 方法傳遞數字來設置塊大小。

ts
const arr = new Uint8Array(64);
const blob = new Blob([arr]);

// 設置 1024 字節的塊大小
const stream = blob.stream(1024);

有關使用 Bun 操作二進制數據的完整文檔,請參閱 文檔 > API > 二進制數據

Bun學習網由www.bunjs.com.cn整理維護