Readable class

Extends

Stream

Properties

closed

Is true after 'close' has been emitted.

destroyed

Is true after readable.destroy() has been called.

errored

Returns error if the stream has been destroyed with an error.

readable

Is true if it is safe to call read, which means the stream has not been destroyed or emitted 'error' or 'end'.

readableAborted

Returns whether the stream was destroyed or errored before emitting 'end'.

readableDidRead

Returns whether 'data' has been emitted.

readableEncoding

Getter for the property encoding of a given Readable stream. The encoding property can be set using the setEncoding method.

readableEnded

Becomes true when 'end' event is emitted.

readableFlowing

This property reflects the current state of a Readable stream as described in the Three states section.

readableHighWaterMark

Returns the value of highWaterMark passed when creating this Readable.

readableLength

This property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the highWaterMark.

readableObjectMode

Getter for the property objectMode of a given Readable stream.

Methods

addListener(string | symbol, (args: any[]) => void)
addListener<E>(E, (args: ReadableEventMap[E]) => void)
compose(WritableStream | WritableStream<any> | TransformStream<any, any> | (source: any) => void, Abortable)
import { Readable } from 'node:stream';

async function* splitToWords(source) {
  for await (const chunk of source) {
    const words = String(chunk).split(' ');

    for (const word of words) {
      yield word;
    }
  }
}

const wordsStream = Readable.from(['text passed through', 'composed stream']).compose(splitToWords);
const words = await wordsStream.toArray();

console.log(words); // prints ['text', 'passed', 'through', 'composed', 'stream']

readable.compose(s) is equivalent to stream.compose(readable, s).

This method also allows for an AbortSignal to be provided, which will destroy the composed stream when aborted.

See stream.compose(...streams) for more information.

destroy(Error)

Destroy the stream. Optionally emit an 'error' event, and emit a 'close' event (unless emitClose is set to false). After this call, the readable stream will release any internal resources and subsequent calls to push() will be ignored.

Once destroy() has been called any further calls will be a no-op and no further errors except from _destroy() may be emitted as 'error'.

Implementors should not override this method, but instead implement readable._destroy().

drop(number, Abortable)

This method returns a new stream with the first limit chunks dropped from the start.

