{ "type": "module", "source": "doc/api/stream.md", "modules": [ { "textRaw": "Stream", "name": "stream", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "

A stream is an abstract interface for working with streaming data in Node.js.\nThe stream module provides a base API that makes it easy to build objects\nthat implement the stream interface.

\n

There are many stream objects provided by Node.js. For instance, a\nrequest to an HTTP server and process.stdout\nare both stream instances.

\n

Streams can be readable, writable, or both. All streams are instances of\nEventEmitter.

\n

The stream module can be accessed using:

\n
const stream = require('stream');\n
\n

While it is important to understand how streams work, the stream module itself\nis most useful for developers that are creating new types of stream instances.\nDevelopers who are primarily consuming stream objects will rarely need to use\nthe stream module directly.

", "modules": [ { "textRaw": "Organization of this Document", "name": "organization_of_this_document", "desc": "

This document is divided into two primary sections with a third section for\nadditional notes. The first section explains the elements of the stream API that\nare required to use streams within an application. The second section explains\nthe elements of the API that are required to implement new types of streams.

", "type": "module", "displayName": "Organization of this Document" }, { "textRaw": "Types of Streams", "name": "types_of_streams", "desc": "

There are four fundamental stream types within Node.js:

\n\n

Additionally, this module includes the utility functions pipeline,\nfinished and Readable.from.

", "modules": [ { "textRaw": "Object Mode", "name": "object_mode", "desc": "

All streams created by Node.js APIs operate exclusively on strings and Buffer\n(or Uint8Array) objects. It is possible, however, for stream implementations\nto work with other types of JavaScript values (with the exception of null,\nwhich serves a special purpose within streams). Such streams are considered to\noperate in \"object mode\".

\n

Stream instances are switched into object mode using the objectMode option\nwhen the stream is created. Attempting to switch an existing stream into\nobject mode is not safe.

", "type": "module", "displayName": "Object Mode" } ], "miscs": [ { "textRaw": "Buffering", "name": "Buffering", "type": "misc", "desc": "

Both Writable and Readable streams will store data in an internal\nbuffer that can be retrieved using writable.writableBuffer or\nreadable.readableBuffer, respectively.

\n

The amount of data potentially buffered depends on the highWaterMark option\npassed into the stream's constructor. For normal streams, the highWaterMark\noption specifies a total number of bytes. For streams operating\nin object mode, the highWaterMark specifies a total number of objects.

\n

Data is buffered in Readable streams when the implementation calls\nstream.push(chunk). If the consumer of the Stream does not\ncall stream.read(), the data will sit in the internal\nqueue until it is consumed.

\n

Once the total size of the internal read buffer reaches the threshold specified\nby highWaterMark, the stream will temporarily stop reading data from the\nunderlying resource until the data currently buffered can be consumed (that is,\nthe stream will stop calling the internal readable._read() method that is\nused to fill the read buffer).

\n

Data is buffered in Writable streams when the\nwritable.write(chunk) method is called repeatedly. While the\ntotal size of the internal write buffer is below the threshold set by\nhighWaterMark, calls to writable.write() will return true. Once\nthe size of the internal buffer reaches or exceeds the highWaterMark, false\nwill be returned.

\n

A key goal of the stream API, particularly the stream.pipe() method,\nis to limit the buffering of data to acceptable levels such that sources and\ndestinations of differing speeds will not overwhelm the available memory.

\n

Because Duplex and Transform streams are both Readable and\nWritable, each maintains two separate internal buffers used for reading and\nwriting, allowing each side to operate independently of the other while\nmaintaining an appropriate and efficient flow of data. For example,\nnet.Socket instances are Duplex streams whose Readable side allows\nconsumption of data received from the socket and whose Writable side allows\nwriting data to the socket. Because data may be written to the socket at a\nfaster or slower rate than data is received, it is important for each side to\noperate (and buffer) independently of the other.

" } ], "type": "module", "displayName": "Types of Streams" } ], "methods": [ { "textRaw": "stream.finished(stream, callback)", "type": "method", "name": "finished", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stream` {Stream} A readable and/or writable stream.", "name": "stream", "type": "Stream", "desc": "A readable and/or writable stream." }, { "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", "name": "callback", "type": "Function", "desc": "A callback function that takes an optional error argument." } ] } ], "desc": "

A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.

\n
const { finished } = require('stream');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n  if (err) {\n    console.error('Stream failed.', err);\n  } else {\n    console.log('Stream is done reading.');\n  }\n});\n\nrs.resume(); // drain the stream\n
\n

Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.

\n

The finished API is promisify-able as well;

\n
const finished = util.promisify(stream.finished);\n\nconst rs = fs.createReadStream('archive.tar');\n\nasync function run() {\n  await finished(rs);\n  console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // drain the stream\n
" }, { "textRaw": "stream.pipeline(...streams[, callback])", "type": "method", "name": "pipeline", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`...streams` {Stream} Two or more streams to pipe between.", "name": "...streams", "type": "Stream", "desc": "Two or more streams to pipe between." }, { "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", "name": "callback", "type": "Function", "desc": "A callback function that takes an optional error argument.", "optional": true } ] } ], "desc": "

A module method to pipe between streams forwarding errors and properly cleaning\nup and provide a callback when the pipeline is complete.

\n
const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n  fs.createReadStream('archive.tar'),\n  zlib.createGzip(),\n  fs.createWriteStream('archive.tar.gz'),\n  (err) => {\n    if (err) {\n      console.error('Pipeline failed.', err);\n    } else {\n      console.log('Pipeline succeeded.');\n    }\n  }\n);\n
\n

The pipeline API is promisify-able as well:

\n
const pipeline = util.promisify(stream.pipeline);\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz')\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
" }, { "textRaw": "Readable.from(iterable, [options])", "type": "method", "name": "from", "signatures": [ { "params": [ { "textRaw": "`iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol.", "name": "iterable", "type": "Iterable", "desc": "Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol." }, { "textRaw": "`options` {Object} 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`.", "name": "options", "type": "Object", "desc": "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`.", "optional": true } ] } ], "desc": "

A utility method for creating Readable Streams out of iterators.

\n
const { Readable } = require('stream');\n\nasync function * generate() {\n  yield 'hello';\n  yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n
" } ], "miscs": [ { "textRaw": "API for Stream Consumers", "name": "API for Stream Consumers", "type": "misc", "desc": "

Almost all Node.js applications, no matter how simple, use streams in some\nmanner. The following is an example of using streams in a Node.js application\nthat implements an HTTP server:

\n
const http = require('http');\n\nconst server = http.createServer((req, res) => {\n  // req is an http.IncomingMessage, which is a Readable Stream\n  // res is an http.ServerResponse, which is a Writable Stream\n\n  let body = '';\n  // Get the data as utf8 strings.\n  // If an encoding is not set, Buffer objects will be received.\n  req.setEncoding('utf8');\n\n  // Readable streams emit 'data' events once a listener is added\n  req.on('data', (chunk) => {\n    body += chunk;\n  });\n\n  // the 'end' event indicates that the entire body has been received\n  req.on('end', () => {\n    try {\n      const data = JSON.parse(body);\n      // write back something interesting to the user:\n      res.write(typeof data);\n      res.end();\n    } catch (er) {\n      // uh oh! bad json!\n      res.statusCode = 400;\n      return res.end(`error: ${er.message}`);\n    }\n  });\n});\n\nserver.listen(1337);\n\n// $ curl localhost:1337 -d \"{}\"\n// object\n// $ curl localhost:1337 -d \"\\\"foo\\\"\"\n// string\n// $ curl localhost:1337 -d \"not json\"\n// error: Unexpected token o in JSON at position 1\n
\n

Writable streams (such as res in the example) expose methods such as\nwrite() and end() that are used to write data onto the stream.

\n

Readable streams use the EventEmitter API for notifying application\ncode when data is available to be read off the stream. That available data can\nbe read from the stream in multiple ways.

\n

Both Writable and Readable streams use the EventEmitter API in\nvarious ways to communicate the current state of the stream.

\n

Duplex and Transform streams are both Writable and\nReadable.

\n

Applications that are either writing data to or consuming data from a stream\nare not required to implement the stream interfaces directly and will generally\nhave no reason to call require('stream').

\n

Developers wishing to implement new types of streams should refer to the\nsection API for Stream Implementers.

", "miscs": [ { "textRaw": "Writable Streams", "name": "writable_streams", "desc": "

Writable streams are an abstraction for a destination to which data is\nwritten.

\n

Examples of Writable streams include:

\n\n

Some of these examples are actually Duplex streams that implement the\nWritable interface.

\n

All Writable streams implement the interface defined by the\nstream.Writable class.

\n

While specific instances of Writable streams may differ in various ways,\nall Writable streams follow the same fundamental usage pattern as illustrated\nin the example below:

\n
const myStream = getWritableStreamSomehow();\nmyStream.write('some data');\nmyStream.write('some more data');\nmyStream.end('done writing data');\n
", "classes": [ { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18438", "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." } ] }, "params": [], "desc": "

The 'close' event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.

\n

A Writable stream will always emit the 'close' event if it is\ncreated with the emitClose option.

" }, { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [], "desc": "

If a call to stream.write(chunk) returns false, the\n'drain' event will be emitted when it is appropriate to resume writing data\nto the stream.

\n
// Write the data to the supplied writable stream one million times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n  let i = 1000000;\n  write();\n  function write() {\n    let ok = true;\n    do {\n      i--;\n      if (i === 0) {\n        // last time!\n        writer.write(data, encoding, callback);\n      } else {\n        // see if we should continue, or wait\n        // don't pass the callback, because we're not done yet.\n        ok = writer.write(data, encoding);\n      }\n    } while (i > 0 && ok);\n    if (i > 0) {\n      // had to stop early!\n      // write some more once it drains\n      writer.once('drain', write);\n    }\n  }\n}\n
" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [ { "textRaw": "{Error}", "type": "Error" } ], "desc": "

The 'error' event is emitted if an error occurred while writing or piping\ndata. The listener callback is passed a single Error argument when called.

\n

The stream is not closed when the 'error' event is emitted.

" }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [], "desc": "

The 'finish' event is emitted after the stream.end() method\nhas been called, and all data has been flushed to the underlying system.

\n
const writer = getWritableStreamSomehow();\nfor (let i = 0; i < 100; i++) {\n  writer.write(`hello, #${i}!\\n`);\n}\nwriter.end('This is the end\\n');\nwriter.on('finish', () => {\n  console.log('All writes are now complete.');\n});\n
" }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [ { "textRaw": "`src` {stream.Readable} source stream that is piping to this writable", "name": "src", "type": "stream.Readable", "desc": "source stream that is piping to this writable" } ], "desc": "

