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);

完整的关于使用 Bun 操作二进制数据的文档见 Docs > API > Binary Data