Skip to main content
Buffer 创建 ReadableStream 的简单方法是使用 ReadableStream 构造函数并将整个数组作为单个块入队。对于大型缓冲区,这可能是不理想的,因为这种方法不会将数据”流式传输”为较小的块。
const buf = Buffer.from("hello world");
const stream = new ReadableStream({
  start(controller) {
    controller.enqueue(buf);
    controller.close();
  },
});

要将数据以较小的块流式传输,首先从 Buffer 创建一个 Blob 实例。然后使用 Blob.stream() 方法创建一个 ReadableStream,它将数据以指定大小的块进行流式传输。
const buf = Buffer.from("hello world");
const blob = new Blob([buf]);
const stream = blob.stream();

可以通过向 .stream() 方法传递一个数字来设置块大小。
const buf = Buffer.from("hello world");
const blob = new Blob([buf]);

// 设置 1024 字节的块大小
const stream = blob.stream(1024);

参阅 文档 > API > 二进制数据 获取关于使用Bun操作二进制数据的完整文档。