The 'pipe' event is emitted when the stream.pipe() method is called on\na readable stream, adding this writable to its set of destinations.

\n
const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('pipe', (src) => {\n  console.log('Something is piping into the writer.');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\n
" }, { "textRaw": "Event: 'unpipe'", "type": "event", "name": "unpipe", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [ { "textRaw": "`src` {stream.Readable} The source stream that [unpiped][`stream.unpipe()`] this writable", "name": "src", "type": "stream.Readable", "desc": "The source stream that [unpiped][`stream.unpipe()`] this writable" } ], "desc": "

The 'unpipe' event is emitted when the stream.unpipe() method is called\non a Readable stream, removing this Writable from its set of\ndestinations.

\n

This is also emitted in case this Writable stream emits an error when a\nReadable stream pipes into it.

\n
const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('unpipe', (src) => {\n  console.log('Something has stopped piping into the writer.');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);\n
" } ], "methods": [ { "textRaw": "writable.cork()", "type": "method", "name": "cork", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The writable.cork() method forces all written data to be buffered in memory.\nThe buffered data will be flushed when either the stream.uncork() or\nstream.end() methods are called.

\n

The primary intent of writable.cork() is to avoid a situation where writing\nmany small chunks of data to a stream do not cause a backup in the internal\nbuffer that would have an adverse impact on performance. In such situations,\nimplementations that implement the writable._writev() method can perform\nbuffered writes in a more optimized manner.

\n

See also: writable.uncork().

" }, { "textRaw": "writable.destroy([error])", "type": "method", "name": "destroy", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error", "optional": true } ] } ], "desc": "

Destroy the stream, and emit the passed 'error' and a 'close' event.\nAfter this call, the writable stream has ended and subsequent calls\nto write() or end() will result in an ERR_STREAM_DESTROYED error.\nImplementors should not override this method,\nbut instead implement writable._destroy().

" }, { "textRaw": "writable.end([chunk][, encoding][, callback])", "type": "method", "name": "end", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18780", "description": "This method now returns a reference to `writable`." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11608", "description": "The `chunk` argument can now be a `Uint8Array` instance." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", "name": "chunk", "type": "string|Buffer|Uint8Array|any", "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", "optional": true }, { "textRaw": "`encoding` {string} The encoding if `chunk` is a string", "name": "encoding", "type": "string", "desc": "The encoding if `chunk` is a string", "optional": true }, { "textRaw": "`callback` {Function} Optional callback for when the stream is finished", "name": "callback", "type": "Function", "desc": "Optional callback for when the stream is finished", "optional": true } ] } ], "desc": "

Calling the writable.end() method signals that no more data will be written\nto the Writable. The optional chunk and encoding arguments allow one\nfinal additional chunk of data to be written immediately before closing the\nstream. If provided, the optional callback function is attached as a listener\nfor the 'finish' event.

\n

Calling the stream.write() method after calling\nstream.end() will raise an error.

\n
// write 'hello, ' and then end with 'world!'\nconst fs = require('fs');\nconst file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// writing more now is not allowed!\n
" }, { "textRaw": "writable.setDefaultEncoding(encoding)", "type": "method", "name": "setDefaultEncoding", "meta": { "added": [ "v0.11.15" ], "changes": [ { "version": "v6.1.0", "pr-url": "https://github.com/nodejs/node/pull/5040", "description": "This method now returns a reference to `writable`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`encoding` {string} The new default encoding", "name": "encoding", "type": "string", "desc": "The new default encoding" } ] } ], "desc": "

The writable.setDefaultEncoding() method sets the default encoding for a\nWritable stream.

" }, { "textRaw": "writable.uncork()", "type": "method", "name": "uncork", "meta": { "added": [ "v0.11.2" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "

The writable.uncork() method flushes all data buffered since\nstream.cork() was called.

\n

When using writable.cork() and writable.uncork() to manage the buffering\nof writes to a stream, it is recommended that calls to writable.uncork() be\ndeferred using process.nextTick(). Doing so allows batching of all\nwritable.write() calls that occur within a given Node.js event loop phase.

\n
stream.cork();\nstream.write('some ');\nstream.write('data ');\nprocess.nextTick(() => stream.uncork());\n
\n

If the writable.cork() method is called multiple times on a stream, the\nsame number of calls to writable.uncork() must be called to flush the buffered\ndata.

\n
stream.cork();\nstream.write('some ');\nstream.cork();\nstream.write('data ');\nprocess.nextTick(() => {\n  stream.uncork();\n  // The data will not be flushed until uncork() is called a second time.\n  stream.uncork();\n});\n
\n

See also: writable.cork().

" }, { "textRaw": "writable.write(chunk[, encoding][, callback])", "type": "method", "name": "write", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11608", "description": "The `chunk` argument can now be a `Uint8Array` instance." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/6170", "description": "Passing `null` as the `chunk` parameter will always be considered invalid now, even in object mode." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", "name": "return", "type": "boolean", "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." }, "params": [ { "textRaw": "`chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", "name": "chunk", "type": "string|Buffer|Uint8Array|any", "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`." }, { "textRaw": "`encoding` {string} The encoding, if `chunk` is a string", "name": "encoding", "type": "string", "desc": "The encoding, if `chunk` is a string", "optional": true }, { "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed", "name": "callback", "type": "Function", "desc": "Callback for when this chunk of data is flushed", "optional": true } ] } ], "desc": "

The writable.write() method writes some data to the stream, and calls the\nsupplied callback once the data has been fully handled. If an error\noccurs, the callback may or may not be called with the error as its\nfirst argument. To reliably detect write errors, add a listener for the\n'error' event.

\n

The return value is true if the internal buffer is less than the\nhighWaterMark configured when the stream was created after admitting chunk.\nIf false is returned, further attempts to write data to the stream should\nstop until the 'drain' event is emitted.

\n

While a stream is not draining, calls to write() will buffer chunk, and\nreturn false. Once all currently buffered chunks are drained (accepted for\ndelivery by the operating system), the 'drain' event will be emitted.\nIt is recommended that once write() returns false, no more chunks be written\nuntil the 'drain' event is emitted. While calling write() on a stream that\nis not draining is allowed, Node.js will buffer all written chunks until\nmaximum memory usage occurs, at which point it will abort unconditionally.\nEven before it aborts, high memory usage will cause poor garbage collector\nperformance and high RSS (which is not typically released back to the system,\neven after the memory is no longer required). Since TCP sockets may never\ndrain if the remote peer does not read the data, writing a socket that is\nnot draining may lead to a remotely exploitable vulnerability.

\n

Writing data while the stream is not draining is particularly\nproblematic for a Transform, because the Transform streams are paused\nby default until they are piped or a 'data' or 'readable' event handler\nis added.

\n

If the data to be written can be generated or fetched on demand, it is\nrecommended to encapsulate the logic into a Readable and use\nstream.pipe(). However, if calling write() is preferred, it is\npossible to respect backpressure and avoid memory issues using the\n'drain' event:

\n
function write(data, cb) {\n  if (!stream.write(data)) {\n    stream.once('drain', cb);\n  } else {\n    process.nextTick(cb);\n  }\n}\n\n// Wait for cb to be called before doing any other write.\nwrite('hello', () => {\n  console.log('Write completed, do more writes now.');\n});\n
\n

A Writable stream in object mode will always ignore the encoding argument.

" } ], "properties": [ { "textRaw": "`writable` {boolean}", "type": "boolean", "name": "writable", "meta": { "added": [ "v0.8.0" ], "changes": [] }, "desc": "

Is true if it is safe to call [writable.write()][].

" }, { "textRaw": "`writableHighWaterMark` {number}", "type": "number", "name": "writableHighWaterMark", "meta": { "added": [ "v9.3.0" ], "changes": [] }, "desc": "

Return the value of highWaterMark passed when constructing this\nWritable.

" }, { "textRaw": "writable.writableLength", "name": "writableLength", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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

" } ] } ], "type": "misc", "displayName": "Writable Streams" }, { "textRaw": "Readable Streams", "name": "readable_streams", "desc": "

Readable streams are an abstraction for a source from which data is\nconsumed.

\n

Examples of Readable streams include:

\n\n

All Readable streams implement the interface defined by the\nstream.Readable class.

", "modules": [ { "textRaw": "Two Reading Modes", "name": "two_reading_modes", "desc": "

Readable streams effectively operate in one of two modes: flowing and\npaused. These modes are separate from object mode.\nA Readable stream can be in object mode or not, regardless of whether\nit is in flowing mode or paused mode.

