Skip to content

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 > 二进制数据

Bun学习网由www.bunjs.com.cn整理维护