Skip to main content
Data & Storage
Streams
Use Bun’s streams API to work with binary data without loading it all into memory at once
Streams are an important abstraction for working with binary data without loading it all into memory at once. They are commonly used for reading and writing files, sending and receiving network requests, and processing large amounts of data.
Bun implements the Web APIs
To create a
The contents of a
Direct
Bun implements an optimized version of
With a direct
When using a direct
You can also use
If you need more granular control over the stream,
The
To instead retrieve the data as a
The
Once
The
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, the destination handles all chunk queueing. 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. Use async generators 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