emit(string | symbol, any[])
emit<E>(E, ReadableEventMap[E])
every((data: any, options?: Abortable) => boolean | Promise<boolean>, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

This method is similar to Array.prototype.every and calls fn on each chunk in the stream to check if all awaited return values are truthy value for fn. Once an fn call on a chunk awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false. If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.

filter((data: any, options?: Abortable) => boolean | Promise<boolean>, ReadableOperatorOptions)

This method allows filtering the stream. For each chunk in the stream the fn function will be called and if it returns a truthy value, the chunk will be passed to the result stream. If the fn function returns a promise - that promise will be awaited.

find((data: any, options?: Abortable) => boolean | Promise<boolean>, Pick<ReadableOperatorOptions, "signal" | "concurrency">)
find<T>((data: any, options?: Abortable) => data, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

This method is similar to Array.prototype.find and calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.

flatMap((data: any, options?: Abortable) => any, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

This method returns a new stream by applying the given callback to each chunk of the stream and then flattening the result.

It is possible to return a stream or another iterable or async iterable from fn and the result streams will be merged (flattened) into the returned stream.

forEach((data: any, options?: Abortable) => void | Promise<void>, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

This method allows iterating a stream. For each chunk in the stream the fn function will be called. If the fn function returns a promise - that promise will be awaited.

This method is different from for await...of loops in that it can optionally process chunks concurrently. In addition, a forEach iteration can only be stopped by having passed a signal option and aborting the related AbortController while for await...of can be stopped with break or return. In either case the stream will be destroyed.

This method is different from listening to the 'data' event in that it uses the readable event in the underlying machinary and can limit the number of concurrent fn calls.

from(Iterable<any> | AsyncIterable<any>, ReadableOptions<Readable>)

A utility method for creating Readable Streams out of iterators.

fromWeb(ReadableStream<any>, Pick<ReadableOptions<Readable>, "encoding" | "highWaterMark" | "objectMode" | "signal">)

A utility method for creating a Readable from a web ReadableStream.

isDisturbed(ReadableStream<any> | ReadableStream)

Returns whether the stream has been read from or cancelled.

isPaused()

The readable.isPaused() method returns the current operating state of the Readable. This is used primarily by the mechanism that underlies the readable.pipe() method. In most typical cases, there will be no reason to use this method directly.

const readable = new stream.Readable();

readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
iterator(ReadableIteratorOptions)

The iterator created by this method gives users the option to cancel the destruction of the stream if the for await...of loop is exited by return, break, or throw, or if the iterator should destroy the stream if the stream emitted an error during iteration.

listenerCount(string | symbol, (args: any[]) => void)
listenerCount<E>(E, (args: ReadableEventMap[E]) => void)
listeners(string | symbol)
listeners<E>(E)
map((data: any, options?: Abortable) => any, ReadableOperatorOptions)

This method allows mapping over the stream. The fn function will be called for every chunk in the stream. If the fn function returns a promise - that promise will be awaited before being passed to the result stream.

off(string | symbol, (args: any[]) => void)
off<E>(E, (args: ReadableEventMap[E]) => void)
on(string | symbol, (args: any[]) => void)
on<E>(E, (args: ReadableEventMap[E]) => void)
once(string | symbol, (args: any[]) => void)
once<E>(E, (args: ReadableEventMap[E]) => void)
pause()

The readable.pause() method will cause a stream in flowing mode to stop emitting 'data' events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.

const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
  console.log(`Received ${chunk.length} bytes of data.`);
  readable.pause();
  console.log('There will be no additional data for 1 second.');
  setTimeout(() => {
    console.log('Now data will start flowing again.');
    readable.resume();
  }, 1000);
});

The readable.pause() method has no effect if there is a 'readable' event listener.

prependListener(string | symbol, (args: any[]) => void)
prependListener<E>(E, (args: ReadableEventMap[E]) => void)
prependOnceListener(string | symbol, (args: any[]) => void)
prependOnceListener<E>(E, (args: ReadableEventMap[E]) => void)
push(any, BufferEncoding)
rawListeners(string | symbol)
rawListeners<E>(E)
read(number)

The readable.read() method reads data out of the internal buffer and returns it. If no data is available to be read, null is returned. By default, the data is returned as a Buffer object unless an encoding has been specified using the readable.setEncoding() method or the stream is operating in object mode.

The optional size argument specifies a specific number of bytes to read. If size bytes are not available to be read, null will be returned unless the stream has ended, in which case all of the data remaining in the internal buffer will be returned.

If the size argument is not specified, all of the data contained in the internal buffer will be returned.

The size argument must be less than or equal to 1 GiB.

The readable.read() method should only be called on Readable streams operating in paused mode. In flowing mode, readable.read() is called automatically until the internal buffer is fully drained.

const readable = getReadableStreamSomehow();

// 'readable' may be triggered multiple times as data is buffered in
readable.on('readable', () => {
  let chunk;
  console.log('Stream is readable (new data received in buffer)');
  // Use a loop to make sure we read all currently available data
  while (null !== (chunk = readable.read())) {
    console.log(`Read ${chunk.length} bytes of data...`);
  }
});

// 'end' will be triggered once when there is no more data available
readable.on('end', () => {
  console.log('Reached end of stream.');
});

Each call to readable.read() returns a chunk of data, or null. The chunks are not concatenated. A while loop is necessary to consume all data currently in the buffer. When reading a large file .read() may return null, having consumed all buffered content so far, but there is still more data to come not yet buffered. In this case a new 'readable' event will be emitted when there is more data in the buffer. Finally the 'end' event will be emitted when there is no more data to come.

Therefore to read a file's whole contents from a readable, it is necessary to collect chunks across multiple 'readable' events:

const chunks = [];

readable.on('readable', () => {
  let chunk;
  while (null !== (chunk = readable.read())) {
    chunks.push(chunk);
  }
});

readable.on('end', () => {
  const content = chunks.join('');
});

A Readable stream in object mode will always return a single item from a call to readable.read(size), regardless of the value of the size argument.

If the readable.read() method returns a chunk of data, a 'data' event will also be emitted.

Calling read after the 'end' event has been emitted will return null. No runtime error will be raised.

reduce<T>((previous: any, data: any, options?: Abortable) => T)

This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.

If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.

The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.

reduce<T>((previous: T, data: any, options?: Abortable) => T, T, Abortable)
removeAllListeners(string | symbol)
removeAllListeners<E>(E)
removeListener(string | symbol, (args: any[]) => void)
removeListener<E>(E, (args: ReadableEventMap[E]) => void)
resume()

The readable.resume() method causes an explicitly paused Readable stream to resume emitting 'data' events, switching the stream into flowing mode.

The readable.resume() method can be used to fully consume the data from a stream without actually processing any of that data:

getReadableStreamSomehow()
  .resume()
  .on('end', () => {
    console.log('Reached the end, but did not read anything.');
  });

The readable.resume() method has no effect if there is a 'readable' event listener.

setEncoding(BufferEncoding)

The readable.setEncoding() method sets the character encoding for data read from the Readable stream.

By default, no encoding is assigned and stream data will be returned as Buffer objects. Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than as Buffer objects. For instance, calling readable.setEncoding('utf8') will cause the output data to be interpreted as UTF-8 data, and passed as strings. Calling readable.setEncoding('hex') will cause the data to be encoded in hexadecimal string format.

The Readable stream will properly handle multi-byte characters delivered through the stream that would otherwise become improperly decoded if simply pulled from the stream as Buffer objects.

const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
  assert.equal(typeof chunk, 'string');
  console.log('Got %d characters of string data:', chunk.length);
});
some((data: any, options?: Abortable) => boolean | Promise<boolean>, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

This method is similar to Array.prototype.some and calls fn on each chunk in the stream until the awaited return value is true (or any truthy value). Once an fn call on a chunk awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true. If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.

take(number, Abortable)

This method returns a new stream with the first limit chunks.

toArray(Abortable)

This method allows easily obtaining the contents of a stream.

As this method reads the entire stream into memory, it negates the benefits of streams. It's intended for interoperability and convenience, not as the primary way to consume streams.

toWeb(ReadableStream, ReadableToWebOptions)

A utility method for creating a web ReadableStream from a Readable.

unpipe(WritableStream)

The readable.unpipe() method detaches a Writable stream previously attached using the pipe method.

If the destination is not specified, then all pipes are detached.

If the destination is specified, but no pipe is set up for it, then the method does nothing.

import fs from 'node:fs';
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second.
readable.pipe(writable);
setTimeout(() => {
  console.log('Stop writing to file.txt.');
  readable.unpipe(writable);
  console.log('Manually close the file stream.');
  writable.end();
}, 1000);
unshift(any, BufferEncoding)

Passing chunk as null signals the end of the stream (EOF) and behaves the same as readable.push(null), after which no more data can be written. The EOF signal is put at the end of the buffer and any buffered data will still be flushed.

The readable.unshift() method pushes a chunk of data back into the internal buffer. This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party.

The stream.unshift(chunk) method cannot be called after the 'end' event has been emitted or a runtime error will be thrown.

Developers using stream.unshift() often should consider switching to use of a Transform stream instead. See the API for stream implementers section for more information.

// Pull off a header delimited by \n\n.
// Use unshift() if we get too much.
// Call the callback with (error, header, stream).
import { StringDecoder } from 'node:string_decoder';
function parseHeader(stream, callback) {
  stream.on('error', callback);
  stream.on('readable', onReadable);
  const decoder = new StringDecoder('utf8');
  let header = '';
  function onReadable() {
    let chunk;
    while (null !== (chunk = stream.read())) {
      const str = decoder.write(chunk);
      if (str.includes('\n\n')) {
        // Found the header boundary.
        const split = str.split(/\n\n/);
        header += split.shift();
        const remaining = split.join('\n\n');
        const buf = Buffer.from(remaining, 'utf8');
        stream.removeListener('error', callback);
        // Remove the 'readable' listener before unshifting.
        stream.removeListener('readable', onReadable);
        if (buf.length)
          stream.unshift(buf);
        // Now the body of the message can be read from the stream.
        callback(null, header, stream);
        return;
      }
      // Still reading the header.
      header += str;
    }
  }
}

Unlike push, stream.unshift(chunk) will not end the reading process by resetting the internal reading state of the stream. This can cause unexpected results if readable.unshift() is called during a read (i.e. from within a _read implementation on a custom stream). Following the call to readable.unshift() with an immediate push will reset the reading state appropriately, however it is best to simply avoid calling readable.unshift() while in the process of performing a read.

wrap(ReadableStream)

Prior to Node.js 0.10, streams did not implement the entire node:stream module API as it is currently defined. (See Compatibility for more information.)

When using an older Node.js library that emits 'data' events and has a pause method that is advisory only, the readable.wrap() method can be used to create a Readable stream that uses the old stream as its data source.

It will rarely be necessary to use readable.wrap() but the method has been provided as a convenience for interacting with older Node.js applications and libraries.

import { OldReader } from './old-api-module.js';
import { Readable } from 'node:stream';
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);

