Stability: 2 - Stable (No longer experimental since v21.0.0)
Overview
The WHATWG Streams Standard (or “web streams”) defines an API for handling streaming data. It is similar to the Node.js Streams API but emerged later and has become the “standard” API for streaming data across many JavaScript environments. There are three primary types of objects:ReadableStream- Represents a source of streaming dataWritableStream- Represents a destination for streaming dataTransformStream- Represents an algorithm for transforming streaming data
Example: ReadableStream
This example creates a simpleReadableStream that pushes the current performance.now() timestamp once every second:
Node.js Streams Interoperability
Node.js streams can be converted to web streams and vice versa via thetoWeb and fromWeb methods:
stream.Readable.toWeb()- Convert Node.js Readable to ReadableStreamstream.Readable.fromWeb()- Convert ReadableStream to Node.js Readablestream.Writable.toWeb()- Convert Node.js Writable to WritableStreamstream.Writable.fromWeb()- Convert WritableStream to Node.js Writablestream.Duplex.toWeb()- Convert Node.js Duplex to web streamsstream.Duplex.fromWeb()- Convert web streams to Node.js Duplex
ReadableStream
new ReadableStream([underlyingSource [, strategy]])
Creates a new ReadableStream instance. Parameters:underlyingSource(Object) - Optional configurationstart(Function) - Invoked immediately when the ReadableStream is createdpull(Function) - Called repeatedly when the internal queue is not fullcancel(Function) - Called when the ReadableStream is canceledtype(string) - Must be'bytes'orundefinedautoAllocateChunkSize(number) - Used whentypeis'bytes'
strategy(Object) - Optional queuing strategyhighWaterMark(number) - Maximum internal queue sizesize(Function) - Function to identify chunk size
Properties
readableStream.locked
Set totrue if there is an active reader for this ReadableStream.
Type: boolean
Methods
readableStream.cancel([reason])
Cancels the stream. Parameters:reason(any) - Optional cancellation reason
undefined
readableStream.getReader([options])
Creates and returns a reader for consuming the stream’s data. Parameters:options(Object)mode(string) -'byob'orundefined
readableStream.pipeThrough(transform[, options])
Connects this ReadableStream to a transform stream, returning the readable side. Parameters:transform(Object)readable(ReadableStream)writable(WritableStream)
options(Object)preventAbort(boolean)preventCancel(boolean)preventClose(boolean)signal(AbortSignal)
transform.readable
readableStream.pipeTo(destination[, options])
Pipes this ReadableStream to a WritableStream. Parameters:destination(WritableStream)options(Object)preventAbort(boolean)preventCancel(boolean)preventClose(boolean)signal(AbortSignal)
undefined
readableStream.tee()
Returns a pair of new ReadableStream instances to which this ReadableStream’s data will be forwarded. Returns: Array of two ReadableStream instancesreadableStream.values([options])
Creates and returns an async iterator for consuming the stream’s data. Parameters:options(Object)preventCancel(boolean) - Prevents closing the stream when iterator terminates
Static Methods
ReadableStream.from(iterable)
Creates a new ReadableStream from an iterable. Parameters:iterable(Iterable) - Object implementingSymbol.asyncIteratororSymbol.iterator
WritableStream
TheWritableStream is a destination to which stream data is sent.
new WritableStream([underlyingSink[, strategy]])
Creates a new WritableStream instance. Parameters:underlyingSink(Object)start(Function) - Invoked when WritableStream is createdwrite(Function) - Invoked when a chunk is writtenclose(Function) - Called when the stream is closedabort(Function) - Called to abruptly close the stream
strategy(Object)highWaterMark(number) - Maximum internal queue sizesize(Function) - Function to identify chunk size
Properties
writableStream.locked
Set totrue while there is an active writer attached to this WritableStream.
Type: boolean
Methods
writableStream.abort([reason])
Abruptly terminates the WritableStream. All queued writes will be canceled. Parameters:reason(any)
undefined
writableStream.close()
Closes the WritableStream when no additional writes are expected. Returns: Promise fulfilled withundefined
writableStream.getWriter()
Creates and returns a new writer instance. Returns: WritableStreamDefaultWriterTransformStream
ATransformStream consists of a ReadableStream and a WritableStream that are connected such that data written to the WritableStream is received, and potentially transformed, before being pushed to the ReadableStream.
new TransformStream([transformer[, writableStrategy[, readableStrategy]]])
Creates a new TransformStream instance. Parameters:transformer(Object)start(Function) - Invoked when TransformStream is createdtransform(Function) - Receives and modifies chunksflush(Function) - Called before writable side closes
writableStrategy(Object) - Queuing strategy for writable sidereadableStrategy(Object) - Queuing strategy for readable side
Properties
transformStream.readable
The readable side of the transform stream. Type: ReadableStreamtransformStream.writable
The writable side of the transform stream. Type: WritableStreamReaders
ReadableStreamDefaultReader
The default reader treats chunks of data as opaque values.new ReadableStreamDefaultReader(stream)
Creates a new reader locked to the given ReadableStream. Parameters:stream(ReadableStream)
Methods
readableStreamDefaultReader.read()
Requests the next chunk of data. Returns: Promise fulfilled with{value, done}
readableStreamDefaultReader.cancel([reason])
Cancels the ReadableStream. Returns: Promise fulfilled withundefined
readableStreamDefaultReader.releaseLock()
Releases the reader’s lock on the ReadableStream.ReadableStreamBYOBReader
An alternative consumer for byte-oriented ReadableStreams using the “bring your own buffer” pattern for more efficient reading.new ReadableStreamBYOBReader(stream)
Creates a new BYOB reader locked to the given ReadableStream. Parameters:stream(ReadableStream) - Must be created withtype: 'bytes'
readableStreamBYOBReader.read(view[, options])
Reads data into the provided buffer. Parameters:view(Buffer|TypedArray|DataView) - The buffer to read intooptions(Object)min(number) - Minimum number of elements required
{value, done}
Controllers
ReadableStreamDefaultController
Controls a non-byte-oriented ReadableStream.Methods
readableStreamDefaultController.close()
Closes the ReadableStream.readableStreamDefaultController.enqueue([chunk])
Appends a new chunk of data to the queue. Parameters:chunk(any)
readableStreamDefaultController.error([error])
Signals an error that causes the stream to error and close. Parameters:error(any)
Properties
readableStreamDefaultController.desiredSize
Returns the amount of data remaining to fill the queue. Type: numberReadableByteStreamController
Controls a byte-oriented ReadableStream.Properties
readableByteStreamController.byobRequest
Provides access to the current BYOB read request. Type: ReadableStreamBYOBRequestreadableByteStreamController.desiredSize
Amount of data remaining to fill the queue. Type: numberMethods
readableByteStreamController.close()
Closes the ReadableStream.readableByteStreamController.enqueue(chunk)
Appends a new chunk to the queue. Parameters:chunk(Buffer|TypedArray|DataView)
readableByteStreamController.error([error])
Signals an error. Parameters:error(any)
WritableStreamDefaultController
Manages the WritableStream’s internal state.Methods
writableStreamDefaultController.error([error])
Signals an error to abort the stream. Parameters:error(any)
Properties
writableStreamDefaultController.signal
An AbortSignal that can be used to cancel pending operations. Type: AbortSignalTransformStreamDefaultController
Manages the internal state of the TransformStream.Properties
transformStreamDefaultController.desiredSize
Amount of data required to fill the readable side’s queue. Type: numberMethods
transformStreamDefaultController.enqueue([chunk])
Appends a chunk to the readable side’s queue. Parameters:chunk(any)
transformStreamDefaultController.error([reason])
Signals an error to both sides. Parameters:reason(any)
transformStreamDefaultController.terminate()
Closes the readable side and abruptly closes the writable side.Queuing Strategies
ByteLengthQueuingStrategy
Provides a built-in byte length queuing strategy.new ByteLengthQueuingStrategy(init)
Parameters:init(Object)highWaterMark(number)
CountQueuingStrategy
Provides a built-in chunk counting queuing strategy.new CountQueuingStrategy(init)
Parameters:init(Object)highWaterMark(number)
Encoding Streams
TextEncoderStream
A TransformStream that encodes strings into UTF-8 bytes.new TextEncoderStream()
Creates a new TextEncoderStream instance.Properties
textEncoderStream.encoding
The encoding supported (always'utf-8').
Type: string
textEncoderStream.readable
Type: ReadableStreamtextEncoderStream.writable
Type: WritableStreamTextDecoderStream
A TransformStream that decodes bytes into strings.new TextDecoderStream([encoding[, options]])
Parameters:encoding(string) - Default:'utf-8'options(Object)fatal(boolean) - If decoding failures are fatalignoreBOM(boolean) - Whether to include byte order mark
Properties
textDecoderStream.encoding
The encoding being used. Type: stringtextDecoderStream.fatal
Type: booleantextDecoderStream.ignoreBOM
Type: booleantextDecoderStream.readable
Type: ReadableStreamtextDecoderStream.writable
Type: WritableStreamCompression Streams
CompressionStream
A TransformStream that compresses data.new CompressionStream(format)
Parameters:format(string) - One of'deflate','deflate-raw','gzip', or'brotli'
Properties
compressionStream.readable
Type: ReadableStreamcompressionStream.writable
Type: WritableStreamDecompressionStream
A TransformStream that decompresses data.new DecompressionStream(format)
Parameters:format(string) - One of'deflate','deflate-raw','gzip', or'brotli'
Properties
decompressionStream.readable
Type: ReadableStreamdecompressionStream.writable
Type: WritableStreamUtility Consumers
Utility functions for consuming streams, available fromnode:stream/consumers.
streamConsumers.arrayBuffer(stream)
Consumes the entire stream into an ArrayBuffer. Parameters:stream(ReadableStream|stream.Readable|AsyncIterator)
streamConsumers.blob(stream)
Consumes the entire stream into a Blob. Parameters:stream(ReadableStream|stream.Readable|AsyncIterator)
streamConsumers.buffer(stream)
Consumes the entire stream into a Buffer. Parameters:stream(ReadableStream|stream.Readable|AsyncIterator)
streamConsumers.bytes(stream)
Consumes the entire stream into a Uint8Array. Parameters:stream(ReadableStream|stream.Readable|AsyncIterator)
streamConsumers.json(stream)
Consumes the stream and parses it as JSON. Parameters:stream(ReadableStream|stream.Readable|AsyncIterator)
streamConsumers.text(stream)
Consumes the stream as UTF-8 encoded text. Parameters:stream(ReadableStream|stream.Readable|AsyncIterator)