\n\n

All Readable streams begin in paused mode but can be switched to flowing\nmode in one of the following ways:

\n\n

The Readable can switch back to paused mode using one of the following:

\n\n

The important concept to remember is that a Readable will not generate data\nuntil a mechanism for either consuming or ignoring that data is provided. If\nthe consuming mechanism is disabled or taken away, the Readable will attempt\nto stop generating the data.

\n

For backward compatibility reasons, removing 'data' event handlers will\nnot automatically pause the stream. Also, if there are piped destinations,\nthen calling stream.pause() will not guarantee that the\nstream will remain paused once those destinations drain and ask for more data.

\n

If a Readable is switched into flowing mode and there are no consumers\navailable to handle the data, that data will be lost. This can occur, for\ninstance, when the readable.resume() method is called without a listener\nattached to the 'data' event, or when a 'data' event handler is removed\nfrom the stream.

\n

Adding a 'readable' event handler automatically make the stream to\nstop flowing, and the data to be consumed via\nreadable.read(). If the 'readable' event handler is\nremoved, then the stream will start flowing again if there is a\n'data' event handler.

", "type": "module", "displayName": "Two Reading Modes" }, { "textRaw": "Three States", "name": "three_states", "desc": "

The \"two modes\" of operation for a Readable stream are a simplified\nabstraction for the more complicated internal state management that is happening\nwithin the Readable stream implementation.

\n

Specifically, at any given point in time, every Readable is in one of three\npossible states:

\n\n

When readable.readableFlowing is null, no mechanism for consuming the\nstream's data is provided. Therefore, the stream will not generate data.\nWhile in this state, attaching a listener for the 'data' event, calling the\nreadable.pipe() method, or calling the readable.resume() method will switch\nreadable.readableFlowing to true, causing the Readable to begin actively\nemitting events as data is generated.

\n

Calling readable.pause(), readable.unpipe(), or receiving backpressure\nwill cause the readable.readableFlowing to be set as false,\ntemporarily halting the flowing of events but not halting the generation of\ndata. While in this state, attaching a listener for the 'data' event\nwill not switch readable.readableFlowing to true.

\n
const { PassThrough, Writable } = require('stream');\nconst pass = new PassThrough();\nconst writable = new Writable();\n\npass.pipe(writable);\npass.unpipe(writable);\n// readableFlowing is now false\n\npass.on('data', (chunk) => { console.log(chunk.toString()); });\npass.write('ok');  // will not emit 'data'\npass.resume();     // must be called to make stream emit 'data'\n
\n

While readable.readableFlowing is false, data may be accumulating\nwithin the stream's internal buffer.

", "type": "module", "displayName": "Three States" }, { "textRaw": "Choose One API Style", "name": "choose_one_api_style", "desc": "

The Readable stream API evolved across multiple Node.js versions and provides\nmultiple methods of consuming stream data. In general, developers should choose\none of the methods of consuming data and should never use multiple methods\nto consume data from a single stream. Specifically, using a combination\nof on('data'), on('readable'), pipe(), or async iterators could\nlead to unintuitive behavior.

\n

Use of the readable.pipe() method is recommended for most users as it has been\nimplemented to provide the easiest way of consuming stream data. Developers that\nrequire more fine-grained control over the transfer and generation of data can\nuse the EventEmitter and readable.on('readable')/readable.read()\nor the readable.pause()/readable.resume() APIs.

", "type": "module", "displayName": "Choose One API Style" } ], "classes": [ { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "events": [ { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18438", "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." } ] }, "params": [], "desc": "

The 'close' event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.

\n

A Readable stream will always emit the 'close' event if it is\ncreated with the emitClose option.

" }, { "textRaw": "Event: 'data'", "type": "event", "name": "data", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [ { "textRaw": "`chunk` {Buffer|string|any} The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. For streams that are in object mode, the chunk can be any JavaScript value other than `null`.", "name": "chunk", "type": "Buffer|string|any", "desc": "The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. For streams that are in object mode, the chunk can be any JavaScript value other than `null`." } ], "desc": "

The 'data' event is emitted whenever the stream is relinquishing ownership of\na chunk of data to a consumer. This may occur whenever the stream is switched\nin flowing mode by calling readable.pipe(), readable.resume(), or by\nattaching a listener callback to the 'data' event. The 'data' event will\nalso be emitted whenever the readable.read() method is called and a chunk of\ndata is available to be returned.

\n

Attaching a 'data' event listener to a stream that has not been explicitly\npaused will switch the stream into flowing mode. Data will then be passed as\nsoon as it is available.

\n

The listener callback will be passed the chunk of data as a string if a default\nencoding has been specified for the stream using the\nreadable.setEncoding() method; otherwise the data will be passed as a\nBuffer.

\n
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n});\n
" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [], "desc": "

The 'end' event is emitted when there is no more data to be consumed from\nthe stream.

\n

The 'end' event will not be emitted unless the data is completely\nconsumed. This can be accomplished by switching the stream into flowing mode,\nor by calling stream.read() repeatedly until all data has been\nconsumed.

\n
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n});\nreadable.on('end', () => {\n  console.log('There will be no more data.');\n});\n
" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "params": [ { "textRaw": "{Error}", "type": "Error" } ], "desc": "

The 'error' event may be emitted by a Readable implementation at any time.\nTypically, this may occur if the underlying stream is unable to generate data\ndue to an underlying internal failure, or when a stream implementation attempts\nto push an invalid chunk of data.

\n

The listener callback will be passed a single Error object.

" }, { "textRaw": "Event: 'readable'", "type": "event", "name": "readable", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17979", "description": "The `'readable'` is always emitted in the next tick after `.push()` is called\n" }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18994", "description": "Using `'readable'` requires calling `.read()`." } ] }, "params": [], "desc": "

The 'readable' event is emitted when there is data available to be read from\nthe stream. In some cases, attaching a listener for the 'readable' event will\ncause some amount of data to be read into an internal buffer.

\n
const readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // there is some data to read now\n  let data;\n\n  while (data = this.read()) {\n    console.log(data);\n  }\n});\n
\n

The 'readable' event will also be emitted once the end of the stream data\nhas been reached but before the 'end' event is emitted.

\n

Effectively, the 'readable' event indicates that the stream has new\ninformation: either new data is available or the end of the stream has been\nreached. In the former case, stream.read() will return the\navailable data. In the latter case, stream.read() will return\nnull. For instance, in the following example, foo.txt is an empty file:

\n
const fs = require('fs');\nconst rr = fs.createReadStream('foo.txt');\nrr.on('readable', () => {\n  console.log(`readable: ${rr.read()}`);\n});\nrr.on('end', () => {\n  console.log('end');\n});\n
\n

The output of running this script is:

\n
$ node test.js\nreadable: null\nend\n
\n

In general, the readable.pipe() and 'data' event mechanisms are easier to\nunderstand than the 'readable' event. However, handling 'readable' might\nresult in increased throughput.

\n

If both 'readable' and 'data' are used at the same time, 'readable'\ntakes precedence in controlling the flow, i.e. 'data' will be emitted\nonly when stream.read() is called. The\nreadableFlowing property would become false.\nIf there are 'data' listeners when 'readable' is removed, the stream\nwill start flowing, i.e. 'data' events will be emitted without calling\n.resume().

" } ], "methods": [ { "textRaw": "readable.destroy([error])", "type": "method", "name": "destroy", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`error` {Error} Error which will be passed as payload in `'error'` event", "name": "error", "type": "Error", "desc": "Error which will be passed as payload in `'error'` event", "optional": true } ] } ], "desc": "

Destroy the stream, and emit 'error' and 'close'. After this call, the\nreadable stream will release any internal resources and subsequent calls\nto push() will be ignored.\nImplementors should not override this method, but instead implement\nreadable._destroy().

" }, { "textRaw": "readable.isPaused()", "type": "method", "name": "isPaused", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [] } ], "desc": "

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

\n
const readable = new stream.Readable();\n\nreadable.isPaused(); // === false\nreadable.pause();\nreadable.isPaused(); // === true\nreadable.resume();\nreadable.isPaused(); // === false\n
" }, { "textRaw": "readable.pause()", "type": "method", "name": "pause", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [] } ], "desc": "

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

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

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

" }, { "textRaw": "readable.pipe(destination[, options])", "type": "method", "name": "pipe", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {stream.Writable} The *destination*, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream", "name": "return", "type": "stream.Writable", "desc": "The *destination*, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream" }, "params": [ { "textRaw": "`destination` {stream.Writable} The destination for writing data", "name": "destination", "type": "stream.Writable", "desc": "The destination for writing data" }, { "textRaw": "`options` {Object} Pipe options", "name": "options", "type": "Object", "desc": "Pipe options", "options": [ { "textRaw": "`end` {boolean} End the writer when the reader ends. **Default:** `true`.", "name": "end", "type": "boolean", "default": "`true`", "desc": "End the writer when the reader ends." } ], "optional": true } ] } ], "desc": "

The readable.pipe() method attaches a Writable stream to the readable,\ncausing it to switch automatically into flowing mode and push all of its data\nto the attached Writable. The flow of data will be automatically managed\nso that the destination Writable stream is not overwhelmed by a faster\nReadable stream.

\n

The following example pipes all of the data from the readable into a file\nnamed file.txt:

\n
const fs = require('fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'\nreadable.pipe(writable);\n
\n

It is possible to attach multiple Writable streams to a single Readable\nstream.

\n

The readable.pipe() method returns a reference to the destination stream\nmaking it possible to set up chains of piped streams:

\n
const fs = require('fs');\nconst r = fs.createReadStream('file.txt');\nconst z = zlib.createGzip();\nconst w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);\n
\n