myReader.on('readable', () => {
  myReader.read(); // etc.
});
[asyncIterator]()

Inherited Methods

eventNames()

Returns an array listing the events for which the emitter has registered listeners.

import { EventEmitter } from 'node:events';

const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});

const sym = Symbol('symbol');
myEE.on(sym, () => {});

console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
getMaxListeners()

Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.

pipe<T>(T, PipeOptions)
setMaxListeners(number)

By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.

Returns a reference to the EventEmitter, so that calls can be chained.

[captureRejectionSymbol](Error, string | symbol, any[])

The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection').

import { EventEmitter, captureRejectionSymbol } from 'node:events';

class MyClass extends EventEmitter {
  constructor() {
    super({ captureRejections: true });
  }

  [captureRejectionSymbol](err, event, ...args) {
    console.log('rejection happened for', event, 'with', err, ...args);
    this.destroy(err);
  }

  destroy(err) {
    // Tear the resource down here.
  }
}

Constructor Details

Readable(ReadableOptions<Readable>)

new Readable(options?: ReadableOptions<Readable>)

Parameters

options

ReadableOptions<Readable>

Property Details

closed

Is true after 'close' has been emitted.

closed: boolean

Property Value

boolean

destroyed

Is true after readable.destroy() has been called.

destroyed: boolean

Property Value

boolean

errored

Returns error if the stream has been destroyed with an error.

errored: null | Error

Property Value

null | Error

readable

Is true if it is safe to call read, which means the stream has not been destroyed or emitted 'error' or 'end'.

readable: boolean

Property Value

boolean

readableAborted

Returns whether the stream was destroyed or errored before emitting 'end'.

readableAborted: boolean

Property Value

boolean

readableDidRead

Returns whether 'data' has been emitted.

readableDidRead: boolean

Property Value

boolean

readableEncoding

Getter for the property encoding of a given Readable stream. The encoding property can be set using the setEncoding method.

readableEncoding: null | BufferEncoding

Property Value

null | BufferEncoding

readableEnded

Becomes true when 'end' event is emitted.

readableEnded: boolean

Property Value

boolean

readableFlowing

This property reflects the current state of a Readable stream as described in the Three states section.

readableFlowing: null | boolean

Property Value

null | boolean

readableHighWaterMark

Returns the value of highWaterMark passed when creating this Readable.

