從 Buffer 創建 ReadableStream 的天真方法是使用 ReadableStream 構造函數並將整個數組作為單個塊入隊。對於大型緩沖區,這可能不理想,因為這種方法不會以較小的塊"流式"傳輸數據。
ts
const buf = Buffer.from("hello world");
const stream = new ReadableStream({
start(controller) {
controller.enqueue(buf);
controller.close();
},
});要以較小的塊流式傳輸數據,首先從 Buffer 創建 Blob 實例。然後使用 Blob.stream() 方法創建一個 ReadableStream,以指定的大小分塊流式傳輸數據。
ts
const buf = Buffer.from("hello world");
const blob = new Blob([buf]);
const stream = blob.stream();可以通過向 .stream() 方法傳遞數字來設置塊大小。
ts
const buf = Buffer.from("hello world");
const blob = new Blob([buf]);
// 設置 1024 字節的塊大小
const stream = blob.stream(1024);有關使用 Bun 操作二進制數據的完整文檔,請參閱 文檔 > API > 二進制數據。