By default, stream.end() is called on the destination Writable\nstream when the source Readable stream emits 'end', so that the\ndestination is no longer writable. To disable this default behavior, the end\noption can be passed as false, causing the destination stream to remain open:

\n
reader.pipe(writer, { end: false });\nreader.on('end', () => {\n  writer.end('Goodbye\\n');\n});\n
\n

One important caveat is that if the Readable stream emits an error during\nprocessing, the Writable destination is not closed automatically. If an\nerror occurs, it will be necessary to manually close each stream in order\nto prevent memory leaks.

\n

The process.stderr and process.stdout Writable streams are never\nclosed until the Node.js process exits, regardless of the specified options.

" }, { "textRaw": "readable.read([size])", "type": "method", "name": "read", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string|Buffer|null|any}", "name": "return", "type": "string|Buffer|null|any" }, "params": [ { "textRaw": "`size` {number} Optional argument to specify how much data to read.", "name": "size", "type": "number", "desc": "Optional argument to specify how much data to read.", "optional": true } ] } ], "desc": "

The readable.read() method pulls some data out of the internal buffer and\nreturns it. If no data available to be read, null is returned. By default,\nthe data will be returned as a Buffer object unless an encoding has been\nspecified using the readable.setEncoding() method or the stream is operating\nin object mode.

\n

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

\n

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

\n

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

\n

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

\n
const readable = getReadableStreamSomehow();\nreadable.on('readable', () => {\n  let chunk;\n  while (null !== (chunk = readable.read())) {\n    console.log(`Received ${chunk.length} bytes of data.`);\n  }\n});\n
\n

Note that the while loop is necessary when processing data with\nreadable.read(). Only after readable.read() returns null,\n'readable' will be emitted.

\n

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

\n

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

\n

Calling stream.read([size]) after the 'end' event has\nbeen emitted will return null. No runtime error will be raised.

" }, { "textRaw": "readable.resume()", "type": "method", "name": "resume", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18994", "description": "The `resume()` has no effect if there is a `'readable'` event listening." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [] } ], "desc": "

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

\n

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

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

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

" }, { "textRaw": "readable.setEncoding(encoding)", "type": "method", "name": "setEncoding", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`encoding` {string} The encoding to use.", "name": "encoding", "type": "string", "desc": "The encoding to use." } ] } ], "desc": "

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

\n

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

\n

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

\n
const readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', (chunk) => {\n  assert.equal(typeof chunk, 'string');\n  console.log('Got %d characters of string data:', chunk.length);\n});\n
" }, { "textRaw": "readable.unpipe([destination])", "type": "method", "name": "unpipe", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`destination` {stream.Writable} Optional specific stream to unpipe", "name": "destination", "type": "stream.Writable", "desc": "Optional specific stream to unpipe", "optional": true } ] } ], "desc": "

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

\n

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

\n

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

\n
const fs = require('fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second\nreadable.pipe(writable);\nsetTimeout(() => {\n  console.log('Stop writing to file.txt.');\n  readable.unpipe(writable);\n  console.log('Manually close the file stream.');\n  writable.end();\n}, 1000);\n
" }, { "textRaw": "readable.unshift(chunk)", "type": "method", "name": "unshift", "meta": { "added": [ "v0.9.11" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11608", "description": "The `chunk` argument can now be a `Uint8Array` instance." } ] }, "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer|Uint8Array|string|any} Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", "name": "chunk", "type": "Buffer|Uint8Array|string|any", "desc": "Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`." } ] } ], "desc": "

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

\n

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

\n

Developers using stream.unshift() often should consider switching to\nuse of a Transform stream instead. See the API for Stream Implementers\nsection for more information.

\n
// Pull off a header delimited by \\n\\n\n// use unshift() if we get too much\n// Call the callback with (error, header, stream)\nconst { StringDecoder } = require('string_decoder');\nfunction parseHeader(stream, callback) {\n  stream.on('error', callback);\n  stream.on('readable', onReadable);\n  const decoder = new StringDecoder('utf8');\n  let header = '';\n  function onReadable() {\n    let chunk;\n    while (null !== (chunk = stream.read())) {\n      const str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // found the header boundary\n        const split = str.split(/\\n\\n/);\n        header += split.shift();\n        const remaining = split.join('\\n\\n');\n        const buf = Buffer.from(remaining, 'utf8');\n        stream.removeListener('error', callback);\n        // remove the 'readable' listener before unshifting\n        stream.removeListener('readable', onReadable);\n        if (buf.length)\n          stream.unshift(buf);\n        // now the body of the message can be read from the stream.\n        callback(null, header, stream);\n      } else {\n        // still reading the header.\n        header += str;\n      }\n    }\n  }\n}\n
\n

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

" }, { "textRaw": "readable.wrap(stream)", "type": "method", "name": "wrap", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" }, "params": [ { "textRaw": "`stream` {Stream} An \"old style\" readable stream", "name": "stream", "type": "Stream", "desc": "An \"old style\" readable stream" } ] } ], "desc": "

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

\n

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

\n

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

\n
const { OldReader } = require('./old-api-module.js');\nconst { Readable } = require('stream');\nconst oreader = new OldReader();\nconst myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', () => {\n  myReader.read(); // etc.\n});\n
" }, { "textRaw": "readable[Symbol.asyncIterator]()", "type": "method", "name": "[Symbol.asyncIterator]", "meta": { "added": [ "v10.0.0" ], "changes": [ { "version": "v10.17.0", "pr-url": "https://github.com/nodejs/node/pull/26989", "description": "Symbol.asyncIterator support is no longer experimental." } ] }, "stability": 2, "stabilityText": "Stable", "signatures": [ { "return": { "textRaw": "Returns: {AsyncIterator} to fully consume the stream.", "name": "return", "type": "AsyncIterator", "desc": "to fully consume the stream." }, "params": [] } ], "desc": "
const fs = require('fs');\n\nasync function print(readable) {\n  readable.setEncoding('utf8');\n  let data = '';\n  for await (const k of readable) {\n    data += k;\n  }\n  console.log(data);\n}\n\nprint(fs.createReadStream('file')).catch(console.log);\n
\n

If the loop terminates with a break or a throw, the stream will be\ndestroyed. In other terms, iterating over a stream will consume the stream\nfully. The stream will be read in chunks of size equal to the highWaterMark\noption. In the code example above, data will be in a single chunk if the file\nhas less then 64kb of data because no highWaterMark option is provided to\nfs.createReadStream().

" } ], "properties": [ { "textRaw": "`readable` {boolean}", "type": "boolean", "name": "readable", "meta": { "added": [ "v0.8.0" ], "changes": [] }, "desc": "

Is true if it is safe to call [readable.read()][].

" }, { "textRaw": "`readableFlowing` {boolean}", "type": "boolean", "name": "readableFlowing", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

This property reflects the current state of a Readable stream as described\nin the Stream Three States section.

" }, { "textRaw": "`readableHighWaterMark` {number}", "type": "number", "name": "readableHighWaterMark", "meta": { "added": [ "v9.3.0" ], "changes": [] }, "desc": "

Returns the value of highWaterMark passed when constructing this\nReadable.

" }, { "textRaw": "`readableLength` {number}", "type": "number", "name": "readableLength", "meta": { "added": [ "v9.4.0" ], "changes": [] }, "desc": "

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

" } ] } ], "type": "misc", "displayName": "Readable Streams" }, { "textRaw": "Duplex and Transform Streams", "name": "duplex_and_transform_streams", "classes": [ { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v6.8.0", "pr-url": "https://github.com/nodejs/node/pull/8834", "description": "Instances of `Duplex` now return `true` when checking `instanceof stream.Writable`." } ] }, "desc": "

Duplex streams are streams that implement both the Readable and\nWritable interfaces.

\n

Examples of Duplex streams include:

\n" }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "meta": { "added": [ "v0.9.4" ], "changes": [] }, "desc": "

Transform streams are Duplex streams where the output is in some way\nrelated to the input. Like all Duplex streams, Transform streams\nimplement both the Readable and Writable interfaces.

\n

Examples of Transform streams include:

\n", "methods": [ { "textRaw": "transform.destroy([error])", "type": "method", "name": "destroy", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`error` {Error}", "name": "error", "type": "Error", "optional": true } ] } ], "desc": "

Destroy the stream, and emit 'error'. After this call, the\ntransform stream would release any internal resources.\nImplementors should not override this method, but instead implement\nreadable._destroy().\nThe default implementation of _destroy() for Transform also emit 'close'.

" } ] } ], "type": "misc", "displayName": "Duplex and Transform Streams" } ], "methods": [ { "textRaw": "stream.finished(stream, callback)", "type": "method", "name": "finished", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`stream` {Stream} A readable and/or writable stream.", "name": "stream", "type": "Stream", "desc": "A readable and/or writable stream." }, { "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", "name": "callback", "type": "Function", "desc": "A callback function that takes an optional error argument." } ] } ], "desc": "

A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.

\n
const { finished } = require('stream');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n  if (err) {\n    console.error('Stream failed.', err);\n  } else {\n    console.log('Stream is done reading.');\n  }\n});\n\nrs.resume(); // drain the stream\n
\n

Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.

\n

The finished API is promisify-able as well;

\n
const finished = util.promisify(stream.finished);\n\nconst rs = fs.createReadStream('archive.tar');\n\nasync function run() {\n  await finished(rs);\n  console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // drain the stream\n
" }, { "textRaw": "stream.pipeline(...streams[, callback])", "type": "method", "name": "pipeline", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`...streams` {Stream} Two or more streams to pipe between.", "name": "...streams", "type": "Stream", "desc": "Two or more streams to pipe between." }, { "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", "name": "callback", "type": "Function", "desc": "A callback function that takes an optional error argument.", "optional": true } ] } ], "desc": "