readableHighWaterMark: number

Property Value

number

readableLength

This property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the highWaterMark.

readableLength: number

Property Value

number

readableObjectMode

Getter for the property objectMode of a given Readable stream.

readableObjectMode: boolean

Property Value

boolean

Method Details

addListener(string | symbol, (args: any[]) => void)

function addListener(eventName: string | symbol, listener: (args: any[]) => void): Readable

Parameters

eventName

string | symbol

listener

(args: any[]) => void

Returns

addListener<E>(E, (args: ReadableEventMap[E]) => void)

function addListener<E>(eventName: E, listener: (args: ReadableEventMap[E]) => void): Readable

Parameters

eventName

E

listener

(args: ReadableEventMap[E]) => void

Returns

compose(WritableStream | WritableStream<any> | TransformStream<any, any> | (source: any) => void, Abortable)

import { Readable } from 'node:stream';

async function* splitToWords(source) {
  for await (const chunk of source) {
    const words = String(chunk).split(' ');

    for (const word of words) {
      yield word;
    }
  }
}

const wordsStream = Readable.from(['text passed through', 'composed stream']).compose(splitToWords);
const words = await wordsStream.toArray();

console.log(words); // prints ['text', 'passed', 'through', 'composed', 'stream']

readable.compose(s) is equivalent to stream.compose(readable, s).

This method also allows for an AbortSignal to be provided, which will destroy the composed stream when aborted.

See stream.compose(...streams) for more information.

function compose(stream: WritableStream | WritableStream<any> | TransformStream<any, any> | (source: any) => void, options?: Abortable): Duplex

Parameters

stream

WritableStream | WritableStream<any> | TransformStream<any, any> | (source: any) => void

options

Abortable

Returns

Duplex

a stream composed with the stream stream.

destroy(Error)

Destroy the stream. Optionally emit an 'error' event, and emit a 'close' event (unless emitClose is set to false). After this call, the readable stream will release any internal resources and subsequent calls to push() will be ignored.

Once destroy() has been called any further calls will be a no-op and no further errors except from _destroy() may be emitted as 'error'.

Implementors should not override this method, but instead implement readable._destroy().

function destroy(error?: Error): Readable

Parameters

error

Error

Error which will be passed as payload in 'error' event

Returns

drop(number, Abortable)

This method returns a new stream with the first limit chunks dropped from the start.

function drop(limit: number, options?: Abortable): Readable

Parameters

limit

number

the number of chunks to drop from the readable.

options

Abortable

Returns

a stream with limit chunks dropped from the start.

emit(string | symbol, any[])

function emit(eventName: string | symbol, args: any[]): boolean

Parameters

eventName

string | symbol

args

any[]

Returns

boolean

emit<E>(E, ReadableEventMap[E])

function emit<E>(eventName: E, args: ReadableEventMap[E]): boolean

Parameters

eventName

E

args

ReadableEventMap[E]

Returns

boolean

