ReadableStream
The ReadableStream
type represents a readable stream of data.
Constructing a ReadableStream
The constructor creates a new ReadableStream
object.
It takes two optional arguments:
underlyingsource
: defines the underlying source of data.queuingStrategy
: the queuing strategy to adopt.
import { ReadableStream } from 'k6/experimental/streams';
new ReadableStream(
{
start(controller) {
// Perform any setup tasks
},
pull(controller) {
// Fetch and queue data into the stream
},
cancel(reason) {
// Perform any cleanup tasks
},
type: 'default',
},
{
highWaterMark: 1,
size(chunk) {
return 1;
},
}
);
Constructor arguments
underlyingSource (optional)
The underlyingSource
argument is an object that defines the source of data for the stream. It can be an object with the following properties:
start(controller)
: An optional function that is called when the stream is created. It can be used to perform any setup tasks. The content of this method is to be defined by the user. Thecontroller
parameter passed to this method is a ReadableStreamDefaultController object.pull(controller)
: An optional function that is called repeatedly to fetch and queue data into the stream, until it reaches its high water mark. Ifpull()
returns a promise, it won’t be called again until the promise is resolved. Thecontroller
parameter passed to this method is a ReadableStreamDefaultController object.cancel(reason)
: An optional function, defined by the user, that is called when the stream is canceled. It can be used to release access to the stream source and perform any cleanup tasks. Thereason
parameter passed to this method is an optional human-readable value that represents the reason for canceling the stream.type
: An optional string that specifies the type of the underlying source. It can currently only receive the value'default'
which is its default value.
queuingStrategy argument (optional)
The queuingStrategy
argument is an object that defines the queuing strategy to adopt for the stream. It can be an object with the following properties:
highWaterMark
: An optional number that represents the maximum number of chunks that the stream can hold in its internal queue. The default value is1
.size(chunk)
: An optional function that returns the size of the chunk passed as an argument. The default value is a function that returns1
.
Although you can define your own custom queueing strategy, the default behavior and recommended way to use the ReadableStream
is to use a CountQueuingStrategy object.
Methods
Examples
The simplest illustrative example of using a ReadableStream
is to create a stream of numbers.
A much more useful illustration of defining a ReadableStream
is to read lines from a file.