ReadableStream
and WritableStream
.
Bun also implements the
node:stream
module, including
Readable
,
Writable
, and
Duplex
. For complete
documentation, refer to the Node.js docs.ReadableStream
:
ReadableStream
can be read chunk-by-chunk with for await
syntax.
Direct ReadableStream
Bun implements an optimized version of ReadableStream
that avoid unnecessary data copying & queue management logic.
With a traditional ReadableStream
, chunks of data are enqueued. Each chunk is copied into a queue, where it sits until the stream is ready to send more data.
ReadableStream
, chunks of data are written directly to the stream. No queueing happens, and there’s no need to clone the chunk data into memory. The controller
API is updated to reflect this; instead of .enqueue()
you call .write
.
ReadableStream
, all chunk queueing is handled by the destination. The consumer of the stream receives exactly what is passed to controller.write()
, without any encoding or modification.
Async generator streams
Bun also supports async generator functions as a source forResponse
and Request
. This is an easy way to create a ReadableStream
that fetches data from an asynchronous source.
[Symbol.asyncIterator]
directly.
yield
will return the direct ReadableStream controller.
Bun.ArrayBufferSink
The Bun.ArrayBufferSink
class is a fast incremental writer for constructing an ArrayBuffer
of unknown size.
Uint8Array
, pass the asUint8Array
option to the start
method.
.write()
method supports strings, typed arrays, ArrayBuffer
, and SharedArrayBuffer
.
.end()
is called, no more data can be written to the ArrayBufferSink
. However, in the context of buffering a stream, it’s useful to continuously write data and periodically .flush()
the contents (say, into a WriteableStream
). To support this, pass stream: true
to the constructor.
.flush()
method returns the buffered data as an ArrayBuffer
(or Uint8Array
if asUint8Array: true
) and clears internal buffer.
To manually set the size of the internal buffer in bytes, pass a value for highWaterMark
:
Reference
See Typescript Definitions