every((data: any, options?: Abortable) => boolean | Promise<boolean>, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

This method is similar to Array.prototype.every and calls fn on each chunk in the stream to check if all awaited return values are truthy value for fn. Once an fn call on a chunk awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false. If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.

function every(fn: (data: any, options?: Abortable) => boolean | Promise<boolean>, options?: Pick<ReadableOperatorOptions, "signal" | "concurrency">): Promise<boolean>

Parameters

fn

(data: any, options?: Abortable) => boolean | Promise<boolean>

a function to call on each chunk of the stream. Async or not.

options

Pick<ReadableOperatorOptions, "signal" | "concurrency">

Returns

Promise<boolean>

a promise evaluating to true if fn returned a truthy value for every one of the chunks.

filter((data: any, options?: Abortable) => boolean | Promise<boolean>, ReadableOperatorOptions)

This method allows filtering the stream. For each chunk in the stream the fn function will be called and if it returns a truthy value, the chunk will be passed to the result stream. If the fn function returns a promise - that promise will be awaited.

function filter(fn: (data: any, options?: Abortable) => boolean | Promise<boolean>, options?: ReadableOperatorOptions): Readable

Parameters

fn

(data: any, options?: Abortable) => boolean | Promise<boolean>

a function to filter chunks from the stream. Async or not.

options

ReadableOperatorOptions

Returns

a stream filtered with the predicate fn.

find((data: any, options?: Abortable) => boolean | Promise<boolean>, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

function find(fn: (data: any, options?: Abortable) => boolean | Promise<boolean>, options?: Pick<ReadableOperatorOptions, "signal" | "concurrency">): Promise<any>

Parameters

fn

(data: any, options?: Abortable) => boolean | Promise<boolean>

options

Pick<ReadableOperatorOptions, "signal" | "concurrency">

Returns

Promise<any>

find<T>((data: any, options?: Abortable) => data, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

This method is similar to Array.prototype.find and calls fn on each chunk in the stream to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value. If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.

function find<T>(fn: (data: any, options?: Abortable) => data, options?: Pick<ReadableOperatorOptions, "signal" | "concurrency">): Promise<undefined | T>

Parameters

fn

(data: any, options?: Abortable) => data

a function to call on each chunk of the stream. Async or not.

options

Pick<ReadableOperatorOptions, "signal" | "concurrency">

Returns

Promise<undefined | T>

a promise evaluating to the first chunk for which fn evaluated with a truthy value, or undefined if no element was found.

flatMap((data: any, options?: Abortable) => any, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

This method returns a new stream by applying the given callback to each chunk of the stream and then flattening the result.

It is possible to return a stream or another iterable or async iterable from fn and the result streams will be merged (flattened) into the returned stream.

function flatMap(fn: (data: any, options?: Abortable) => any, options?: Pick<ReadableOperatorOptions, "signal" | "concurrency">): Readable

Parameters

fn

(data: any, options?: Abortable) => any

a function to map over every chunk in the stream. May be async. May be a stream or generator.

options

Pick<ReadableOperatorOptions, "signal" | "concurrency">

Returns

a stream flat-mapped with the function fn.

forEach((data: any, options?: Abortable) => void | Promise<void>, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

This method allows iterating a stream. For each chunk in the stream the fn function will be called. If the fn function returns a promise - that promise will be awaited.

This method is different from for await...of loops in that it can optionally process chunks concurrently. In addition, a forEach iteration can only be stopped by having passed a signal option and aborting the related AbortController while for await...of can be stopped with break or return. In either case the stream will be destroyed.

This method is different from listening to the 'data' event in that it uses the readable event in the underlying machinary and can limit the number of concurrent fn calls.

function forEach(fn: (data: any, options?: Abortable) => void | Promise<void>, options?: Pick<ReadableOperatorOptions, "signal" | "concurrency">): Promise<void>

Parameters

fn

(data: any, options?: Abortable) => void | Promise<void>

a function to call on each chunk of the stream. Async or not.

options

Pick<ReadableOperatorOptions, "signal" | "concurrency">

Returns

Promise<void>

a promise for when the stream has finished.

from(Iterable<any> | AsyncIterable<any>, ReadableOptions<Readable>)

A utility method for creating Readable Streams out of iterators.

static function from(iterable: Iterable<any> | AsyncIterable<any>, options?: ReadableOptions<Readable>): Readable

Parameters

iterable

Iterable<any> | AsyncIterable<any>

Object implementing the Symbol.asyncIterator or Symbol.iterator iterable protocol. Emits an 'error' event if a null value is passed.

options

ReadableOptions<Readable>

Options provided to new stream.Readable([options]). By default, Readable.from() will set options.objectMode to true, unless this is explicitly opted out by setting options.objectMode to false.

Returns

fromWeb(ReadableStream<any>, Pick<ReadableOptions<Readable>, "encoding" | "highWaterMark" | "objectMode" | "signal">)

A utility method for creating a Readable from a web ReadableStream.

static function fromWeb(readableStream: ReadableStream<any>, options?: Pick<ReadableOptions<Readable>, "encoding" | "highWaterMark" | "objectMode" | "signal">): Readable

Parameters

readableStream

ReadableStream<any>

options

Pick<ReadableOptions<Readable>, "encoding" | "highWaterMark" | "objectMode" | "signal">

Returns

isDisturbed(ReadableStream<any> | ReadableStream)

Returns whether the stream has been read from or cancelled.

static function isDisturbed(stream: ReadableStream<any> | ReadableStream): boolean

Parameters

stream

ReadableStream<any> | ReadableStream

Returns

boolean

isPaused()

The readable.isPaused() method returns the current operating state of the Readable. This is used primarily by the mechanism that underlies the readable.pipe() method. In most typical cases, there will be no reason to use this method directly.

const readable = new stream.Readable();

readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
function isPaused(): boolean

Returns

boolean

iterator(ReadableIteratorOptions)

The iterator created by this method gives users the option to cancel the destruction of the stream if the for await...of loop is exited by return, break, or throw, or if the iterator should destroy the stream if the stream emitted an error during iteration.

function iterator(options?: ReadableIteratorOptions): AsyncIterator<any, undefined, any>

Parameters

options

ReadableIteratorOptions

Returns

AsyncIterator<any, undefined, any>

listenerCount(string | symbol, (args: any[]) => void)

function listenerCount(eventName: string | symbol, listener?: (args: any[]) => void): number

Parameters

eventName

string | symbol

listener

(args: any[]) => void

Returns

number

listenerCount<E>(E, (args: ReadableEventMap[E]) => void)

function listenerCount<E>(eventName: E, listener?: (args: ReadableEventMap[E]) => void): number

Parameters

eventName

E

listener

(args: ReadableEventMap[E]) => void

Returns

number

listeners(string | symbol)

function listeners(eventName: string | symbol): (args: any[]) => void[]

Parameters

eventName

string | symbol

Returns

(args: any[]) => void[]

listeners<E>(E)

function listeners<E>(eventName: E): (args: ReadableEventMap[E]) => void[]

Parameters

eventName

E

Returns

(args: ReadableEventMap[E]) => void[]

map((data: any, options?: Abortable) => any, ReadableOperatorOptions)

This method allows mapping over the stream. The fn function will be called for every chunk in the stream. If the fn function returns a promise - that promise will be awaited before being passed to the result stream.

function map(fn: (data: any, options?: Abortable) => any, options?: ReadableOperatorOptions): Readable

Parameters

fn

(data: any, options?: Abortable) => any

a function to map over every chunk in the stream. Async or not.

options

ReadableOperatorOptions

Returns

a stream mapped with the function fn.

off(string | symbol, (args: any[]) => void)

function off(eventName: string | symbol, listener: (args: any[]) => void): Readable

Parameters

eventName

string | symbol

listener

(args: any[]) => void

Returns

off<E>(E, (args: ReadableEventMap[E]) => void)

function off<E>(eventName: E, listener: (args: ReadableEventMap[E]) => void): Readable

Parameters

eventName

E

listener

(args: ReadableEventMap[E]) => void

Returns

on(string | symbol, (args: any[]) => void)

function on(eventName: string | symbol, listener: (args: any[]) => void): Readable

Parameters

eventName

string | symbol

listener

(args: any[]) => void

Returns

on<E>(E, (args: ReadableEventMap[E]) => void)

function on<E>(eventName: E, listener: (args: ReadableEventMap[E]) => void): Readable

Parameters

eventName

E

listener

(args: ReadableEventMap[E]) => void

Returns

once(string | symbol, (args: any[]) => void)

function once(eventName: string | symbol, listener: (args: any[]) => void): Readable

Parameters

eventName

string | symbol

listener

(args: any[]) => void

Returns

once<E>(E, (args: ReadableEventMap[E]) => void)

function once<E>(eventName: E, listener: (args: ReadableEventMap[E]) => void): Readable

Parameters

eventName

E

listener

(args: ReadableEventMap[E]) => void

Returns

pause()

The readable.pause() method will cause a stream in flowing mode to stop emitting 'data' events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.

const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
  console.log(`Received ${chunk.length} bytes of data.`);
  readable.pause();
  console.log('There will be no additional data for 1 second.');
  setTimeout(() => {
    console.log('Now data will start flowing again.');
    readable.resume();
  }, 1000);
});

The readable.pause() method has no effect if there is a 'readable' event listener.

function pause(): Readable

Returns

prependListener(string | symbol, (args: any[]) => void)

function prependListener(eventName: string | symbol, listener: (args: any[]) => void): Readable

Parameters

eventName

string | symbol

listener

(args: any[]) => void

Returns

prependListener<E>(E, (args: ReadableEventMap[E]) => void)

function prependListener<E>(eventName: E, listener: (args: ReadableEventMap[E]) => void): Readable

Parameters

eventName

E

listener

(args: ReadableEventMap[E]) => void

Returns

prependOnceListener(string | symbol, (args: any[]) => void)

function prependOnceListener(eventName: string | symbol, listener: (args: any[]) => void): Readable

Parameters

eventName

string | symbol

listener

(args: any[]) => void

Returns

prependOnceListener<E>(E, (args: ReadableEventMap[E]) => void)

function prependOnceListener<E>(eventName: E, listener: (args: ReadableEventMap[E]) => void): Readable

Parameters

eventName

E

listener

(args: ReadableEventMap[E]) => void

Returns

push(any, BufferEncoding)

function push(chunk: any, encoding?: BufferEncoding): boolean

Parameters

chunk

any

encoding

BufferEncoding

Returns

boolean

rawListeners(string | symbol)

function rawListeners(eventName: string | symbol): (args: any[]) => void[]

Parameters

eventName

string | symbol

Returns

(args: any[]) => void[]

rawListeners<E>(E)

function rawListeners<E>(eventName: E): (args: ReadableEventMap[E]) => void[]

Parameters

eventName

E

Returns

(args: ReadableEventMap[E]) => void[]

read(number)

The readable.read() method reads data out of the internal buffer and returns it. If no data is available to be read, null is returned. By default, the data is returned as a Buffer object unless an encoding has been specified using the readable.setEncoding() method or the stream is operating in object mode.

The optional size argument specifies a specific number of bytes to read. If size bytes are not available to be read, null will be returned unless the stream has ended, in which case all of the data remaining in the internal buffer will be returned.

If the size argument is not specified, all of the data contained in the internal buffer will be returned.

The size argument must be less than or equal to 1 GiB.

The readable.read() method should only be called on Readable streams operating in paused mode. In flowing mode, readable.read() is called automatically until the internal buffer is fully drained.

const readable = getReadableStreamSomehow();

// 'readable' may be triggered multiple times as data is buffered in
readable.on('readable', () => {
  let chunk;
  console.log('Stream is readable (new data received in buffer)');
  // Use a loop to make sure we read all currently available data
  while (null !== (chunk = readable.read())) {
    console.log(`Read ${chunk.length} bytes of data...`);
  }
});

// 'end' will be triggered once when there is no more data available
readable.on('end', () => {
  console.log('Reached end of stream.');
});

Each call to readable.read() returns a chunk of data, or null. The chunks are not concatenated. A while loop is necessary to consume all data currently in the buffer. When reading a large file .read() may return null, having consumed all buffered content so far, but there is still more data to come not yet buffered. In this case a new 'readable' event will be emitted when there is more data in the buffer. Finally the 'end' event will be emitted when there is no more data to come.

Therefore to read a file's whole contents from a readable, it is necessary to collect chunks across multiple 'readable' events:

const chunks = [];

readable.on('readable', () => {
  let chunk;
  while (null !== (chunk = readable.read())) {
    chunks.push(chunk);
  }
});

readable.on('end', () => {
  const content = chunks.join('');
});

A Readable stream in object mode will always return a single item from a call to readable.read(size), regardless of the value of the size argument.

If the readable.read() method returns a chunk of data, a 'data' event will also be emitted.

Calling read after the 'end' event has been emitted will return null. No runtime error will be raised.

function read(size?: number): any

Parameters

size

number

Optional argument to specify how much data to read.

Returns

any

reduce<T>((previous: any, data: any, options?: Abortable) => T)

This method calls fn on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.

If no initial value is supplied the first chunk of the stream is used as the initial value. If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.

The reducer function iterates the stream element-by-element which means that there is no concurrency parameter or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.

function reduce<T>(fn: (previous: any, data: any, options?: Abortable) => T): Promise<T>

Parameters

fn

(previous: any, data: any, options?: Abortable) => T

a reducer function to call over every chunk in the stream. Async or not.

Returns

Promise<T>

a promise for the final value of the reduction.

reduce<T>((previous: T, data: any, options?: Abortable) => T, T, Abortable)

function reduce<T>(fn: (previous: T, data: any, options?: Abortable) => T, initial: T, options?: Abortable): Promise<T>

Parameters

fn

(previous: T, data: any, options?: Abortable) => T

initial

T

options

Abortable

Returns

Promise<T>

removeAllListeners(string | symbol)

function removeAllListeners(eventName?: string | symbol): Readable

Parameters

eventName

string | symbol

Returns

removeAllListeners<E>(E)

function removeAllListeners<E>(eventName?: E): Readable

Parameters

eventName

E

Returns

removeListener(string | symbol, (args: any[]) => void)

function removeListener(eventName: string | symbol, listener: (args: any[]) => void): Readable

Parameters

eventName

string | symbol

listener

(args: any[]) => void

Returns

removeListener<E>(E, (args: ReadableEventMap[E]) => void)

function removeListener<E>(eventName: E, listener: (args: ReadableEventMap[E]) => void): Readable

Parameters

eventName

E

listener

(args: ReadableEventMap[E]) => void

Returns

resume()

The readable.resume() method causes an explicitly paused Readable stream to resume emitting 'data' events, switching the stream into flowing mode.

The readable.resume() method can be used to fully consume the data from a stream without actually processing any of that data:

getReadableStreamSomehow()
  .resume()
  .on('end', () => {
    console.log('Reached the end, but did not read anything.');
  });

The readable.resume() method has no effect if there is a 'readable' event listener.

function resume(): Readable

Returns

setEncoding(BufferEncoding)

The readable.setEncoding() method sets the character encoding for data read from the Readable stream.

By default, no encoding is assigned and stream data will be returned as Buffer objects. Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than as Buffer objects. For instance, calling readable.setEncoding('utf8') will cause the output data to be interpreted as UTF-8 data, and passed as strings. Calling readable.setEncoding('hex') will cause the data to be encoded in hexadecimal string format.

The Readable stream will properly handle multi-byte characters delivered through the stream that would otherwise become improperly decoded if simply pulled from the stream as Buffer objects.

const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
  assert.equal(typeof chunk, 'string');
  console.log('Got %d characters of string data:', chunk.length);
});
function setEncoding(encoding: BufferEncoding): Readable

Parameters

encoding

BufferEncoding

The encoding to use.

Returns

some((data: any, options?: Abortable) => boolean | Promise<boolean>, Pick<ReadableOperatorOptions, "signal" | "concurrency">)

This method is similar to Array.prototype.some and calls fn on each chunk in the stream until the awaited return value is true (or any truthy value). Once an fn call on a chunk awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true. If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.

function some(fn: (data: any, options?: Abortable) => boolean | Promise<boolean>, options?: Pick<ReadableOperatorOptions, "signal" | "concurrency">): Promise<boolean>

Parameters

fn

(data: any, options?: Abortable) => boolean | Promise<boolean>

a function to call on each chunk of the stream. Async or not.

options

Pick<ReadableOperatorOptions, "signal" | "concurrency">

Returns

Promise<boolean>

a promise evaluating to true if fn returned a truthy value for at least one of the chunks.

take(number, Abortable)

This method returns a new stream with the first limit chunks.

function take(limit: number, options?: Abortable): Readable

Parameters

limit

number

the number of chunks to take from the readable.

options

Abortable

Returns

a stream with limit chunks taken.

toArray(Abortable)

This method allows easily obtaining the contents of a stream.

As this method reads the entire stream into memory, it negates the benefits of streams. It's intended for interoperability and convenience, not as the primary way to consume streams.

function toArray(options?: Abortable): Promise<any[]>

Parameters

options

Abortable

Returns

Promise<any[]>

a promise containing an array with the contents of the stream.

toWeb(ReadableStream, ReadableToWebOptions)

A utility method for creating a web ReadableStream from a Readable.

static function toWeb(streamReadable: ReadableStream, options?: ReadableToWebOptions): ReadableStream<any>

Parameters

streamReadable

ReadableStream

options

ReadableToWebOptions

Returns

ReadableStream<any>

unpipe(WritableStream)

The readable.unpipe() method detaches a Writable stream previously attached using the pipe method.

If the destination is not specified, then all pipes are detached.

If the destination is specified, but no pipe is set up for it, then the method does nothing.

import fs from 'node:fs';
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second.
readable.pipe(writable);
setTimeout(() => {
  console.log('Stop writing to file.txt.');
  readable.unpipe(writable);
  console.log('Manually close the file stream.');
  writable.end();
}, 1000);
function unpipe(destination?: WritableStream): Readable

Parameters

destination

WritableStream

Optional specific stream to unpipe

Returns

unshift(any, BufferEncoding)

Passing chunk as null signals the end of the stream (EOF) and behaves the same as readable.push(null), after which no more data can be written. The EOF signal is put at the end of the buffer and any buffered data will still be flushed.

The readable.unshift() method pushes a chunk of data back into the internal buffer. This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party.

The stream.unshift(chunk) method cannot be called after the 'end' event has been emitted or a runtime error will be thrown.

Developers using stream.unshift() often should consider switching to use of a Transform stream instead. See the API for stream implementers section for more information.

// Pull off a header delimited by \n\n.
// Use unshift() if we get too much.
// Call the callback with (error, header, stream).
import { StringDecoder } from 'node:string_decoder';
function parseHeader(stream, callback) {
  stream.on('error', callback);
  stream.on('readable', onReadable);
  const decoder = new StringDecoder('utf8');
  let header = '';
  function onReadable() {
    let chunk;
    while (null !== (chunk = stream.read())) {
      const str = decoder.write(chunk);
      if (str.includes('\n\n')) {
        // Found the header boundary.
        const split = str.split(/\n\n/);
        header += split.shift();
        const remaining = split.join('\n\n');
        const buf = Buffer.from(remaining, 'utf8');
        stream.removeListener('error', callback);
        // Remove the 'readable' listener before unshifting.
        stream.removeListener('readable', onReadable);
        if (buf.length)
          stream.unshift(buf);
        // Now the body of the message can be read from the stream.
        callback(null, header, stream);
        return;
      }
      // Still reading the header.
      header += str;
    }
  }
}

Unlike push, stream.unshift(chunk) will not end the reading process by resetting the internal reading state of the stream. This can cause unexpected results if readable.unshift() is called during a read (i.e. from within a _read implementation on a custom stream). Following the call to readable.unshift() with an immediate push will reset the reading state appropriately, however it is best to simply avoid calling readable.unshift() while in the process of performing a read.

function unshift(chunk: any, encoding?: BufferEncoding)

Parameters

chunk

any

Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk must be a {string}, {Buffer}, {TypedArray}, {DataView} or null. For object mode streams, chunk may be any JavaScript value.

encoding

BufferEncoding

Encoding of string chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'.

wrap(ReadableStream)

Prior to Node.js 0.10, streams did not implement the entire node:stream module API as it is currently defined. (See Compatibility for more information.)

When using an older Node.js library that emits 'data' events and has a pause method that is advisory only, the readable.wrap() method can be used to create a Readable stream that uses the old stream as its data source.

It will rarely be necessary to use readable.wrap() but the method has been provided as a convenience for interacting with older Node.js applications and libraries.

import { OldReader } from './old-api-module.js';
import { Readable } from 'node:stream';
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);