A module method to pipe between streams forwarding errors and properly cleaning\nup and provide a callback when the pipeline is complete.

\n
const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n  fs.createReadStream('archive.tar'),\n  zlib.createGzip(),\n  fs.createWriteStream('archive.tar.gz'),\n  (err) => {\n    if (err) {\n      console.error('Pipeline failed.', err);\n    } else {\n      console.log('Pipeline succeeded.');\n    }\n  }\n);\n
\n

The pipeline API is promisify-able as well:

\n
const pipeline = util.promisify(stream.pipeline);\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz')\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
" }, { "textRaw": "Readable.from(iterable, [options])", "type": "method", "name": "from", "signatures": [ { "params": [ { "textRaw": "`iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol.", "name": "iterable", "type": "Iterable", "desc": "Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol." }, { "textRaw": "`options` {Object} 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`.", "name": "options", "type": "Object", "desc": "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`.", "optional": true } ] } ], "desc": "

A utility method for creating Readable Streams out of iterators.

\n
const { Readable } = require('stream');\n\nasync function * generate() {\n  yield 'hello';\n  yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n
" } ] }, { "textRaw": "API for Stream Implementers", "name": "API for Stream Implementers", "type": "misc", "desc": "

The stream module API has been designed to make it possible to easily\nimplement streams using JavaScript's prototypal inheritance model.

\n

First, a stream developer would declare a new JavaScript class that extends one\nof the four basic stream classes (stream.Writable, stream.Readable,\nstream.Duplex, or stream.Transform), making sure they call the appropriate\nparent class constructor:

\n\n
const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n
\n

The new stream class must then implement one or more specific methods, depending\non the type of stream being created, as detailed in the chart below:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Use-caseClassMethod(s) to implement
Reading onlyReadable_read
Writing onlyWritable_write, _writev, _final
Reading and writingDuplex_read, _write, _writev, _final
Operate on written data, then read the resultTransform_transform, _flush, _final
\n

The implementation code for a stream should never call the \"public\" methods\nof a stream that are intended for use by consumers (as described in the\nAPI for Stream Consumers section). Doing so may lead to adverse side effects\nin application code consuming the stream.

", "miscs": [ { "textRaw": "Simplified Construction", "name": "simplified_construction", "meta": { "added": [ "v1.2.0" ], "changes": [] }, "desc": "

For many simple cases, it is possible to construct a stream without relying on\ninheritance. This can be accomplished by directly creating instances of the\nstream.Writable, stream.Readable, stream.Duplex or stream.Transform\nobjects and passing appropriate methods as constructor options.

\n
const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  }\n});\n
", "type": "misc", "displayName": "Simplified Construction" }, { "textRaw": "Implementing a Writable Stream", "name": "implementing_a_writable_stream", "desc": "

The stream.Writable class is extended to implement a Writable stream.

\n

Custom Writable streams must call the new stream.Writable([options])\nconstructor and implement the writable._write() method. The\nwritable._writev() method may also be implemented.

", "ctors": [ { "textRaw": "Constructor: new stream.Writable([options])", "type": "ctor", "name": "stream.Writable", "meta": { "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/18438", "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy\n" }, { "version": "v10.16.0", "pr-url": "https://github.com/nodejs/node/pull/22795", "description": "Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'finish'` or errors\n" } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number} Buffer level when [`stream.write()`][stream-write] starts returning `false`. **Default:** `16384` (16kb), or `16` for `objectMode` streams.", "name": "highWaterMark", "type": "number", "default": "`16384` (16kb), or `16` for `objectMode` streams", "desc": "Buffer level when [`stream.write()`][stream-write] starts returning `false`." }, { "textRaw": "`decodeStrings` {boolean} Whether to encode `string`s passed to [`stream.write()`][stream-write] to `Buffer`s (with the encoding specified in the [`stream.write()`][stream-write] call) before passing them to [`stream._write()`][stream-_write]. Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent `string`s from being converted. **Default:** `true`.", "name": "decodeStrings", "type": "boolean", "default": "`true`", "desc": "Whether to encode `string`s passed to [`stream.write()`][stream-write] to `Buffer`s (with the encoding specified in the [`stream.write()`][stream-write] call) before passing them to [`stream._write()`][stream-_write]. Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent `string`s from being converted." }, { "textRaw": "`defaultEncoding` {string} The default encoding that is used when no encoding is specified as an argument to [`stream.write()`][stream-write]. **Default:** `'utf8'`.", "name": "defaultEncoding", "type": "string", "default": "`'utf8'`", "desc": "The default encoding that is used when no encoding is specified as an argument to [`stream.write()`][stream-write]." }, { "textRaw": "`objectMode` {boolean} Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation. **Default:** `false`.", "name": "objectMode", "type": "boolean", "default": "`false`", "desc": "Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation." }, { "textRaw": "`emitClose` {boolean} Whether or not the stream should emit `'close'` after it has been destroyed. **Default:** `true`.", "name": "emitClose", "type": "boolean", "default": "`true`", "desc": "Whether or not the stream should emit `'close'` after it has been destroyed." }, { "textRaw": "`write` {Function} Implementation for the [`stream._write()`][stream-_write] method.", "name": "write", "type": "Function", "desc": "Implementation for the [`stream._write()`][stream-_write] method." }, { "textRaw": "`writev` {Function} Implementation for the [`stream._writev()`][stream-_writev] method.", "name": "writev", "type": "Function", "desc": "Implementation for the [`stream._writev()`][stream-_writev] method." }, { "textRaw": "`destroy` {Function} Implementation for the [`stream._destroy()`][writable-_destroy] method.", "name": "destroy", "type": "Function", "desc": "Implementation for the [`stream._destroy()`][writable-_destroy] method." }, { "textRaw": "`final` {Function} Implementation for the [`stream._final()`][stream-_final] method.", "name": "final", "type": "Function", "desc": "Implementation for the [`stream._final()`][stream-_final] method." }, { "textRaw": "`autoDestroy` {boolean} Whether this stream should automatically call `.destroy()` on itself after ending. **Default:** `false`.", "name": "autoDestroy", "type": "boolean", "default": "`false`", "desc": "Whether this stream should automatically call `.destroy()` on itself after ending." } ], "optional": true } ] } ], "desc": "\n
const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    // Calls the stream.Writable() constructor\n    super(options);\n    // ...\n  }\n}\n
\n

Or, when using pre-ES6 style constructors:

\n
const { Writable } = require('stream');\nconst util = require('util');\n\nfunction MyWritable(options) {\n  if (!(this instanceof MyWritable))\n    return new MyWritable(options);\n  Writable.call(this, options);\n}\nutil.inherits(MyWritable, Writable);\n
\n

Or, using the Simplified Constructor approach:

\n
const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  writev(chunks, callback) {\n    // ...\n  }\n});\n
" } ], "methods": [ { "textRaw": "writable._write(chunk, encoding, callback)", "type": "method", "name": "_write", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer|string|any} The `Buffer` to be written, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write].", "name": "chunk", "type": "Buffer|string|any", "desc": "The `Buffer` to be written, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write]." }, { "textRaw": "`encoding` {string} If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored.", "name": "encoding", "type": "string", "desc": "If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored." }, { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when processing is complete for the supplied chunk.", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when processing is complete for the supplied chunk." } ] } ], "desc": "

All Writable stream implementations must provide a\nwritable._write() method to send data to the underlying\nresource.

\n

Transform streams provide their own implementation of the\nwritable._write().

\n

This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Writable class\nmethods only.

\n

The callback method must be called to signal either that the write completed\nsuccessfully or failed with an error. The first argument passed to the\ncallback must be the Error object if the call failed or null if the\nwrite succeeded.

\n

All calls to writable.write() that occur between the time writable._write()\nis called and the callback is called will cause the written data to be\nbuffered. When the callback is invoked, the stream might emit a 'drain'\nevent. If a stream implementation is capable of processing multiple chunks of\ndata at once, the writable._writev() method should be implemented.

\n

If the decodeStrings property is explicitly set to false in the constructor\noptions, then chunk will remain the same object that is passed to .write(),\nand may be a string rather than a Buffer. This is to support implementations\nthat have an optimized handling for certain string data encodings. In that case,\nthe encoding argument will indicate the character encoding of the string.\nOtherwise, the encoding argument can be safely ignored.

\n

The writable._write() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

" }, { "textRaw": "writable._writev(chunks, callback)", "type": "method", "name": "_writev", "signatures": [ { "params": [ { "textRaw": "`chunks` {Object[]} The chunks to be written. Each chunk has following format: `{ chunk: ..., encoding: ... }`.", "name": "chunks", "type": "Object[]", "desc": "The chunks to be written. Each chunk has following format: `{ chunk: ..., encoding: ... }`." }, { "textRaw": "`callback` {Function} A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks.", "name": "callback", "type": "Function", "desc": "A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks." } ] } ], "desc": "

This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Writable class\nmethods only.

\n

The writable._writev() method may be implemented in addition to\nwritable._write() in stream implementations that are capable of processing\nmultiple chunks of data at once. If implemented, the method will be called with\nall chunks of data currently buffered in the write queue.

\n

The writable._writev() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

" }, { "textRaw": "writable._destroy(err, callback)", "type": "method", "name": "_destroy", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`err` {Error} A possible error.", "name": "err", "type": "Error", "desc": "A possible error." }, { "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", "name": "callback", "type": "Function", "desc": "A callback function that takes an optional error argument." } ] } ], "desc": "

