{"$schema":"https://doc-kit.nodejs.org/schemas/api-doc/1.0.0.json","id":"stream","path":"/stream","type":"module","module":"stream","title":"Stream","introducedIn":"v0.10.0","sourceLink":{"path":"lib/stream.js","url":"https://github.com/nodejs/node/blob/HEAD/lib/stream.js"},"stability":{"index":"2","description":"Stable"},"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"A stream is an abstract interface for working with streaming data in Node.js.\nThe `node:stream` module provides an API for implementing the stream interface.\n\nThere are many stream objects provided by Node.js. For instance, a\n[request to an HTTP server](http.html#class-httpincomingmessage) and [`process.stdout`](process.html#processstdout)\nare both stream instances.\n\nStreams can be readable, writable, or both. All streams are instances of\n[`EventEmitter`](events.html#class-eventemitter).\n\nTo access the `node:stream` module:\n\n```js\nconst stream = require('node:stream');\n```\n\nThe `node:stream` module is useful for creating new types of stream instances.\nIt is usually not necessary to use the `node:stream` module to consume streams.","summary":"A stream is an abstract interface for working with streaming data in Node.js. The `node:stream` module provides an API for implementing the stream interface.","examples":[{"language":"js","displayName":null,"code":"const stream = require('node:stream');"}],"children":[{"kind":"section","id":"organization-of-this-document","name":"Organization of this document","title":"Organization of this document","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"This document contains two primary sections and a third section for notes. The\nfirst section explains how to use existing streams within an application. The\nsecond section explains how to create new types of streams.","summary":"This document contains two primary sections and a third section for notes. The first section explains how to use existing streams within an application. The second section explains how to create new types of streams.","examples":[],"children":[]},{"kind":"section","id":"types-of-streams","name":"Types of streams","title":"Types of streams","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"There are four fundamental stream types within Node.js:\n\n* [`Writable`](#class-streamwritable): streams to which data can be written (for example,\n  [`fs.createWriteStream()`](fs.html#fscreatewritestreampath-options)).\n* [`Readable`](#class-streamreadable): streams from which data can be read (for example,\n  [`fs.createReadStream()`](fs.html#fscreatereadstreampath-options)).\n* [`Duplex`](#class-streamduplex): streams that are both `Readable` and `Writable` (for example,\n  [`net.Socket`](net.html#class-netsocket)).\n* [`Transform`](#class-streamtransform): `Duplex` streams that can modify or transform the data as it\n  is written and read (for example, [`zlib.createDeflate()`](zlib.html#zlibcreatedeflateoptions)).\n\nAdditionally, this module includes the utility functions\n[`stream.duplexPair()`](#streamduplexpairoptions),\n[`stream.pipeline()`](#streampipelinesource-transforms-destination-callback),\n[`stream.finished()`](#streamfinishedstream-options-callback)\n[`stream.Readable.from()`](#streamreadablefromiterable-options), and\n[`stream.addAbortSignal()`](#streamaddabortsignalsignal-stream).","summary":"There are four fundamental stream types within Node.js:","examples":[],"children":[{"kind":"section","id":"streams-promises-api","name":"Streams Promises API","title":"Streams Promises API","scope":"module","overloadOf":null,"stability":null,"added":["v15.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `stream/promises` API provides an alternative set of asynchronous utility\nfunctions for streams that return `Promise` objects rather than using\ncallbacks. The API is accessible via `require('node:stream/promises')`\nor `require('node:stream').promises`.","summary":"The `stream/promises` API provides an alternative set of asynchronous utility functions for streams that return `Promise` objects rather than using callbacks. The API is accessible via `require('node:stream/promises')` or `require('node:stream').promises`.","examples":[],"children":[]},{"kind":"method","id":"streampipelinestreams-options","name":"pipeline","title":"`stream.pipeline(streams[, options])`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"streams","type":null,"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":null,"description":"","default":null,"optional":true,"rest":false,"properties":[]}],"returns":null},"description":"","summary":"","examples":[],"children":[]},{"kind":"method","id":"streampipelinesource-transforms-destination-options","name":"pipeline","title":"`stream.pipeline(source[, ...transforms], destination[, options])`","scope":"module","overloadOf":"streampipelinestreams-options","stability":null,"added":["v15.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v19.7.0","v18.16.0"],"prUrl":"https://github.com/nodejs/node/pull/46307","commit":null,"description":"Added support for webstreams."},{"versions":["v18.0.0","v17.2.0","v16.14.0"],"prUrl":"https://github.com/nodejs/node/pull/40886","commit":null,"description":"Add the `end` option, which can be set to `false` to prevent automatically closing the destination stream when the source ends."}],"signature":{"parameters":[{"name":"source","type":{"text":"Stream | Iterable | AsyncIterable | Function | ReadableStream","links":[{"name":"Stream","href":"stream.html#stream","start":0,"end":6},{"name":"Iterable","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol","start":9,"end":17},{"name":"AsyncIterable","href":"https://tc39.github.io/ecma262/#sec-asynciterable-interface","start":20,"end":33},{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":36,"end":44},{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":47,"end":61}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"","type":{"text":"Promise | AsyncIterable","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7},{"name":"AsyncIterable","href":"https://tc39.github.io/ecma262/#sec-asynciterable-interface","start":10,"end":23}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]},{"name":"transforms","type":{"text":"Stream | Function | TransformStream","links":[{"name":"Stream","href":"stream.html#stream","start":0,"end":6},{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":9,"end":17},{"name":"TransformStream","href":"webstreams.html#class-transformstream","start":20,"end":35}]},"description":"","default":null,"optional":true,"rest":true,"properties":[{"name":"source","type":{"text":"AsyncIterable","links":[{"name":"AsyncIterable","href":"https://tc39.github.io/ecma262/#sec-asynciterable-interface","start":0,"end":13}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"","type":{"text":"Promise | AsyncIterable","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7},{"name":"AsyncIterable","href":"https://tc39.github.io/ecma262/#sec-asynciterable-interface","start":10,"end":23}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]},{"name":"destination","type":{"text":"Stream | Function | WritableStream","links":[{"name":"Stream","href":"stream.html#stream","start":0,"end":6},{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":9,"end":17},{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":20,"end":34}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"source","type":{"text":"AsyncIterable","links":[{"name":"AsyncIterable","href":"https://tc39.github.io/ecma262/#sec-asynciterable-interface","start":0,"end":13}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"","type":{"text":"Promise | AsyncIterable","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7},{"name":"AsyncIterable","href":"https://tc39.github.io/ecma262/#sec-asynciterable-interface","start":10,"end":23}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"Pipeline options","default":null,"optional":true,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"end","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"End the destination stream when the source stream ends.\nTransform streams are always ended, even if this value is `false`.","default":"true","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"Fulfills when the pipeline is complete."}},"description":"```cjs\nconst { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\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```\n\n```mjs\nimport { pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { createGzip } from 'node:zlib';\n\nawait pipeline(\n  createReadStream('archive.tar'),\n  createGzip(),\n  createWriteStream('archive.tar.gz'),\n);\nconsole.log('Pipeline succeeded.');\n```\n\nTo use an `AbortSignal`, pass it inside an options object, as the last argument.\nWhen the signal is aborted, `destroy` will be called on the underlying pipeline,\nwith an `AbortError`.\n\n```cjs\nconst { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\nasync function run() {\n  const ac = new AbortController();\n  const signal = ac.signal;\n\n  setImmediate(() => ac.abort());\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz'),\n    { signal },\n  );\n}\n\nrun().catch(console.error); // AbortError\n```\n\n```mjs\nimport { pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { createGzip } from 'node:zlib';\n\nconst ac = new AbortController();\nconst { signal } = ac;\nsetImmediate(() => ac.abort());\ntry {\n  await pipeline(\n    createReadStream('archive.tar'),\n    createGzip(),\n    createWriteStream('archive.tar.gz'),\n    { signal },\n  );\n} catch (err) {\n  console.error(err); // AbortError\n}\n```\n\nThe `pipeline` API also supports async generators:\n\n```cjs\nconst { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('lowercase.txt'),\n    async function* (source, { signal }) {\n      source.setEncoding('utf8');  // Work with strings rather than `Buffer`s.\n      for await (const chunk of source) {\n        yield await processChunk(chunk, { signal });\n      }\n    },\n    fs.createWriteStream('uppercase.txt'),\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n```\n\n```mjs\nimport { pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\n\nawait pipeline(\n  createReadStream('lowercase.txt'),\n  async function* (source, { signal }) {\n    source.setEncoding('utf8');  // Work with strings rather than `Buffer`s.\n    for await (const chunk of source) {\n      yield await processChunk(chunk, { signal });\n    }\n  },\n  createWriteStream('uppercase.txt'),\n);\nconsole.log('Pipeline succeeded.');\n```\n\nRemember to handle the `signal` argument passed into the async generator.\nEspecially in the case where the async generator is the source for the\npipeline (i.e. first argument) or the pipeline will never complete.\n\n```cjs\nconst { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\n\nasync function run() {\n  await pipeline(\n    async function* ({ signal }) {\n      await someLongRunningfn({ signal });\n      yield 'asd';\n    },\n    fs.createWriteStream('uppercase.txt'),\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n```\n\n```mjs\nimport { pipeline } from 'node:stream/promises';\nimport fs from 'node:fs';\nawait pipeline(\n  async function* ({ signal }) {\n    await someLongRunningfn({ signal });\n    yield 'asd';\n  },\n  fs.createWriteStream('uppercase.txt'),\n);\nconsole.log('Pipeline succeeded.');\n```\n\nThe `pipeline` API provides [callback version](#streampipelinesource-transforms-destination-callback):","summary":"To use an `AbortSignal`, pass it inside an options object, as the last argument. When the signal is aborted, `destroy` will be called on the underlying pipeline, with an `AbortError`.","examples":[{"language":"cjs","displayName":null,"code":"const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\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);"},{"language":"mjs","displayName":null,"code":"import { pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { createGzip } from 'node:zlib';\n\nawait pipeline(\n  createReadStream('archive.tar'),\n  createGzip(),\n  createWriteStream('archive.tar.gz'),\n);\nconsole.log('Pipeline succeeded.');"},{"language":"cjs","displayName":null,"code":"const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\nasync function run() {\n  const ac = new AbortController();\n  const signal = ac.signal;\n\n  setImmediate(() => ac.abort());\n  await pipeline(\n    fs.createReadStream('archive.tar'),\n    zlib.createGzip(),\n    fs.createWriteStream('archive.tar.gz'),\n    { signal },\n  );\n}\n\nrun().catch(console.error); // AbortError"},{"language":"mjs","displayName":null,"code":"import { pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { createGzip } from 'node:zlib';\n\nconst ac = new AbortController();\nconst { signal } = ac;\nsetImmediate(() => ac.abort());\ntry {\n  await pipeline(\n    createReadStream('archive.tar'),\n    createGzip(),\n    createWriteStream('archive.tar.gz'),\n    { signal },\n  );\n} catch (err) {\n  console.error(err); // AbortError\n}"},{"language":"cjs","displayName":null,"code":"const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\n\nasync function run() {\n  await pipeline(\n    fs.createReadStream('lowercase.txt'),\n    async function* (source, { signal }) {\n      source.setEncoding('utf8');  // Work with strings rather than `Buffer`s.\n      for await (const chunk of source) {\n        yield await processChunk(chunk, { signal });\n      }\n    },\n    fs.createWriteStream('uppercase.txt'),\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);"},{"language":"mjs","displayName":null,"code":"import { pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\n\nawait pipeline(\n  createReadStream('lowercase.txt'),\n  async function* (source, { signal }) {\n    source.setEncoding('utf8');  // Work with strings rather than `Buffer`s.\n    for await (const chunk of source) {\n      yield await processChunk(chunk, { signal });\n    }\n  },\n  createWriteStream('uppercase.txt'),\n);\nconsole.log('Pipeline succeeded.');"},{"language":"cjs","displayName":null,"code":"const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\n\nasync function run() {\n  await pipeline(\n    async function* ({ signal }) {\n      await someLongRunningfn({ signal });\n      yield 'asd';\n    },\n    fs.createWriteStream('uppercase.txt'),\n  );\n  console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);"},{"language":"mjs","displayName":null,"code":"import { pipeline } from 'node:stream/promises';\nimport fs from 'node:fs';\nawait pipeline(\n  async function* ({ signal }) {\n    await someLongRunningfn({ signal });\n    yield 'asd';\n  },\n  fs.createWriteStream('uppercase.txt'),\n);\nconsole.log('Pipeline succeeded.');"}],"children":[]},{"kind":"method","id":"streamfinishedstream-options","name":"finished","title":"`stream.finished(stream[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v15.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v19.5.0","v18.14.0"],"prUrl":"https://github.com/nodejs/node/pull/46205","commit":null,"description":"Added support for `ReadableStream` and `WritableStream`."},{"versions":["v19.1.0","v18.13.0"],"prUrl":"https://github.com/nodejs/node/pull/44862","commit":null,"description":"The `cleanup` option was added."}],"signature":{"parameters":[{"name":"stream","type":{"text":"Stream | ReadableStream | WritableStream","links":[{"name":"Stream","href":"stream.html#stream","start":0,"end":6},{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":9,"end":23},{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":26,"end":40}]},"description":"A readable and/or writable\nstream/webstream.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"error","type":{"text":"boolean | undefined","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":10,"end":19}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"readable","type":{"text":"boolean | undefined","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":10,"end":19}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"writable","type":{"text":"boolean | undefined","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":10,"end":19}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal | undefined","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":14,"end":23}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"cleanup","type":{"text":"boolean | undefined","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7},{"name":"undefined","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type","start":10,"end":19}]},"description":"If `true`, removes the listeners registered by\nthis function before the promise is fulfilled.","default":"false","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"Fulfills when the stream is no\nlonger readable or writable."}},"description":"```cjs\nconst { finished } = require('node:stream/promises');\nconst fs = require('node:fs');\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```\n\n```mjs\nimport { finished } from 'node:stream/promises';\nimport { createReadStream } from 'node:fs';\n\nconst rs = 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```\n\nThe `finished` API also provides a [callback version](#streamfinishedstream-options-callback).\n\n`stream.finished()` leaves dangling event listeners (in particular\n`'error'`, `'end'`, `'finish'` and `'close'`) after the returned promise is\nresolved or rejected. The reason for this is so that unexpected `'error'`\nevents (due to incorrect stream implementations) do not cause unexpected\ncrashes. If this is unwanted behavior then `options.cleanup` should be set to\n`true`:\n\n```mjs\nawait finished(rs, { cleanup: true });\n```","summary":"The `finished` API also provides a callback version.","examples":[{"language":"cjs","displayName":null,"code":"const { finished } = require('node:stream/promises');\nconst fs = require('node:fs');\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."},{"language":"mjs","displayName":null,"code":"import { finished } from 'node:stream/promises';\nimport { createReadStream } from 'node:fs';\n\nconst rs = 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."},{"language":"mjs","displayName":null,"code":"await finished(rs, { cleanup: true });"}],"children":[]},{"kind":"section","id":"object-mode","name":"Object mode","title":"Object mode","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"All streams created by Node.js APIs operate exclusively on strings, {Buffer},\n{TypedArray} and {DataView} objects:\n\n* `Strings` and `Buffers` are the most common types used with streams.\n* `TypedArray` and `DataView` lets you handle binary data with types like\n  `Int32Array` or `Uint8Array`. When you write a TypedArray or DataView to a\n  stream, Node.js processes\n  the raw bytes.\n\nIt is possible, however, for stream\nimplementations to work with other types of JavaScript values (with the\nexception of `null`, which serves a special purpose within streams).\nSuch streams are considered to operate in \"object mode\".\n\nStream 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.","summary":"All streams created by Node.js APIs operate exclusively on strings, {Buffer}, {TypedArray} and {DataView} objects:","examples":[],"children":[]},{"kind":"section","id":"buffering","name":"Buffering","title":"Buffering","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Both [`Writable`](#class-streamwritable) and [`Readable`](#class-streamreadable) streams will store data in an internal\nbuffer.\n\nThe 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](#highwatermark-discrepancy-after-calling-readablesetencoding). For streams operating\nin object mode, the `highWaterMark` specifies a total number of objects. For\nstreams operating on (but not decoding) strings, the `highWaterMark` specifies\na total number of UTF-16 code units.\n\nData is buffered in `Readable` streams when the implementation calls\n[`stream.push(chunk)`](#readablepushchunk-encoding). If the consumer of the Stream does not\ncall [`stream.read()`](#readablereadsize), the data will sit in the internal\nqueue until it is consumed.\n\nOnce 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()`](#readable_readsize) method that is\nused to fill the read buffer).\n\nData is buffered in `Writable` streams when the\n[`writable.write(chunk)`](#writablewritechunk-encoding-callback) method is called repeatedly. While the\ntotal size of the internal write buffer is below the threshold set by\n`highWaterMark`, calls to `writable.write()` will return `true`. Once\nthe size of the internal buffer reaches or exceeds the `highWaterMark`, `false`\nwill be returned.\n\nA key goal of the `stream` API, particularly the [`stream.pipe()`](#readablepipedestination-options) 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\nThe `highWaterMark` option is a threshold, not a limit: it dictates the amount\nof data that a stream buffers before it stops asking for more data. It does not\nenforce a strict memory limitation in general. Specific stream implementations\nmay choose to enforce stricter limits but doing so is optional.\n\nBecause [`Duplex`](#class-streamduplex) and [`Transform`](#class-streamtransform) streams are both `Readable` and\n`Writable`, 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,\n[`net.Socket`](net.html#class-netsocket) instances are [`Duplex`](#class-streamduplex) 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, each side should\noperate (and buffer) independently of the other.\n\nThe mechanics of the internal buffering are an internal implementation detail\nand may be changed at any time. However, for certain advanced implementations,\nthe internal buffers can be retrieved using `writable.writableBuffer` or\n`readable.readableBuffer`. Use of these undocumented properties is discouraged.","summary":"Both `Writable` and `Readable` streams will store data in an internal buffer.","examples":[],"children":[]}]},{"kind":"section","id":"api-for-stream-consumers","name":"API for stream consumers","title":"API for stream consumers","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"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\n```js\nconst http = require('node: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', \"not json\" is not valid JSON\n```\n\n[`Writable`](#class-streamwritable) streams (such as `res` in the example) expose methods such as\n`write()` and `end()` that are used to write data onto the stream.\n\n[`Readable`](#class-streamreadable) streams use the [`EventEmitter`](events.html#class-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\nBoth [`Writable`](#class-streamwritable) and [`Readable`](#class-streamreadable) streams use the [`EventEmitter`](events.html#class-eventemitter) API in\nvarious ways to communicate the current state of the stream.\n\n[`Duplex`](#class-streamduplex) and [`Transform`](#class-streamtransform) streams are both [`Writable`](#class-streamwritable) and\n[`Readable`](#class-streamreadable).\n\nApplications 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('node:stream')`.\n\nDevelopers wishing to implement new types of streams should refer to the\nsection [API for stream implementers](#api-for-stream-implementers).","summary":"Almost all Node.js applications, no matter how simple, use streams in some manner. The following is an example of using streams in a Node.js application that implements an HTTP server:","examples":[{"language":"js","displayName":null,"code":"const http = require('node: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', \"not json\" is not valid JSON"}],"children":[{"kind":"section","id":"writable-streams","name":"Writable streams","title":"Writable streams","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Writable streams are an abstraction for a *destination* to which data is\nwritten.\n\nExamples of [`Writable`](#class-streamwritable) streams include:\n\n* [HTTP requests, on the client](http.html#class-httpclientrequest)\n* [HTTP responses, on the server](http.html#class-httpserverresponse)\n* [fs write streams](fs.html#class-fswritestream)\n* [zlib streams](zlib.html)\n* [crypto streams](crypto.html)\n* [TCP sockets](net.html#class-netsocket)\n* [child process stdin](child_process.html#subprocessstdin)\n* [`process.stdout`](process.html#processstdout), [`process.stderr`](process.html#processstderr)\n\nSome of these examples are actually [`Duplex`](#class-streamduplex) streams that implement the\n[`Writable`](#class-streamwritable) interface.\n\nAll [`Writable`](#class-streamwritable) streams implement the interface defined by the\n`stream.Writable` class.\n\nWhile specific instances of [`Writable`](#class-streamwritable) streams may differ in various ways,\nall `Writable` streams follow the same fundamental usage pattern as illustrated\nin the example below:\n\n```js\nconst myStream = getWritableStreamSomehow();\nmyStream.write('some data');\nmyStream.write('some more data');\nmyStream.end('done writing data');\n```","summary":"Writable streams are an abstraction for a _destination_ to which data is written.","examples":[{"language":"js","displayName":null,"code":"const myStream = getWritableStreamSomehow();\nmyStream.write('some data');\nmyStream.write('some more data');\nmyStream.end('done writing data');"}],"children":[{"kind":"class","id":"class-streamwritable","name":"Writable","title":"Class: `stream.Writable`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"","summary":"","examples":[],"children":[{"kind":"event","id":"event-close","name":"close","title":"Event: `'close'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/18438","commit":null,"description":"Add `emitClose` option to specify if `'close'` is emitted on destroy."}],"parameters":[],"description":"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\nA [`Writable`](#class-streamwritable) stream will always emit the `'close'` event if it is\ncreated with the `emitClose` option.","summary":"The `'close'` event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates that no more events will be emitted, and no further computation will occur.","examples":[],"children":[]},{"kind":"event","id":"event-drain","name":"drain","title":"Event: `'drain'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"If a call to [`stream.write(chunk)`](#writablewritechunk-encoding-callback) returns `false`, the\n`'drain'` event will be emitted when it is appropriate to resume writing data\nto the stream.\n\n```js\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```","summary":"If a call to `stream.write(chunk)` returns `false`, the `'drain'` event will be emitted when it is appropriate to resume writing data to the stream.","examples":[{"language":"js","displayName":null,"code":"// 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}"}],"children":[]},{"kind":"event","id":"event-error","name":"error","title":"Event: `'error'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"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\nThe stream is closed when the `'error'` event is emitted unless the\n[`autoDestroy`](#new-streamwritableoptions) option was set to `false` when creating the\nstream.\n\nAfter `'error'`, no further events other than `'close'` *should* be emitted\n(including `'error'` events).","summary":"The `'error'` event is emitted if an error occurred while writing or piping data. The listener callback is passed a single `Error` argument when called.","examples":[],"children":[]},{"kind":"event","id":"event-finish","name":"finish","title":"Event: `'finish'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"The `'finish'` event is emitted after the [`stream.end()`](#writableendchunk-encoding-callback) method\nhas been called, and all data has been flushed to the underlying system.\n\n```js\nconst writer = getWritableStreamSomehow();\nfor (let i = 0; i < 100; i++) {\n  writer.write(`hello, #${i}!\\n`);\n}\nwriter.on('finish', () => {\n  console.log('All writes are now complete.');\n});\nwriter.end('This is the end\\n');\n```","summary":"The `'finish'` event is emitted after the `stream.end()` method has been called, and all data has been flushed to the underlying system.","examples":[{"language":"js","displayName":null,"code":"const writer = getWritableStreamSomehow();\nfor (let i = 0; i < 100; i++) {\n  writer.write(`hello, #${i}!\\n`);\n}\nwriter.on('finish', () => {\n  console.log('All writes are now complete.');\n});\nwriter.end('This is the end\\n');"}],"children":[]},{"kind":"event","id":"event-pipe","name":"pipe","title":"Event: `'pipe'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"src","type":{"text":"stream.Readable","links":[{"name":"stream.Readable","href":"stream.html#class-streamreadable","start":0,"end":15}]},"description":"source stream that is piping to this writable","default":null,"optional":false,"rest":false,"properties":[]}],"description":"The `'pipe'` event is emitted when the [`stream.pipe()`](#readablepipedestination-options) method is called on\na readable stream, adding this writable to its set of destinations.\n\n```js\nconst 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```","summary":"The `'pipe'` event is emitted when the `stream.pipe()` method is called on a readable stream, adding this writable to its set of destinations.","examples":[{"language":"js","displayName":null,"code":"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);"}],"children":[]},{"kind":"event","id":"event-unpipe","name":"unpipe","title":"Event: `'unpipe'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"src","type":{"text":"stream.Readable","links":[{"name":"stream.Readable","href":"stream.html#class-streamreadable","start":0,"end":15}]},"description":"The source stream that\n[unpiped](#readableunpipedestination) this writable","default":null,"optional":false,"rest":false,"properties":[]}],"description":"The `'unpipe'` event is emitted when the [`stream.unpipe()`](#readableunpipedestination) method is called\non a [`Readable`](#class-streamreadable) stream, removing this [`Writable`](#class-streamwritable) from its set of\ndestinations.\n\nThis is also emitted in case this [`Writable`](#class-streamwritable) stream emits an error when a\n[`Readable`](#class-streamreadable) stream pipes into it.\n\n```js\nconst 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```","summary":"The `'unpipe'` event is emitted when the `stream.unpipe()` method is called on a `Readable` stream, removing this `Writable` from its set of destinations.","examples":[{"language":"js","displayName":null,"code":"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);"}],"children":[]},{"kind":"method","id":"writablecork","name":"cork","title":"`writable.cork()`","scope":"module","overloadOf":null,"stability":null,"added":["v0.11.2"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"The `writable.cork()` method forces all written data to be buffered in memory.\nThe buffered data will be flushed when either the [`stream.uncork()`](#writableuncork) or\n[`stream.end()`](#writableendchunk-encoding-callback) methods are called.\n\nThe primary intent of `writable.cork()` is to accommodate a situation in which\nseveral small chunks are written to the stream in rapid succession. Instead of\nimmediately forwarding them to the underlying destination, `writable.cork()`\nbuffers all the chunks until `writable.uncork()` is called, which will pass them\nall to `writable._writev()`, if present. This prevents a head-of-line blocking\nsituation where data is being buffered while waiting for the first small chunk\nto be processed. However, use of `writable.cork()` without implementing\n`writable._writev()` may have an adverse effect on throughput.\n\nSee also: [`writable.uncork()`](#writableuncork), [`writable._writev()`](#writable_writevchunks-callback).","summary":"The `writable.cork()` method forces all written data to be buffered in memory. The buffered data will be flushed when either the `stream.uncork()` or `stream.end()` methods are called.","examples":[],"children":[]},{"kind":"method","id":"writabledestroyerror","name":"destroy","title":"`writable.destroy([error])`","scope":"module","overloadOf":null,"stability":null,"added":["v8.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v14.0.0"],"prUrl":"https://github.com/nodejs/node/pull/29197","commit":null,"description":"Work as a no-op on a stream that has already been destroyed."}],"signature":{"parameters":[{"name":"error","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"Optional, an error to emit with `'error'` event.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"this","links":[{"name":"this","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this","start":0,"end":4}]},"description":""}},"description":"Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`\nevent (unless `emitClose` is set to `false`). After this call, the writable\nstream has ended and subsequent calls to `write()` or `end()` will result in\nan `ERR_STREAM_DESTROYED` error.\nThis is a destructive and immediate way to destroy a stream. Previous calls to\n`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error.\nUse `end()` instead of destroy if data should flush before close, or wait for\nthe `'drain'` event before destroying the stream.\n\n```cjs\nconst { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nconst fooErr = new Error('foo error');\nmyStream.destroy(fooErr);\nmyStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error\n```\n\n```cjs\nconst { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nmyStream.destroy();\nmyStream.on('error', function wontHappen() {});\n```\n\n```cjs\nconst { Writable } = require('node:stream');\n\nconst myStream = new Writable();\nmyStream.destroy();\n\nmyStream.write('foo', (error) => console.error(error.code));\n// ERR_STREAM_DESTROYED\n```\n\nOnce `destroy()` has been called any further calls will be a no-op and no\nfurther errors except from `_destroy()` may be emitted as `'error'`.\n\nImplementors should not override this method,\nbut instead implement [`writable._destroy()`](#writable_destroyerr-callback).","summary":"Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable stream has ended and subsequent calls to `write()` or `end()` will result in an `ERR_STREAM_DESTROYED` error. This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. Use `end()` instead of destroy if data should flush before close, or wait for the `'drain'` event before destroying the stream.","examples":[{"language":"cjs","displayName":null,"code":"const { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nconst fooErr = new Error('foo error');\nmyStream.destroy(fooErr);\nmyStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error"},{"language":"cjs","displayName":null,"code":"const { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nmyStream.destroy();\nmyStream.on('error', function wontHappen() {});"},{"language":"cjs","displayName":null,"code":"const { Writable } = require('node:stream');\n\nconst myStream = new Writable();\nmyStream.destroy();\n\nmyStream.write('foo', (error) => console.error(error.code));\n// ERR_STREAM_DESTROYED"}],"children":[]},{"kind":"property","id":"writableclosed","name":"closed","title":"`writable.closed`","scope":"module","overloadOf":null,"stability":null,"added":["v18.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is `true` after `'close'` has been emitted.","summary":"Is `true` after `'close'` has been emitted.","examples":[],"children":[]},{"kind":"property","id":"writabledestroyed","name":"destroyed","title":"`writable.destroyed`","scope":"module","overloadOf":null,"stability":null,"added":["v8.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is `true` after [`writable.destroy()`](#writabledestroyerror) has been called.\n\n```cjs\nconst { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nconsole.log(myStream.destroyed); // false\nmyStream.destroy();\nconsole.log(myStream.destroyed); // true\n```","summary":"Is `true` after `writable.destroy()` has been called.","examples":[{"language":"cjs","displayName":null,"code":"const { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nconsole.log(myStream.destroyed); // false\nmyStream.destroy();\nconsole.log(myStream.destroyed); // true"}],"children":[]},{"kind":"method","id":"writableendchunk-encoding-callback","name":"end","title":"`writable.end([chunk[, encoding]][, callback])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v22.0.0","v20.13.0"],"prUrl":"https://github.com/nodejs/node/pull/51866","commit":null,"description":"The `chunk` argument can now be a `TypedArray` or `DataView` instance."},{"versions":["v15.0.0"],"prUrl":"https://github.com/nodejs/node/pull/34101","commit":null,"description":"The `callback` is invoked before 'finish' or on error."},{"versions":["v14.0.0"],"prUrl":"https://github.com/nodejs/node/pull/29747","commit":null,"description":"The `callback` is invoked if 'finish' or 'error' is emitted."},{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/18780","commit":null,"description":"This method now returns a reference to `writable`."},{"versions":["v8.0.0"],"prUrl":"https://github.com/nodejs/node/pull/11608","commit":null,"description":"The `chunk` argument can now be a `Uint8Array` instance."}],"signature":{"parameters":[{"name":"chunk","type":{"text":"string | Buffer | TypedArray | DataView | any","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6},{"name":"Buffer","href":"buffer.html#class-buffer","start":9,"end":15},{"name":"TypedArray","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray","start":18,"end":28},{"name":"DataView","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DataView","start":31,"end":39},{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":42,"end":45}]},"description":"Optional data to write. For\nstreams not operating in object mode, `chunk` must be a {string}, {Buffer},\n{TypedArray} or {DataView}. For object mode streams, `chunk` may be any\nJavaScript value other than `null`.","default":null,"optional":true,"rest":false,"properties":[]},{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The encoding if `chunk` is a string","default":null,"optional":true,"rest":false,"properties":[]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Callback for when the stream is finished.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"this","links":[{"name":"this","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this","start":0,"end":4}]},"description":""}},"description":"Calling the `writable.end()` method signals that no more data will be written\nto the [`Writable`](#class-streamwritable). The optional `chunk` and `encoding` arguments allow one\nfinal additional chunk of data to be written immediately before closing the\nstream.\n\nCalling the [`stream.write()`](#writablewritechunk-encoding-callback) method after calling\n[`stream.end()`](#writableendchunk-encoding-callback) will raise an error.\n\n```js\n// Write 'hello, ' and then end with 'world!'.\nconst fs = require('node:fs');\nconst file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// Writing more now is not allowed!\n```","summary":"Calling the `writable.end()` method signals that no more data will be written to the `Writable`. The optional `chunk` and `encoding` arguments allow one final additional chunk of data to be written immediately before closing the stream.","examples":[{"language":"js","displayName":null,"code":"// Write 'hello, ' and then end with 'world!'.\nconst fs = require('node:fs');\nconst file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// Writing more now is not allowed!"}],"children":[]},{"kind":"method","id":"writablesetdefaultencodingencoding","name":"setDefaultEncoding","title":"`writable.setDefaultEncoding(encoding)`","scope":"module","overloadOf":null,"stability":null,"added":["v0.11.15"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v6.1.0"],"prUrl":"https://github.com/nodejs/node/pull/5040","commit":null,"description":"This method now returns a reference to `writable`."}],"signature":{"parameters":[{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The new default encoding","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"this","links":[{"name":"this","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this","start":0,"end":4}]},"description":""}},"description":"The `writable.setDefaultEncoding()` method sets the default `encoding` for a\n[`Writable`](#class-streamwritable) stream.","summary":"The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream.","examples":[],"children":[]},{"kind":"method","id":"writableuncork","name":"uncork","title":"`writable.uncork()`","scope":"module","overloadOf":null,"stability":null,"added":["v0.11.2"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":null},"description":"The `writable.uncork()` method flushes all data buffered since\n[`stream.cork()`](#writablecork) was called.\n\nWhen using [`writable.cork()`](#writablecork) and `writable.uncork()` to manage the buffering\nof writes to a stream, defer calls to `writable.uncork()` using\n`process.nextTick()`. Doing so allows batching of all\n`writable.write()` calls that occur within a given Node.js event loop phase.\n\n```js\nstream.cork();\nstream.write('some ');\nstream.write('data ');\nprocess.nextTick(() => stream.uncork());\n```\n\nIf the [`writable.cork()`](#writablecork) 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\n```js\nstream.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\nSee also: [`writable.cork()`](#writablecork).","summary":"The `writable.uncork()` method flushes all data buffered since `stream.cork()` was called.","examples":[{"language":"js","displayName":null,"code":"stream.cork();\nstream.write('some ');\nstream.write('data ');\nprocess.nextTick(() => stream.uncork());"},{"language":"js","displayName":null,"code":"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});"}],"children":[]},{"kind":"property","id":"writablewritable","name":"writable","title":"`writable.writable`","scope":"module","overloadOf":null,"stability":null,"added":["v11.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is `true` if it is safe to call [`writable.write()`](#writablewritechunk-encoding-callback), which means\nthe stream has not been destroyed, errored, or ended.","summary":"Is `true` if it is safe to call `writable.write()`, which means the stream has not been destroyed, errored, or ended.","examples":[],"children":[]},{"kind":"property","id":"writablewritableaborted","name":"writableAborted","title":"`writable.writableAborted`","scope":"module","overloadOf":null,"stability":null,"added":["v18.0.0","v16.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Returns whether the stream was destroyed or errored before emitting `'finish'`.","summary":"Returns whether the stream was destroyed or errored before emitting `'finish'`.","examples":[],"children":[]},{"kind":"property","id":"writablewritableended","name":"writableEnded","title":"`writable.writableEnded`","scope":"module","overloadOf":null,"stability":null,"added":["v12.9.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is `true` after [`writable.end()`](#writableendchunk-encoding-callback) has been called. This property\ndoes not indicate whether the data has been flushed, for this use\n[`writable.writableFinished`](#writablewritablefinished) instead.","summary":"Is `true` after `writable.end()` has been called. This property does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead.","examples":[],"children":[]},{"kind":"property","id":"writablewritablecorked","name":"writableCorked","title":"`writable.writableCorked`","scope":"module","overloadOf":null,"stability":null,"added":["v13.2.0","v12.16.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"default":null,"description":"Number of times [`writable.uncork()`](#writableuncork) needs to be\ncalled in order to fully uncork the stream.","summary":"Number of times `writable.uncork()` needs to be called in order to fully uncork the stream.","examples":[],"children":[]},{"kind":"property","id":"writableerrored","name":"errored","title":"`writable.errored`","scope":"module","overloadOf":null,"stability":null,"added":["v18.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"default":null,"description":"Returns error if the stream has been destroyed with an error.","summary":"Returns error if the stream has been destroyed with an error.","examples":[],"children":[]},{"kind":"property","id":"writablewritablefinished","name":"writableFinished","title":"`writable.writableFinished`","scope":"module","overloadOf":null,"stability":null,"added":["v12.6.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is set to `true` immediately before the [`'finish'`](#event-finish) event is emitted.","summary":"Is set to `true` immediately before the `'finish'` event is emitted.","examples":[],"children":[]},{"kind":"property","id":"writablewritablehighwatermark","name":"writableHighWaterMark","title":"`writable.writableHighWaterMark`","scope":"module","overloadOf":null,"stability":null,"added":["v9.3.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"default":null,"description":"Return the value of `highWaterMark` passed when creating this `Writable`.","summary":"Return the value of `highWaterMark` passed when creating this `Writable`.","examples":[],"children":[]},{"kind":"property","id":"writablewritablelength","name":"writableLength","title":"`writable.writableLength`","scope":"module","overloadOf":null,"stability":null,"added":["v9.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"default":null,"description":"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`.","summary":"This property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the `highWaterMark`.","examples":[],"children":[]},{"kind":"property","id":"writablewritableneeddrain","name":"writableNeedDrain","title":"`writable.writableNeedDrain`","scope":"module","overloadOf":null,"stability":null,"added":["v15.2.0","v14.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is `true` if the stream's buffer has been full and stream will emit `'drain'`.","summary":"Is `true` if the stream's buffer has been full and stream will emit `'drain'`.","examples":[],"children":[]},{"kind":"property","id":"writablewritableobjectmode","name":"writableObjectMode","title":"`writable.writableObjectMode`","scope":"module","overloadOf":null,"stability":null,"added":["v12.3.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Getter for the property `objectMode` of a given `Writable` stream.","summary":"Getter for the property `objectMode` of a given `Writable` stream.","examples":[],"children":[]},{"kind":"method","id":"writablesymbolasyncdispose","name":"[Symbol.asyncDispose]","title":"`writable[Symbol.asyncDispose]()`","scope":"module","overloadOf":null,"stability":null,"added":["v22.4.0","v20.16.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.2.0"],"prUrl":"https://github.com/nodejs/node/pull/58467","commit":null,"description":"No longer experimental."}],"signature":{"parameters":[],"returns":null},"description":"Calls [`writable.destroy()`](#writabledestroyerror) with an `AbortError` and returns\na promise that fulfills when the stream is finished.","summary":"Calls `writable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished.","examples":[],"children":[]},{"kind":"method","id":"writablewritechunk-encoding-callback","name":"write","title":"`writable.write(chunk[, encoding][, callback])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v22.0.0","v20.13.0"],"prUrl":"https://github.com/nodejs/node/pull/51866","commit":null,"description":"The `chunk` argument can now be a `TypedArray` or `DataView` instance."},{"versions":["v8.0.0"],"prUrl":"https://github.com/nodejs/node/pull/11608","commit":null,"description":"The `chunk` argument can now be a `Uint8Array` instance."},{"versions":["v6.0.0"],"prUrl":"https://github.com/nodejs/node/pull/6170","commit":null,"description":"Passing `null` as the `chunk` parameter will always be considered invalid now, even in object mode."}],"signature":{"parameters":[{"name":"chunk","type":{"text":"string | Buffer | TypedArray | DataView | any","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6},{"name":"Buffer","href":"buffer.html#class-buffer","start":9,"end":15},{"name":"TypedArray","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray","start":18,"end":28},{"name":"DataView","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DataView","start":31,"end":39},{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":42,"end":45}]},"description":"Optional data to write. For\nstreams not operating in object mode, `chunk` must be a {string}, {Buffer},\n{TypedArray} or {DataView}. For object mode streams, `chunk` may be any\nJavaScript value other than `null`.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"encoding","type":{"text":"string | null","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6},{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":9,"end":13}]},"description":"The encoding, if `chunk` is a string.","default":"'utf8'","optional":true,"rest":false,"properties":[]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Callback for when this chunk of data is flushed.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"`false` if the stream wishes for the calling code to\nwait for the `'drain'` event to be emitted before continuing to write\nadditional data; otherwise `true`."}},"description":"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` will be called with the error as its\nfirst argument. The `callback` is called asynchronously and before `'error'` is\nemitted.\n\nThe return value is `true` if the internal buffer is less than the\n`highWaterMark` 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-drain) event is emitted.\n\nWhile 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.\nOnce `write()` returns false, do not write more chunks\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\nWriting data while the stream is not draining is particularly\nproblematic for a [`Transform`](#class-streamtransform), because the `Transform` streams are paused\nby default until they are piped or a `'data'` or `'readable'` event handler\nis added.\n\nIf the data to be written can be generated or fetched on demand, it is\nrecommended to encapsulate the logic into a [`Readable`](#class-streamreadable) and use\n[`stream.pipe()`](#readablepipedestination-options). However, if calling `write()` is preferred, it is\npossible to respect backpressure and avoid memory issues using the\n[`'drain'`](#event-drain) event:\n\n```js\nfunction 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\nA `Writable` stream in object mode will always ignore the `encoding` argument.","summary":"The `writable.write()` method writes some data to the stream, and calls the supplied `callback` once the data has been fully handled. If an error occurs, the `callback` will be called with the error as its first argument. The `callback` is called asynchronously and before `'error'` is emitted.","examples":[{"language":"js","displayName":null,"code":"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});"}],"children":[]}]}]},{"kind":"section","id":"readable-streams","name":"Readable streams","title":"Readable streams","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Readable streams are an abstraction for a *source* from which data is\nconsumed.\n\nExamples of `Readable` streams include:\n\n* [HTTP responses, on the client](http.html#class-httpincomingmessage)\n* [HTTP requests, on the server](http.html#class-httpincomingmessage)\n* [fs read streams](fs.html#class-fsreadstream)\n* [zlib streams](zlib.html)\n* [crypto streams](crypto.html)\n* [TCP sockets](net.html#class-netsocket)\n* [child process stdout and stderr](child_process.html#subprocessstdout)\n* [`process.stdin`](process.html#processstdin)\n\nAll [`Readable`](#class-streamreadable) streams implement the interface defined by the\n`stream.Readable` class.","summary":"Readable streams are an abstraction for a _source_ from which data is consumed.","examples":[],"children":[{"kind":"section","id":"two-reading-modes","name":"Two reading modes","title":"Two reading modes","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"`Readable` streams effectively operate in one of two modes: flowing and\npaused. These modes are separate from [object mode](#object-mode).\nA [`Readable`](#class-streamreadable) stream can be in object mode or not, regardless of whether\nit is in flowing mode or paused mode.\n\n* In flowing mode, data is read from the underlying system automatically\n  and provided to an application as quickly as possible using events via the\n  [`EventEmitter`](events.html#class-eventemitter) interface.\n\n* In paused mode, the [`stream.read()`](#readablereadsize) method must be called\n  explicitly to read chunks of data from the stream.\n\nAll [`Readable`](#class-streamreadable) streams begin in paused mode but can be switched to flowing\nmode in one of the following ways:\n\n* Adding a [`'data'`](#event-data) event handler.\n* Calling the [`stream.resume()`](#readableresume) method.\n* Calling the [`stream.pipe()`](#readablepipedestination-options) method to send the data to a [`Writable`](#class-streamwritable).\n\nThe `Readable` can switch back to paused mode using one of the following:\n\n* If there are no pipe destinations, by calling the\n  [`stream.pause()`](#readablepause) method.\n* If there are pipe destinations, by removing all pipe destinations.\n  Multiple pipe destinations may be removed by calling the\n  [`stream.unpipe()`](#readableunpipedestination) method.\n\nThe 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\nFor backward compatibility reasons, removing [`'data'`](#event-data) event handlers will\n**not** automatically pause the stream. Also, if there are piped destinations,\nthen calling [`stream.pause()`](#readablepause) will not guarantee that the\nstream will *remain* paused once those destinations drain and ask for more data.\n\nIf a [`Readable`](#class-streamreadable) 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\nAdding a [`'readable'`](#event-readable) event handler automatically makes the stream\nstop flowing, and the data has to be consumed via\n[`readable.read()`](#readablereadsize). If the [`'readable'`](#event-readable) event handler is\nremoved, then the stream will start flowing again if there is a\n[`'data'`](#event-data) event handler.","summary":"`Readable` streams effectively operate in one of two modes: flowing and paused. These modes are separate from object mode. A `Readable` stream can be in object mode or not, regardless of whether it is in flowing mode or paused mode.","examples":[],"children":[]},{"kind":"section","id":"three-states","name":"Three states","title":"Three states","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"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\nSpecifically, at any given point in time, every `Readable` is in one of three\npossible states:\n\n* `readable.readableFlowing === null`\n* `readable.readableFlowing === false`\n* `readable.readableFlowing === true`\n\nWhen `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\n`readable.pipe()` method, or calling the `readable.resume()` method will switch\n`readable.readableFlowing` to `true`, causing the `Readable` to begin actively\nemitting events as data is generated.\n\nCalling `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\n```js\nconst { PassThrough, Writable } = require('node: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()); });\n// readableFlowing is still false.\npass.write('ok');  // Will not emit 'data'.\npass.resume();     // Must be called to make stream emit 'data'.\n// readableFlowing is now true.\n```\n\nWhile `readable.readableFlowing` is `false`, data may be accumulating\nwithin the stream's internal buffer.","summary":"The \"two modes\" of operation for a `Readable` stream are a simplified abstraction for the more complicated internal state management that is happening within the `Readable` stream implementation.","examples":[{"language":"js","displayName":null,"code":"const { PassThrough, Writable } = require('node: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()); });\n// readableFlowing is still false.\npass.write('ok');  // Will not emit 'data'.\npass.resume();     // Must be called to make stream emit 'data'.\n// readableFlowing is now true."}],"children":[]},{"kind":"section","id":"choose-one-api-style","name":"Choose one API style","title":"Choose one API style","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `Readable` stream API evolved across multiple Node.js versions and provides\nmultiple methods of consuming stream data. In general, developers should choose\n*one* 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.","summary":"The `Readable` stream API evolved across multiple Node.js versions and provides multiple methods of consuming stream data. In general, developers should choose _one_ of the methods of consuming data and _should never_ use multiple methods to consume data from a single stream. Specifically, using a combination of `on('data')`, `on('readable')`, `pipe()`, or async iterators could lead to unintuitive behavior.","examples":[],"children":[]},{"kind":"class","id":"class-streamreadable","name":"Readable","title":"Class: `stream.Readable`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"","summary":"","examples":[],"children":[{"kind":"event","id":"event-close-1","name":"close","title":"Event: `'close'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/18438","commit":null,"description":"Add `emitClose` option to specify if `'close'` is emitted on destroy."}],"parameters":[],"description":"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\nA [`Readable`](#class-streamreadable) stream will always emit the `'close'` event if it is\ncreated with the `emitClose` option.","summary":"The `'close'` event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates that no more events will be emitted, and no further computation will occur.","examples":[],"children":[]},{"kind":"event","id":"event-data","name":"data","title":"Event: `'data'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"chunk","type":{"text":"Buffer | string | any","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":9,"end":15},{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":18,"end":21}]},"description":"The chunk of data. For streams that are not\noperating in object mode, the chunk will be either a string or `Buffer`.\nFor streams that are in object mode, the chunk can be any JavaScript value\nother than `null`.","default":null,"optional":false,"rest":false,"properties":[]}],"description":"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\nAttaching 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\nThe listener callback will be passed the chunk of data as a string if a default\nencoding has been specified for the stream using the\n`readable.setEncoding()` method; otherwise the data will be passed as a\n`Buffer`.\n\n```js\nconst readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n});\n```","summary":"The `'data'` event is emitted whenever the stream is relinquishing ownership of a chunk of data to a consumer. This may occur whenever the stream is switched in flowing mode by calling `readable.pipe()`, `readable.resume()`, or by attaching a listener callback to the `'data'` event. The `'data'` event will also be emitted whenever the `readable.read()` method is called and a chunk of data is available to be returned.","examples":[{"language":"js","displayName":null,"code":"const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n  console.log(`Received ${chunk.length} bytes of data.`);\n});"}],"children":[]},{"kind":"event","id":"event-end","name":"end","title":"Event: `'end'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"The `'end'` event is emitted when there is no more data to be consumed from\nthe stream.\n\nThe `'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()`](#readablereadsize) repeatedly until all data has been\nconsumed.\n\n```js\nconst 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```","summary":"The `'end'` event is emitted when there is no more data to be consumed from the stream.","examples":[{"language":"js","displayName":null,"code":"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});"}],"children":[]},{"kind":"event","id":"event-error-1","name":"error","title":"Event: `'error'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[{"name":"","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"description":"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\nThe listener callback will be passed a single `Error` object.","summary":"The `'error'` event may be emitted by a `Readable` implementation at any time. Typically, this may occur if the underlying stream is unable to generate data due to an underlying internal failure, or when a stream implementation attempts to push an invalid chunk of data.","examples":[],"children":[]},{"kind":"event","id":"event-pause","name":"pause","title":"Event: `'pause'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"The `'pause'` event is emitted when [`stream.pause()`](#readablepause) is called\nand `readableFlowing` is not `false`.","summary":"The `'pause'` event is emitted when `stream.pause()` is called and `readableFlowing` is not `false`.","examples":[],"children":[]},{"kind":"event","id":"event-readable","name":"readable","title":"Event: `'readable'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/17979","commit":null,"description":"The `'readable'` is always emitted in the next tick after `.push()` is called."},{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/18994","commit":null,"description":"Using `'readable'` requires calling `.read()`."}],"parameters":[],"description":"The `'readable'` event is emitted when there is data available to be read from\nthe stream, up to the configured high water mark (`state.highWaterMark`). Effectively,\nit indicates that the stream has new information within the buffer. If data is available\nwithin this buffer, [`stream.read()`](#readablereadsize) can be called to retrieve that data.\nAdditionally, the `'readable'` event may also be emitted when the end of the stream has been\nreached.\n\n```js\nconst readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // There is some data to read now.\n  let data;\n\n  while ((data = this.read()) !== null) {\n    console.log(data);\n  }\n});\n```\n\nIf the end of the stream has been reached, calling\n[`stream.read()`](#readablereadsize) will return `null` and trigger the `'end'`\nevent. This is also true if there never was any data to be read. For instance,\nin the following example, `foo.txt` is an empty file:\n\n```js\nconst fs = require('node: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\nThe output of running this script is:\n\n```console\n$ node test.js\nreadable: null\nend\n```\n\nIn some cases, attaching a listener for the `'readable'` event will cause some\namount of data to be read into an internal buffer.\n\nIn 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\nIf both `'readable'` and [`'data'`](#event-data) are used at the same time, `'readable'`\ntakes precedence in controlling the flow, i.e. `'data'` will be emitted\nonly when [`stream.read()`](#readablereadsize) is called. The\n`readableFlowing` 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()`.","summary":"The `'readable'` event is emitted when there is data available to be read from the stream, up to the configured high water mark (`state.highWaterMark`). Effectively, it indicates that the stream has new information within the buffer. If data is available within this buffer, `stream.read()` can be called to retrieve that data. Additionally, the `'readable'` event may also be emitted when the end of the stream has been reached.","examples":[{"language":"js","displayName":null,"code":"const readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // There is some data to read now.\n  let data;\n\n  while ((data = this.read()) !== null) {\n    console.log(data);\n  }\n});"},{"language":"js","displayName":null,"code":"const fs = require('node: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});"},{"language":"console","displayName":null,"code":"$ node test.js\nreadable: null\nend"}],"children":[]},{"kind":"event","id":"event-resume","name":"resume","title":"Event: `'resume'`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"The `'resume'` event is emitted when [`stream.resume()`](#readableresume) is\ncalled and `readableFlowing` is not `true`.","summary":"The `'resume'` event is emitted when `stream.resume()` is called and `readableFlowing` is not `true`.","examples":[],"children":[]},{"kind":"method","id":"readabledestroyerror","name":"destroy","title":"`readable.destroy([error])`","scope":"module","overloadOf":null,"stability":null,"added":["v8.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v14.0.0"],"prUrl":"https://github.com/nodejs/node/pull/29197","commit":null,"description":"Work as a no-op on a stream that has already been destroyed."}],"signature":{"parameters":[{"name":"error","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"Error which will be passed as payload in `'error'` event","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"this","links":[{"name":"this","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this","start":0,"end":4}]},"description":""}},"description":"Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`\nevent (unless `emitClose` is set to `false`). After this call, the readable\nstream will release any internal resources and subsequent calls to `push()`\nwill be ignored.\n\nOnce `destroy()` has been called any further calls will be a no-op and no\nfurther errors except from `_destroy()` may be emitted as `'error'`.\n\nImplementors should not override this method, but instead implement\n[`readable._destroy()`](#readable_destroyerr-callback).","summary":"Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable stream will release any internal resources and subsequent calls to `push()` will be ignored.","examples":[],"children":[]},{"kind":"property","id":"readableclosed","name":"closed","title":"`readable.closed`","scope":"module","overloadOf":null,"stability":null,"added":["v18.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is `true` after `'close'` has been emitted.","summary":"Is `true` after `'close'` has been emitted.","examples":[],"children":[]},{"kind":"property","id":"readabledestroyed","name":"destroyed","title":"`readable.destroyed`","scope":"module","overloadOf":null,"stability":null,"added":["v8.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is `true` after [`readable.destroy()`](#readabledestroyerror) has been called.","summary":"Is `true` after `readable.destroy()` has been called.","examples":[],"children":[]},{"kind":"method","id":"readableispaused","name":"isPaused","title":"`readable.isPaused()`","scope":"module","overloadOf":null,"stability":null,"added":["v0.11.14"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":""}},"description":"The `readable.isPaused()` method returns the current operating state of the\n`Readable`. This is used primarily by the mechanism that underlies the\n`readable.pipe()` method. In most typical cases, there will be no reason to\nuse this method directly.\n\n```js\nconst readable = new stream.Readable();\n\nreadable.isPaused(); // === false\nreadable.pause();\nreadable.isPaused(); // === true\nreadable.resume();\nreadable.isPaused(); // === false\n```","summary":"The `readable.isPaused()` method returns the current operating state of the `Readable`. This is used primarily by the mechanism that underlies the `readable.pipe()` method. In most typical cases, there will be no reason to use this method directly.","examples":[{"language":"js","displayName":null,"code":"const readable = new stream.Readable();\n\nreadable.isPaused(); // === false\nreadable.pause();\nreadable.isPaused(); // === true\nreadable.resume();\nreadable.isPaused(); // === false"}],"children":[]},{"kind":"method","id":"readablepause","name":"pause","title":"`readable.pause()`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"this","links":[{"name":"this","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this","start":0,"end":4}]},"description":""}},"description":"The `readable.pause()` method will cause a stream in flowing mode to stop\nemitting [`'data'`](#event-data) events, switching out of flowing mode. Any data that\nbecomes available will remain in the internal buffer.\n\n```js\nconst 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\nThe `readable.pause()` method has no effect if there is a `'readable'`\nevent listener.","summary":"The `readable.pause()` method will cause a stream in flowing mode to stop emitting `'data'` events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.","examples":[{"language":"js","displayName":null,"code":"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});"}],"children":[]},{"kind":"method","id":"readablepipedestination-options","name":"pipe","title":"`readable.pipe(destination[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"destination","type":{"text":"stream.Writable","links":[{"name":"stream.Writable","href":"stream.html#class-streamwritable","start":0,"end":15}]},"description":"The destination for writing data","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"Pipe options","default":null,"optional":true,"rest":false,"properties":[{"name":"end","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"End the writer when the reader ends.","default":"true","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"stream.Writable","links":[{"name":"stream.Writable","href":"stream.html#class-streamwritable","start":0,"end":15}]},"description":"The *destination*, allowing for a chain of pipes if\nit is a [`Duplex`](#class-streamduplex) or a [`Transform`](#class-streamtransform) stream"}},"description":"The `readable.pipe()` method attaches a [`Writable`](#class-streamwritable) stream to the `readable`,\ncausing it to switch automatically into flowing mode and push all of its data\nto the attached [`Writable`](#class-streamwritable). The flow of data will be automatically managed\nso that the destination `Writable` stream is not overwhelmed by a faster\n`Readable` stream.\n\nThe following example pipes all of the data from the `readable` into a file\nnamed `file.txt`:\n\n```js\nconst fs = require('node: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\nIt is possible to attach multiple `Writable` streams to a single `Readable`\nstream.\n\nThe `readable.pipe()` method returns a reference to the *destination* stream\nmaking it possible to set up chains of piped streams:\n\n```js\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\nconst r = fs.createReadStream('file.txt');\nconst z = zlib.createGzip();\nconst w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);\n```\n\nBy default, [`stream.end()`](#writableendchunk-encoding-callback) is called on the destination `Writable`\nstream when the source `Readable` stream emits [`'end'`](#event-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\n```js\nreader.pipe(writer, { end: false });\nreader.on('end', () => {\n  writer.end('Goodbye\\n');\n});\n```\n\nOne 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\nThe [`process.stderr`](process.html#processstderr) and [`process.stdout`](process.html#processstdout) `Writable` streams are never\nclosed until the Node.js process exits, regardless of the specified options.","summary":"The `readable.pipe()` method attaches a `Writable` stream to the `readable`, causing it to switch automatically into flowing mode and push all of its data to the attached `Writable`. The flow of data will be automatically managed so that the destination `Writable` stream is not overwhelmed by a faster `Readable` stream.","examples":[{"language":"js","displayName":null,"code":"const fs = require('node:fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'.\nreadable.pipe(writable);"},{"language":"js","displayName":null,"code":"const fs = require('node:fs');\nconst zlib = require('node:zlib');\nconst r = fs.createReadStream('file.txt');\nconst z = zlib.createGzip();\nconst w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);"},{"language":"js","displayName":null,"code":"reader.pipe(writer, { end: false });\nreader.on('end', () => {\n  writer.end('Goodbye\\n');\n});"}],"children":[]},{"kind":"method","id":"readablereadsize","name":"read","title":"`readable.read([size])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"size","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Optional argument to specify how much data to read.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"string | Buffer | null | any","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6},{"name":"Buffer","href":"buffer.html#class-buffer","start":9,"end":15},{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":18,"end":22},{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":25,"end":28}]},"description":""}},"description":"The `readable.read()` method reads data out of the internal buffer and\nreturns it. If no data is available to be read, `null` is returned. By default,\nthe data is 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\nThe optional `size` argument specifies a specific number of bytes to read. If\n`size` 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\nIf the `size` argument is not specified, all of the data contained in the\ninternal buffer will be returned.\n\nThe `size` argument must be less than or equal to 1 GiB.\n\nThe `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\n```js\nconst readable = getReadableStreamSomehow();\n\n// 'readable' may be triggered multiple times as data is buffered in\nreadable.on('readable', () => {\n  let chunk;\n  console.log('Stream is readable (new data received in buffer)');\n  // Use a loop to make sure we read all currently available data\n  while (null !== (chunk = readable.read())) {\n    console.log(`Read ${chunk.length} bytes of data...`);\n  }\n});\n\n// 'end' will be triggered once when there is no more data available\nreadable.on('end', () => {\n  console.log('Reached end of stream.');\n});\n```\n\nEach call to `readable.read()` returns a chunk of data or `null`, signifying\nthat there's no more data to read at that moment. These chunks aren't automatically\nconcatenated. Because a single `read()` call does not return all the data, using\na while loop may be necessary to continuously read chunks until all data is retrieved.\nWhen reading a large file, `.read()` might return `null` temporarily, indicating\nthat it has consumed all buffered content but there may be more data yet to be\nbuffered. In such cases, a new `'readable'` event is emitted once there's more\ndata in the buffer, and the `'end'` event signifies the end of data transmission.\n\nTherefore to read a file's whole contents from a `readable`, it is necessary\nto collect chunks across multiple `'readable'` events:\n\n```js\nconst chunks = [];\n\nreadable.on('readable', () => {\n  let chunk;\n  while (null !== (chunk = readable.read())) {\n    chunks.push(chunk);\n  }\n});\n\nreadable.on('end', () => {\n  const content = chunks.join('');\n});\n```\n\nA `Readable` stream in object mode will always return a single item from\na call to [`readable.read(size)`](#readablereadsize), regardless of the value of the\n`size` argument.\n\nIf the `readable.read()` method returns a chunk of data, a `'data'` event will\nalso be emitted.\n\nCalling [`stream.read([size])`](#readablereadsize) after the [`'end'`](#event-end) event has\nbeen emitted will return `null`. No runtime error will be raised.","summary":"The `readable.read()` method reads data out of the internal buffer and returns it. If no data is available to be read, `null` is returned. By default, the data is returned as a `Buffer` object unless an encoding has been specified using the `readable.setEncoding()` method or the stream is operating in object mode.","examples":[{"language":"js","displayName":null,"code":"const readable = getReadableStreamSomehow();\n\n// 'readable' may be triggered multiple times as data is buffered in\nreadable.on('readable', () => {\n  let chunk;\n  console.log('Stream is readable (new data received in buffer)');\n  // Use a loop to make sure we read all currently available data\n  while (null !== (chunk = readable.read())) {\n    console.log(`Read ${chunk.length} bytes of data...`);\n  }\n});\n\n// 'end' will be triggered once when there is no more data available\nreadable.on('end', () => {\n  console.log('Reached end of stream.');\n});"},{"language":"js","displayName":null,"code":"const chunks = [];\n\nreadable.on('readable', () => {\n  let chunk;\n  while (null !== (chunk = readable.read())) {\n    chunks.push(chunk);\n  }\n});\n\nreadable.on('end', () => {\n  const content = chunks.join('');\n});"}],"children":[]},{"kind":"property","id":"readablereadable","name":"readable","title":"`readable.readable`","scope":"module","overloadOf":null,"stability":null,"added":["v11.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Is `true` if it is safe to call [`readable.read()`](#readablereadsize), which means\nthe stream has not been destroyed or emitted `'error'` or `'end'`.","summary":"Is `true` if it is safe to call `readable.read()`, which means the stream has not been destroyed or emitted `'error'` or `'end'`.","examples":[],"children":[]},{"kind":"property","id":"readablereadableaborted","name":"readableAborted","title":"`readable.readableAborted`","scope":"module","overloadOf":null,"stability":null,"added":["v16.8.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Returns whether the stream was destroyed or errored before emitting `'end'`.","summary":"Returns whether the stream was destroyed or errored before emitting `'end'`.","examples":[],"children":[]},{"kind":"property","id":"readablereadabledidread","name":"readableDidRead","title":"`readable.readableDidRead`","scope":"module","overloadOf":null,"stability":null,"added":["v16.7.0","v14.18.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Returns whether `'data'` has been emitted.","summary":"Returns whether `'data'` has been emitted.","examples":[],"children":[]},{"kind":"property","id":"readablereadableencoding","name":"readableEncoding","title":"`readable.readableEncoding`","scope":"module","overloadOf":null,"stability":null,"added":["v12.7.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"null | string","links":[{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":0,"end":4},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":7,"end":13}]},"default":null,"description":"Getter for the property `encoding` of a given `Readable` stream. The `encoding`\nproperty can be set using the [`readable.setEncoding()`](#readablesetencodingencoding) method.","summary":"Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the `readable.setEncoding()` method.","examples":[],"children":[]},{"kind":"property","id":"readablereadableended","name":"readableEnded","title":"`readable.readableEnded`","scope":"module","overloadOf":null,"stability":null,"added":["v12.9.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Becomes `true` when [`'end'`](#event-end) event is emitted.","summary":"Becomes `true` when `'end'` event is emitted.","examples":[],"children":[]},{"kind":"property","id":"readableerrored","name":"errored","title":"`readable.errored`","scope":"module","overloadOf":null,"stability":null,"added":["v18.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"default":null,"description":"Returns error if the stream has been destroyed with an error.","summary":"Returns error if the stream has been destroyed with an error.","examples":[],"children":[]},{"kind":"property","id":"readablereadableflowing","name":"readableFlowing","title":"`readable.readableFlowing`","scope":"module","overloadOf":null,"stability":null,"added":["v9.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"This property reflects the current state of a `Readable` stream as described\nin the [Three states](#three-states) section.","summary":"This property reflects the current state of a `Readable` stream as described in the Three states section.","examples":[],"children":[]},{"kind":"property","id":"readablereadablehighwatermark","name":"readableHighWaterMark","title":"`readable.readableHighWaterMark`","scope":"module","overloadOf":null,"stability":null,"added":["v9.3.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"default":null,"description":"Returns the value of `highWaterMark` passed when creating this `Readable`.","summary":"Returns the value of `highWaterMark` passed when creating this `Readable`.","examples":[],"children":[]},{"kind":"property","id":"readablereadablelength","name":"readableLength","title":"`readable.readableLength`","scope":"module","overloadOf":null,"stability":null,"added":["v9.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"default":null,"description":"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`.","summary":"This property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the `highWaterMark`.","examples":[],"children":[]},{"kind":"property","id":"readablereadableobjectmode","name":"readableObjectMode","title":"`readable.readableObjectMode`","scope":"module","overloadOf":null,"stability":null,"added":["v12.3.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"Getter for the property `objectMode` of a given `Readable` stream.","summary":"Getter for the property `objectMode` of a given `Readable` stream.","examples":[],"children":[]},{"kind":"method","id":"readableresume","name":"resume","title":"`readable.resume()`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/18994","commit":null,"description":"The `resume()` has no effect if there is a `'readable'` event listening."}],"signature":{"parameters":[],"returns":{"type":{"text":"this","links":[{"name":"this","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this","start":0,"end":4}]},"description":""}},"description":"The `readable.resume()` method causes an explicitly paused `Readable` stream to\nresume emitting [`'data'`](#event-data) events, switching the stream into flowing mode.\n\nThe `readable.resume()` method can be used to fully consume the data from a\nstream without actually processing any of that data:\n\n```js\ngetReadableStreamSomehow()\n  .resume()\n  .on('end', () => {\n    console.log('Reached the end, but did not read anything.');\n  });\n```\n\nThe `readable.resume()` method has no effect if there is a `'readable'`\nevent listener.","summary":"The `readable.resume()` method causes an explicitly paused `Readable` stream to resume emitting `'data'` events, switching the stream into flowing mode.","examples":[{"language":"js","displayName":null,"code":"getReadableStreamSomehow()\n  .resume()\n  .on('end', () => {\n    console.log('Reached the end, but did not read anything.');\n  });"}],"children":[]},{"kind":"method","id":"readablesetencodingencoding","name":"setEncoding","title":"`readable.setEncoding(encoding)`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The encoding to use.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"this","links":[{"name":"this","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this","start":0,"end":4}]},"description":""}},"description":"The `readable.setEncoding()` method sets the character encoding for\ndata read from the `Readable` stream.\n\nBy default, no encoding is assigned and stream data will be returned as\n`Buffer` 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\n`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal\nstring format.\n\nThe `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\n```js\nconst 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```","summary":"The `readable.setEncoding()` method sets the character encoding for data read from the `Readable` stream.","examples":[{"language":"js","displayName":null,"code":"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});"}],"children":[]},{"kind":"method","id":"readableunpipedestination","name":"unpipe","title":"`readable.unpipe([destination])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"destination","type":{"text":"stream.Writable","links":[{"name":"stream.Writable","href":"stream.html#class-streamwritable","start":0,"end":15}]},"description":"Optional specific stream to unpipe","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"this","links":[{"name":"this","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this","start":0,"end":4}]},"description":""}},"description":"The `readable.unpipe()` method detaches a `Writable` stream previously attached\nusing the [`stream.pipe()`](#readablepipedestination-options) method.\n\nIf the `destination` is not specified, then *all* pipes are detached.\n\nIf the `destination` is specified, but no pipe is set up for it, then\nthe method does nothing.\n\n```js\nconst fs = require('node: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```","summary":"The `readable.unpipe()` method detaches a `Writable` stream previously attached using the `stream.pipe()` method.","examples":[{"language":"js","displayName":null,"code":"const fs = require('node: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);"}],"children":[]},{"kind":"method","id":"readableunshiftchunk-encoding","name":"unshift","title":"`readable.unshift(chunk[, encoding])`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.11"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v22.0.0","v20.13.0"],"prUrl":"https://github.com/nodejs/node/pull/51866","commit":null,"description":"The `chunk` argument can now be a `TypedArray` or `DataView` instance."},{"versions":["v8.0.0"],"prUrl":"https://github.com/nodejs/node/pull/11608","commit":null,"description":"The `chunk` argument can now be a `Uint8Array` instance."}],"signature":{"parameters":[{"name":"chunk","type":{"text":"Buffer | TypedArray | DataView | string | null | any","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"TypedArray","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray","start":9,"end":19},{"name":"DataView","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DataView","start":22,"end":30},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":33,"end":39},{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":42,"end":46},{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":49,"end":52}]},"description":"Chunk of data to unshift\nonto the read queue. For streams not operating in object mode, `chunk` must\nbe a {string}, {Buffer}, {TypedArray}, {DataView} or `null`.\nFor object mode streams, `chunk` may be any JavaScript value.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Encoding of string chunks. Must be a valid\n`Buffer` encoding, such as `'utf8'` or `'ascii'`.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":null},"description":"Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the\nsame as `readable.push(null)`, after which no more data can be written. The EOF\nsignal is put at the end of the buffer and any buffered data will still be\nflushed.\n\nThe `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\nThe `stream.unshift(chunk)` method cannot be called after the [`'end'`](#event-end) event\nhas been emitted or a runtime error will be thrown.\n\nDevelopers using `stream.unshift()` often should consider switching to\nuse of a [`Transform`](#class-streamtransform) stream instead. See the [API for stream implementers](#api-for-stream-implementers)\nsection for more information.\n\n```js\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('node: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.includes('\\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        return;\n      }\n      // Still reading the header.\n      header += str;\n    }\n  }\n}\n```\n\nUnlike [`stream.push(chunk)`](#readablepushchunk-encoding), `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()`](#readable_readsize) implementation on a\ncustom stream). Following the call to `readable.unshift()` with an immediate\n[`stream.push('')`](#readablepushchunk-encoding) will reset the reading state appropriately,\nhowever it is best to simply avoid calling `readable.unshift()` while in the\nprocess of performing a read.","summary":"Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the same as `readable.push(null)`, after which no more data can be written. The EOF signal is put at the end of the buffer and any buffered data will still be flushed.","examples":[{"language":"js","displayName":null,"code":"// 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('node: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.includes('\\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        return;\n      }\n      // Still reading the header.\n      header += str;\n    }\n  }\n}"}],"children":[]},{"kind":"method","id":"readablewrapstream","name":"wrap","title":"`readable.wrap(stream)`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"stream","type":{"text":"Stream","links":[{"name":"Stream","href":"stream.html#stream","start":0,"end":6}]},"description":"An \"old style\" readable stream","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"this","links":[{"name":"this","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this","start":0,"end":4}]},"description":""}},"description":"Prior to Node.js 0.10, streams did not implement the entire `node:stream`\nmodule API as it is currently defined. (See [Compatibility](#compatibility-with-older-nodejs-versions) for more\ninformation.)\n\nWhen using an older Node.js library that emits [`'data'`](#event-data) events and has a\n[`stream.pause()`](#readablepause) method that is advisory only, the\n`readable.wrap()` method can be used to create a [`Readable`](#class-streamreadable) stream that uses\nthe old stream as its data source.\n\nIt 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\n```js\nconst { OldReader } = require('./old-api-module.js');\nconst { Readable } = require('node:stream');\nconst oreader = new OldReader();\nconst myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', () => {\n  myReader.read(); // etc.\n});\n```","summary":"Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See Compatibility for more information.)","examples":[{"language":"js","displayName":null,"code":"const { OldReader } = require('./old-api-module.js');\nconst { Readable } = require('node:stream');\nconst oreader = new OldReader();\nconst myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', () => {\n  myReader.read(); // etc.\n});"}],"children":[]},{"kind":"method","id":"readablesymbolasynciterator","name":"[Symbol.asyncIterator]","title":"`readable[Symbol.asyncIterator]()`","scope":"module","overloadOf":null,"stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v11.14.0"],"prUrl":"https://github.com/nodejs/node/pull/26989","commit":null,"description":"Symbol.asyncIterator support is no longer experimental."}],"signature":{"parameters":[],"returns":{"type":{"text":"AsyncIterator","links":[{"name":"AsyncIterator","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator","start":0,"end":13}]},"description":"to fully consume the stream."}},"description":"```js\nconst fs = require('node:fs');\n\nasync function print(readable) {\n  readable.setEncoding('utf8');\n  let data = '';\n  for await (const chunk of readable) {\n    data += chunk;\n  }\n  console.log(data);\n}\n\nprint(fs.createReadStream('file')).catch(console.error);\n```\n\nIf the loop terminates with a `break`, `return`, or a `throw`, the stream will\nbe destroyed. 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 than 64 KiB of data because no `highWaterMark` option is provided to\n[`fs.createReadStream()`](fs.html#fscreatereadstreampath-options).","summary":"If the loop terminates with a `break`, `return`, or a `throw`, the stream will be destroyed. In other terms, iterating over a stream will consume the stream fully. The stream will be read in chunks of size equal to the `highWaterMark` option. In the code example above, data will be in a single chunk if the file has less than 64 KiB of data because no `highWaterMark` option is provided to `fs.createReadStream()`.","examples":[{"language":"js","displayName":null,"code":"const fs = require('node:fs');\n\nasync function print(readable) {\n  readable.setEncoding('utf8');\n  let data = '';\n  for await (const chunk of readable) {\n    data += chunk;\n  }\n  console.log(data);\n}\n\nprint(fs.createReadStream('file')).catch(console.error);"}],"children":[]},{"kind":"method","id":"readablesymbolforstreamtoasyncstreamable","name":"[Symbol.for('Stream.toAsyncStreamable')]","title":"`readable[Symbol.for('Stream.toAsyncStreamable')]()`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v26.1.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[],"returns":{"type":{"text":"AsyncIterable","links":[{"name":"AsyncIterable","href":"https://tc39.github.io/ecma262/#sec-asynciterable-interface","start":0,"end":13}]},"description":"An `AsyncIterable<Uint8Array[]>` that yields\nbatched chunks from the stream."}},"description":"When the `--experimental-stream-iter` flag is enabled, `Readable` streams\nimplement the [`Stream.toAsyncStreamable`](stream_iter.html#streamtoasyncstreamable) protocol, enabling efficient\nconsumption by the [`stream/iter`](stream_iter.html) API.\n\nThis provides a batched async iterator that drains the stream's internal\nbuffer into `Uint8Array[]` batches, amortizing the per-chunk Promise overhead\nof the standard `Symbol.asyncIterator` path. For byte-mode streams, chunks\nare yielded directly as `Buffer` instances (which are `Uint8Array` subclasses).\nFor object-mode or encoded streams, each chunk is normalized to `Uint8Array`\nbefore batching.\n\nThe returned iterator is tagged as a validated source, so [`from()`](stream_iter.html#frominput)\npasses it through without additional normalization.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { text, from } from 'node:stream/iter';\n\nconst readable = new Readable({\n  read() { this.push('hello'); this.push(null); },\n});\n\n// Readable is automatically consumed via toAsyncStreamable\nconsole.log(await text(from(readable))); // 'hello'\n```\n\n```cjs\nconst { Readable } = require('node:stream');\nconst { text, from } = require('node:stream/iter');\n\nasync function run() {\n  const readable = new Readable({\n    read() { this.push('hello'); this.push(null); },\n  });\n\n  console.log(await text(from(readable))); // 'hello'\n}\n\nrun().catch(console.error);\n```\n\nWithout the `--experimental-stream-iter` flag, calling this method throws\n[`ERR_STREAM_ITER_MISSING_FLAG`](errors.html#err_stream_iter_missing_flag).","summary":"When the `--experimental-stream-iter` flag is enabled, `Readable` streams implement the `Stream.toAsyncStreamable` protocol, enabling efficient consumption by the `stream/iter` API.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { text, from } from 'node:stream/iter';\n\nconst readable = new Readable({\n  read() { this.push('hello'); this.push(null); },\n});\n\n// Readable is automatically consumed via toAsyncStreamable\nconsole.log(await text(from(readable))); // 'hello'"},{"language":"cjs","displayName":null,"code":"const { Readable } = require('node:stream');\nconst { text, from } = require('node:stream/iter');\n\nasync function run() {\n  const readable = new Readable({\n    read() { this.push('hello'); this.push(null); },\n  });\n\n  console.log(await text(from(readable))); // 'hello'\n}\n\nrun().catch(console.error);"}],"children":[]},{"kind":"method","id":"readablesymbolasyncdispose","name":"[Symbol.asyncDispose]","title":"`readable[Symbol.asyncDispose]()`","scope":"module","overloadOf":null,"stability":null,"added":["v20.4.0","v18.18.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.2.0"],"prUrl":"https://github.com/nodejs/node/pull/58467","commit":null,"description":"No longer experimental."}],"signature":{"parameters":[],"returns":null},"description":"Calls [`readable.destroy()`](#readabledestroyerror) with an `AbortError` and returns\na promise that fulfills when the stream is finished.","summary":"Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished.","examples":[],"children":[]},{"kind":"method","id":"readablecomposestream-options","name":"compose","title":"`readable.compose(stream[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v19.1.0","v18.13.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[{"name":"stream","type":{"text":"Writable | Duplex | WritableStream | TransformStream | Function","links":[{"name":"Writable","href":"stream.html#class-streamwritable","start":0,"end":8},{"name":"Duplex","href":"stream.html#class-streamduplex","start":11,"end":17},{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":20,"end":34},{"name":"TransformStream","href":"webstreams.html#class-transformstream","start":37,"end":52},{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":55,"end":63}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Duplex","links":[{"name":"Duplex","href":"stream.html#class-streamduplex","start":0,"end":6}]},"description":"a stream composed with the stream `stream`."}},"description":"```mjs\nimport { Readable } from 'node:stream';\n\nasync function* splitToWords(source) {\n  for await (const chunk of source) {\n    const words = String(chunk).split(' ');\n\n    for (const word of words) {\n      yield word;\n    }\n  }\n}\n\nconst wordsStream = Readable.from(['text passed through', 'composed stream']).compose(splitToWords);\nconst words = await wordsStream.toArray();\n\nconsole.log(words); // prints ['text', 'passed', 'through', 'composed', 'stream']\n```\n\n`readable.compose(s)` is equivalent to `stream.compose(readable, s)`.\n\nThis method also allows for an {AbortSignal} to be provided, which will destroy\nthe composed stream when aborted.\n\nSee [`stream.compose(...streams)`](#streamcomposestreams) for more information.","summary":"`readable.compose(s)` is equivalent to `stream.compose(readable, s)`.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\n\nasync function* splitToWords(source) {\n  for await (const chunk of source) {\n    const words = String(chunk).split(' ');\n\n    for (const word of words) {\n      yield word;\n    }\n  }\n}\n\nconst wordsStream = Readable.from(['text passed through', 'composed stream']).compose(splitToWords);\nconst words = await wordsStream.toArray();\n\nconsole.log(words); // prints ['text', 'passed', 'through', 'composed', 'stream']"}],"children":[]},{"kind":"method","id":"readableiteratoroptions","name":"iterator","title":"`readable.iterator([options])`","scope":"module","overloadOf":null,"stability":null,"added":["v16.3.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"destroyOnReturn","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"When set to `false`, calling `return` on the\nasync iterator, or exiting a `for await...of` iteration using a `break`,\n`return`, or `throw` will not destroy the stream.","default":"true","optional":true,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"AsyncIterator","links":[{"name":"AsyncIterator","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator","start":0,"end":13}]},"description":"to consume the stream."}},"description":"The iterator created by this method gives users the option to cancel the\ndestruction of the stream if the `for await...of` loop is exited by `return`,\n`break`, or `throw`, or if the iterator should destroy the stream if the stream\nemitted an error during iteration.\n\n```js\nconst { Readable } = require('node:stream');\n\nasync function printIterator(readable) {\n  for await (const chunk of readable.iterator({ destroyOnReturn: false })) {\n    console.log(chunk); // 1\n    break;\n  }\n\n  console.log(readable.destroyed); // false\n\n  for await (const chunk of readable.iterator({ destroyOnReturn: false })) {\n    console.log(chunk); // Will print 2 and then 3\n  }\n\n  console.log(readable.destroyed); // True, stream was totally consumed\n}\n\nasync function printSymbolAsyncIterator(readable) {\n  for await (const chunk of readable) {\n    console.log(chunk); // 1\n    break;\n  }\n\n  console.log(readable.destroyed); // true\n}\n\nasync function showBoth() {\n  await printIterator(Readable.from([1, 2, 3]));\n  await printSymbolAsyncIterator(Readable.from([1, 2, 3]));\n}\n\nshowBoth();\n```","summary":"The iterator created by this method gives users the option to cancel the destruction of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, or if the iterator should destroy the stream if the stream emitted an error during iteration.","examples":[{"language":"js","displayName":null,"code":"const { Readable } = require('node:stream');\n\nasync function printIterator(readable) {\n  for await (const chunk of readable.iterator({ destroyOnReturn: false })) {\n    console.log(chunk); // 1\n    break;\n  }\n\n  console.log(readable.destroyed); // false\n\n  for await (const chunk of readable.iterator({ destroyOnReturn: false })) {\n    console.log(chunk); // Will print 2 and then 3\n  }\n\n  console.log(readable.destroyed); // True, stream was totally consumed\n}\n\nasync function printSymbolAsyncIterator(readable) {\n  for await (const chunk of readable) {\n    console.log(chunk); // 1\n    break;\n  }\n\n  console.log(readable.destroyed); // true\n}\n\nasync function showBoth() {\n  await printIterator(Readable.from([1, 2, 3]));\n  await printSymbolAsyncIterator(Readable.from([1, 2, 3]));\n}\n\nshowBoth();"}],"children":[]},{"kind":"method","id":"readablemapfn-options","name":"map","title":"`readable.map(fn[, options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.4.0","v16.14.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v20.7.0","v18.19.0"],"prUrl":"https://github.com/nodejs/node/pull/49249","commit":null,"description":"added `highWaterMark` in options."}],"signature":{"parameters":[{"name":"fn","type":{"text":"Function | AsyncFunction","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"AsyncFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction","start":11,"end":24}]},"description":"a function to map over every chunk in the\nstream.","default":null,"optional":false,"rest":false,"properties":[{"name":"data","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"a chunk of data from the stream.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"aborted if the stream is destroyed allowing to\nabort the `fn` call early.","default":null,"optional":false,"rest":false,"properties":[]}]}]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"concurrency","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"the maximum concurrent invocation of `fn` to call\non the stream at once.","default":"1","optional":true,"rest":false,"properties":[]},{"name":"highWaterMark","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"how many items to buffer while waiting for user\nconsumption of the mapped items.","default":"concurrency * 2 - 1","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Readable","links":[{"name":"Readable","href":"stream.html#class-streamreadable","start":0,"end":8}]},"description":"a stream mapped with the function `fn`."}},"description":"This method allows mapping over the stream. The `fn` function will be called\nfor every chunk in the stream. If the `fn` function returns a promise - that\npromise will be `await`ed before being passed to the result stream.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous mapper.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).map((x) => x * 2)) {\n  console.log(chunk); // 2, 4, 6, 8\n}\n// With an asynchronous mapper, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n  'nodejs.org',\n  'openjsf.org',\n  'www.linuxfoundation.org',\n]).map((domain) => resolver.resolve4(domain), { concurrency: 2 });\nfor await (const result of dnsResults) {\n  console.log(result); // Logs the DNS result of resolver.resolve4.\n}\n```","summary":"This method allows mapping over the stream. The `fn` function will be called for every chunk in the stream. If the `fn` function returns a promise - that promise will be `await`ed before being passed to the result stream.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous mapper.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).map((x) => x * 2)) {\n  console.log(chunk); // 2, 4, 6, 8\n}\n// With an asynchronous mapper, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n  'nodejs.org',\n  'openjsf.org',\n  'www.linuxfoundation.org',\n]).map((domain) => resolver.resolve4(domain), { concurrency: 2 });\nfor await (const result of dnsResults) {\n  console.log(result); // Logs the DNS result of resolver.resolve4.\n}"}],"children":[]},{"kind":"method","id":"readablefilterfn-options","name":"filter","title":"`readable.filter(fn[, options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.4.0","v16.14.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v20.7.0","v18.19.0"],"prUrl":"https://github.com/nodejs/node/pull/49249","commit":null,"description":"added `highWaterMark` in options."}],"signature":{"parameters":[{"name":"fn","type":{"text":"Function | AsyncFunction","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"AsyncFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction","start":11,"end":24}]},"description":"a function to filter chunks from the stream.","default":null,"optional":false,"rest":false,"properties":[{"name":"data","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"a chunk of data from the stream.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"aborted if the stream is destroyed allowing to\nabort the `fn` call early.","default":null,"optional":false,"rest":false,"properties":[]}]}]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"concurrency","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"the maximum concurrent invocation of `fn` to call\non the stream at once.","default":"1","optional":true,"rest":false,"properties":[]},{"name":"highWaterMark","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"how many items to buffer while waiting for user\nconsumption of the filtered items.","default":"concurrency * 2 - 1","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Readable","links":[{"name":"Readable","href":"stream.html#class-streamreadable","start":0,"end":8}]},"description":"a stream filtered with the predicate `fn`."}},"description":"This method allows filtering the stream. For each chunk in the stream the `fn`\nfunction will be called and if it returns a truthy value, the chunk will be\npassed to the result stream. If the `fn` function returns a promise - that\npromise will be `await`ed.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous predicate.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {\n  console.log(chunk); // 3, 4\n}\n// With an asynchronous predicate, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n  'nodejs.org',\n  'openjsf.org',\n  'www.linuxfoundation.org',\n]).filter(async (domain) => {\n  const { address } = await resolver.resolve4(domain, { ttl: true });\n  return address.ttl > 60;\n}, { concurrency: 2 });\nfor await (const result of dnsResults) {\n  // Logs domains with more than 60 seconds on the resolved dns record.\n  console.log(result);\n}\n```","summary":"This method allows filtering the stream. For each chunk in the stream the `fn` function will be called and if it returns a truthy value, the chunk will be passed to the result stream. If the `fn` function returns a promise - that promise will be `await`ed.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous predicate.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {\n  console.log(chunk); // 3, 4\n}\n// With an asynchronous predicate, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n  'nodejs.org',\n  'openjsf.org',\n  'www.linuxfoundation.org',\n]).filter(async (domain) => {\n  const { address } = await resolver.resolve4(domain, { ttl: true });\n  return address.ttl > 60;\n}, { concurrency: 2 });\nfor await (const result of dnsResults) {\n  // Logs domains with more than 60 seconds on the resolved dns record.\n  console.log(result);\n}"}],"children":[]},{"kind":"method","id":"readableforeachfn-options","name":"forEach","title":"`readable.forEach(fn[, options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.5.0","v16.15.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"fn","type":{"text":"Function | AsyncFunction","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"AsyncFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction","start":11,"end":24}]},"description":"a function to call on each chunk of the stream.","default":null,"optional":false,"rest":false,"properties":[{"name":"data","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"a chunk of data from the stream.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"aborted if the stream is destroyed allowing to\nabort the `fn` call early.","default":null,"optional":false,"rest":false,"properties":[]}]}]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"concurrency","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"the maximum concurrent invocation of `fn` to call\non the stream at once.","default":"1","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"a promise for when the stream has finished."}},"description":"This method allows iterating a stream. For each chunk in the stream the\n`fn` function will be called. If the `fn` function returns a promise - that\npromise will be `await`ed.\n\nThis method is different from `for await...of` loops in that it can optionally\nprocess chunks concurrently. In addition, a `forEach` iteration can only be\nstopped by having passed a `signal` option and aborting the related\n`AbortController` while `for await...of` can be stopped with `break` or\n`return`. In either case the stream will be destroyed.\n\nThis method is different from listening to the [`'data'`](#event-data) event in that it\nuses the [`readable`](#class-streamreadable) event in the underlying machinery and can limit the\nnumber of concurrent `fn` calls.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous predicate.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {\n  console.log(chunk); // 3, 4\n}\n// With an asynchronous predicate, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n  'nodejs.org',\n  'openjsf.org',\n  'www.linuxfoundation.org',\n]).map(async (domain) => {\n  const { address } = await resolver.resolve4(domain, { ttl: true });\n  return address;\n}, { concurrency: 2 });\nawait dnsResults.forEach((result) => {\n  // Logs result, similar to `for await (const result of dnsResults)`\n  console.log(result);\n});\nconsole.log('done'); // Stream has finished\n```","summary":"This method allows iterating a stream. For each chunk in the stream the `fn` function will be called. If the `fn` function returns a promise - that promise will be `await`ed.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous predicate.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {\n  console.log(chunk); // 3, 4\n}\n// With an asynchronous predicate, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n  'nodejs.org',\n  'openjsf.org',\n  'www.linuxfoundation.org',\n]).map(async (domain) => {\n  const { address } = await resolver.resolve4(domain, { ttl: true });\n  return address;\n}, { concurrency: 2 });\nawait dnsResults.forEach((result) => {\n  // Logs result, similar to `for await (const result of dnsResults)`\n  console.log(result);\n});\nconsole.log('done'); // Stream has finished"}],"children":[]},{"kind":"method","id":"readabletoarrayoptions","name":"toArray","title":"`readable.toArray([options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.5.0","v16.15.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows cancelling the toArray operation if the\nsignal is aborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"a promise containing an array with the contents of the\nstream."}},"description":"This method allows easily obtaining the contents of a stream.\n\nAs this method reads the entire stream into memory, it negates the benefits of\nstreams. It's intended for interoperability and convenience, not as the primary\nway to consume streams.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\nawait Readable.from([1, 2, 3, 4]).toArray(); // [1, 2, 3, 4]\n\nconst resolver = new Resolver();\n\n// Make dns queries concurrently using .map and collect\n// the results into an array using toArray\nconst dnsResults = await Readable.from([\n  'nodejs.org',\n  'openjsf.org',\n  'www.linuxfoundation.org',\n]).map(async (domain) => {\n  const { address } = await resolver.resolve4(domain, { ttl: true });\n  return address;\n}, { concurrency: 2 }).toArray();\n```","summary":"This method allows easily obtaining the contents of a stream.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\nawait Readable.from([1, 2, 3, 4]).toArray(); // [1, 2, 3, 4]\n\nconst resolver = new Resolver();\n\n// Make dns queries concurrently using .map and collect\n// the results into an array using toArray\nconst dnsResults = await Readable.from([\n  'nodejs.org',\n  'openjsf.org',\n  'www.linuxfoundation.org',\n]).map(async (domain) => {\n  const { address } = await resolver.resolve4(domain, { ttl: true });\n  return address;\n}, { concurrency: 2 }).toArray();"}],"children":[]},{"kind":"method","id":"readablesomefn-options","name":"some","title":"`readable.some(fn[, options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.5.0","v16.15.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"fn","type":{"text":"Function | AsyncFunction","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"AsyncFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction","start":11,"end":24}]},"description":"a function to call on each chunk of the stream.","default":null,"optional":false,"rest":false,"properties":[{"name":"data","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"a chunk of data from the stream.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"aborted if the stream is destroyed allowing to\nabort the `fn` call early.","default":null,"optional":false,"rest":false,"properties":[]}]}]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"concurrency","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"the maximum concurrent invocation of `fn` to call\non the stream at once.","default":"1","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"a promise evaluating to `true` if `fn` returned a truthy\nvalue for at least one of the chunks."}},"description":"This method is similar to `Array.prototype.some` and calls `fn` on each chunk\nin the stream until the awaited return value is `true` (or any truthy value).\nOnce an `fn` call on a chunk awaited return value is truthy, the stream is\ndestroyed and the promise is fulfilled with `true`. If none of the `fn`\ncalls on the chunks return a truthy value, the promise is fulfilled with\n`false`.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).some((x) => x > 2); // true\nawait Readable.from([1, 2, 3, 4]).some((x) => x < 0); // false\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst anyBigFile = await Readable.from([\n  'file1',\n  'file2',\n  'file3',\n]).some(async (fileName) => {\n  const stats = await stat(fileName);\n  return stats.size > 1024 * 1024;\n}, { concurrency: 2 });\nconsole.log(anyBigFile); // `true` if any file in the list is bigger than 1MB\nconsole.log('done'); // Stream has finished\n```","summary":"This method is similar to `Array.prototype.some` and calls `fn` on each chunk in the stream until the awaited return value is `true` (or any truthy value). Once an `fn` call on a chunk awaited return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. If none of the `fn` calls on the chunks return a truthy value, the promise is fulfilled with `false`.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).some((x) => x > 2); // true\nawait Readable.from([1, 2, 3, 4]).some((x) => x < 0); // false\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst anyBigFile = await Readable.from([\n  'file1',\n  'file2',\n  'file3',\n]).some(async (fileName) => {\n  const stats = await stat(fileName);\n  return stats.size > 1024 * 1024;\n}, { concurrency: 2 });\nconsole.log(anyBigFile); // `true` if any file in the list is bigger than 1MB\nconsole.log('done'); // Stream has finished"}],"children":[]},{"kind":"method","id":"readablefindfn-options","name":"find","title":"`readable.find(fn[, options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.5.0","v16.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"fn","type":{"text":"Function | AsyncFunction","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"AsyncFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction","start":11,"end":24}]},"description":"a function to call on each chunk of the stream.","default":null,"optional":false,"rest":false,"properties":[{"name":"data","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"a chunk of data from the stream.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"aborted if the stream is destroyed allowing to\nabort the `fn` call early.","default":null,"optional":false,"rest":false,"properties":[]}]}]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"concurrency","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"the maximum concurrent invocation of `fn` to call\non the stream at once.","default":"1","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"a promise evaluating to the first chunk for which `fn`\nevaluated with a truthy value, or `undefined` if no element was found."}},"description":"This method is similar to `Array.prototype.find` and calls `fn` on each chunk\nin the stream to find a chunk with a truthy value for `fn`. Once an `fn` call's\nawaited return value is truthy, the stream is destroyed and the promise is\nfulfilled with value for which `fn` returned a truthy value. If all of the\n`fn` calls on the chunks return a falsy value, the promise is fulfilled with\n`undefined`.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 2); // 3\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 0); // 1\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 10); // undefined\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst foundBigFile = await Readable.from([\n  'file1',\n  'file2',\n  'file3',\n]).find(async (fileName) => {\n  const stats = await stat(fileName);\n  return stats.size > 1024 * 1024;\n}, { concurrency: 2 });\nconsole.log(foundBigFile); // File name of large file, if any file in the list is bigger than 1MB\nconsole.log('done'); // Stream has finished\n```","summary":"This method is similar to `Array.prototype.find` and calls `fn` on each chunk in the stream to find a chunk with a truthy value for `fn`. Once an `fn` call's awaited return value is truthy, the stream is destroyed and the promise is fulfilled with value for which `fn` returned a truthy value. If all of the `fn` calls on the chunks return a falsy value, the promise is fulfilled with `undefined`.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 2); // 3\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 0); // 1\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 10); // undefined\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst foundBigFile = await Readable.from([\n  'file1',\n  'file2',\n  'file3',\n]).find(async (fileName) => {\n  const stats = await stat(fileName);\n  return stats.size > 1024 * 1024;\n}, { concurrency: 2 });\nconsole.log(foundBigFile); // File name of large file, if any file in the list is bigger than 1MB\nconsole.log('done'); // Stream has finished"}],"children":[]},{"kind":"method","id":"readableeveryfn-options","name":"every","title":"`readable.every(fn[, options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.5.0","v16.15.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"fn","type":{"text":"Function | AsyncFunction","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"AsyncFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction","start":11,"end":24}]},"description":"a function to call on each chunk of the stream.","default":null,"optional":false,"rest":false,"properties":[{"name":"data","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"a chunk of data from the stream.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"aborted if the stream is destroyed allowing to\nabort the `fn` call early.","default":null,"optional":false,"rest":false,"properties":[]}]}]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"concurrency","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"the maximum concurrent invocation of `fn` to call\non the stream at once.","default":"1","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"a promise evaluating to `true` if `fn` returned a truthy\nvalue for all of the chunks."}},"description":"This method is similar to `Array.prototype.every` and calls `fn` on each chunk\nin the stream to check if all awaited return values are truthy value for `fn`.\nOnce an `fn` call on a chunk awaited return value is falsy, the stream is\ndestroyed and the promise is fulfilled with `false`. If all of the `fn` calls\non the chunks return a truthy value, the promise is fulfilled with `true`.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).every((x) => x > 2); // false\nawait Readable.from([1, 2, 3, 4]).every((x) => x > 0); // true\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst allBigFiles = await Readable.from([\n  'file1',\n  'file2',\n  'file3',\n]).every(async (fileName) => {\n  const stats = await stat(fileName);\n  return stats.size > 1024 * 1024;\n}, { concurrency: 2 });\n// `true` if all files in the list are bigger than 1MiB\nconsole.log(allBigFiles);\nconsole.log('done'); // Stream has finished\n```","summary":"This method is similar to `Array.prototype.every` and calls `fn` on each chunk in the stream to check if all awaited return values are truthy value for `fn`. Once an `fn` call on a chunk awaited return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. If all of the `fn` calls on the chunks return a truthy value, the promise is fulfilled with `true`.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).every((x) => x > 2); // false\nawait Readable.from([1, 2, 3, 4]).every((x) => x > 0); // true\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst allBigFiles = await Readable.from([\n  'file1',\n  'file2',\n  'file3',\n]).every(async (fileName) => {\n  const stats = await stat(fileName);\n  return stats.size > 1024 * 1024;\n}, { concurrency: 2 });\n// `true` if all files in the list are bigger than 1MiB\nconsole.log(allBigFiles);\nconsole.log('done'); // Stream has finished"}],"children":[]},{"kind":"method","id":"readableflatmapfn-options","name":"flatMap","title":"`readable.flatMap(fn[, options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.5.0","v16.15.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"fn","type":{"text":"Function | AsyncGeneratorFunction | AsyncFunction","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"AsyncGeneratorFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncGeneratorFunction","start":11,"end":33},{"name":"AsyncFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction","start":36,"end":49}]},"description":"a function to map over\nevery chunk in the stream.","default":null,"optional":false,"rest":false,"properties":[{"name":"data","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"a chunk of data from the stream.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"aborted if the stream is destroyed allowing to\nabort the `fn` call early.","default":null,"optional":false,"rest":false,"properties":[]}]}]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"concurrency","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"the maximum concurrent invocation of `fn` to call\non the stream at once.","default":"1","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Readable","links":[{"name":"Readable","href":"stream.html#class-streamreadable","start":0,"end":8}]},"description":"a stream flat-mapped with the function `fn`."}},"description":"This method returns a new stream by applying the given callback to each\nchunk of the stream and then flattening the result.\n\nIt is possible to return a stream or another iterable or async iterable from\n`fn` and the result streams will be merged (flattened) into the returned\nstream.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { createReadStream } from 'node:fs';\n\n// With a synchronous mapper.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).flatMap((x) => [x, x])) {\n  console.log(chunk); // 1, 1, 2, 2, 3, 3, 4, 4\n}\n// With an asynchronous mapper, combine the contents of 4 files\nconst concatResult = Readable.from([\n  './1.mjs',\n  './2.mjs',\n  './3.mjs',\n  './4.mjs',\n]).flatMap((fileName) => createReadStream(fileName));\nfor await (const result of concatResult) {\n  // This will contain the contents (all chunks) of all 4 files\n  console.log(result);\n}\n```","summary":"This method returns a new stream by applying the given callback to each chunk of the stream and then flattening the result.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { createReadStream } from 'node:fs';\n\n// With a synchronous mapper.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).flatMap((x) => [x, x])) {\n  console.log(chunk); // 1, 1, 2, 2, 3, 3, 4, 4\n}\n// With an asynchronous mapper, combine the contents of 4 files\nconst concatResult = Readable.from([\n  './1.mjs',\n  './2.mjs',\n  './3.mjs',\n  './4.mjs',\n]).flatMap((fileName) => createReadStream(fileName));\nfor await (const result of concatResult) {\n  // This will contain the contents (all chunks) of all 4 files\n  console.log(result);\n}"}],"children":[]},{"kind":"method","id":"readabledroplimit-options","name":"drop","title":"`readable.drop(limit[, options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.5.0","v16.15.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"limit","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"the number of chunks to drop from the readable.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Readable","links":[{"name":"Readable","href":"stream.html#class-streamreadable","start":0,"end":8}]},"description":"a stream with `limit` chunks dropped."}},"description":"This method returns a new stream with the first `limit` chunks dropped.\n\n```mjs\nimport { Readable } from 'node:stream';\n\nawait Readable.from([1, 2, 3, 4]).drop(2).toArray(); // [3, 4]\n```","summary":"This method returns a new stream with the first `limit` chunks dropped.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\n\nawait Readable.from([1, 2, 3, 4]).drop(2).toArray(); // [3, 4]"}],"children":[]},{"kind":"method","id":"readabletakelimit-options","name":"take","title":"`readable.take(limit[, options])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.5.0","v16.15.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"limit","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"the number of chunks to take from the readable.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Readable","links":[{"name":"Readable","href":"stream.html#class-streamreadable","start":0,"end":8}]},"description":"a stream with `limit` chunks taken."}},"description":"This method returns a new stream with the first `limit` chunks.\n\n```mjs\nimport { Readable } from 'node:stream';\n\nawait Readable.from([1, 2, 3, 4]).take(2).toArray(); // [1, 2]\n```","summary":"This method returns a new stream with the first `limit` chunks.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\n\nawait Readable.from([1, 2, 3, 4]).take(2).toArray(); // [1, 2]"}],"children":[]},{"kind":"method","id":"readablereducefn-initial-options","name":"reduce","title":"`readable.reduce(fn[, initial[, options]])`","scope":"module","overloadOf":null,"stability":{"index":"1","description":"Experimental"},"added":["v17.5.0","v16.15.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"fn","type":{"text":"Function | AsyncFunction","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8},{"name":"AsyncFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction","start":11,"end":24}]},"description":"a reducer function to call over every chunk\nin the stream.","default":null,"optional":false,"rest":false,"properties":[{"name":"previous","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"the value obtained from the last call to `fn` or the\n`initial` value if specified or the first chunk of the stream otherwise.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"data","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"a chunk of data from the stream.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"aborted if the stream is destroyed allowing to\nabort the `fn` call early.","default":null,"optional":false,"rest":false,"properties":[]}]}]},{"name":"initial","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"the initial value to use in the reduction.","default":null,"optional":true,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows destroying the stream if the signal is\naborted.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Promise","links":[{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":0,"end":7}]},"description":"a promise for the final value of the reduction."}},"description":"This method calls `fn` on each chunk of the stream in order, passing it the\nresult from the calculation on the previous element. It returns a promise for\nthe final value of the reduction.\n\nIf no `initial` value is supplied the first chunk of the stream is used as the\ninitial value. If the stream is empty, the promise is rejected with a\n`TypeError` with the `ERR_INVALID_ARGS` code property.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nconst directoryPath = './src';\nconst filesInDir = await readdir(directoryPath);\n\nconst folderSize = await Readable.from(filesInDir)\n  .reduce(async (totalSize, file) => {\n    const { size } = await stat(join(directoryPath, file));\n    return totalSize + size;\n  }, 0);\n\nconsole.log(folderSize);\n```\n\nThe reducer function iterates the stream element-by-element which means that\nthere is no `concurrency` parameter or parallelism. To perform a `reduce`\nconcurrently, you can extract the async function to [`readable.map`](#readablemapfn-options) method.\n\n```mjs\nimport { Readable } from 'node:stream';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nconst directoryPath = './src';\nconst filesInDir = await readdir(directoryPath);\n\nconst folderSize = await Readable.from(filesInDir)\n  .map((file) => stat(join(directoryPath, file)), { concurrency: 2 })\n  .reduce((totalSize, { size }) => totalSize + size, 0);\n\nconsole.log(folderSize);\n```","summary":"This method calls `fn` on each chunk of the stream in order, passing it the result from the calculation on the previous element. It returns a promise for the final value of the reduction.","examples":[{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nconst directoryPath = './src';\nconst filesInDir = await readdir(directoryPath);\n\nconst folderSize = await Readable.from(filesInDir)\n  .reduce(async (totalSize, file) => {\n    const { size } = await stat(join(directoryPath, file));\n    return totalSize + size;\n  }, 0);\n\nconsole.log(folderSize);"},{"language":"mjs","displayName":null,"code":"import { Readable } from 'node:stream';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nconst directoryPath = './src';\nconst filesInDir = await readdir(directoryPath);\n\nconst folderSize = await Readable.from(filesInDir)\n  .map((file) => stat(join(directoryPath, file)), { concurrency: 2 })\n  .reduce((totalSize, { size }) => totalSize + size, 0);\n\nconsole.log(folderSize);"}],"children":[]}]}]},{"kind":"section","id":"duplex-and-transform-streams","name":"Duplex and transform streams","title":"Duplex and transform streams","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"","summary":"","examples":[],"children":[{"kind":"class","id":"class-streamduplex","name":"Duplex","title":"Class: `stream.Duplex`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v6.8.0"],"prUrl":"https://github.com/nodejs/node/pull/8834","commit":null,"description":"Instances of `Duplex` now return `true` when checking `instanceof stream.Writable`."}],"extends":null,"description":"Duplex streams are streams that implement both the [`Readable`](#class-streamreadable) and\n[`Writable`](#class-streamwritable) interfaces.\n\nExamples of `Duplex` streams include:\n\n* [TCP sockets](net.html#class-netsocket)\n* [zlib streams](zlib.html)\n* [crypto streams](crypto.html)","summary":"Duplex streams are streams that implement both the `Readable` and `Writable` interfaces.","examples":[],"children":[{"kind":"property","id":"duplexallowhalfopen","name":"allowHalfOpen","title":"`duplex.allowHalfOpen`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"default":null,"description":"If `false` then the stream will automatically end the writable side when the\nreadable side ends. Set initially by the `allowHalfOpen` constructor option,\nwhich defaults to `true`.\n\nThis can be changed manually to change the half-open behavior of an existing\n`Duplex` stream instance, but must be changed before the `'end'` event is\nemitted.","summary":"If `false` then the stream will automatically end the writable side when the readable side ends. Set initially by the `allowHalfOpen` constructor option, which defaults to `true`.","examples":[],"children":[]}]},{"kind":"class","id":"class-streamtransform","name":"Transform","title":"Class: `stream.Transform`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"Transform streams are [`Duplex`](#class-streamduplex) streams where the output is in some way\nrelated to the input. Like all [`Duplex`](#class-streamduplex) streams, `Transform` streams\nimplement both the [`Readable`](#class-streamreadable) and [`Writable`](#class-streamwritable) interfaces.\n\nExamples of `Transform` streams include:\n\n* [zlib streams](zlib.html)\n* [crypto streams](crypto.html)","summary":"Transform streams are `Duplex` streams where the output is in some way related to the input. Like all `Duplex` streams, `Transform` streams implement both the `Readable` and `Writable` interfaces.","examples":[],"children":[{"kind":"method","id":"transformdestroyerror","name":"destroy","title":"`transform.destroy([error])`","scope":"module","overloadOf":null,"stability":null,"added":["v8.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v14.0.0"],"prUrl":"https://github.com/nodejs/node/pull/29197","commit":null,"description":"Work as a no-op on a stream that has already been destroyed."}],"signature":{"parameters":[{"name":"error","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"this","links":[{"name":"this","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/this","start":0,"end":4}]},"description":""}},"description":"Destroy the stream, and optionally emit an `'error'` event. After this call, the\ntransform stream would release any internal resources.\nImplementors should not override this method, but instead implement\n[`readable._destroy()`](#readable_destroyerr-callback).\nThe default implementation of `_destroy()` for `Transform` also emit `'close'`\nunless `emitClose` is set in false.\n\nOnce `destroy()` has been called, any further calls will be a no-op and no\nfurther errors except from `_destroy()` may be emitted as `'error'`.","summary":"Destroy the stream, and optionally emit an `'error'` event. After this call, the transform stream would release any internal resources. Implementors should not override this method, but instead implement `readable._destroy()`. The default implementation of `_destroy()` for `Transform` also emit `'close'` unless `emitClose` is set in false.","examples":[],"children":[]}]},{"kind":"method","id":"streamduplexpairoptions","name":"duplexPair","title":"`stream.duplexPair([options])`","scope":"module","overloadOf":null,"stability":null,"added":["v22.6.0","v20.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"A value to pass to both [`Duplex`](#class-streamduplex) constructors,\nto set options such as buffering.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"Array","links":[{"name":"Array","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array","start":0,"end":5}]},"description":"of two [`Duplex`](#class-streamduplex) instances."}},"description":"The utility function `duplexPair` returns an Array with two items,\neach being a `Duplex` stream connected to the other side:\n\n```js\nconst [ sideA, sideB ] = duplexPair();\n```\n\nWhatever is written to one stream is made readable on the other. It provides\nbehavior analogous to a network connection, where the data written by the client\nbecomes readable by the server, and vice-versa.\n\nThe Duplex streams are symmetrical; one or the other may be used without any\ndifference in behavior.","summary":"The utility function `duplexPair` returns an Array with two items, each being a `Duplex` stream connected to the other side:","examples":[{"language":"js","displayName":null,"code":"const [ sideA, sideB ] = duplexPair();"}],"children":[]}]},{"kind":"method","id":"streamfinishedstream-options-callback","name":"finished","title":"`stream.finished(stream[, options], callback)`","scope":"module","overloadOf":null,"stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v19.5.0"],"prUrl":"https://github.com/nodejs/node/pull/46205","commit":null,"description":"Added support for `ReadableStream` and `WritableStream`."},{"versions":["v15.11.0"],"prUrl":"https://github.com/nodejs/node/pull/37354","commit":null,"description":"The `signal` option was added."},{"versions":["v14.0.0"],"prUrl":"https://github.com/nodejs/node/pull/32158","commit":null,"description":"The `finished(stream, cb)` will wait for the `'close'` event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit `'close'`."},{"versions":["v14.0.0"],"prUrl":"https://github.com/nodejs/node/pull/31545","commit":null,"description":"Emitting `'close'` before `'end'` on a `Readable` stream will cause an `ERR_STREAM_PREMATURE_CLOSE` error."},{"versions":["v14.0.0"],"prUrl":"https://github.com/nodejs/node/pull/31509","commit":null,"description":"Callback will be invoked on streams which have already finished before the call to `finished(stream, cb)`."}],"signature":{"parameters":[{"name":"stream","type":{"text":"Stream | ReadableStream | WritableStream","links":[{"name":"Stream","href":"stream.html#stream","start":0,"end":6},{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":9,"end":23},{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":26,"end":40}]},"description":"A readable and/or writable\nstream/webstream.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"error","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If set to `false`, then a call to `emit('error', err)` is\nnot treated as finished.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"readable","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"When set to `false`, the callback will be called when\nthe stream ends even though the stream might still be readable.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"writable","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"When set to `false`, the callback will be called when\nthe stream ends even though the stream might still be writable.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"allows aborting the wait for the stream finish. The\nunderlying stream will *not* be aborted if the signal is aborted. The\ncallback will get called with an `AbortError`. All registered\nlisteners added by this function will also be removed.","default":null,"optional":false,"rest":false,"properties":[]}]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"A callback function that takes an optional error\nargument.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"A cleanup function which removes all registered\nlisteners."}},"description":"A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.\n\n```js\nconst { finished } = require('node:stream');\nconst fs = require('node:fs');\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\nEspecially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit `'end'`\nor `'finish'`.\n\nThe `finished` API provides [promise version](#streamfinishedstream-options).\n\n`stream.finished()` leaves dangling event listeners (in particular\n`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been\ninvoked. The reason for this is so that unexpected `'error'` events (due to\nincorrect stream implementations) do not cause unexpected crashes.\nIf this is unwanted behavior then the returned cleanup function needs to be\ninvoked in the callback:\n\n```js\nconst cleanup = finished(rs, (err) => {\n  cleanup();\n  // ...\n});\n```","summary":"A function to get notified when a stream is no longer readable, writable or has experienced an error or a premature close event.","examples":[{"language":"js","displayName":null,"code":"const { finished } = require('node:stream');\nconst fs = require('node:fs');\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."},{"language":"js","displayName":null,"code":"const cleanup = finished(rs, (err) => {\n  cleanup();\n  // ...\n});"}],"children":[]},{"kind":"method","id":"streampipelinesource-transforms-destination-callback","name":"pipeline","title":"`stream.pipeline(source[, ...transforms], destination, callback)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"source","type":null,"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"transforms","type":null,"description":"","default":null,"optional":true,"rest":true,"properties":[]},{"name":"destination","type":null,"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"callback","type":null,"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"","summary":"","examples":[],"children":[]},{"kind":"method","id":"streampipelinestreams-callback","name":"pipeline","title":"`stream.pipeline(streams, callback)`","scope":"module","overloadOf":"streampipelinesource-transforms-destination-callback","stability":null,"added":["v10.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v19.7.0","v18.16.0"],"prUrl":"https://github.com/nodejs/node/pull/46307","commit":null,"description":"Added support for webstreams."},{"versions":["v18.0.0"],"prUrl":"https://github.com/nodejs/node/pull/41678","commit":null,"description":"Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."},{"versions":["v14.0.0"],"prUrl":"https://github.com/nodejs/node/pull/32158","commit":null,"description":"The `pipeline(..., cb)` will wait for the `'close'` event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit `'close'`."},{"versions":["v13.10.0"],"prUrl":"https://github.com/nodejs/node/pull/31223","commit":null,"description":"Add support for async generators."}],"signature":{"parameters":[{"name":"streams","type":{"text":"Stream[] | Iterable[] | AsyncIterable[] | Function[] | ReadableStream[] | WritableStream[] | TransformStream[]","links":[{"name":"Stream","href":"stream.html#stream","start":0,"end":6},{"name":"Iterable","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol","start":11,"end":19},{"name":"AsyncIterable","href":"https://tc39.github.io/ecma262/#sec-asynciterable-interface","start":24,"end":37},{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":42,"end":50},{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":55,"end":69},{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":74,"end":88},{"name":"TransformStream","href":"webstreams.html#class-transformstream","start":93,"end":108}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Called when the pipeline is fully done.","default":null,"optional":false,"rest":false,"properties":[{"name":"err","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"val","type":null,"description":"Resolved value of `Promise` returned by `destination`.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Stream","links":[{"name":"Stream","href":"stream.html#stream","start":0,"end":6}]},"description":""}},"description":"A module method to pipe between streams and generators forwarding errors and\nproperly cleaning up and provide a callback when the pipeline is complete.\n\n```js\nconst { pipeline } = require('node:stream');\nconst fs = require('node:fs');\nconst zlib = require('node: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\nThe `pipeline` API provides a [promise version](#streampipelinesource-transforms-destination-options).\n\n`stream.pipeline()` will call `stream.destroy(err)` on all streams except:\n\n* `Readable` streams which have emitted `'end'` or `'close'`.\n* `Writable` streams which have emitted `'finish'` or `'close'`.\n\n`stream.pipeline()` leaves dangling event listeners on the streams\nafter the `callback` has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors. If the last\nstream is readable, dangling event listeners will be removed so that the last\nstream can be consumed later.\n\n`stream.pipeline()` closes all the streams when an error is raised.\nThe `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior\nonce it would destroy the socket without sending the expected response.\nSee the example below:\n\n```js\nconst fs = require('node:fs');\nconst http = require('node:http');\nconst { pipeline } = require('node:stream');\n\nconst server = http.createServer((req, res) => {\n  const fileStream = fs.createReadStream('./fileNotExist.txt');\n  pipeline(fileStream, res, (err) => {\n    if (err) {\n      console.log(err); // No such file\n      // this message can't be sent once `pipeline` already destroyed the socket\n      return res.end('error!!!');\n    }\n  });\n});\n```","summary":"A module method to pipe between streams and generators forwarding errors and properly cleaning up and provide a callback when the pipeline is complete.","examples":[{"language":"js","displayName":null,"code":"const { pipeline } = require('node:stream');\nconst fs = require('node:fs');\nconst zlib = require('node: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);"},{"language":"js","displayName":null,"code":"const fs = require('node:fs');\nconst http = require('node:http');\nconst { pipeline } = require('node:stream');\n\nconst server = http.createServer((req, res) => {\n  const fileStream = fs.createReadStream('./fileNotExist.txt');\n  pipeline(fileStream, res, (err) => {\n    if (err) {\n      console.log(err); // No such file\n      // this message can't be sent once `pipeline` already destroyed the socket\n      return res.end('error!!!');\n    }\n  });\n});"}],"children":[]},{"kind":"method","id":"streamcomposestreams","name":"compose","title":"`stream.compose(...streams)`","scope":"module","overloadOf":null,"stability":null,"added":["v16.9.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v26.2.0"],"prUrl":"https://github.com/nodejs/node/pull/62562","commit":null,"description":"Marking the API stable."},{"versions":["v21.1.0","v20.10.0"],"prUrl":"https://github.com/nodejs/node/pull/50187","commit":null,"description":"Added support for stream class."},{"versions":["v19.8.0","v18.16.0"],"prUrl":"https://github.com/nodejs/node/pull/46675","commit":null,"description":"Added support for webstreams."}],"signature":{"parameters":[{"name":"streams","type":null,"description":"","default":null,"optional":false,"rest":true,"properties":[]}],"returns":{"type":{"text":"stream.Duplex","links":[{"name":"stream.Duplex","href":"stream.html#class-streamduplex","start":0,"end":13}]},"description":""}},"description":"Combines two or more streams into a `Duplex` stream that writes to the\nfirst stream and reads from the last. Each provided stream is piped into\nthe next, using `stream.pipeline`. If any of the streams error then all\nare destroyed, including the outer `Duplex` stream.\n\nBecause `stream.compose` returns a new stream that in turn can (and\nshould) be piped into other streams, it enables composition. In contrast,\nwhen passing streams to `stream.pipeline`, typically the first stream is\na readable stream and the last a writable stream, forming a closed\ncircuit.\n\nIf passed a `Function` it must be a factory method taking a `source`\n`Iterable`.\n\n```mjs\nimport { compose, Transform } from 'node:stream';\n\nconst removeSpaces = new Transform({\n  transform(chunk, encoding, callback) {\n    callback(null, String(chunk).replace(' ', ''));\n  },\n});\n\nasync function* toUpper(source) {\n  for await (const chunk of source) {\n    yield String(chunk).toUpperCase();\n  }\n}\n\nlet res = '';\nfor await (const buf of compose(removeSpaces, toUpper).end('hello world')) {\n  res += buf;\n}\n\nconsole.log(res); // prints 'HELLOWORLD'\n```\n\n`stream.compose` can be used to convert async iterables, generators and\nfunctions into streams.\n\n* `AsyncIterable` converts into a readable `Duplex`. Cannot yield\n  `null`.\n* `AsyncGeneratorFunction` converts into a readable/writable transform `Duplex`.\n  Must take a source `AsyncIterable` as first parameter. Cannot yield\n  `null`.\n* `AsyncFunction` converts into a writable `Duplex`. Must return\n  either `null` or `undefined`.\n\n```mjs\nimport { compose } from 'node:stream';\nimport { finished } from 'node:stream/promises';\n\n// Convert AsyncIterable into readable Duplex.\nconst s1 = compose(async function*() {\n  yield 'Hello';\n  yield 'World';\n}());\n\n// Convert AsyncGenerator into transform Duplex.\nconst s2 = compose(async function*(source) {\n  for await (const chunk of source) {\n    yield String(chunk).toUpperCase();\n  }\n});\n\nlet res = '';\n\n// Convert AsyncFunction into writable Duplex.\nconst s3 = compose(async function(source) {\n  for await (const chunk of source) {\n    res += chunk;\n  }\n});\n\nawait finished(compose(s1, s2, s3));\n\nconsole.log(res); // prints 'HELLOWORLD'\n```\n\nFor convenience, the [`readable.compose(stream)`](#readablecomposestream-options) method is available on\n{Readable} and {Duplex} streams as a wrapper for this function.","summary":"Combines two or more streams into a `Duplex` stream that writes to the first stream and reads from the last. Each provided stream is piped into the next, using `stream.pipeline`. If any of the streams error then all are destroyed, including the outer `Duplex` stream.","examples":[{"language":"mjs","displayName":null,"code":"import { compose, Transform } from 'node:stream';\n\nconst removeSpaces = new Transform({\n  transform(chunk, encoding, callback) {\n    callback(null, String(chunk).replace(' ', ''));\n  },\n});\n\nasync function* toUpper(source) {\n  for await (const chunk of source) {\n    yield String(chunk).toUpperCase();\n  }\n}\n\nlet res = '';\nfor await (const buf of compose(removeSpaces, toUpper).end('hello world')) {\n  res += buf;\n}\n\nconsole.log(res); // prints 'HELLOWORLD'"},{"language":"mjs","displayName":null,"code":"import { compose } from 'node:stream';\nimport { finished } from 'node:stream/promises';\n\n// Convert AsyncIterable into readable Duplex.\nconst s1 = compose(async function*() {\n  yield 'Hello';\n  yield 'World';\n}());\n\n// Convert AsyncGenerator into transform Duplex.\nconst s2 = compose(async function*(source) {\n  for await (const chunk of source) {\n    yield String(chunk).toUpperCase();\n  }\n});\n\nlet res = '';\n\n// Convert AsyncFunction into writable Duplex.\nconst s3 = compose(async function(source) {\n  for await (const chunk of source) {\n    res += chunk;\n  }\n});\n\nawait finished(compose(s1, s2, s3));\n\nconsole.log(res); // prints 'HELLOWORLD'"}],"children":[]},{"kind":"method","id":"streamisdestroyedstream","name":"isDestroyed","title":"`stream.isDestroyed(stream)`","scope":"module","overloadOf":null,"stability":null,"added":["v19.9.0","v18.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"stream","type":{"text":"Readable | Writable | Duplex","links":[{"name":"Readable","href":"stream.html#class-streamreadable","start":0,"end":8},{"name":"Writable","href":"stream.html#class-streamwritable","start":11,"end":19},{"name":"Duplex","href":"stream.html#class-streamduplex","start":22,"end":28}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"boolean | null","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7},{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":10,"end":14}]},"description":"Only returns `null` if `stream` is not a valid `Readable`, `Writable` or `Duplex`."}},"description":"Returns whether the stream has been destroyed.","summary":"Returns whether the stream has been destroyed.","examples":[],"children":[]},{"kind":"method","id":"streamiserroredstream","name":"isErrored","title":"`stream.isErrored(stream)`","scope":"module","overloadOf":null,"stability":null,"added":["v17.3.0","v16.14.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[{"name":"stream","type":{"text":"Readable | Writable | Duplex | WritableStream | ReadableStream","links":[{"name":"Readable","href":"stream.html#class-streamreadable","start":0,"end":8},{"name":"Writable","href":"stream.html#class-streamwritable","start":11,"end":19},{"name":"Duplex","href":"stream.html#class-streamduplex","start":22,"end":28},{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":31,"end":45},{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":48,"end":62}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":""}},"description":"Returns whether the stream has encountered an error.","summary":"Returns whether the stream has encountered an error.","examples":[],"children":[]},{"kind":"method","id":"streamisreadablestream","name":"isReadable","title":"`stream.isReadable(stream)`","scope":"module","overloadOf":null,"stability":null,"added":["v17.4.0","v16.14.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[{"name":"stream","type":{"text":"Readable | Duplex | ReadableStream","links":[{"name":"Readable","href":"stream.html#class-streamreadable","start":0,"end":8},{"name":"Duplex","href":"stream.html#class-streamduplex","start":11,"end":17},{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":20,"end":34}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"boolean | null","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7},{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":10,"end":14}]},"description":"Only returns `null` if `stream` is not a valid `Readable`, `Duplex` or `ReadableStream`."}},"description":"Returns whether the stream is readable.","summary":"Returns whether the stream is readable.","examples":[],"children":[]},{"kind":"method","id":"streamiswritablestream","name":"isWritable","title":"`stream.isWritable(stream)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"stream","type":{"text":"Writable | Duplex | WritableStream","links":[{"name":"Writable","href":"stream.html#class-streamwritable","start":0,"end":8},{"name":"Duplex","href":"stream.html#class-streamduplex","start":11,"end":17},{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":20,"end":34}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"boolean | null","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7},{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":10,"end":14}]},"description":"Only returns `null` if `stream` is not a valid `Writable`, `Duplex` or `WritableStream`."}},"description":"Returns whether the stream is writable.","summary":"Returns whether the stream is writable.","examples":[],"children":[]},{"kind":"method","id":"streamreadablefromiterable-options","name":"from","title":"`stream.Readable.from(iterable[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v12.3.0","v10.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"iterable","type":{"text":"Iterable","links":[{"name":"Iterable","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol","start":0,"end":8}]},"description":"Object implementing the `Symbol.asyncIterator` or\n`Symbol.iterator` iterable protocol. Emits an 'error' event if a null\nvalue is passed.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"Options provided to `new stream.Readable([options])`.\nBy default, `Readable.from()` will set `options.objectMode` to `true`, unless\nthis is explicitly opted out by setting `options.objectMode` to `false`.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"stream.Readable","links":[{"name":"stream.Readable","href":"stream.html#class-streamreadable","start":0,"end":15}]},"description":""}},"description":"A utility method for creating readable streams out of iterators.\n\n```js\nconst { Readable } = require('node: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```\n\nCalling `Readable.from(string)` or `Readable.from(buffer)` will not have\nthe strings or buffers be iterated to match the other streams semantics\nfor performance reasons.\n\nIf an `Iterable` object containing promises is passed as an argument,\nit might result in unhandled rejection.\n\n```js\nconst { Readable } = require('node:stream');\n\nReadable.from([\n  new Promise((resolve) => setTimeout(resolve('1'), 1500)),\n  new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection\n]);\n```","summary":"A utility method for creating readable streams out of iterators.","examples":[{"language":"js","displayName":null,"code":"const { Readable } = require('node: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});"},{"language":"js","displayName":null,"code":"const { Readable } = require('node:stream');\n\nReadable.from([\n  new Promise((resolve) => setTimeout(resolve('1'), 1500)),\n  new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection\n]);"}],"children":[]},{"kind":"method","id":"streamreadablefromwebreadablestream-options","name":"fromWeb","title":"`stream.Readable.fromWeb(readableStream[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v17.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[{"name":"readableStream","type":{"text":"ReadableStream","links":[{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":0,"end":14}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"highWaterMark","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"objectMode","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"stream.Readable","links":[{"name":"stream.Readable","href":"stream.html#class-streamreadable","start":0,"end":15}]},"description":""}},"description":"","summary":"","examples":[],"children":[]},{"kind":"method","id":"streamreadableisdisturbedstream","name":"isDisturbed","title":"`stream.Readable.isDisturbed(stream)`","scope":"module","overloadOf":null,"stability":null,"added":["v16.8.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[{"name":"stream","type":{"text":"stream.Readable | ReadableStream","links":[{"name":"stream.Readable","href":"stream.html#class-streamreadable","start":0,"end":15},{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":18,"end":32}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":null,"description":"`boolean`"}},"description":"Returns whether the stream has been read from or cancelled.","summary":"Returns whether the stream has been read from or cancelled.","examples":[],"children":[]},{"kind":"method","id":"streamreadabletowebstreamreadable-options","name":"toWeb","title":"`stream.Readable.toWeb(streamReadable[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v17.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v25.4.0","v24.14.0"],"prUrl":"https://github.com/nodejs/node/pull/58664","commit":null,"description":"Add 'type' option to specify 'bytes'."},{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."},{"versions":["v18.7.0"],"prUrl":"https://github.com/nodejs/node/pull/43515","commit":null,"description":"include strategy options on Readable."}],"signature":{"parameters":[{"name":"streamReadable","type":{"text":"stream.Readable","links":[{"name":"stream.Readable","href":"stream.html#class-streamreadable","start":0,"end":15}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"strategy","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"highWaterMark","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The maximum internal queue size (of the created\n`ReadableStream`) before backpressure is applied in reading from the given\n`stream.Readable`. If no value is provided, it will be taken from the\ngiven `stream.Readable`.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"size","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"A function that size of the given chunk of data.\nIf no value is provided, the size will be `1` for all the chunks.","default":null,"optional":false,"rest":false,"properties":[{"name":"chunk","type":{"text":"any","links":[{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":0,"end":3}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]}]},{"name":"type","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Specifies the type of the created `ReadableStream`. Must be\n`'bytes'` or undefined.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"ReadableStream","links":[{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":0,"end":14}]},"description":""}},"description":"","summary":"","examples":[],"children":[]},{"kind":"method","id":"streamwritablefromwebwritablestream-options","name":"fromWeb","title":"`stream.Writable.fromWeb(writableStream[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v17.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[{"name":"writableStream","type":{"text":"WritableStream","links":[{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":0,"end":14}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"decodeStrings","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"highWaterMark","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"objectMode","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"stream.Writable","links":[{"name":"stream.Writable","href":"stream.html#class-streamwritable","start":0,"end":15}]},"description":""}},"description":"","summary":"","examples":[],"children":[]},{"kind":"method","id":"streamwritabletowebstreamwritable","name":"toWeb","title":"`stream.Writable.toWeb(streamWritable)`","scope":"module","overloadOf":null,"stability":null,"added":["v17.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[{"name":"streamWritable","type":{"text":"stream.Writable","links":[{"name":"stream.Writable","href":"stream.html#class-streamwritable","start":0,"end":15}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"WritableStream","links":[{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":0,"end":14}]},"description":""}},"description":"","summary":"","examples":[],"children":[]},{"kind":"method","id":"streamduplexfromsrc","name":"from","title":"`stream.Duplex.from(src)`","scope":"module","overloadOf":null,"stability":null,"added":["v16.8.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v19.5.0","v18.17.0"],"prUrl":"https://github.com/nodejs/node/pull/46190","commit":null,"description":"The `src` argument can now be a `ReadableStream` or `WritableStream`."}],"signature":{"parameters":[{"name":"src","type":{"text":"Stream | Blob | ArrayBuffer | string | Iterable | AsyncIterable | AsyncGeneratorFunction | AsyncFunction | Promise | Object | ReadableStream | WritableStream","links":[{"name":"Stream","href":"stream.html#stream","start":0,"end":6},{"name":"Blob","href":"buffer.html#class-blob","start":9,"end":13},{"name":"ArrayBuffer","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer","start":16,"end":27},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":30,"end":36},{"name":"Iterable","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol","start":39,"end":47},{"name":"AsyncIterable","href":"https://tc39.github.io/ecma262/#sec-asynciterable-interface","start":50,"end":63},{"name":"AsyncGeneratorFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncGeneratorFunction","start":66,"end":88},{"name":"AsyncFunction","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction","start":91,"end":104},{"name":"Promise","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise","start":107,"end":114},{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":117,"end":123},{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":126,"end":140},{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":143,"end":157}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"A utility method for creating duplex streams.\n\n* `Stream` converts writable stream into writable `Duplex` and readable stream\n  to `Duplex`.\n* `Blob` converts into readable `Duplex`.\n* `string` converts into readable `Duplex`.\n* `ArrayBuffer` converts into readable `Duplex`.\n* `AsyncIterable` converts into a readable `Duplex`. Cannot yield\n  `null`.\n* `AsyncGeneratorFunction` converts into a readable/writable transform\n  `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield\n  `null`.\n* `AsyncFunction` converts into a writable `Duplex`. Must return\n  either `null` or `undefined`\n* `Object ({ writable, readable })` converts `readable` and\n  `writable` into `Stream` and then combines them into `Duplex` where the\n  `Duplex` will write to the `writable` and read from the `readable`.\n* `Promise` converts into readable `Duplex`. Value `null` is ignored.\n* `ReadableStream` converts into readable `Duplex`.\n* `WritableStream` converts into writable `Duplex`.\n* Returns: {stream.Duplex}\n\nIf an `Iterable` object containing promises is passed as an argument,\nit might result in unhandled rejection.\n\n```js\nconst { Duplex } = require('node:stream');\n\nDuplex.from([\n  new Promise((resolve) => setTimeout(resolve('1'), 1500)),\n  new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection\n]);\n```","summary":"A utility method for creating duplex streams.","examples":[{"language":"js","displayName":null,"code":"const { Duplex } = require('node:stream');\n\nDuplex.from([\n  new Promise((resolve) => setTimeout(resolve('1'), 1500)),\n  new Promise((_, reject) => setTimeout(reject(new Error('2')), 1000)), // Unhandled rejection\n]);"}],"children":[]},{"kind":"method","id":"streamduplexfromwebpair-options","name":"fromWeb","title":"`stream.Duplex.fromWeb(pair[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v17.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[{"name":"pair","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[{"name":"readable","type":{"text":"ReadableStream","links":[{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":0,"end":14}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"writable","type":{"text":"WritableStream","links":[{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":0,"end":14}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"allowHalfOpen","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"decodeStrings","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"highWaterMark","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"objectMode","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"stream.Duplex","links":[{"name":"stream.Duplex","href":"stream.html#class-streamduplex","start":0,"end":13}]},"description":""}},"description":"```mjs\nimport { Duplex } from 'node:stream';\nimport {\n  ReadableStream,\n  WritableStream,\n} from 'node:stream/web';\n\nconst readable = new ReadableStream({\n  start(controller) {\n    controller.enqueue('world');\n  },\n});\n\nconst writable = new WritableStream({\n  write(chunk) {\n    console.log('writable', chunk);\n  },\n});\n\nconst pair = {\n  readable,\n  writable,\n};\nconst duplex = Duplex.fromWeb(pair, { encoding: 'utf8', objectMode: true });\n\nduplex.write('hello');\n\nfor await (const chunk of duplex) {\n  console.log('readable', chunk);\n}\n```\n\n```cjs\nconst { Duplex } = require('node:stream');\nconst {\n  ReadableStream,\n  WritableStream,\n} = require('node:stream/web');\n\nconst readable = new ReadableStream({\n  start(controller) {\n    controller.enqueue('world');\n  },\n});\n\nconst writable = new WritableStream({\n  write(chunk) {\n    console.log('writable', chunk);\n  },\n});\n\nconst pair = {\n  readable,\n  writable,\n};\nconst duplex = Duplex.fromWeb(pair, { encoding: 'utf8', objectMode: true });\n\nduplex.write('hello');\nduplex.once('readable', () => console.log('readable', duplex.read()));\n```","summary":"","examples":[{"language":"mjs","displayName":null,"code":"import { Duplex } from 'node:stream';\nimport {\n  ReadableStream,\n  WritableStream,\n} from 'node:stream/web';\n\nconst readable = new ReadableStream({\n  start(controller) {\n    controller.enqueue('world');\n  },\n});\n\nconst writable = new WritableStream({\n  write(chunk) {\n    console.log('writable', chunk);\n  },\n});\n\nconst pair = {\n  readable,\n  writable,\n};\nconst duplex = Duplex.fromWeb(pair, { encoding: 'utf8', objectMode: true });\n\nduplex.write('hello');\n\nfor await (const chunk of duplex) {\n  console.log('readable', chunk);\n}"},{"language":"cjs","displayName":null,"code":"const { Duplex } = require('node:stream');\nconst {\n  ReadableStream,\n  WritableStream,\n} = require('node:stream/web');\n\nconst readable = new ReadableStream({\n  start(controller) {\n    controller.enqueue('world');\n  },\n});\n\nconst writable = new WritableStream({\n  write(chunk) {\n    console.log('writable', chunk);\n  },\n});\n\nconst pair = {\n  readable,\n  writable,\n};\nconst duplex = Duplex.fromWeb(pair, { encoding: 'utf8', objectMode: true });\n\nduplex.write('hello');\nduplex.once('readable', () => console.log('readable', duplex.read()));"}],"children":[]},{"kind":"method","id":"streamduplextowebstreamduplex-options","name":"toWeb","title":"`stream.Duplex.toWeb(streamDuplex[, options])`","scope":"module","overloadOf":null,"stability":null,"added":["v17.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v25.7.0"],"prUrl":"https://github.com/nodejs/node/pull/61632","commit":null,"description":"Added the 'readableType' option to specify the ReadableStream type. The 'type' option is deprecated."},{"versions":["v25.4.0","v24.14.0"],"prUrl":"https://github.com/nodejs/node/pull/58664","commit":null,"description":"Added the 'type' option to specify the ReadableStream type."},{"versions":["v24.0.0","v22.17.0"],"prUrl":"https://github.com/nodejs/node/pull/57513","commit":null,"description":"Marking the API stable."}],"signature":{"parameters":[{"name":"streamDuplex","type":{"text":"stream.Duplex","links":[{"name":"stream.Duplex","href":"stream.html#class-streamduplex","start":0,"end":13}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"readableType","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Specifies the type of the `ReadableStream` half of\nthe created readable-writable pair. Must be `'bytes'` or undefined.\n(`options.type` is a deprecated alias for this option.)","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":{"type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":""}},"description":"```mjs\nimport { Duplex } from 'node:stream';\n\nconst duplex = Duplex({\n  objectMode: true,\n  read() {\n    this.push('world');\n    this.push(null);\n  },\n  write(chunk, encoding, callback) {\n    console.log('writable', chunk);\n    callback();\n  },\n});\n\nconst { readable, writable } = Duplex.toWeb(duplex);\nwritable.getWriter().write('hello');\n\nconst { value } = await readable.getReader().read();\nconsole.log('readable', value);\n```\n\n```cjs\nconst { Duplex } = require('node:stream');\n\nconst duplex = Duplex({\n  objectMode: true,\n  read() {\n    this.push('world');\n    this.push(null);\n  },\n  write(chunk, encoding, callback) {\n    console.log('writable', chunk);\n    callback();\n  },\n});\n\nconst { readable, writable } = Duplex.toWeb(duplex);\nwritable.getWriter().write('hello');\n\nreadable.getReader().read().then((result) => {\n  console.log('readable', result.value);\n});\n```","summary":"","examples":[{"language":"mjs","displayName":null,"code":"import { Duplex } from 'node:stream';\n\nconst duplex = Duplex({\n  objectMode: true,\n  read() {\n    this.push('world');\n    this.push(null);\n  },\n  write(chunk, encoding, callback) {\n    console.log('writable', chunk);\n    callback();\n  },\n});\n\nconst { readable, writable } = Duplex.toWeb(duplex);\nwritable.getWriter().write('hello');\n\nconst { value } = await readable.getReader().read();\nconsole.log('readable', value);"},{"language":"cjs","displayName":null,"code":"const { Duplex } = require('node:stream');\n\nconst duplex = Duplex({\n  objectMode: true,\n  read() {\n    this.push('world');\n    this.push(null);\n  },\n  write(chunk, encoding, callback) {\n    console.log('writable', chunk);\n    callback();\n  },\n});\n\nconst { readable, writable } = Duplex.toWeb(duplex);\nwritable.getWriter().write('hello');\n\nreadable.getReader().read().then((result) => {\n  console.log('readable', result.value);\n});"}],"children":[]},{"kind":"method","id":"streamaddabortsignalsignal-stream","name":"addAbortSignal","title":"`stream.addAbortSignal(signal, stream)`","scope":"module","overloadOf":null,"stability":null,"added":["v15.4.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v19.7.0","v18.16.0"],"prUrl":"https://github.com/nodejs/node/pull/46273","commit":null,"description":"Added support for `ReadableStream` and `WritableStream`."}],"signature":{"parameters":[{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"A signal representing possible cancellation","default":null,"optional":false,"rest":false,"properties":[]},{"name":"stream","type":{"text":"Stream | ReadableStream | WritableStream","links":[{"name":"Stream","href":"stream.html#stream","start":0,"end":6},{"name":"ReadableStream","href":"webstreams.html#class-readablestream","start":9,"end":23},{"name":"WritableStream","href":"webstreams.html#class-writablestream","start":26,"end":40}]},"description":"A stream to attach a signal\nto.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"Attaches an AbortSignal to a readable or writable stream. This lets code\ncontrol stream destruction using an `AbortController`.\n\nCalling `abort` on the `AbortController` corresponding to the passed\n`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`\non the stream, and `controller.error(new AbortError())` for webstreams.\n\n```js\nconst fs = require('node:fs');\n\nconst controller = new AbortController();\nconst read = addAbortSignal(\n  controller.signal,\n  fs.createReadStream(('object.json')),\n);\n// Later, abort the operation closing the stream\ncontroller.abort();\n```\n\nOr using an `AbortSignal` with a readable stream as an async iterable:\n\n```js\nconst controller = new AbortController();\nsetTimeout(() => controller.abort(), 10_000); // set a timeout\nconst stream = addAbortSignal(\n  controller.signal,\n  fs.createReadStream(('object.json')),\n);\n(async () => {\n  try {\n    for await (const chunk of stream) {\n      await process(chunk);\n    }\n  } catch (e) {\n    if (e.name === 'AbortError') {\n      // The operation was cancelled\n    } else {\n      throw e;\n    }\n  }\n})();\n```\n\nOr using an `AbortSignal` with a ReadableStream:\n\n```js\nconst controller = new AbortController();\nconst rs = new ReadableStream({\n  start(controller) {\n    controller.enqueue('hello');\n    controller.enqueue('world');\n    controller.close();\n  },\n});\n\naddAbortSignal(controller.signal, rs);\n\nfinished(rs, (err) => {\n  if (err) {\n    if (err.name === 'AbortError') {\n      // The operation was cancelled\n    }\n  }\n});\n\nconst reader = rs.getReader();\n\nreader.read().then(({ value, done }) => {\n  console.log(value); // hello\n  console.log(done); // false\n  controller.abort();\n});\n```","summary":"Attaches an AbortSignal to a readable or writable stream. This lets code control stream destruction using an `AbortController`.","examples":[{"language":"js","displayName":null,"code":"const fs = require('node:fs');\n\nconst controller = new AbortController();\nconst read = addAbortSignal(\n  controller.signal,\n  fs.createReadStream(('object.json')),\n);\n// Later, abort the operation closing the stream\ncontroller.abort();"},{"language":"js","displayName":null,"code":"const controller = new AbortController();\nsetTimeout(() => controller.abort(), 10_000); // set a timeout\nconst stream = addAbortSignal(\n  controller.signal,\n  fs.createReadStream(('object.json')),\n);\n(async () => {\n  try {\n    for await (const chunk of stream) {\n      await process(chunk);\n    }\n  } catch (e) {\n    if (e.name === 'AbortError') {\n      // The operation was cancelled\n    } else {\n      throw e;\n    }\n  }\n})();"},{"language":"js","displayName":null,"code":"const controller = new AbortController();\nconst rs = new ReadableStream({\n  start(controller) {\n    controller.enqueue('hello');\n    controller.enqueue('world');\n    controller.close();\n  },\n});\n\naddAbortSignal(controller.signal, rs);\n\nfinished(rs, (err) => {\n  if (err) {\n    if (err.name === 'AbortError') {\n      // The operation was cancelled\n    }\n  }\n});\n\nconst reader = rs.getReader();\n\nreader.read().then(({ value, done }) => {\n  console.log(value); // hello\n  console.log(done); // false\n  controller.abort();\n});"}],"children":[]},{"kind":"method","id":"streamgetdefaulthighwatermarkobjectmode","name":"getDefaultHighWaterMark","title":"`stream.getDefaultHighWaterMark(objectMode)`","scope":"module","overloadOf":null,"stability":null,"added":["v19.9.0","v18.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v22.0.0"],"prUrl":"https://github.com/nodejs/node/pull/52037","commit":null,"description":"bump default highWaterMark."}],"signature":{"parameters":[{"name":"objectMode","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":{"type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":""}},"description":"Returns the default highWaterMark used by streams. Defaults to `16` for\n`objectMode`. For byte streams, it defaults to `65536` (64 KiB) on non-Windows\nplatforms and `16384` (16 KiB) on Windows.","summary":"Returns the default highWaterMark used by streams. Defaults to `16` for `objectMode`. For byte streams, it defaults to `65536` (64 KiB) on non-Windows platforms and `16384` (16 KiB) on Windows.","examples":[],"children":[]},{"kind":"method","id":"streamsetdefaulthighwatermarkobjectmode-value","name":"setDefaultHighWaterMark","title":"`stream.setDefaultHighWaterMark(objectMode, value)`","scope":"module","overloadOf":null,"stability":null,"added":["v19.9.0","v18.17.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"objectMode","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"","default":null,"optional":false,"rest":false,"properties":[]},{"name":"value","type":{"text":"integer","links":[{"name":"integer","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":7}]},"description":"highWaterMark value","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"Sets the default highWaterMark used by streams.","summary":"Sets the default highWaterMark used by streams.","examples":[],"children":[]}]},{"kind":"section","id":"api-for-stream-implementers","name":"API for stream implementers","title":"API for stream implementers","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `node:stream` module API has been designed to make it possible to easily\nimplement streams using JavaScript's prototypal inheritance model.\n\nFirst, a stream developer would declare a new JavaScript class that extends one\nof the four basic stream classes (`stream.Writable`, `stream.Readable`,\n`stream.Duplex`, or `stream.Transform`), making sure they call the appropriate\nparent class constructor:\n\n```js\nconst { Writable } = require('node:stream');\n\nclass MyWritable extends Writable {\n  constructor({ highWaterMark, ...options }) {\n    super({ highWaterMark });\n    // ...\n  }\n}\n```\n\nWhen extending streams, keep in mind what options the user\ncan and should provide before forwarding these to the base constructor. For\nexample, if the implementation makes assumptions in regard to the\n`autoDestroy` and `emitClose` options, do not allow the\nuser to override these. Be explicit about what\noptions are forwarded instead of implicitly forwarding all options.\n\nThe 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| Use-case                                      | Class                                 | Method(s) to implement                                                                                                                                                       |\n| --------------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Reading only                                  | [`Readable`](#class-streamreadable)   | [`_read()`](#readable_readsize)                                                                                                                                              |\n| Writing only                                  | [`Writable`](#class-streamwritable)   | [`_write()`](#writable_writechunk-encoding-callback), [`_writev()`](#writable_writevchunks-callback), [`_final()`](#writable_finalcallback)                                  |\n| Reading and writing                           | [`Duplex`](#class-streamduplex)       | [`_read()`](#readable_readsize), [`_write()`](#writable_writechunk-encoding-callback), [`_writev()`](#writable_writevchunks-callback), [`_final()`](#writable_finalcallback) |\n| Operate on written data, then read the result | [`Transform`](#class-streamtransform) | [`_transform()`](#transform_transformchunk-encoding-callback), [`_flush()`](#transform_flushcallback), [`_final()`](#writable_finalcallback)                                 |\n\nThe 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\n[API for stream consumers](#api-for-stream-consumers) section). Doing so may lead to adverse side effects\nin application code consuming the stream.\n\nAvoid overriding public methods such as `write()`, `end()`, `cork()`,\n`uncork()`, `read()` and `destroy()`, or emitting internal events such\nas `'error'`, `'data'`, `'end'`, `'finish'` and `'close'` through `.emit()`.\nDoing so can break current and future stream invariants leading to behavior\nand/or compatibility issues with other streams, stream utilities, and user\nexpectations.","summary":"The `node:stream` module API has been designed to make it possible to easily implement streams using JavaScript's prototypal inheritance model.","examples":[{"language":"js","displayName":null,"code":"const { Writable } = require('node:stream');\n\nclass MyWritable extends Writable {\n  constructor({ highWaterMark, ...options }) {\n    super({ highWaterMark });\n    // ...\n  }\n}"}],"children":[{"kind":"section","id":"simplified-construction","name":"Simplified construction","title":"Simplified construction","scope":"module","overloadOf":null,"stability":null,"added":["v1.2.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"For many simple cases, it is possible to create a stream without relying on\ninheritance. This can be accomplished by directly creating instances of the\n`stream.Writable`, `stream.Readable`, `stream.Duplex`, or `stream.Transform`\nobjects and passing appropriate methods as constructor options.\n\n```js\nconst { Writable } = require('node:stream');\n\nconst myWritable = new Writable({\n  construct(callback) {\n    // Initialize state and load resources...\n  },\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  destroy() {\n    // Free resources...\n  },\n});\n```","summary":"For many simple cases, it is possible to create a stream without relying on inheritance. This can be accomplished by directly creating instances of the `stream.Writable`, `stream.Readable`, `stream.Duplex`, or `stream.Transform` objects and passing appropriate methods as constructor options.","examples":[{"language":"js","displayName":null,"code":"const { Writable } = require('node:stream');\n\nconst myWritable = new Writable({\n  construct(callback) {\n    // Initialize state and load resources...\n  },\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  destroy() {\n    // Free resources...\n  },\n});"}],"children":[]},{"kind":"section","id":"implementing-a-writable-stream","name":"Implementing a writable stream","title":"Implementing a writable stream","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `stream.Writable` class is extended to implement a [`Writable`](#class-streamwritable) stream.\n\nCustom `Writable` streams *must* call the `new stream.Writable([options])`\nconstructor and implement the `writable._write()` and/or `writable._writev()`\nmethod.","summary":"The `stream.Writable` class is extended to implement a `Writable` stream.","examples":[],"children":[{"kind":"constructor","id":"new-streamwritableoptions","name":"Writable","title":"`new stream.Writable([options])`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v22.0.0"],"prUrl":"https://github.com/nodejs/node/pull/52037","commit":null,"description":"bump default highWaterMark."},{"versions":["v15.5.0"],"prUrl":"https://github.com/nodejs/node/pull/36431","commit":null,"description":"support passing in an AbortSignal."},{"versions":["v14.0.0"],"prUrl":"https://github.com/nodejs/node/pull/30623","commit":null,"description":"Change `autoDestroy` option default to `true`."},{"versions":["v11.2.0","v10.16.0"],"prUrl":"https://github.com/nodejs/node/pull/22795","commit":null,"description":"Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'finish'` or errors."},{"versions":["v10.0.0"],"prUrl":"https://github.com/nodejs/node/pull/18438","commit":null,"description":"Add `emitClose` option to specify if `'close'` is emitted on destroy."}],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"highWaterMark","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Buffer level when\n[`stream.write()`](#writablewritechunk-encoding-callback) starts returning `false`.","default":"See `stream.getDefaultHighWaterMark()`","optional":true,"rest":false,"properties":[]},{"name":"decodeStrings","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Whether to encode `string`s passed to\n[`stream.write()`](#writablewritechunk-encoding-callback) to `Buffer`s (with the encoding\nspecified in the [`stream.write()`](#writablewritechunk-encoding-callback) call) before passing\nthem to [`stream._write()`](#writable_writechunk-encoding-callback). Other types of data are not\nconverted (i.e. `Buffer`s are not decoded into `string`s). Setting to\nfalse will prevent `string`s from being converted.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"defaultEncoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The default encoding that is used when no\nencoding is specified as an argument to [`stream.write()`](#writablewritechunk-encoding-callback).","default":"'utf8'","optional":true,"rest":false,"properties":[]},{"name":"objectMode","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Whether or not the\n[`stream.write(anyObj)`](#writablewritechunk-encoding-callback) is a valid operation. When set,\nit becomes possible to write JavaScript values other than string, {Buffer},\n{TypedArray} or {DataView} if supported by the stream implementation.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"emitClose","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Whether or not the stream should emit `'close'`\nafter it has been destroyed.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"write","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Implementation for the\n[`stream._write()`](#writable_writechunk-encoding-callback) method.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"writev","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Implementation for the\n[`stream._writev()`](#writable_writevchunks-callback) method.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"destroy","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Implementation for the\n[`stream._destroy()`](#writable_destroyerr-callback) method.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"final","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Implementation for the\n[`stream._final()`](#writable_finalcallback) method.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"construct","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Implementation for the\n[`stream._construct()`](#writable_constructcallback) method.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"autoDestroy","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Whether this stream should automatically call\n`.destroy()` on itself after ending.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"A signal representing possible cancellation.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":null},"description":"```cjs\nconst { Writable } = require('node:stream');\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    // Calls the stream.Writable() constructor.\n    super(options);\n    // ...\n  }\n}\n```\n\n```mjs\nimport { Writable } from 'node:stream';\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    // Calls the stream.Writable() constructor.\n    super(options);\n    // ...\n  }\n}\n```\n\nOr, using the simplified constructor approach:\n\n```js\nconst { Writable } = require('node:stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  writev(chunks, callback) {\n    // ...\n  },\n});\n```\n\nCalling `abort` on the `AbortController` corresponding to the passed\n`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`\non the writable stream.\n\n```js\nconst { Writable } = require('node:stream');\n\nconst controller = new AbortController();\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  writev(chunks, callback) {\n    // ...\n  },\n  signal: controller.signal,\n});\n// Later, abort the operation closing the stream\ncontroller.abort();\n```","summary":"Or, using the simplified constructor approach:","examples":[{"language":"cjs","displayName":null,"code":"const { Writable } = require('node:stream');\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    // Calls the stream.Writable() constructor.\n    super(options);\n    // ...\n  }\n}"},{"language":"mjs","displayName":null,"code":"import { Writable } from 'node:stream';\n\nclass MyWritable extends Writable {\n  constructor(options) {\n    // Calls the stream.Writable() constructor.\n    super(options);\n    // ...\n  }\n}"},{"language":"js","displayName":null,"code":"const { Writable } = require('node:stream');\n\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  writev(chunks, callback) {\n    // ...\n  },\n});"},{"language":"js","displayName":null,"code":"const { Writable } = require('node:stream');\n\nconst controller = new AbortController();\nconst myWritable = new Writable({\n  write(chunk, encoding, callback) {\n    // ...\n  },\n  writev(chunks, callback) {\n    // ...\n  },\n  signal: controller.signal,\n});\n// Later, abort the operation closing the stream\ncontroller.abort();"}],"children":[]},{"kind":"method","id":"writable_constructcallback","name":"_construct","title":"`writable._construct(callback)`","scope":"module","overloadOf":null,"stability":null,"added":["v15.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Call this function (optionally with an error\nargument) when the stream has finished initializing.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"The `_construct()` 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\nThis optional function will be called in a tick after the stream constructor\nhas returned, delaying any `_write()`, `_final()` and `_destroy()` calls until\n`callback` is called. This is useful to initialize state or asynchronously\ninitialize resources before the stream can be used.\n\n```js\nconst { Writable } = require('node:stream');\nconst fs = require('node:fs');\n\nclass WriteStream extends Writable {\n  constructor(filename) {\n    super();\n    this.filename = filename;\n    this.fd = null;\n  }\n  _construct(callback) {\n    fs.open(this.filename, 'w', (err, fd) => {\n      if (err) {\n        callback(err);\n      } else {\n        this.fd = fd;\n        callback();\n      }\n    });\n  }\n  _write(chunk, encoding, callback) {\n    fs.write(this.fd, chunk, callback);\n  }\n  _destroy(err, callback) {\n    if (this.fd) {\n      fs.close(this.fd, (er) => callback(er || err));\n    } else {\n      callback(err);\n    }\n  }\n}\n```","summary":"The `_construct()` method MUST NOT be called directly. It may be implemented by child classes, and if so, will be called by the internal `Writable` class methods only.","examples":[{"language":"js","displayName":null,"code":"const { Writable } = require('node:stream');\nconst fs = require('node:fs');\n\nclass WriteStream extends Writable {\n  constructor(filename) {\n    super();\n    this.filename = filename;\n    this.fd = null;\n  }\n  _construct(callback) {\n    fs.open(this.filename, 'w', (err, fd) => {\n      if (err) {\n        callback(err);\n      } else {\n        this.fd = fd;\n        callback();\n      }\n    });\n  }\n  _write(chunk, encoding, callback) {\n    fs.write(this.fd, chunk, callback);\n  }\n  _destroy(err, callback) {\n    if (this.fd) {\n      fs.close(this.fd, (er) => callback(er || err));\n    } else {\n      callback(err);\n    }\n  }\n}"}],"children":[]},{"kind":"method","id":"writable_writechunk-encoding-callback","name":"_write","title":"`writable._write(chunk, encoding, callback)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v12.11.0"],"prUrl":"https://github.com/nodejs/node/pull/29639","commit":null,"description":"_write() is optional when providing _writev()."}],"signature":{"parameters":[{"name":"chunk","type":{"text":"Buffer | string | any","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":9,"end":15},{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":18,"end":21}]},"description":"The `Buffer` to be written, converted from the\n`string` passed to [`stream.write()`](#writablewritechunk-encoding-callback). If the stream's\n`decodeStrings` option is `false` or the stream is operating in object mode,\nthe chunk will not be converted & will be whatever was passed to\n[`stream.write()`](#writablewritechunk-encoding-callback).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"If the chunk is a string, then `encoding` is the\ncharacter encoding of that string. If chunk is a `Buffer`, or if the\nstream is operating in object mode, `encoding` may be ignored.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Call this function (optionally with an error\nargument) when processing is complete for the supplied chunk.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"All `Writable` stream implementations must provide a\n[`writable._write()`](#writable_writechunk-encoding-callback) and/or\n[`writable._writev()`](#writable_writevchunks-callback) method to send data to the underlying\nresource.\n\n[`Transform`](#class-streamtransform) streams provide their own implementation of the\n[`writable._write()`](#writable_writechunk-encoding-callback).\n\nThis 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\nThe `callback` function must be called synchronously inside of\n`writable._write()` or asynchronously (i.e. different tick) to signal either\nthat the write completed successfully or failed with an error.\nThe first argument passed to the `callback` must be the `Error` object if the\ncall failed or `null` if the write succeeded.\n\nAll 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'`](#event-drain)\nevent. If a stream implementation is capable of processing multiple chunks of\ndata at once, the `writable._writev()` method should be implemented.\n\nIf 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\nThe `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.","summary":"All `Writable` stream implementations must provide a `writable._write()` and/or `writable._writev()` method to send data to the underlying resource.","examples":[],"children":[]},{"kind":"method","id":"writable_writevchunks-callback","name":"_writev","title":"`writable._writev(chunks, callback)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"chunks","type":{"text":"Object[]","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"The data to be written. The value is an array of {Object}\nthat each represent a discrete chunk of data to write. The properties of\nthese objects are:","default":null,"optional":false,"rest":false,"properties":[{"name":"chunk","type":{"text":"Buffer | string","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":9,"end":15}]},"description":"A buffer instance or string containing the data to\nbe written. The `chunk` will be a string if the `Writable` was created with\nthe `decodeStrings` option set to `false` and a string was passed to `write()`.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"The character encoding of the `chunk`. If `chunk` is\na `Buffer`, the `encoding` will be `'buffer'`.","default":null,"optional":false,"rest":false,"properties":[]}]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"A callback function (optionally with an error\nargument) to be invoked when processing is complete for the supplied chunks.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"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\nThe `writable._writev()` method may be implemented in addition or alternatively\nto `writable._write()` in stream implementations that are capable of processing\nmultiple chunks of data at once. If implemented and if there is buffered data\nfrom previous writes, `_writev()` will be called instead of `_write()`.\n\nThe `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.","summary":"This function MUST NOT be called by application code directly. It should be implemented by child classes, and called by the internal `Writable` class methods only.","examples":[],"children":[]},{"kind":"method","id":"writable_destroyerr-callback","name":"_destroy","title":"`writable._destroy(err, callback)`","scope":"module","overloadOf":null,"stability":null,"added":["v8.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"err","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"A possible error.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"A callback function that takes an optional error\nargument.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"The `_destroy()` method is called by [`writable.destroy()`](#writabledestroyerror).\nIt can be overridden by child classes but it **must not** be called directly.","summary":"The `_destroy()` method is called by `writable.destroy()`. It can be overridden by child classes but it **must not** be called directly.","examples":[],"children":[]},{"kind":"method","id":"writable_finalcallback","name":"_final","title":"`writable._final(callback)`","scope":"module","overloadOf":null,"stability":null,"added":["v8.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Call this function (optionally with an error\nargument) when finished writing any remaining data.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"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\nThis 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.","summary":"The `_final()` method **must not** be called directly. It may be implemented by child classes, and if so, will be called by the internal `Writable` class methods only.","examples":[],"children":[]},{"kind":"section","id":"errors-while-writing","name":"Errors while writing","title":"Errors while writing","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Errors occurring during the processing of the [`writable._write()`](#writable_writechunk-encoding-callback),\n[`writable._writev()`](#writable_writevchunks-callback) and [`writable._final()`](#writable_finalcallback) methods must be propagated\nby invoking the callback and passing the error as the first argument.\nThrowing an `Error` from within these methods or manually emitting an `'error'`\nevent results in undefined behavior.\n\nIf a `Readable` stream pipes into a `Writable` stream when `Writable` emits an\nerror, the `Readable` stream will be unpiped.\n\n```js\nconst { Writable } = require('node: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```","summary":"Errors occurring during the processing of the `writable._write()`, `writable._writev()` and `writable._final()` methods must be propagated by invoking the callback and passing the error as the first argument. Throwing an `Error` from within these methods or manually emitting an `'error'` event results in undefined behavior.","examples":[{"language":"js","displayName":null,"code":"const { Writable } = require('node: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});"}],"children":[]},{"kind":"section","id":"an-example-writable-stream","name":"An example writable stream","title":"An example writable stream","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The following illustrates a rather simplistic (and somewhat pointless) custom\n`Writable` 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`](#class-streamwritable) stream instance:\n\n```js\nconst { Writable } = require('node: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```","summary":"The following illustrates a rather simplistic (and somewhat pointless) custom `Writable` stream implementation. While this specific `Writable` stream instance is not of any real particular usefulness, the example illustrates each of the required elements of a custom `Writable` stream instance:","examples":[{"language":"js","displayName":null,"code":"const { Writable } = require('node: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}"}],"children":[]},{"kind":"section","id":"decoding-buffers-in-a-writable-stream","name":"Decoding buffers in a writable stream","title":"Decoding buffers in a writable stream","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"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`](#class-streamwritable).\n\n```js\nconst { Writable } = require('node:stream');\nconst { StringDecoder } = require('node:string_decoder');\n\nclass StringWritable extends Writable {\n  constructor(options) {\n    super(options);\n    this._decoder = new StringDecoder(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```","summary":"Decoding buffers is a common task, for instance, when using transformers whose input is a string. This is not a trivial process when using multi-byte characters encoding, such as UTF-8. The following example shows how to decode multi-byte strings using `StringDecoder` and `Writable`.","examples":[{"language":"js","displayName":null,"code":"const { Writable } = require('node:stream');\nconst { StringDecoder } = require('node:string_decoder');\n\nclass StringWritable extends Writable {\n  constructor(options) {\n    super(options);\n    this._decoder = new StringDecoder(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: €"}],"children":[]}]},{"kind":"section","id":"implementing-a-readable-stream","name":"Implementing a readable stream","title":"Implementing a readable stream","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The `stream.Readable` class is extended to implement a [`Readable`](#class-streamreadable) stream.\n\nCustom `Readable` streams *must* call the `new stream.Readable([options])`\nconstructor and implement the [`readable._read()`](#readable_readsize) method.","summary":"The `stream.Readable` class is extended to implement a `Readable` stream.","examples":[],"children":[{"kind":"constructor","id":"new-streamreadableoptions","name":"Readable","title":"`new stream.Readable([options])`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v22.0.0"],"prUrl":"https://github.com/nodejs/node/pull/52037","commit":null,"description":"bump default highWaterMark."},{"versions":["v15.5.0"],"prUrl":"https://github.com/nodejs/node/pull/36431","commit":null,"description":"support passing in an AbortSignal."},{"versions":["v14.0.0"],"prUrl":"https://github.com/nodejs/node/pull/30623","commit":null,"description":"Change `autoDestroy` option default to `true`."},{"versions":["v11.2.0","v10.16.0"],"prUrl":"https://github.com/nodejs/node/pull/22795","commit":null,"description":"Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'end'` or errors."}],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"","default":null,"optional":true,"rest":false,"properties":[{"name":"highWaterMark","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"The maximum [number of bytes](#highwatermark-discrepancy-after-calling-readablesetencoding) to store\nin the internal buffer before ceasing to read from the underlying resource.","default":"See `stream.getDefaultHighWaterMark()`","optional":true,"rest":false,"properties":[]},{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"If specified, then buffers will be decoded to\nstrings using the specified encoding.","default":"null","optional":true,"rest":false,"properties":[]},{"name":"objectMode","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Whether this stream should behave\nas a stream of objects. Meaning that [`stream.read(n)`](#readablereadsize) returns\na single value instead of a `Buffer` of size `n`.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"emitClose","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Whether or not the stream should emit `'close'`\nafter it has been destroyed.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"read","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Implementation for the [`stream._read()`](#readable_readsize)\nmethod.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"destroy","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Implementation for the\n[`stream._destroy()`](#readable_destroyerr-callback) method.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"construct","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Implementation for the\n[`stream._construct()`](#readable_constructcallback) method.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"autoDestroy","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Whether this stream should automatically call\n`.destroy()` on itself after ending.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"signal","type":{"text":"AbortSignal","links":[{"name":"AbortSignal","href":"globals.html#class-abortsignal","start":0,"end":11}]},"description":"A signal representing possible cancellation.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":null},"description":"```js\nconst { Readable } = require('node:stream');\n\nclass MyReadable extends Readable {\n  constructor(options) {\n    // Calls the stream.Readable(options) constructor.\n    super(options);\n    // ...\n  }\n}\n```\n\nOr, using the simplified constructor approach:\n\n```js\nconst { Readable } = require('node:stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    // ...\n  },\n});\n```\n\nCalling `abort` on the `AbortController` corresponding to the passed\n`AbortSignal` will behave the same way as calling `.destroy(new AbortError())`\non the readable created.\n\n```js\nconst { Readable } = require('node:stream');\nconst controller = new AbortController();\nconst read = new Readable({\n  read(size) {\n    // ...\n  },\n  signal: controller.signal,\n});\n// Later, abort the operation closing the stream\ncontroller.abort();\n```","summary":"Or, using the simplified constructor approach:","examples":[{"language":"js","displayName":null,"code":"const { Readable } = require('node:stream');\n\nclass MyReadable extends Readable {\n  constructor(options) {\n    // Calls the stream.Readable(options) constructor.\n    super(options);\n    // ...\n  }\n}"},{"language":"js","displayName":null,"code":"const { Readable } = require('node:stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    // ...\n  },\n});"},{"language":"js","displayName":null,"code":"const { Readable } = require('node:stream');\nconst controller = new AbortController();\nconst read = new Readable({\n  read(size) {\n    // ...\n  },\n  signal: controller.signal,\n});\n// Later, abort the operation closing the stream\ncontroller.abort();"}],"children":[]},{"kind":"method","id":"readable_constructcallback","name":"_construct","title":"`readable._construct(callback)`","scope":"module","overloadOf":null,"stability":null,"added":["v15.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Call this function (optionally with an error\nargument) when the stream has finished initializing.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"The `_construct()` method MUST NOT be called directly. It may be implemented\nby child classes, and if so, will be called by the internal `Readable`\nclass methods only.\n\nThis optional function will be scheduled in the next tick by the stream\nconstructor, delaying any `_read()` and `_destroy()` calls until `callback` is\ncalled. This is useful to initialize state or asynchronously initialize\nresources before the stream can be used.\n\n```js\nconst { Readable } = require('node:stream');\nconst fs = require('node:fs');\n\nclass ReadStream extends Readable {\n  constructor(filename) {\n    super();\n    this.filename = filename;\n    this.fd = null;\n  }\n  _construct(callback) {\n    fs.open(this.filename, (err, fd) => {\n      if (err) {\n        callback(err);\n      } else {\n        this.fd = fd;\n        callback();\n      }\n    });\n  }\n  _read(n) {\n    const buf = Buffer.alloc(n);\n    fs.read(this.fd, buf, 0, n, null, (err, bytesRead) => {\n      if (err) {\n        this.destroy(err);\n      } else {\n        this.push(bytesRead > 0 ? buf.slice(0, bytesRead) : null);\n      }\n    });\n  }\n  _destroy(err, callback) {\n    if (this.fd) {\n      fs.close(this.fd, (er) => callback(er || err));\n    } else {\n      callback(err);\n    }\n  }\n}\n```","summary":"The `_construct()` method MUST NOT be called directly. It may be implemented by child classes, and if so, will be called by the internal `Readable` class methods only.","examples":[{"language":"js","displayName":null,"code":"const { Readable } = require('node:stream');\nconst fs = require('node:fs');\n\nclass ReadStream extends Readable {\n  constructor(filename) {\n    super();\n    this.filename = filename;\n    this.fd = null;\n  }\n  _construct(callback) {\n    fs.open(this.filename, (err, fd) => {\n      if (err) {\n        callback(err);\n      } else {\n        this.fd = fd;\n        callback();\n      }\n    });\n  }\n  _read(n) {\n    const buf = Buffer.alloc(n);\n    fs.read(this.fd, buf, 0, n, null, (err, bytesRead) => {\n      if (err) {\n        this.destroy(err);\n      } else {\n        this.push(bytesRead > 0 ? buf.slice(0, bytesRead) : null);\n      }\n    });\n  }\n  _destroy(err, callback) {\n    if (this.fd) {\n      fs.close(this.fd, (er) => callback(er || err));\n    } else {\n      callback(err);\n    }\n  }\n}"}],"children":[]},{"kind":"method","id":"readable_readsize","name":"_read","title":"`readable._read(size)`","scope":"module","overloadOf":null,"stability":null,"added":["v0.9.4"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"size","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Number of bytes to read asynchronously","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"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\nAll `Readable` stream implementations must provide an implementation of the\n[`readable._read()`](#readable_readsize) method to fetch data from the underlying resource.\n\nWhen [`readable._read()`](#readable_readsize) is called, if data is available from the resource,\nthe implementation should begin pushing that data into the read queue using the\n[`this.push(dataChunk)`](#readablepushchunk-encoding) method. `_read()` will be called again\nafter each call to [`this.push(dataChunk)`](#readablepushchunk-encoding) once the stream is\nready to accept more data. `_read()` may continue reading from the resource and\npushing data until `readable.push()` returns `false`. Only when `_read()` is\ncalled again after it has stopped should it resume pushing additional data into\nthe queue.\n\nOnce the [`readable._read()`](#readable_readsize) method has been called, it will not be called\nagain until more data is pushed through the [`readable.push()`](#readablepushchunk-encoding)\nmethod. Empty data such as empty buffers and strings will not cause\n[`readable._read()`](#readable_readsize) to be called.\n\nThe `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\n`size` bytes are available before calling [`stream.push(chunk)`](#readablepushchunk-encoding).\n\nThe [`readable._read()`](#readable_readsize) 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.","summary":"This function MUST NOT be called by application code directly. It should be implemented by child classes, and called by the internal `Readable` class methods only.","examples":[],"children":[]},{"kind":"method","id":"readable_destroyerr-callback","name":"_destroy","title":"`readable._destroy(err, callback)`","scope":"module","overloadOf":null,"stability":null,"added":["v8.0.0"],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"err","type":{"text":"Error","links":[{"name":"Error","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error","start":0,"end":5}]},"description":"A possible error.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"A callback function that takes an optional error\nargument.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"The `_destroy()` method is called by [`readable.destroy()`](#readabledestroyerror).\nIt can be overridden by child classes but it **must not** be called directly.","summary":"The `_destroy()` method is called by `readable.destroy()`. It can be overridden by child classes but it **must not** be called directly.","examples":[],"children":[]},{"kind":"method","id":"readablepushchunk-encoding","name":"push","title":"`readable.push(chunk[, encoding])`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v22.0.0","v20.13.0"],"prUrl":"https://github.com/nodejs/node/pull/51866","commit":null,"description":"The `chunk` argument can now be a `TypedArray` or `DataView` instance."},{"versions":["v8.0.0"],"prUrl":"https://github.com/nodejs/node/pull/11608","commit":null,"description":"The `chunk` argument can now be a `Uint8Array` instance."}],"signature":{"parameters":[{"name":"chunk","type":{"text":"Buffer | TypedArray | DataView | string | null | any","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"TypedArray","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypedArray","start":9,"end":19},{"name":"DataView","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/DataView","start":22,"end":30},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":33,"end":39},{"name":"null","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type","start":42,"end":46},{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":49,"end":52}]},"description":"Chunk of data to push\ninto the read queue. For streams not operating in object mode, `chunk` must\nbe a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams,\n`chunk` may be any JavaScript value.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"Encoding of string chunks. Must be a valid\n`Buffer` encoding, such as `'utf8'` or `'ascii'`.","default":null,"optional":true,"rest":false,"properties":[]}],"returns":{"type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"`true` if additional chunks of data may continue to be\npushed; `false` otherwise."}},"description":"When `chunk` is a {Buffer}, {TypedArray}, {DataView} or {string}, the `chunk`\nof data will be 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\nWhen the `Readable` is operating in paused mode, the data added with\n`readable.push()` can be read out by calling the\n[`readable.read()`](#readablereadsize) method when the [`'readable'`](#event-readable) event is\nemitted.\n\nWhen the `Readable` is operating in flowing mode, the data added with\n`readable.push()` will be delivered by emitting a `'data'` event.\n\nThe `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\n```js\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\nThe `readable.push()` method is used to push the content\ninto the internal buffer. It can be driven by the [`readable._read()`](#readable_readsize) method.\n\nFor streams not operating in object mode, if the `chunk` parameter of\n`readable.push()` is `undefined`, it will be treated as empty string or\nbuffer. See [`readable.push('')`](#readablepush) for more information.","summary":"When `chunk` is a {Buffer}, {TypedArray}, {DataView} or {string}, the `chunk` of data will be added to the internal queue for users of the stream to consume. Passing `chunk` as `null` signals the end of the stream (EOF), after which no more data can be written.","examples":[{"language":"js","displayName":null,"code":"// `_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}"}],"children":[]},{"kind":"section","id":"errors-while-reading","name":"Errors while reading","title":"Errors while reading","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Errors occurring during processing of the [`readable._read()`](#readable_readsize) must be\npropagated through the [`readable.destroy(err)`](#readable_destroyerr-callback) method.\nThrowing an `Error` from within [`readable._read()`](#readable_readsize) or manually emitting an\n`'error'` event results in undefined behavior.\n\n```js\nconst { Readable } = require('node:stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    const err = checkSomeErrorCondition();\n    if (err) {\n      this.destroy(err);\n    } else {\n      // Do some work.\n    }\n  },\n});\n```","summary":"Errors occurring during processing of the `readable._read()` must be propagated through the `readable.destroy(err)` method. Throwing an `Error` from within `readable._read()` or manually emitting an `'error'` event results in undefined behavior.","examples":[{"language":"js","displayName":null,"code":"const { Readable } = require('node:stream');\n\nconst myReadable = new Readable({\n  read(size) {\n    const err = checkSomeErrorCondition();\n    if (err) {\n      this.destroy(err);\n    } else {\n      // Do some work.\n    }\n  },\n});"}],"children":[]},{"kind":"section","id":"an-example-counting-stream","name":"An example counting stream","title":"An example counting stream","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"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\n```js\nconst { Readable } = require('node: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```","summary":"The following is a basic example of a `Readable` stream that emits the numerals from 1 to 1,000,000 in ascending order, and then ends.","examples":[{"language":"js","displayName":null,"code":"const { Readable } = require('node: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}"}],"children":[]}]},{"kind":"section","id":"implementing-a-duplex-stream","name":"Implementing a duplex stream","title":"Implementing a duplex stream","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"A [`Duplex`](#class-streamduplex) stream is one that implements both [`Readable`](#class-streamreadable) and\n[`Writable`](#class-streamwritable), such as a TCP socket connection.\n\nBecause JavaScript does not have support for multiple inheritance, the\n`stream.Duplex` class is extended to implement a [`Duplex`](#class-streamduplex) stream (as opposed\nto extending the `stream.Readable` *and* `stream.Writable` classes).\n\nThe `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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance) on\n`stream.Writable`.\n\nCustom `Duplex` streams *must* call the `new stream.Duplex([options])`\nconstructor and implement *both* the [`readable._read()`](#readable_readsize) and\n`writable._write()` methods.","summary":"A `Duplex` stream is one that implements both `Readable` and `Writable`, such as a TCP socket connection.","examples":[],"children":[{"kind":"constructor","id":"new-streamduplexoptions","name":"Duplex","title":"`new stream.Duplex(options)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[{"versions":["v8.4.0"],"prUrl":"https://github.com/nodejs/node/pull/14636","commit":null,"description":"The `readableHighWaterMark` and `writableHighWaterMark` options are supported now."}],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"Passed to both `Writable` and `Readable`\nconstructors. Also has the following fields:","default":null,"optional":false,"rest":false,"properties":[{"name":"allowHalfOpen","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"If set to `false`, then the stream will\nautomatically end the writable side when the readable side ends.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"readable","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Sets whether the `Duplex` should be readable.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"writable","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Sets whether the `Duplex` should be writable.","default":"true","optional":true,"rest":false,"properties":[]},{"name":"readableObjectMode","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Sets `objectMode` for readable side of the\nstream. Has no effect if `objectMode` is `true`.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"writableObjectMode","type":{"text":"boolean","links":[{"name":"boolean","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type","start":0,"end":7}]},"description":"Sets `objectMode` for writable side of the\nstream. Has no effect if `objectMode` is `true`.","default":"false","optional":true,"rest":false,"properties":[]},{"name":"readableHighWaterMark","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Sets `highWaterMark` for the readable side\nof the stream. Has no effect if `highWaterMark` is provided.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"writableHighWaterMark","type":{"text":"number","links":[{"name":"number","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type","start":0,"end":6}]},"description":"Sets `highWaterMark` for the writable side\nof the stream. Has no effect if `highWaterMark` is provided.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":null},"description":"```cjs\nconst { Duplex } = require('node:stream');\n\nclass MyDuplex extends Duplex {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n```\n\n```mjs\nimport { Duplex } from 'node:stream';\n\nclass MyDuplex extends Duplex {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n```\n\nOr, using the simplified constructor approach:\n\n```js\nconst { Duplex } = require('node:stream');\n\nconst myDuplex = new Duplex({\n  read(size) {\n    // ...\n  },\n  write(chunk, encoding, callback) {\n    // ...\n  },\n});\n```\n\nWhen using pipeline:\n\n```js\nconst { Transform, pipeline } = require('node:stream');\nconst fs = require('node:fs');\n\npipeline(\n  fs.createReadStream('object.json')\n    .setEncoding('utf8'),\n  new Transform({\n    decodeStrings: false, // Accept string input rather than Buffers\n    construct(callback) {\n      this.data = '';\n      callback();\n    },\n    transform(chunk, encoding, callback) {\n      this.data += chunk;\n      callback();\n    },\n    flush(callback) {\n      try {\n        // Make sure is valid json.\n        JSON.parse(this.data);\n        this.push(this.data);\n        callback();\n      } catch (err) {\n        callback(err);\n      }\n    },\n  }),\n  fs.createWriteStream('valid-object.json'),\n  (err) => {\n    if (err) {\n      console.error('failed', err);\n    } else {\n      console.log('completed');\n    }\n  },\n);\n```","summary":"Or, using the simplified constructor approach:","examples":[{"language":"cjs","displayName":null,"code":"const { Duplex } = require('node:stream');\n\nclass MyDuplex extends Duplex {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}"},{"language":"mjs","displayName":null,"code":"import { Duplex } from 'node:stream';\n\nclass MyDuplex extends Duplex {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}"},{"language":"js","displayName":null,"code":"const { Duplex } = require('node:stream');\n\nconst myDuplex = new Duplex({\n  read(size) {\n    // ...\n  },\n  write(chunk, encoding, callback) {\n    // ...\n  },\n});"},{"language":"js","displayName":null,"code":"const { Transform, pipeline } = require('node:stream');\nconst fs = require('node:fs');\n\npipeline(\n  fs.createReadStream('object.json')\n    .setEncoding('utf8'),\n  new Transform({\n    decodeStrings: false, // Accept string input rather than Buffers\n    construct(callback) {\n      this.data = '';\n      callback();\n    },\n    transform(chunk, encoding, callback) {\n      this.data += chunk;\n      callback();\n    },\n    flush(callback) {\n      try {\n        // Make sure is valid json.\n        JSON.parse(this.data);\n        this.push(this.data);\n        callback();\n      } catch (err) {\n        callback(err);\n      }\n    },\n  }),\n  fs.createWriteStream('valid-object.json'),\n  (err) => {\n    if (err) {\n      console.error('failed', err);\n    } else {\n      console.log('completed');\n    }\n  },\n);"}],"children":[]},{"kind":"section","id":"an-example-duplex-stream","name":"An example duplex stream","title":"An example duplex stream","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"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`](#class-streamwritable) interface that is read back out\nvia the [`Readable`](#class-streamreadable) interface.\n\n```js\nconst { Duplex } = require('node: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\nThe most important aspect of a `Duplex` stream is that the `Readable` and\n`Writable` sides operate independently of one another despite co-existing within\na single object instance.","summary":"The following illustrates a simple example of a `Duplex` stream that wraps a hypothetical lower-level source object to which data can be written, and from which data can be read, albeit using an API that is not compatible with Node.js streams. The following illustrates a simple example of a `Duplex` stream that buffers incoming written data via the `Writable` interface that is read back out via the `Readable` interface.","examples":[{"language":"js","displayName":null,"code":"const { Duplex } = require('node: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}"}],"children":[]},{"kind":"section","id":"object-mode-duplex-streams","name":"Object mode duplex streams","title":"Object mode duplex streams","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"For `Duplex` streams, `objectMode` can be set exclusively for either the\n`Readable` or `Writable` side using the `readableObjectMode` and\n`writableObjectMode` options respectively.\n\nIn the following example, for instance, a new `Transform` stream (which is a\ntype of [`Duplex`](#class-streamduplex) 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\n```js\nconst { Transform } = require('node: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```","summary":"For `Duplex` streams, `objectMode` can be set exclusively for either the `Readable` or `Writable` side using the `readableObjectMode` and `writableObjectMode` options respectively.","examples":[{"language":"js","displayName":null,"code":"const { Transform } = require('node: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"}],"children":[]}]},{"kind":"section","id":"implementing-a-transform-stream","name":"Implementing a transform stream","title":"Implementing a transform stream","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"A [`Transform`](#class-streamtransform) stream is a [`Duplex`](#class-streamduplex) stream where the output is computed\nin some way from the input. Examples include [zlib](zlib.html) streams or [crypto](crypto.html)\nstreams that compress, encrypt, or decrypt data.\n\nThere 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\nThe `stream.Transform` class is extended to implement a [`Transform`](#class-streamtransform) stream.\n\nThe `stream.Transform` class prototypically inherits from `stream.Duplex` and\nimplements its own versions of the `writable._write()` and\n[`readable._read()`](#readable_readsize) methods. Custom `Transform` implementations *must*\nimplement the [`transform._transform()`](#transform_transformchunk-encoding-callback) method and *may*\nalso implement the [`transform._flush()`](#transform_flushcallback) method.\n\nCare 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.","summary":"A `Transform` stream is a `Duplex` stream where the output is computed in some way from the input. Examples include zlib streams or crypto streams that compress, encrypt, or decrypt data.","examples":[],"children":[{"kind":"constructor","id":"new-streamtransformoptions","name":"Transform","title":"`new stream.Transform([options])`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"options","type":{"text":"Object","links":[{"name":"Object","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object","start":0,"end":6}]},"description":"Passed to both `Writable` and `Readable`\nconstructors. Also has the following fields:","default":null,"optional":true,"rest":false,"properties":[{"name":"transform","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Implementation for the\n[`stream._transform()`](#transform_transformchunk-encoding-callback) method.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"flush","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"Implementation for the [`stream._flush()`](#transform_flushcallback)\nmethod.","default":null,"optional":false,"rest":false,"properties":[]}]}],"returns":null},"description":"```cjs\nconst { Transform } = require('node:stream');\n\nclass MyTransform extends Transform {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n```\n\n```mjs\nimport { Transform } from 'node:stream';\n\nclass MyTransform extends Transform {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}\n```\n\nOr, using the simplified constructor approach:\n\n```js\nconst { Transform } = require('node:stream');\n\nconst myTransform = new Transform({\n  transform(chunk, encoding, callback) {\n    // ...\n  },\n});\n```","summary":"Or, using the simplified constructor approach:","examples":[{"language":"cjs","displayName":null,"code":"const { Transform } = require('node:stream');\n\nclass MyTransform extends Transform {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}"},{"language":"mjs","displayName":null,"code":"import { Transform } from 'node:stream';\n\nclass MyTransform extends Transform {\n  constructor(options) {\n    super(options);\n    // ...\n  }\n}"},{"language":"js","displayName":null,"code":"const { Transform } = require('node:stream');\n\nconst myTransform = new Transform({\n  transform(chunk, encoding, callback) {\n    // ...\n  },\n});"}],"children":[]},{"kind":"event","id":"event-end-1","name":"end","title":"Event: `'end'`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"The [`'end'`](#event-end) event is from the `stream.Readable` class. The `'end'` event is\nemitted after all data has been output, which occurs after the callback in\n[`transform._flush()`](#transform_flushcallback) has been called. In the case of an error,\n`'end'` should not be emitted.","summary":"The `'end'` event is from the `stream.Readable` class. The `'end'` event is emitted after all data has been output, which occurs after the callback in `transform._flush()` has been called. In the case of an error, `'end'` should not be emitted.","examples":[],"children":[]},{"kind":"event","id":"event-finish-1","name":"finish","title":"Event: `'finish'`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"parameters":[],"description":"The [`'finish'`](#event-finish) event is from the `stream.Writable` class. The `'finish'`\nevent is emitted after [`stream.end()`](#writableendchunk-encoding-callback) is called and all chunks\nhave been processed by [`stream._transform()`](#transform_transformchunk-encoding-callback). In the case\nof an error, `'finish'` should not be emitted.","summary":"The `'finish'` event is from the `stream.Writable` class. The `'finish'` event is emitted after `stream.end()` is called and all chunks have been processed by `stream._transform()`. In the case of an error, `'finish'` should not be emitted.","examples":[],"children":[]},{"kind":"method","id":"transform_flushcallback","name":"_flush","title":"`transform._flush(callback)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"A callback function (optionally with an error\nargument and data) to be called when remaining data has been flushed.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"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\nIn 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\nCustom [`Transform`](#class-streamtransform) 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-end) event is emitted signaling the end of the\n[`Readable`](#class-streamreadable) stream.\n\nWithin the `transform._flush()` implementation, the `transform.push()` method\nmay be called zero or more times, as appropriate. The `callback` function must\nbe called when the flush operation is complete.\n\nThe `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.","summary":"This function MUST NOT be called by application code directly. It should be implemented by child classes, and called by the internal `Readable` class methods only.","examples":[],"children":[]},{"kind":"method","id":"transform_transformchunk-encoding-callback","name":"_transform","title":"`transform._transform(chunk, encoding, callback)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"chunk","type":{"text":"Buffer | string | any","links":[{"name":"Buffer","href":"buffer.html#class-buffer","start":0,"end":6},{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":9,"end":15},{"name":"any","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types","start":18,"end":21}]},"description":"The `Buffer` to be transformed, converted from\nthe `string` passed to [`stream.write()`](#writablewritechunk-encoding-callback). If the stream's\n`decodeStrings` option is `false` or the stream is operating in object mode,\nthe chunk will not be converted & will be whatever was passed to\n[`stream.write()`](#writablewritechunk-encoding-callback).","default":null,"optional":false,"rest":false,"properties":[]},{"name":"encoding","type":{"text":"string","links":[{"name":"string","href":"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type","start":0,"end":6}]},"description":"If the chunk is a string, then this is the\nencoding type. If chunk is a buffer, then this is the special\nvalue `'buffer'`. Ignore it in that case.","default":null,"optional":false,"rest":false,"properties":[]},{"name":"callback","type":{"text":"Function","links":[{"name":"Function","href":"https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function","start":0,"end":8}]},"description":"A callback function (optionally with an error\nargument and data) to be called after the supplied `chunk` has been\nprocessed.","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"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\nAll `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 `transform.push()` method.\n\nThe `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\nIt is possible that no output is generated from any given chunk of input data.\n\nThe `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\n`transform.push()` method, but only if the first argument is falsy. In other\nwords, the following are equivalent:\n\n```js\ntransform.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\nThe `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\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.","summary":"This function MUST NOT be called by application code directly. It should be implemented by child classes, and called by the internal `Readable` class methods only.","examples":[{"language":"js","displayName":null,"code":"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};"}],"children":[]},{"kind":"class","id":"class-streampassthrough","name":"PassThrough","title":"Class: `stream.PassThrough`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"extends":null,"description":"The `stream.PassThrough` class is a trivial implementation of a [`Transform`](#class-streamtransform)\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\n`stream.PassThrough` is useful as a building block for novel sorts of streams.","summary":"The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams.","examples":[],"children":[]}]}]},{"kind":"section","id":"additional-notes","name":"Additional notes","title":"Additional notes","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"","summary":"","examples":[],"children":[{"kind":"section","id":"streams-compatibility-with-async-generators-and-async-iterators","name":"Streams compatibility with async generators and async iterators","title":"Streams compatibility with async generators and async iterators","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"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\nSome common interop cases of using Node.js streams with async generators\nand async iterators are provided below.","summary":"With the support of async generators and iterators in JavaScript, async generators are effectively a first-class language-level stream construct at this point.","examples":[],"children":[{"kind":"section","id":"consuming-readable-streams-with-async-iterators","name":"Consuming readable streams with async iterators","title":"Consuming readable streams with async iterators","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"```js\n(async function() {\n  for await (const chunk of readable) {\n    console.log(chunk);\n  }\n})();\n```\n\nAsync iterators register a permanent error handler on the stream to prevent any\nunhandled post-destroy errors.","summary":"Async iterators register a permanent error handler on the stream to prevent any unhandled post-destroy errors.","examples":[{"language":"js","displayName":null,"code":"(async function() {\n  for await (const chunk of readable) {\n    console.log(chunk);\n  }\n})();"}],"children":[]},{"kind":"section","id":"creating-readable-streams-with-async-generators","name":"Creating readable streams with async generators","title":"Creating readable streams with async generators","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"A Node.js readable stream can be created from an asynchronous generator using\nthe `Readable.from()` utility method:\n\n```js\nconst { Readable } = require('node:stream');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nasync function * generate() {\n  yield 'a';\n  await someLongRunningFn({ signal });\n  yield 'b';\n  yield 'c';\n}\n\nconst readable = Readable.from(generate());\nreadable.on('close', () => {\n  ac.abort();\n});\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});\n```","summary":"A Node.js readable stream can be created from an asynchronous generator using the `Readable.from()` utility method:","examples":[{"language":"js","displayName":null,"code":"const { Readable } = require('node:stream');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nasync function * generate() {\n  yield 'a';\n  await someLongRunningFn({ signal });\n  yield 'b';\n  yield 'c';\n}\n\nconst readable = Readable.from(generate());\nreadable.on('close', () => {\n  ac.abort();\n});\n\nreadable.on('data', (chunk) => {\n  console.log(chunk);\n});"}],"children":[]},{"kind":"section","id":"piping-to-writable-streams-from-async-iterators","name":"Piping to writable streams from async iterators","title":"Piping to writable streams from async iterators","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"When writing to a writable stream from an async iterator, ensure correct\nhandling of backpressure and errors. [`stream.pipeline()`](#streampipelinesource-transforms-destination-callback) abstracts away\nthe handling of backpressure and backpressure-related errors:\n\n```js\nconst fs = require('node:fs');\nconst { pipeline } = require('node:stream');\nconst { pipeline: pipelinePromise } = require('node:stream/promises');\n\nconst writable = fs.createWriteStream('./file');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nconst iterator = createIterator({ signal });\n\n// Callback Pattern\npipeline(iterator, writable, (err, value) => {\n  if (err) {\n    console.error(err);\n  } else {\n    console.log(value, 'value returned');\n  }\n}).on('close', () => {\n  ac.abort();\n});\n\n// Promise Pattern\npipelinePromise(iterator, writable)\n  .then((value) => {\n    console.log(value, 'value returned');\n  })\n  .catch((err) => {\n    console.error(err);\n    ac.abort();\n  });\n```","summary":"When writing to a writable stream from an async iterator, ensure correct handling of backpressure and errors. `stream.pipeline()` abstracts away the handling of backpressure and backpressure-related errors:","examples":[{"language":"js","displayName":null,"code":"const fs = require('node:fs');\nconst { pipeline } = require('node:stream');\nconst { pipeline: pipelinePromise } = require('node:stream/promises');\n\nconst writable = fs.createWriteStream('./file');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nconst iterator = createIterator({ signal });\n\n// Callback Pattern\npipeline(iterator, writable, (err, value) => {\n  if (err) {\n    console.error(err);\n  } else {\n    console.log(value, 'value returned');\n  }\n}).on('close', () => {\n  ac.abort();\n});\n\n// Promise Pattern\npipelinePromise(iterator, writable)\n  .then((value) => {\n    console.log(value, 'value returned');\n  })\n  .catch((err) => {\n    console.error(err);\n    ac.abort();\n  });"}],"children":[]}]},{"kind":"section","id":"compatibility-with-older-nodejs-versions","name":"Compatibility with older Node.js versions","title":"Compatibility with older Node.js versions","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"Prior to Node.js 0.10, the `Readable` stream interface was simpler, but also\nless powerful and less useful.\n\n* Rather than waiting for calls to the [`stream.read()`](#readablereadsize) method,\n  [`'data'`](#event-data) events would begin emitting immediately. Applications that\n  would need to perform some amount of work to decide how to handle data\n  were required to store read data into buffers so the data would not be lost.\n* The [`stream.pause()`](#readablepause) method was advisory, rather than\n  guaranteed. This meant that it was still necessary to be prepared to receive\n  [`'data'`](#event-data) events *even when the stream was in a paused state*.\n\nIn Node.js 0.10, the [`Readable`](#class-streamreadable) class was added. For backward\ncompatibility with older Node.js programs, `Readable` streams switch into\n\"flowing mode\" when a [`'data'`](#event-data) event handler is added, or when the\n[`stream.resume()`](#readableresume) method is called. The effect is that, even\nwhen not using the new [`stream.read()`](#readablereadsize) method and\n[`'readable'`](#event-readable) event, it is no longer necessary to worry about losing\n[`'data'`](#event-data) chunks.\n\nWhile most applications will continue to function normally, this introduces an\nedge case in the following conditions:\n\n* No [`'data'`](#event-data) event listener is added.\n* The [`stream.resume()`](#readableresume) method is never called.\n* The stream is not piped to any writable destination.\n\nFor example, consider the following code:\n\n```js\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\nPrior 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\nThe workaround in this situation is to call the\n[`stream.resume()`](#readableresume) method to begin the flow of data:\n\n```js\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\nIn addition to new `Readable` streams switching into flowing mode,\npre-0.10 style streams can be wrapped in a `Readable` class using the\n[`readable.wrap()`](#readablewrapstream) method.","summary":"Prior to Node.js 0.10, the `Readable` stream interface was simpler, but also less powerful and less useful.","examples":[{"language":"js","displayName":null,"code":"// 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);"},{"language":"js","displayName":null,"code":"// 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);"}],"children":[]},{"kind":"method","id":"readableread0","name":"read","title":"`readable.read(0)`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"0","type":null,"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"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\nIf 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()`](#readable_readsize) call.\n\nWhile most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\n`Readable` stream class internals.","summary":"There are some cases where it is necessary to trigger a refresh of the underlying readable stream mechanisms, without actually consuming any data. In such cases, it is possible to call `readable.read(0)`, which will always return `null`.","examples":[],"children":[]},{"kind":"method","id":"readablepush","name":"push","title":"`readable.push('')`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"signature":{"parameters":[{"name":"''","type":null,"description":"","default":null,"optional":false,"rest":false,"properties":[]}],"returns":null},"description":"Use of `readable.push('')` is not recommended.\n\nPushing a zero-byte {string}, {Buffer}, {TypedArray} or {DataView} to a stream\nthat is not in object mode has an interesting side effect.\nBecause it *is* a call to\n[`readable.push()`](#readablepushchunk-encoding), 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.","summary":"Use of `readable.push('')` is not recommended.","examples":[],"children":[]},{"kind":"section","id":"highwatermark-discrepancy-after-calling-readablesetencoding","name":"highWaterMark discrepancy after calling readable.setEncoding()","title":"`highWaterMark` discrepancy after calling `readable.setEncoding()`","scope":"module","overloadOf":null,"stability":null,"added":[],"deprecated":[],"removed":[],"napiVersion":[],"changes":[],"description":"The use of `readable.setEncoding()` will change the behavior of how the\n`highWaterMark` operates in non-object mode.\n\nTypically, the size of the current buffer is measured against the\n`highWaterMark` in *bytes*. However, after `setEncoding()` is called, the\ncomparison function will begin to measure the buffer's size in *characters*.\n\nThis 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.","summary":"The use of `readable.setEncoding()` will change the behavior of how the `highWaterMark` operates in non-object mode.","examples":[],"children":[]}]}]}