myReader.on('readable', () => {
  myReader.read(); // etc.
});
function wrap(stream: ReadableStream): Readable

Parameters

stream

ReadableStream

An "old style" readable stream

Returns

[asyncIterator]()

function [asyncIterator](): AsyncIterator<any, undefined, any>

Returns

AsyncIterator<any, undefined, any>

AsyncIterator to fully consume the stream.

Inherited Method Details

eventNames()

Returns an array listing the events for which the emitter has registered listeners.

import { EventEmitter } from 'node:events';

const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});

const sym = Symbol('symbol');
myEE.on(sym, () => {});

console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
function eventNames(): (string | symbol)[]

Returns

(string | symbol)[]

Inherited From Stream.eventNames

getMaxListeners()

Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners.

function getMaxListeners(): number

Returns

number

Inherited From Stream.getMaxListeners

pipe<T>(T, PipeOptions)

function pipe<T>(destination: T, options?: PipeOptions): T

Parameters

destination

T

options

PipeOptions

Returns

T

Inherited From Stream.pipe

setMaxListeners(number)

By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0) to indicate an unlimited number of listeners.

Returns a reference to the EventEmitter, so that calls can be chained.

function setMaxListeners(n: number): Readable

Parameters

n

number

Returns

Inherited From Stream.setMaxListeners

[captureRejectionSymbol](Error, string | symbol, any[])

The Symbol.for('nodejs.rejection') method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for('nodejs.rejection').

import { EventEmitter, captureRejectionSymbol } from 'node:events';

class MyClass extends EventEmitter {
  constructor() {
    super({ captureRejections: true });
  }

  [captureRejectionSymbol](err, event, ...args) {
    console.log('rejection happened for', event, 'with', err, ...args);
    this.destroy(err);
  }

  destroy(err) {
    // Tear the resource down here.
  }
}
function [captureRejectionSymbol](error: Error, event: string | symbol, args: any[])

Parameters

error

Error

event

string | symbol

args

any[]

Inherited From Stream.__@captureRejectionSymbol@175