The _destroy() method is called by writable.destroy().\nIt can be overridden by child classes but it must not be called directly.

" }, { "textRaw": "writable._final(callback)", "type": "method", "name": "_final", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when finished writing any remaining data.", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when finished writing any remaining data." } ] } ], "desc": "

The _final() method must not be called directly. It may be implemented\nby child classes, and if so, will be called by the internal Writable\nclass methods only.

\n

This optional function will be called before the stream closes, delaying the\n'finish' event until callback is called. This is useful to close resources\nor write buffered data before a stream ends.

" } ], "modules": [ { "textRaw": "Errors While Writing", "name": "errors_while_writing", "desc": "

It is recommended that errors occurring during the processing of the\nwritable._write() and writable._writev() methods are reported by invoking\nthe callback and passing the error as the first argument. This will cause an\n'error' event to be emitted by the Writable. Throwing an Error from within\nwritable._write() can result in unexpected and inconsistent behavior depending\non how the stream is being used. Using the callback ensures consistent and\npredictable handling of errors.

\n

If a Readable stream pipes into a Writable stream when Writable emits an\nerror, the Readable stream will be unpiped.

\n
const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    if (chunk.toString().indexOf('a') >= 0) {\n      callback(new Error('chunk is invalid'));\n    } else {\n      callback();\n    }\n  }\n});\n
", "type": "module", "displayName": "Errors While Writing" }, { "textRaw": "An Example Writable Stream", "name": "an_example_writable_stream", "desc": "

The following illustrates a rather simplistic (and somewhat pointless) custom\nWritable stream implementation. While this specific Writable stream instance\nis not of any real particular usefulness, the example illustrates each of the\nrequired elements of a custom Writable stream instance:

\n
const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n  _write(chunk, encoding, callback) {\n    if (chunk.toString().indexOf('a') >= 0) {\n      callback(new Error('chunk is invalid'));\n    } else {\n      callback();\n    }\n  }\n}\n
", "type": "module", "displayName": "An Example Writable Stream" }, { "textRaw": "Decoding buffers in a Writable Stream", "name": "decoding_buffers_in_a_writable_stream", "desc": "

Decoding buffers is a common task, for instance, when using transformers whose\ninput is a string. This is not a trivial process when using multi-byte\ncharacters encoding, such as UTF-8. The following example shows how to decode\nmulti-byte strings using StringDecoder and Writable.

\n
const { Writable } = require('stream');\nconst { StringDecoder } = require('string_decoder');\n\nclass StringWritable extends Writable {\n  constructor(options) {\n    super(options);\n    this._decoder = new StringDecoder(options && options.defaultEncoding);\n    this.data = '';\n  }\n  _write(chunk, encoding, callback) {\n    if (encoding === 'buffer') {\n      chunk = this._decoder.write(chunk);\n    }\n    this.data += chunk;\n    callback();\n  }\n  _final(callback) {\n    this.data += this._decoder.end();\n    callback();\n  }\n}\n\nconst euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);\nconst w = new StringWritable();\n\nw.write('currency: ');\nw.write(euro[0]);\nw.end(euro[1]);\n\nconsole.log(w.data); // currency: €\n
", "type": "module", "displayName": "Decoding buffers in a Writable Stream" } ], "type": "misc", "displayName": "Implementing a Writable Stream" }, { "textRaw": "Implementing a Readable Stream", "name": "implementing_a_readable_stream", "desc": "

The stream.Readable class is extended to implement a Readable stream.

\n

Custom Readable streams must call the new stream.Readable([options])\nconstructor and implement the readable._read() method.

", "ctors": [ { "textRaw": "new stream.Readable([options])", "type": "ctor", "name": "stream.Readable", "meta": { "changes": [ { "version": "v10.16.0", "pr-url": "https://github.com/nodejs/node/pull/22795", "description": "Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'end'` or errors\n" } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`highWaterMark` {number} The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource. **Default:** `16384` (16kb), or `16` for `objectMode` streams.", "name": "highWaterMark", "type": "number", "default": "`16384` (16kb), or `16` for `objectMode` streams", "desc": "The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource." }, { "textRaw": "`encoding` {string} If specified, then buffers will be decoded to strings using the specified encoding. **Default:** `null`.", "name": "encoding", "type": "string", "default": "`null`", "desc": "If specified, then buffers will be decoded to strings using the specified encoding." }, { "textRaw": "`objectMode` {boolean} Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns a single value instead of a `Buffer` of size `n`. **Default:** `false`.", "name": "objectMode", "type": "boolean", "default": "`false`", "desc": "Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns a single value instead of a `Buffer` of size `n`." }, { "textRaw": "`read` {Function} Implementation for the [`stream._read()`][stream-_read] method.", "name": "read", "type": "Function", "desc": "Implementation for the [`stream._read()`][stream-_read] method." }, { "textRaw": "`destroy` {Function} Implementation for the [`stream._destroy()`][readable-_destroy] method.", "name": "destroy", "type": "Function", "desc": "Implementation for the [`stream._destroy()`][readable-_destroy] method." }, { "textRaw": "`autoDestroy` {boolean} Whether this stream should automatically call `.destroy()` on itself after ending. **Default:** `false`.", "name": "autoDestroy", "type": "boolean", "default": "`false`", "desc": "Whether this stream should automatically call `.destroy()` on itself after ending." } ], "optional": true } ] } ], "desc": "\n
const { Readable } = require('stream');\n\nclass MyReadable extends Readable {\n  constructor(options) {\n    // Calls the stream.Readable(options) constructor\n    super(options);\n    // ...\n  }\n}\n
\n

Or, when using pre-ES6 style constructors:

\n
const { Readable } = require('stream');\nconst util = require('util');\n\nfunction MyReadable(options) {\n  if (!(this instanceof MyReadable))\n    return new MyReadable(options);\n  Readable.call(this, options);\n}\nutil.inherits(MyReadable, Readable);\n
\n

Or, using the Simplified Constructor approach:

\n
const { Readable } = require('stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    // ...\n  }\n});\n
" } ], "methods": [ { "textRaw": "readable._read(size)", "type": "method", "name": "_read", "meta": { "added": [ "v0.9.4" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/17979", "description": "call `_read()` only once per microtick" } ] }, "signatures": [ { "params": [ { "textRaw": "`size` {number} Number of bytes to read asynchronously", "name": "size", "type": "number", "desc": "Number of bytes to read asynchronously" } ] } ], "desc": "

This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.

\n

All Readable stream implementations must provide an implementation of the\nreadable._read() method to fetch data from the underlying resource.

\n

When readable._read() is called, if data is available from the resource, the\nimplementation should begin pushing that data into the read queue using the\nthis.push(dataChunk) method. _read() should continue reading\nfrom the resource and pushing data until readable.push() returns false. Only\nwhen _read() is called again after it has stopped should it resume pushing\nadditional data onto the queue.

\n

Once the readable._read() method has been called, it will not be called again\nuntil the readable.push() method is called. readable._read()\nis guaranteed to be called only once within a synchronous execution, i.e. a\nmicrotick.

\n

The size argument is advisory. For implementations where a \"read\" is a\nsingle operation that returns data can use the size argument to determine how\nmuch data to fetch. Other implementations may ignore this argument and simply\nprovide data whenever it becomes available. There is no need to \"wait\" until\nsize bytes are available before calling stream.push(chunk).

\n

The readable._read() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

" }, { "textRaw": "readable._destroy(err, callback)", "type": "method", "name": "_destroy", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`err` {Error} A possible error.", "name": "err", "type": "Error", "desc": "A possible error." }, { "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", "name": "callback", "type": "Function", "desc": "A callback function that takes an optional error argument." } ] } ], "desc": "

The _destroy() method is called by readable.destroy().\nIt can be overridden by child classes but it must not be called directly.

" }, { "textRaw": "readable.push(chunk[, encoding])", "type": "method", "name": "push", "meta": { "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11608", "description": "The `chunk` argument can now be a `Uint8Array` instance." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` if additional chunks of data may continue to be pushed; `false` otherwise.", "name": "return", "type": "boolean", "desc": "`true` if additional chunks of data may continue to be pushed; `false` otherwise." }, "params": [ { "textRaw": "`chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value.", "name": "chunk", "type": "Buffer|Uint8Array|string|null|any", "desc": "Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value." }, { "textRaw": "`encoding` {string} Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.", "name": "encoding", "type": "string", "desc": "Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.", "optional": true } ] } ], "desc": "

When chunk is a Buffer, Uint8Array or string, the chunk of data will\nbe added to the internal queue for users of the stream to consume.\nPassing chunk as null signals the end of the stream (EOF), after which no\nmore data can be written.

\n

When the Readable is operating in paused mode, the data added with\nreadable.push() can be read out by calling the\nreadable.read() method when the 'readable' event is\nemitted.

\n

When the Readable is operating in flowing mode, the data added with\nreadable.push() will be delivered by emitting a 'data' event.

\n

The readable.push() method is designed to be as flexible as possible. For\nexample, when wrapping a lower-level source that provides some form of\npause/resume mechanism, and a data callback, the low-level source can be wrapped\nby the custom Readable instance:

\n
// source is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nclass SourceWrapper extends Readable {\n  constructor(options) {\n    super(options);\n\n    this._source = getLowlevelSourceObject();\n\n    // Every time there's data, push it into the internal buffer.\n    this._source.ondata = (chunk) => {\n      // if push() returns false, then stop reading from source\n      if (!this.push(chunk))\n        this._source.readStop();\n    };\n\n    // When the source ends, push the EOF-signaling `null` chunk\n    this._source.onend = () => {\n      this.push(null);\n    };\n  }\n  // _read will be called when the stream wants to pull more data in\n  // the advisory size argument is ignored in this case.\n  _read(size) {\n    this._source.readStart();\n  }\n}\n
\n

The readable.push() method is intended be called only by Readable\nimplementers, and only from within the readable._read() method.

\n

For streams not operating in object mode, if the chunk parameter of\nreadable.push() is undefined, it will be treated as empty string or\nbuffer. See readable.push('') for more information.

" } ], "modules": [ { "textRaw": "Errors While Reading", "name": "errors_while_reading", "desc": "

It is recommended that errors occurring during the processing of the\nreadable._read() method are emitted using the 'error' event rather than\nbeing thrown. Throwing an Error from within readable._read() can result in\nunexpected and inconsistent behavior depending on whether the stream is\noperating in flowing or paused mode. Using the 'error' event ensures\nconsistent and predictable handling of errors.

\n\n
const { Readable } = require('stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    if (checkSomeErrorCondition()) {\n      process.nextTick(() => this.emit('error', err));\n      return;\n    }\n    // do some work\n  }\n});\n
", "type": "module", "displayName": "Errors While Reading" } ], "examples": [ { "textRaw": "An Example Counting Stream", "name": "An Example Counting Stream", "type": "example", "desc": "

The following is a basic example of a Readable stream that emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.

\n
const { Readable } = require('stream');\n\nclass Counter extends Readable {\n  constructor(opt) {\n    super(opt);\n    this._max = 1000000;\n    this._index = 1;\n  }\n\n  _read() {\n    const i = this._index++;\n    if (i > this._max)\n      this.push(null);\n    else {\n      const str = String(i);\n      const buf = Buffer.from(str, 'ascii');\n      this.push(buf);\n    }\n  }\n}\n
" } ], "type": "misc", "displayName": "Implementing a Readable Stream" }, { "textRaw": "Implementing a Duplex Stream", "name": "implementing_a_duplex_stream", "desc": "

A Duplex stream is one that implements both Readable and\nWritable, such as a TCP socket connection.

\n

Because JavaScript does not have support for multiple inheritance, the\nstream.Duplex class is extended to implement a Duplex stream (as opposed\nto extending the stream.Readable and stream.Writable classes).

\n

The stream.Duplex class prototypically inherits from stream.Readable and\nparasitically from stream.Writable, but instanceof will work properly for\nboth base classes due to overriding Symbol.hasInstance on\nstream.Writable.

\n

Custom Duplex streams must call the new stream.Duplex([options])\nconstructor and implement both the readable._read() and\nwritable._write() methods.

", "ctors": [ { "textRaw": "new stream.Duplex(options)", "type": "ctor", "name": "stream.Duplex", "meta": { "changes": [ { "version": "v8.4.0", "pr-url": "https://github.com/nodejs/node/pull/14636", "description": "The `readableHighWaterMark` and `writableHighWaterMark` options are supported now." } ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields:", "name": "options", "type": "Object", "desc": "Passed to both `Writable` and `Readable` constructors. Also has the following fields:", "options": [ { "textRaw": "`allowHalfOpen` {boolean} If set to `false`, then the stream will automatically end the writable side when the readable side ends. **Default:** `true`.", "name": "allowHalfOpen", "type": "boolean", "default": "`true`", "desc": "If set to `false`, then the stream will automatically end the writable side when the readable side ends." }, { "textRaw": "`readableObjectMode` {boolean} Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`. **Default:** `false`.", "name": "readableObjectMode", "type": "boolean", "default": "`false`", "desc": "Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`." }, { "textRaw": "`writableObjectMode` {boolean} Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`. **Default:** `false`.", "name": "writableObjectMode", "type": "boolean", "default": "`false`", "desc": "Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`." }, { "textRaw": "`readableHighWaterMark` {number} Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided.", "name": "readableHighWaterMark", "type": "number", "desc": "Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided." }, { "textRaw": "`writableHighWaterMark` {number} Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided.", "name": "writableHighWaterMark", "type": "number", "desc": "Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided." } ] } ] } ], "desc": "\n
const { Duplex } = require('stream');\n\nclass MyDuplex extends Duplex {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n
\n

Or, when using pre-ES6 style constructors:

\n
const { Duplex } = require('stream');\nconst util = require('util');\n\nfunction MyDuplex(options) {\n  if (!(this instanceof MyDuplex))\n    return new MyDuplex(options);\n  Duplex.call(this, options);\n}\nutil.inherits(MyDuplex, Duplex);\n
\n

Or, using the Simplified Constructor approach:

\n
const { Duplex } = require('stream');\n\nconst myDuplex = new Duplex({\n  read(size) {\n    // ...\n  },\n  write(chunk, encoding, callback) {\n    // ...\n  }\n});\n
" } ], "modules": [ { "textRaw": "An Example Duplex Stream", "name": "an_example_duplex_stream", "desc": "

The following illustrates a simple example of a Duplex stream that wraps a\nhypothetical lower-level source object to which data can be written, and\nfrom which data can be read, albeit using an API that is not compatible with\nNode.js streams.\nThe following illustrates a simple example of a Duplex stream that buffers\nincoming written data via the Writable interface that is read back out\nvia the Readable interface.

\n
const { Duplex } = require('stream');\nconst kSource = Symbol('source');\n\nclass MyDuplex extends Duplex {\n  constructor(source, options) {\n    super(options);\n    this[kSource] = source;\n  }\n\n  _write(chunk, encoding, callback) {\n    // The underlying source only deals with strings\n    if (Buffer.isBuffer(chunk))\n      chunk = chunk.toString();\n    this[kSource].writeSomeData(chunk);\n    callback();\n  }\n\n  _read(size) {\n    this[kSource].fetchSomeData(size, (data, encoding) => {\n      this.push(Buffer.from(data, encoding));\n    });\n  }\n}\n
\n

The most important aspect of a Duplex stream is that the Readable and\nWritable sides operate independently of one another despite co-existing within\na single object instance.

", "type": "module", "displayName": "An Example Duplex Stream" }, { "textRaw": "Object Mode Duplex Streams", "name": "object_mode_duplex_streams", "desc": "

For Duplex streams, objectMode can be set exclusively for either the\nReadable or Writable side using the readableObjectMode and\nwritableObjectMode options respectively.

\n

In the following example, for instance, a new Transform stream (which is a\ntype of Duplex stream) is created that has an object mode Writable side\nthat accepts JavaScript numbers that are converted to hexadecimal strings on\nthe Readable side.

\n
const { Transform } = require('stream');\n\n// All Transform streams are also Duplex Streams\nconst myTransform = new Transform({\n  writableObjectMode: true,\n\n  transform(chunk, encoding, callback) {\n    // Coerce the chunk to a number if necessary\n    chunk |= 0;\n\n    // Transform the chunk into something else.\n    const data = chunk.toString(16);\n\n    // Push the data onto the readable queue.\n    callback(null, '0'.repeat(data.length % 2) + data);\n  }\n});\n\nmyTransform.setEncoding('ascii');\nmyTransform.on('data', (chunk) => console.log(chunk));\n\nmyTransform.write(1);\n// Prints: 01\nmyTransform.write(10);\n// Prints: 0a\nmyTransform.write(100);\n// Prints: 64\n
", "type": "module", "displayName": "Object Mode Duplex Streams" } ], "type": "misc", "displayName": "Implementing a Duplex Stream" }, { "textRaw": "Implementing a Transform Stream", "name": "implementing_a_transform_stream", "desc": "

A Transform stream is a Duplex stream where the output is computed\nin some way from the input. Examples include zlib streams or crypto\nstreams that compress, encrypt, or decrypt data.

\n

There is no requirement that the output be the same size as the input, the same\nnumber of chunks, or arrive at the same time. For example, a Hash stream will\nonly ever have a single chunk of output which is provided when the input is\nended. A zlib stream will produce output that is either much smaller or much\nlarger than its input.

\n

The stream.Transform class is extended to implement a Transform stream.

\n

The stream.Transform class prototypically inherits from stream.Duplex and\nimplements its own versions of the writable._write() and readable._read()\nmethods. Custom Transform implementations must implement the\ntransform._transform() method and may also implement\nthe transform._flush() method.

\n

Care must be taken when using Transform streams in that data written to the\nstream can cause the Writable side of the stream to become paused if the\noutput on the Readable side is not consumed.

", "ctors": [ { "textRaw": "new stream.Transform([options])", "type": "ctor", "name": "stream.Transform", "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields:", "name": "options", "type": "Object", "desc": "Passed to both `Writable` and `Readable` constructors. Also has the following fields:", "options": [ { "textRaw": "`transform` {Function} Implementation for the [`stream._transform()`][stream-_transform] method.", "name": "transform", "type": "Function", "desc": "Implementation for the [`stream._transform()`][stream-_transform] method." }, { "textRaw": "`flush` {Function} Implementation for the [`stream._flush()`][stream-_flush] method.", "name": "flush", "type": "Function", "desc": "Implementation for the [`stream._flush()`][stream-_flush] method." } ], "optional": true } ] } ], "desc": "\n
const { Transform } = require('stream');\n\nclass MyTransform extends Transform {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n
\n

Or, when using pre-ES6 style constructors:

\n
const { Transform } = require('stream');\nconst util = require('util');\n\nfunction MyTransform(options) {\n  if (!(this instanceof MyTransform))\n    return new MyTransform(options);\n  Transform.call(this, options);\n}\nutil.inherits(MyTransform, Transform);\n
\n

Or, using the Simplified Constructor approach:

\n
const { Transform } = require('stream');\n\nconst myTransform = new Transform({\n  transform(chunk, encoding, callback) {\n    // ...\n  }\n});\n
" } ], "modules": [ { "textRaw": "Events: 'finish' and 'end'", "name": "events:_'finish'_and_'end'", "desc": "

The 'finish' and 'end' events are from the stream.Writable\nand stream.Readable classes, respectively. The 'finish' event is emitted\nafter stream.end() is called and all chunks have been processed\nby stream._transform(). The 'end' event is emitted\nafter all data has been output, which occurs after the callback in\ntransform._flush() has been called.

", "type": "module", "displayName": "Events: 'finish' and 'end'" } ], "methods": [ { "textRaw": "transform._flush(callback)", "type": "method", "name": "_flush", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called when remaining data has been flushed.", "name": "callback", "type": "Function", "desc": "A callback function (optionally with an error argument and data) to be called when remaining data has been flushed." } ] } ], "desc": "

This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.

\n

In some cases, a transform operation may need to emit an additional bit of\ndata at the end of the stream. For example, a zlib compression stream will\nstore an amount of internal state used to optimally compress the output. When\nthe stream ends, however, that additional data needs to be flushed so that the\ncompressed data will be complete.

\n

Custom Transform implementations may implement the transform._flush()\nmethod. This will be called when there is no more written data to be consumed,\nbut before the 'end' event is emitted signaling the end of the\nReadable stream.

\n

Within the transform._flush() implementation, the readable.push() method\nmay be called zero or more times, as appropriate. The callback function must\nbe called when the flush operation is complete.

\n

The transform._flush() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.

" }, { "textRaw": "transform._transform(chunk, encoding, callback)", "type": "method", "name": "_transform", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer|string|any} The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write].", "name": "chunk", "type": "Buffer|string|any", "desc": "The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write]." }, { "textRaw": "`encoding` {string} If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value - 'buffer', ignore it in this case.", "name": "encoding", "type": "string", "desc": "If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value - 'buffer', ignore it in this case." }, { "textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called after the supplied `chunk` has been processed.", "name": "callback", "type": "Function", "desc": "A callback function (optionally with an error argument and data) to be called after the supplied `chunk` has been processed." } ] } ], "desc": "

This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.

\n

All Transform stream implementations must provide a _transform()\nmethod to accept input and produce output. The transform._transform()\nimplementation handles the bytes being written, computes an output, then passes\nthat output off to the readable portion using the readable.push() method.

\n

The transform.push() method may be called zero or more times to generate\noutput from a single input chunk, depending on how much is to be output\nas a result of the chunk.

\n

It is possible that no output is generated from any given chunk of input data.

\n

The callback function must be called only when the current chunk is completely\nconsumed. The first argument passed to the callback must be an Error object\nif an error occurred while processing the input or null otherwise. If a second\nargument is passed to the callback, it will be forwarded on to the\nreadable.push() method. In other words, the following are equivalent:

\n
transform.prototype._transform = function(data, encoding, callback) {\n  this.push(data);\n  callback();\n};\n\ntransform.prototype._transform = function(data, encoding, callback) {\n  callback(null, data);\n};\n
\n

The transform._transform() method is prefixed with an underscore because it\nis internal to the class that defines it, and should never be called directly by\nuser programs.

\n

transform._transform() is never called in parallel; streams implement a\nqueue mechanism, and to receive the next chunk, callback must be\ncalled, either synchronously or asynchronously.

" } ], "classes": [ { "textRaw": "Class: stream.PassThrough", "type": "class", "name": "stream.PassThrough", "desc": "

The stream.PassThrough class is a trivial implementation of a Transform\nstream that simply passes the input bytes across to the output. Its purpose is\nprimarily for examples and testing, but there are some use cases where\nstream.PassThrough is useful as a building block for novel sorts of streams.

" } ], "type": "misc", "displayName": "Implementing a Transform Stream" } ] }, { "textRaw": "Additional Notes", "name": "Additional Notes", "type": "misc", "miscs": [ { "textRaw": "Streams Compatibility with Async Generators and Async Iterators", "name": "streams_compatibility_with_async_generators_and_async_iterators", "desc": "

With the support of async generators and iterators in JavaScript, async\ngenerators are effectively a first-class language-level stream construct at\nthis point.

\n

Some common interop cases of using Node.js streams with async generators\nand async iterators are provided below.

", "modules": [ { "textRaw": "Consuming Readable Streams with Async Iterators", "name": "consuming_readable_streams_with_async_iterators", "desc": "
(async function() {\n  for await (const chunk of readable) {\n    console.log(chunk);\n  }\n})();\n
", "type": "module", "displayName": "Consuming Readable Streams with Async Iterators" }, { "textRaw": "Creating Readable Streams with Async Generators", "name": "creating_readable_streams_with_async_generators", "desc": "

We can construct a Node.js Readable Stream from an asynchronous generator\nusing the Readable.from utility method:

\n
const { Readable } = require('stream');\n\nasync function * generate() {\n  yield 'a';\n  yield 'b';\n  yield 'c';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n
", "type": "module", "displayName": "Creating Readable Streams with Async Generators" } ], "miscs": [ { "textRaw": "Piping to Writable Streams from Async Iterators", "name": "Piping to Writable Streams from Async Iterators", "type": "misc", "desc": "

In the scenario of writing to a writeable stream from an async iterator,\nit is important to ensure the correct handling of backpressure and errors.

\n
const { once } = require('events');\n\nconst writeable = fs.createWriteStream('./file');\n\n(async function() {\n  for await (const chunk of iterator) {\n    // Handle backpressure on write\n    if (!writeable.write(value))\n      await once(writeable, 'drain');\n  }\n  writeable.end();\n  // Ensure completion without errors\n  await once(writeable, 'finish');\n})();\n
\n

In the above, errors on the write stream would be caught and thrown by the two\nonce listeners, since once will also handle 'error' events.

\n

Alternatively the readable stream could be wrapped with Readable.from and\nthen piped via .pipe:

\n
const { once } = require('events');\n\nconst writeable = fs.createWriteStream('./file');\n\n(async function() {\n  const readable = Readable.from(iterator);\n  readable.pipe(writeable);\n  // Ensure completion without errors\n  await once(writeable, 'finish');\n})();\n
" } ], "type": "misc", "displayName": "Streams Compatibility with Async Generators and Async Iterators" }, { "textRaw": "Compatibility with Older Node.js Versions", "name": "Compatibility with Older Node.js Versions", "type": "misc", "desc": "

Prior to Node.js 0.10, the Readable stream interface was simpler, but also\nless powerful and less useful.

\n\n

In Node.js 0.10, the Readable class was added. For backward\ncompatibility with older Node.js programs, Readable streams switch into\n\"flowing mode\" when a 'data' event handler is added, or when the\nstream.resume() method is called. The effect is that, even\nwhen not using the new stream.read() method and\n'readable' event, it is no longer necessary to worry about losing\n'data' chunks.

\n

While most applications will continue to function normally, this introduces an\nedge case in the following conditions:

\n\n

For example, consider the following code:

\n
// WARNING!  BROKEN!\nnet.createServer((socket) => {\n\n  // we add an 'end' listener, but never consume the data\n  socket.on('end', () => {\n    // It will never get here.\n    socket.end('The message was received but was not processed.\\n');\n  });\n\n}).listen(1337);\n
\n

Prior to Node.js 0.10, the incoming message data would be simply discarded.\nHowever, in Node.js 0.10 and beyond, the socket remains paused forever.

\n

The workaround in this situation is to call the\nstream.resume() method to begin the flow of data:

\n
// Workaround\nnet.createServer((socket) => {\n  socket.on('end', () => {\n    socket.end('The message was received but was not processed.\\n');\n  });\n\n  // start the flow of data, discarding it.\n  socket.resume();\n}).listen(1337);\n
\n

In addition to new Readable streams switching into flowing mode,\npre-0.10 style streams can be wrapped in a Readable class using the\nreadable.wrap() method.

" }, { "textRaw": "`readable.read(0)`", "name": "`readable.read(0)`", "desc": "

There are some cases where it is necessary to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In such cases, it is possible to call readable.read(0), which will\nalways return null.

\n

If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling stream.read(0) will trigger\na low-level stream._read() call.

\n

While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\nReadable stream class internals.

", "type": "misc", "displayName": "`readable.read(0)`" }, { "textRaw": "`readable.push('')`", "name": "`readable.push('')`", "desc": "

Use of readable.push('') is not recommended.

\n

Pushing a zero-byte string, Buffer or Uint8Array to a stream that is not in\nobject mode has an interesting side effect. Because it is a call to\nreadable.push(), the call will end the reading process.\nHowever, because the argument is an empty string, no data is added to the\nreadable buffer so there is nothing for a user to consume.

", "type": "misc", "displayName": "`readable.push('')`" }, { "textRaw": "`highWaterMark` discrepancy after calling `readable.setEncoding()`", "name": "`highwatermark`_discrepancy_after_calling_`readable.setencoding()`", "desc": "

The use of readable.setEncoding() will change the behavior of how the\nhighWaterMark operates in non-object mode.

\n

Typically, the size of the current buffer is measured against the\nhighWaterMark in bytes. However, after setEncoding() is called, the\ncomparison function will begin to measure the buffer's size in characters.

\n

This is not a problem in common cases with latin1 or ascii. But it is\nadvised to be mindful about this behavior when working with strings that could\ncontain multi-byte characters.

", "type": "misc", "displayName": "`highWaterMark` discrepancy after calling `readable.setEncoding()`" } ] } ], "type": "module", "displayName": "Stream" } ] }