1{ 2 "type": "module", 3 "source": "doc/api/stream.md", 4 "modules": [ 5 { 6 "textRaw": "Stream", 7 "name": "stream", 8 "introduced_in": "v0.10.0", 9 "stability": 2, 10 "stabilityText": "Stable", 11 "desc": "<p><strong>Source Code:</strong> <a href=\"https://github.com/nodejs/node/blob/v14.20.1/lib/stream.js\">lib/stream.js</a></p>\n<p>A stream is an abstract interface for working with streaming data in Node.js.\nThe <code>stream</code> module provides an API for implementing the stream interface.</p>\n<p>There are many stream objects provided by Node.js. For instance, a\n<a href=\"http.html#http_class_http_incomingmessage\">request to an HTTP server</a> and <a href=\"process.html#process_process_stdout\"><code>process.stdout</code></a>\nare both stream instances.</p>\n<p>Streams can be readable, writable, or both. All streams are instances of\n<a href=\"events.html#events_class_eventemitter\"><code>EventEmitter</code></a>.</p>\n<p>To access the <code>stream</code> module:</p>\n<pre><code class=\"language-js\">const stream = require('stream');\n</code></pre>\n<p>The <code>stream</code> module is useful for creating new types of stream instances. It is\nusually not necessary to use the <code>stream</code> module to consume streams.</p>", 12 "modules": [ 13 { 14 "textRaw": "Organization of this document", 15 "name": "organization_of_this_document", 16 "desc": "<p>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.</p>", 17 "type": "module", 18 "displayName": "Organization of this document" 19 }, 20 { 21 "textRaw": "Types of streams", 22 "name": "types_of_streams", 23 "desc": "<p>There are four fundamental stream types within Node.js:</p>\n<ul>\n<li><a href=\"#stream_class_stream_writable\"><code>Writable</code></a>: streams to which data can be written (for example,\n<a href=\"fs.html#fs_fs_createwritestream_path_options\"><code>fs.createWriteStream()</code></a>).</li>\n<li><a href=\"#stream_class_stream_readable\"><code>Readable</code></a>: streams from which data can be read (for example,\n<a href=\"fs.html#fs_fs_createreadstream_path_options\"><code>fs.createReadStream()</code></a>).</li>\n<li><a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a>: streams that are both <code>Readable</code> and <code>Writable</code> (for example,\n<a href=\"net.html#net_class_net_socket\"><code>net.Socket</code></a>).</li>\n<li><a href=\"#stream_class_stream_transform\"><code>Transform</code></a>: <code>Duplex</code> streams that can modify or transform the data as it\nis written and read (for example, <a href=\"zlib.html#zlib_zlib_createdeflate_options\"><code>zlib.createDeflate()</code></a>).</li>\n</ul>\n<p>Additionally, this module includes the utility functions\n<a href=\"#stream_stream_pipeline_source_transforms_destination_callback\"><code>stream.pipeline()</code></a>, <a href=\"#stream_stream_finished_stream_options_callback\"><code>stream.finished()</code></a> and\n<a href=\"#stream_stream_readable_from_iterable_options\"><code>stream.Readable.from()</code></a>.</p>", 24 "modules": [ 25 { 26 "textRaw": "Object mode", 27 "name": "object_mode", 28 "desc": "<p>All streams created by Node.js APIs operate exclusively on strings and <code>Buffer</code>\n(or <code>Uint8Array</code>) objects. It is possible, however, for stream implementations\nto work with other types of JavaScript values (with the exception of <code>null</code>,\nwhich serves a special purpose within streams). Such streams are considered to\noperate in \"object mode\".</p>\n<p>Stream instances are switched into object mode using the <code>objectMode</code> option\nwhen the stream is created. Attempting to switch an existing stream into\nobject mode is not safe.</p>", 29 "type": "module", 30 "displayName": "Object mode" 31 } 32 ], 33 "miscs": [ 34 { 35 "textRaw": "Buffering", 36 "name": "Buffering", 37 "type": "misc", 38 "desc": "<p>Both <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> and <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> streams will store data in an internal\nbuffer.</p>\n<p>The amount of data potentially buffered depends on the <code>highWaterMark</code> option\npassed into the stream's constructor. For normal streams, the <code>highWaterMark</code>\noption specifies a <a href=\"#stream_highwatermark_discrepancy_after_calling_readable_setencoding\">total number of bytes</a>. For streams operating\nin object mode, the <code>highWaterMark</code> specifies a total number of objects.</p>\n<p>Data is buffered in <code>Readable</code> streams when the implementation calls\n<a href=\"#stream_readable_push_chunk_encoding\"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not\ncall <a href=\"#stream_readable_read_size\"><code>stream.read()</code></a>, the data will sit in the internal\nqueue until it is consumed.</p>\n<p>Once the total size of the internal read buffer reaches the threshold specified\nby <code>highWaterMark</code>, 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 <a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> method that is\nused to fill the read buffer).</p>\n<p>Data is buffered in <code>Writable</code> streams when the\n<a href=\"#stream_writable_write_chunk_encoding_callback\"><code>writable.write(chunk)</code></a> method is called repeatedly. While the\ntotal size of the internal write buffer is below the threshold set by\n<code>highWaterMark</code>, calls to <code>writable.write()</code> will return <code>true</code>. Once\nthe size of the internal buffer reaches or exceeds the <code>highWaterMark</code>, <code>false</code>\nwill be returned.</p>\n<p>A key goal of the <code>stream</code> API, particularly the <a href=\"#stream_readable_pipe_destination_options\"><code>stream.pipe()</code></a> 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.</p>\n<p>The <code>highWaterMark</code> 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.</p>\n<p>Because <a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a> and <a href=\"#stream_class_stream_transform\"><code>Transform</code></a> streams are both <code>Readable</code> and\n<code>Writable</code>, each maintains <em>two</em> 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<a href=\"net.html#net_class_net_socket\"><code>net.Socket</code></a> instances are <a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a> streams whose <code>Readable</code> side allows\nconsumption of data received <em>from</em> the socket and whose <code>Writable</code> side allows\nwriting data <em>to</em> 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.</p>\n<p>The 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 <code>writable.writableBuffer</code> or\n<code>readable.readableBuffer</code>. Use of these undocumented properties is discouraged.</p>" 39 } 40 ], 41 "type": "module", 42 "displayName": "Types of streams" 43 } 44 ], 45 "methods": [ 46 { 47 "textRaw": "`stream.finished(stream[, options], callback)`", 48 "type": "method", 49 "name": "finished", 50 "meta": { 51 "added": [ 52 "v10.0.0" 53 ], 54 "changes": [ 55 { 56 "version": "v14.0.0", 57 "pr-url": "https://github.com/nodejs/node/pull/32158", 58 "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'`." 59 }, 60 { 61 "version": "v14.0.0", 62 "pr-url": "https://github.com/nodejs/node/pull/31545", 63 "description": "Emitting `'close'` before `'end'` on a `Readable` stream will cause an `ERR_STREAM_PREMATURE_CLOSE` error." 64 }, 65 { 66 "version": "v14.0.0", 67 "pr-url": "https://github.com/nodejs/node/pull/31509", 68 "description": "Callback will be invoked on streams which have already finished before the call to `finished(stream, cb)`." 69 } 70 ] 71 }, 72 "signatures": [ 73 { 74 "return": { 75 "textRaw": "Returns: {Function} A cleanup function which removes all registered listeners.", 76 "name": "return", 77 "type": "Function", 78 "desc": "A cleanup function which removes all registered listeners." 79 }, 80 "params": [ 81 { 82 "textRaw": "`stream` {Stream} A readable and/or writable stream.", 83 "name": "stream", 84 "type": "Stream", 85 "desc": "A readable and/or writable stream." 86 }, 87 { 88 "textRaw": "`options` {Object}", 89 "name": "options", 90 "type": "Object", 91 "options": [ 92 { 93 "textRaw": "`error` {boolean} If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`.", 94 "name": "error", 95 "type": "boolean", 96 "desc": "If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`." 97 }, 98 { 99 "textRaw": "`readable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`.", 100 "name": "readable", 101 "type": "boolean", 102 "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`." 103 }, 104 { 105 "textRaw": "`writable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`.", 106 "name": "writable", 107 "type": "boolean", 108 "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`." 109 } 110 ] 111 }, 112 { 113 "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", 114 "name": "callback", 115 "type": "Function", 116 "desc": "A callback function that takes an optional error argument." 117 } 118 ] 119 } 120 ], 121 "desc": "<p>A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.</p>\n<pre><code class=\"language-js\">const { finished } = require('stream');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n if (err) {\n console.error('Stream failed.', err);\n } else {\n console.log('Stream is done reading.');\n }\n});\n\nrs.resume(); // Drain the stream.\n</code></pre>\n<p>Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit <code>'end'</code>\nor <code>'finish'</code>.</p>\n<p>The <code>finished</code> API is promisify-able as well;</p>\n<pre><code class=\"language-js\">const finished = util.promisify(stream.finished);\n\nconst rs = fs.createReadStream('archive.tar');\n\nasync function run() {\n await finished(rs);\n console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // Drain the stream.\n</code></pre>\n<p><code>stream.finished()</code> leaves dangling event listeners (in particular\n<code>'error'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code>) after <code>callback</code> has been\ninvoked. The reason for this is so that unexpected <code>'error'</code> 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:</p>\n<pre><code class=\"language-js\">const cleanup = finished(rs, (err) => {\n cleanup();\n // ...\n});\n</code></pre>" 122 }, 123 { 124 "textRaw": "`stream.pipeline(source[, ...transforms], destination, callback)`", 125 "type": "method", 126 "name": "pipeline", 127 "meta": { 128 "added": [ 129 "v10.0.0" 130 ], 131 "changes": [ 132 { 133 "version": "v14.0.0", 134 "pr-url": "https://github.com/nodejs/node/pull/32158", 135 "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'`." 136 }, 137 { 138 "version": "v13.10.0", 139 "pr-url": "https://github.com/nodejs/node/pull/31223", 140 "description": "Add support for async generators." 141 } 142 ] 143 }, 144 "signatures": [ 145 { 146 "return": { 147 "textRaw": "Returns: {Stream}", 148 "name": "return", 149 "type": "Stream" 150 }, 151 "params": [ 152 { 153 "textRaw": "`streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]}", 154 "name": "streams", 155 "type": "Stream[]|Iterable[]|AsyncIterable[]|Function[]" 156 }, 157 { 158 "textRaw": "`source` {Stream|Iterable|AsyncIterable|Function}", 159 "name": "source", 160 "type": "Stream|Iterable|AsyncIterable|Function", 161 "options": [ 162 { 163 "textRaw": "Returns: {Iterable|AsyncIterable}", 164 "name": "return", 165 "type": "Iterable|AsyncIterable" 166 } 167 ] 168 }, 169 { 170 "textRaw": "`...transforms` {Stream|Function}", 171 "name": "...transforms", 172 "type": "Stream|Function", 173 "options": [ 174 { 175 "textRaw": "`source` {AsyncIterable}", 176 "name": "source", 177 "type": "AsyncIterable" 178 }, 179 { 180 "textRaw": "Returns: {AsyncIterable}", 181 "name": "return", 182 "type": "AsyncIterable" 183 } 184 ] 185 }, 186 { 187 "textRaw": "`destination` {Stream|Function}", 188 "name": "destination", 189 "type": "Stream|Function", 190 "options": [ 191 { 192 "textRaw": "`source` {AsyncIterable}", 193 "name": "source", 194 "type": "AsyncIterable" 195 }, 196 { 197 "textRaw": "Returns: {AsyncIterable|Promise}", 198 "name": "return", 199 "type": "AsyncIterable|Promise" 200 } 201 ] 202 }, 203 { 204 "textRaw": "`callback` {Function} Called when the pipeline is fully done.", 205 "name": "callback", 206 "type": "Function", 207 "desc": "Called when the pipeline is fully done.", 208 "options": [ 209 { 210 "textRaw": "`err` {Error}", 211 "name": "err", 212 "type": "Error" 213 }, 214 { 215 "textRaw": "`val` Resolved value of `Promise` returned by `destination`.", 216 "name": "val", 217 "desc": "Resolved value of `Promise` returned by `destination`." 218 } 219 ] 220 } 221 ] 222 } 223 ], 224 "desc": "<p>A module method to pipe between streams and generators forwarding errors and\nproperly cleaning up and provide a callback when the pipeline is complete.</p>\n<pre><code class=\"language-js\">const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz'),\n (err) => {\n if (err) {\n console.error('Pipeline failed.', err);\n } else {\n console.log('Pipeline succeeded.');\n }\n }\n);\n</code></pre>\n<p>The <code>pipeline</code> API is promisify-able as well:</p>\n<pre><code class=\"language-js\">const pipeline = util.promisify(stream.pipeline);\n\nasync function run() {\n await pipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n</code></pre>\n<p>The <code>pipeline</code> API also supports async generators:</p>\n<pre><code class=\"language-js\">const pipeline = util.promisify(stream.pipeline);\nconst fs = require('fs');\n\nasync function run() {\n await pipeline(\n fs.createReadStream('lowercase.txt'),\n async function* (source) {\n source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.\n for await (const chunk of source) {\n yield chunk.toUpperCase();\n }\n },\n fs.createWriteStream('uppercase.txt')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n</code></pre>\n<p><code>stream.pipeline()</code> will call <code>stream.destroy(err)</code> on all streams except:</p>\n<ul>\n<li><code>Readable</code> streams which have emitted <code>'end'</code> or <code>'close'</code>.</li>\n<li><code>Writable</code> streams which have emitted <code>'finish'</code> or <code>'close'</code>.</li>\n</ul>\n<p><code>stream.pipeline()</code> leaves dangling event listeners on the streams\nafter the <code>callback</code> has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors.</p>" 225 }, 226 { 227 "textRaw": "`stream.pipeline(streams, callback)`", 228 "type": "method", 229 "name": "pipeline", 230 "meta": { 231 "added": [ 232 "v10.0.0" 233 ], 234 "changes": [ 235 { 236 "version": "v14.0.0", 237 "pr-url": "https://github.com/nodejs/node/pull/32158", 238 "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'`." 239 }, 240 { 241 "version": "v13.10.0", 242 "pr-url": "https://github.com/nodejs/node/pull/31223", 243 "description": "Add support for async generators." 244 } 245 ] 246 }, 247 "signatures": [ 248 { 249 "return": { 250 "textRaw": "Returns: {Stream}", 251 "name": "return", 252 "type": "Stream" 253 }, 254 "params": [ 255 { 256 "textRaw": "`streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]}", 257 "name": "streams", 258 "type": "Stream[]|Iterable[]|AsyncIterable[]|Function[]" 259 }, 260 { 261 "textRaw": "`source` {Stream|Iterable|AsyncIterable|Function}", 262 "name": "source", 263 "type": "Stream|Iterable|AsyncIterable|Function", 264 "options": [ 265 { 266 "textRaw": "Returns: {Iterable|AsyncIterable}", 267 "name": "return", 268 "type": "Iterable|AsyncIterable" 269 } 270 ] 271 }, 272 { 273 "textRaw": "`...transforms` {Stream|Function}", 274 "name": "...transforms", 275 "type": "Stream|Function", 276 "options": [ 277 { 278 "textRaw": "`source` {AsyncIterable}", 279 "name": "source", 280 "type": "AsyncIterable" 281 }, 282 { 283 "textRaw": "Returns: {AsyncIterable}", 284 "name": "return", 285 "type": "AsyncIterable" 286 } 287 ] 288 }, 289 { 290 "textRaw": "`destination` {Stream|Function}", 291 "name": "destination", 292 "type": "Stream|Function", 293 "options": [ 294 { 295 "textRaw": "`source` {AsyncIterable}", 296 "name": "source", 297 "type": "AsyncIterable" 298 }, 299 { 300 "textRaw": "Returns: {AsyncIterable|Promise}", 301 "name": "return", 302 "type": "AsyncIterable|Promise" 303 } 304 ] 305 }, 306 { 307 "textRaw": "`callback` {Function} Called when the pipeline is fully done.", 308 "name": "callback", 309 "type": "Function", 310 "desc": "Called when the pipeline is fully done.", 311 "options": [ 312 { 313 "textRaw": "`err` {Error}", 314 "name": "err", 315 "type": "Error" 316 }, 317 { 318 "textRaw": "`val` Resolved value of `Promise` returned by `destination`.", 319 "name": "val", 320 "desc": "Resolved value of `Promise` returned by `destination`." 321 } 322 ] 323 } 324 ] 325 } 326 ], 327 "desc": "<p>A module method to pipe between streams and generators forwarding errors and\nproperly cleaning up and provide a callback when the pipeline is complete.</p>\n<pre><code class=\"language-js\">const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz'),\n (err) => {\n if (err) {\n console.error('Pipeline failed.', err);\n } else {\n console.log('Pipeline succeeded.');\n }\n }\n);\n</code></pre>\n<p>The <code>pipeline</code> API is promisify-able as well:</p>\n<pre><code class=\"language-js\">const pipeline = util.promisify(stream.pipeline);\n\nasync function run() {\n await pipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n</code></pre>\n<p>The <code>pipeline</code> API also supports async generators:</p>\n<pre><code class=\"language-js\">const pipeline = util.promisify(stream.pipeline);\nconst fs = require('fs');\n\nasync function run() {\n await pipeline(\n fs.createReadStream('lowercase.txt'),\n async function* (source) {\n source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.\n for await (const chunk of source) {\n yield chunk.toUpperCase();\n }\n },\n fs.createWriteStream('uppercase.txt')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n</code></pre>\n<p><code>stream.pipeline()</code> will call <code>stream.destroy(err)</code> on all streams except:</p>\n<ul>\n<li><code>Readable</code> streams which have emitted <code>'end'</code> or <code>'close'</code>.</li>\n<li><code>Writable</code> streams which have emitted <code>'finish'</code> or <code>'close'</code>.</li>\n</ul>\n<p><code>stream.pipeline()</code> leaves dangling event listeners on the streams\nafter the <code>callback</code> has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors.</p>" 328 }, 329 { 330 "textRaw": "`stream.Readable.from(iterable, [options])`", 331 "type": "method", 332 "name": "from", 333 "meta": { 334 "added": [ 335 "v12.3.0", 336 "v10.17.0" 337 ], 338 "changes": [] 339 }, 340 "signatures": [ 341 { 342 "return": { 343 "textRaw": "Returns: {stream.Readable}", 344 "name": "return", 345 "type": "stream.Readable" 346 }, 347 "params": [ 348 { 349 "textRaw": "`iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed.", 350 "name": "iterable", 351 "type": "Iterable", 352 "desc": "Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed." 353 }, 354 { 355 "textRaw": "`options` {Object} Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`.", 356 "name": "options", 357 "type": "Object", 358 "desc": "Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`." 359 } 360 ] 361 } 362 ], 363 "desc": "<p>A utility method for creating readable streams out of iterators.</p>\n<pre><code class=\"language-js\">const { Readable } = require('stream');\n\nasync function * generate() {\n yield 'hello';\n yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n console.log(chunk);\n});\n</code></pre>\n<p>Calling <code>Readable.from(string)</code> or <code>Readable.from(buffer)</code> will not have\nthe strings or buffers be iterated to match the other streams semantics\nfor performance reasons.</p>" 364 }, 365 { 366 "textRaw": "`readable.read(0)`", 367 "type": "method", 368 "name": "read", 369 "signatures": [ 370 { 371 "params": [] 372 } 373 ], 374 "desc": "<p>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 <code>readable.read(0)</code>, which will\nalways return <code>null</code>.</p>\n<p>If the internal read buffer is below the <code>highWaterMark</code>, and the\nstream is not currently reading, then calling <code>stream.read(0)</code> will trigger\na low-level <a href=\"#stream_readable_read_size_1\"><code>stream._read()</code></a> call.</p>\n<p>While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\n<code>Readable</code> stream class internals.</p>" 375 }, 376 { 377 "textRaw": "`readable.push('')`", 378 "type": "method", 379 "name": "push", 380 "signatures": [ 381 { 382 "params": [] 383 } 384 ], 385 "desc": "<p>Use of <code>readable.push('')</code> is not recommended.</p>\n<p>Pushing a zero-byte string, <code>Buffer</code> or <code>Uint8Array</code> to a stream that is not in\nobject mode has an interesting side effect. Because it <em>is</em> a call to\n<a href=\"#stream_readable_push_chunk_encoding\"><code>readable.push()</code></a>, 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.</p>" 386 } 387 ], 388 "miscs": [ 389 { 390 "textRaw": "API for stream consumers", 391 "name": "API for stream consumers", 392 "type": "misc", 393 "desc": "<p>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:</p>\n<pre><code class=\"language-js\">const http = require('http');\n\nconst server = http.createServer((req, res) => {\n // `req` is an http.IncomingMessage, which is a readable stream.\n // `res` is an http.ServerResponse, which is a writable stream.\n\n let body = '';\n // Get the data as utf8 strings.\n // If an encoding is not set, Buffer objects will be received.\n req.setEncoding('utf8');\n\n // Readable streams emit 'data' events once a listener is added.\n req.on('data', (chunk) => {\n body += chunk;\n });\n\n // The 'end' event indicates that the entire body has been received.\n req.on('end', () => {\n try {\n const data = JSON.parse(body);\n // Write back something interesting to the user:\n res.write(typeof data);\n res.end();\n } catch (er) {\n // uh oh! bad json!\n res.statusCode = 400;\n return res.end(`error: ${er.message}`);\n }\n });\n});\n\nserver.listen(1337);\n\n// $ curl localhost:1337 -d \"{}\"\n// object\n// $ curl localhost:1337 -d \"\\\"foo\\\"\"\n// string\n// $ curl localhost:1337 -d \"not json\"\n// error: Unexpected token o in JSON at position 1\n</code></pre>\n<p><a href=\"#stream_class_stream_writable\"><code>Writable</code></a> streams (such as <code>res</code> in the example) expose methods such as\n<code>write()</code> and <code>end()</code> that are used to write data onto the stream.</p>\n<p><a href=\"#stream_class_stream_readable\"><code>Readable</code></a> streams use the <a href=\"events.html#events_class_eventemitter\"><code>EventEmitter</code></a> 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.</p>\n<p>Both <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> and <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> streams use the <a href=\"events.html#events_class_eventemitter\"><code>EventEmitter</code></a> API in\nvarious ways to communicate the current state of the stream.</p>\n<p><a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a> and <a href=\"#stream_class_stream_transform\"><code>Transform</code></a> streams are both <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> and\n<a href=\"#stream_class_stream_readable\"><code>Readable</code></a>.</p>\n<p>Applications that are either writing data to or consuming data from a stream\nare not required to implement the stream interfaces directly and will generally\nhave no reason to call <code>require('stream')</code>.</p>\n<p>Developers wishing to implement new types of streams should refer to the\nsection <a href=\"#stream_api_for_stream_implementers\">API for stream implementers</a>.</p>", 394 "miscs": [ 395 { 396 "textRaw": "Writable streams", 397 "name": "writable_streams", 398 "desc": "<p>Writable streams are an abstraction for a <em>destination</em> to which data is\nwritten.</p>\n<p>Examples of <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> streams include:</p>\n<ul>\n<li><a href=\"http.html#http_class_http_clientrequest\">HTTP requests, on the client</a></li>\n<li><a href=\"http.html#http_class_http_serverresponse\">HTTP responses, on the server</a></li>\n<li><a href=\"fs.html#fs_class_fs_writestream\">fs write streams</a></li>\n<li><a href=\"zlib.html\">zlib streams</a></li>\n<li><a href=\"crypto.html\">crypto streams</a></li>\n<li><a href=\"net.html#net_class_net_socket\">TCP sockets</a></li>\n<li><a href=\"child_process.html#child_process_subprocess_stdin\">child process stdin</a></li>\n<li><a href=\"process.html#process_process_stdout\"><code>process.stdout</code></a>, <a href=\"process.html#process_process_stderr\"><code>process.stderr</code></a></li>\n</ul>\n<p>Some of these examples are actually <a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a> streams that implement the\n<a href=\"#stream_class_stream_writable\"><code>Writable</code></a> interface.</p>\n<p>All <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> streams implement the interface defined by the\n<code>stream.Writable</code> class.</p>\n<p>While specific instances of <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> streams may differ in various ways,\nall <code>Writable</code> streams follow the same fundamental usage pattern as illustrated\nin the example below:</p>\n<pre><code class=\"language-js\">const myStream = getWritableStreamSomehow();\nmyStream.write('some data');\nmyStream.write('some more data');\nmyStream.end('done writing data');\n</code></pre>", 399 "classes": [ 400 { 401 "textRaw": "Class: `stream.Writable`", 402 "type": "class", 403 "name": "stream.Writable", 404 "meta": { 405 "added": [ 406 "v0.9.4" 407 ], 408 "changes": [] 409 }, 410 "events": [ 411 { 412 "textRaw": "Event: `'close'`", 413 "type": "event", 414 "name": "close", 415 "meta": { 416 "added": [ 417 "v0.9.4" 418 ], 419 "changes": [ 420 { 421 "version": "v10.0.0", 422 "pr-url": "https://github.com/nodejs/node/pull/18438", 423 "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." 424 } 425 ] 426 }, 427 "params": [], 428 "desc": "<p>The <code>'close'</code> 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.</p>\n<p>A <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> stream will always emit the <code>'close'</code> event if it is\ncreated with the <code>emitClose</code> option.</p>" 429 }, 430 { 431 "textRaw": "Event: `'drain'`", 432 "type": "event", 433 "name": "drain", 434 "meta": { 435 "added": [ 436 "v0.9.4" 437 ], 438 "changes": [] 439 }, 440 "params": [], 441 "desc": "<p>If a call to <a href=\"#stream_writable_write_chunk_encoding_callback\"><code>stream.write(chunk)</code></a> returns <code>false</code>, the\n<code>'drain'</code> event will be emitted when it is appropriate to resume writing data\nto the stream.</p>\n<pre><code class=\"language-js\">// 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</code></pre>" 442 }, 443 { 444 "textRaw": "Event: `'error'`", 445 "type": "event", 446 "name": "error", 447 "meta": { 448 "added": [ 449 "v0.9.4" 450 ], 451 "changes": [] 452 }, 453 "params": [ 454 { 455 "textRaw": "{Error}", 456 "type": "Error" 457 } 458 ], 459 "desc": "<p>The <code>'error'</code> event is emitted if an error occurred while writing or piping\ndata. The listener callback is passed a single <code>Error</code> argument when called.</p>\n<p>The stream is closed when the <code>'error'</code> event is emitted unless the\n<a href=\"#stream_new_stream_writable_options\"><code>autoDestroy</code></a> option was set to <code>false</code> when creating the\nstream.</p>\n<p>After <code>'error'</code>, no further events other than <code>'close'</code> <em>should</em> be emitted\n(including <code>'error'</code> events).</p>" 460 }, 461 { 462 "textRaw": "Event: `'finish'`", 463 "type": "event", 464 "name": "finish", 465 "meta": { 466 "added": [ 467 "v0.9.4" 468 ], 469 "changes": [] 470 }, 471 "params": [], 472 "desc": "<p>The <code>'finish'</code> event is emitted after the <a href=\"#stream_writable_end_chunk_encoding_callback\"><code>stream.end()</code></a> method\nhas been called, and all data has been flushed to the underlying system.</p>\n<pre><code class=\"language-js\">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');\n</code></pre>" 473 }, 474 { 475 "textRaw": "Event: `'pipe'`", 476 "type": "event", 477 "name": "pipe", 478 "meta": { 479 "added": [ 480 "v0.9.4" 481 ], 482 "changes": [] 483 }, 484 "params": [ 485 { 486 "textRaw": "`src` {stream.Readable} source stream that is piping to this writable", 487 "name": "src", 488 "type": "stream.Readable", 489 "desc": "source stream that is piping to this writable" 490 } 491 ], 492 "desc": "<p>The <code>'pipe'</code> event is emitted when the <a href=\"#stream_readable_pipe_destination_options\"><code>stream.pipe()</code></a> method is called on\na readable stream, adding this writable to its set of destinations.</p>\n<pre><code class=\"language-js\">const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('pipe', (src) => {\n console.log('Something is piping into the writer.');\n assert.equal(src, reader);\n});\nreader.pipe(writer);\n</code></pre>" 493 }, 494 { 495 "textRaw": "Event: `'unpipe'`", 496 "type": "event", 497 "name": "unpipe", 498 "meta": { 499 "added": [ 500 "v0.9.4" 501 ], 502 "changes": [] 503 }, 504 "params": [ 505 { 506 "textRaw": "`src` {stream.Readable} The source stream that [unpiped][`stream.unpipe()`] this writable", 507 "name": "src", 508 "type": "stream.Readable", 509 "desc": "The source stream that [unpiped][`stream.unpipe()`] this writable" 510 } 511 ], 512 "desc": "<p>The <code>'unpipe'</code> event is emitted when the <a href=\"#stream_readable_unpipe_destination\"><code>stream.unpipe()</code></a> method is called\non a <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> stream, removing this <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> from its set of\ndestinations.</p>\n<p>This is also emitted in case this <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> stream emits an error when a\n<a href=\"#stream_class_stream_readable\"><code>Readable</code></a> stream pipes into it.</p>\n<pre><code class=\"language-js\">const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('unpipe', (src) => {\n console.log('Something has stopped piping into the writer.');\n assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);\n</code></pre>" 513 } 514 ], 515 "methods": [ 516 { 517 "textRaw": "`writable.cork()`", 518 "type": "method", 519 "name": "cork", 520 "meta": { 521 "added": [ 522 "v0.11.2" 523 ], 524 "changes": [] 525 }, 526 "signatures": [ 527 { 528 "params": [] 529 } 530 ], 531 "desc": "<p>The <code>writable.cork()</code> method forces all written data to be buffered in memory.\nThe buffered data will be flushed when either the <a href=\"#stream_writable_uncork\"><code>stream.uncork()</code></a> or\n<a href=\"#stream_writable_end_chunk_encoding_callback\"><code>stream.end()</code></a> methods are called.</p>\n<p>The primary intent of <code>writable.cork()</code> 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, <code>writable.cork()</code>\nbuffers all the chunks until <code>writable.uncork()</code> is called, which will pass them\nall to <code>writable._writev()</code>, 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 <code>writable.cork()</code> without implementing\n<code>writable._writev()</code> may have an adverse effect on throughput.</p>\n<p>See also: <a href=\"#stream_writable_uncork\"><code>writable.uncork()</code></a>, <a href=\"#stream_writable_writev_chunks_callback\"><code>writable._writev()</code></a>.</p>" 532 }, 533 { 534 "textRaw": "`writable.destroy([error])`", 535 "type": "method", 536 "name": "destroy", 537 "meta": { 538 "added": [ 539 "v8.0.0" 540 ], 541 "changes": [ 542 { 543 "version": "v14.0.0", 544 "pr-url": "https://github.com/nodejs/node/pull/29197", 545 "description": "Work as a no-op on a stream that has already been destroyed." 546 } 547 ] 548 }, 549 "signatures": [ 550 { 551 "return": { 552 "textRaw": "Returns: {this}", 553 "name": "return", 554 "type": "this" 555 }, 556 "params": [ 557 { 558 "textRaw": "`error` {Error} Optional, an error to emit with `'error'` event.", 559 "name": "error", 560 "type": "Error", 561 "desc": "Optional, an error to emit with `'error'` event." 562 } 563 ] 564 } 565 ], 566 "desc": "<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code>\nevent (unless <code>emitClose</code> is set to <code>false</code>). After this call, the writable\nstream has ended and subsequent calls to <code>write()</code> or <code>end()</code> will result in\nan <code>ERR_STREAM_DESTROYED</code> error.\nThis is a destructive and immediate way to destroy a stream. Previous calls to\n<code>write()</code> may not have drained, and may trigger an <code>ERR_STREAM_DESTROYED</code> error.\nUse <code>end()</code> instead of destroy if data should flush before close, or wait for\nthe <code>'drain'</code> event before destroying the stream.</p>\n<pre><code class=\"language-cjs\">const { Writable } = require('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</code></pre>\n<pre><code class=\"language-cjs\">const { Writable } = require('stream');\n\nconst myStream = new Writable();\n\nmyStream.destroy();\nmyStream.on('error', function wontHappen() {});\n</code></pre>\n<pre><code class=\"language-cjs\">const { Writable } = require('stream');\n\nconst myStream = new Writable();\nmyStream.destroy();\n\nmyStream.write('foo', (error) => console.error(error.code));\n// ERR_STREAM_DESTROYED\n</code></pre>\n<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no\nfurther errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p>\n<p>Implementors should not override this method,\nbut instead implement <a href=\"#stream_writable_destroy_err_callback\"><code>writable._destroy()</code></a>.</p>" 567 }, 568 { 569 "textRaw": "`writable.end([chunk[, encoding]][, callback])`", 570 "type": "method", 571 "name": "end", 572 "meta": { 573 "added": [ 574 "v0.9.4" 575 ], 576 "changes": [ 577 { 578 "version": "v14.0.0", 579 "pr-url": "https://github.com/nodejs/node/pull/29747", 580 "description": "The `callback` is invoked if 'finish' or 'error' is emitted." 581 }, 582 { 583 "version": "v10.0.0", 584 "pr-url": "https://github.com/nodejs/node/pull/18780", 585 "description": "This method now returns a reference to `writable`." 586 }, 587 { 588 "version": "v8.0.0", 589 "pr-url": "https://github.com/nodejs/node/pull/11608", 590 "description": "The `chunk` argument can now be a `Uint8Array` instance." 591 } 592 ] 593 }, 594 "signatures": [ 595 { 596 "return": { 597 "textRaw": "Returns: {this}", 598 "name": "return", 599 "type": "this" 600 }, 601 "params": [ 602 { 603 "textRaw": "`chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", 604 "name": "chunk", 605 "type": "string|Buffer|Uint8Array|any", 606 "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`." 607 }, 608 { 609 "textRaw": "`encoding` {string} The encoding if `chunk` is a string", 610 "name": "encoding", 611 "type": "string", 612 "desc": "The encoding if `chunk` is a string" 613 }, 614 { 615 "textRaw": "`callback` {Function} Optional callback for when the stream finishes or errors", 616 "name": "callback", 617 "type": "Function", 618 "desc": "Optional callback for when the stream finishes or errors" 619 } 620 ] 621 } 622 ], 623 "desc": "<p>Calling the <code>writable.end()</code> method signals that no more data will be written\nto the <a href=\"#stream_class_stream_writable\"><code>Writable</code></a>. The optional <code>chunk</code> and <code>encoding</code> arguments allow one\nfinal additional chunk of data to be written immediately before closing the\nstream. If provided, the optional <code>callback</code> function is attached as a listener\nfor the <a href=\"#stream_event_finish\"><code>'finish'</code></a> and the <code>'error'</code> event.</p>\n<p>Calling the <a href=\"#stream_writable_write_chunk_encoding_callback\"><code>stream.write()</code></a> method after calling\n<a href=\"#stream_writable_end_chunk_encoding_callback\"><code>stream.end()</code></a> will raise an error.</p>\n<pre><code class=\"language-js\">// Write 'hello, ' and then end with 'world!'.\nconst fs = require('fs');\nconst file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// Writing more now is not allowed!\n</code></pre>" 624 }, 625 { 626 "textRaw": "`writable.setDefaultEncoding(encoding)`", 627 "type": "method", 628 "name": "setDefaultEncoding", 629 "meta": { 630 "added": [ 631 "v0.11.15" 632 ], 633 "changes": [ 634 { 635 "version": "v6.1.0", 636 "pr-url": "https://github.com/nodejs/node/pull/5040", 637 "description": "This method now returns a reference to `writable`." 638 } 639 ] 640 }, 641 "signatures": [ 642 { 643 "return": { 644 "textRaw": "Returns: {this}", 645 "name": "return", 646 "type": "this" 647 }, 648 "params": [ 649 { 650 "textRaw": "`encoding` {string} The new default encoding", 651 "name": "encoding", 652 "type": "string", 653 "desc": "The new default encoding" 654 } 655 ] 656 } 657 ], 658 "desc": "<p>The <code>writable.setDefaultEncoding()</code> method sets the default <code>encoding</code> for a\n<a href=\"#stream_class_stream_writable\"><code>Writable</code></a> stream.</p>" 659 }, 660 { 661 "textRaw": "`writable.uncork()`", 662 "type": "method", 663 "name": "uncork", 664 "meta": { 665 "added": [ 666 "v0.11.2" 667 ], 668 "changes": [] 669 }, 670 "signatures": [ 671 { 672 "params": [] 673 } 674 ], 675 "desc": "<p>The <code>writable.uncork()</code> method flushes all data buffered since\n<a href=\"#stream_writable_cork\"><code>stream.cork()</code></a> was called.</p>\n<p>When using <a href=\"#stream_writable_cork\"><code>writable.cork()</code></a> and <code>writable.uncork()</code> to manage the buffering\nof writes to a stream, it is recommended that calls to <code>writable.uncork()</code> be\ndeferred using <code>process.nextTick()</code>. Doing so allows batching of all\n<code>writable.write()</code> calls that occur within a given Node.js event loop phase.</p>\n<pre><code class=\"language-js\">stream.cork();\nstream.write('some ');\nstream.write('data ');\nprocess.nextTick(() => stream.uncork());\n</code></pre>\n<p>If the <a href=\"#stream_writable_cork\"><code>writable.cork()</code></a> method is called multiple times on a stream, the\nsame number of calls to <code>writable.uncork()</code> must be called to flush the buffered\ndata.</p>\n<pre><code class=\"language-js\">stream.cork();\nstream.write('some ');\nstream.cork();\nstream.write('data ');\nprocess.nextTick(() => {\n stream.uncork();\n // The data will not be flushed until uncork() is called a second time.\n stream.uncork();\n});\n</code></pre>\n<p>See also: <a href=\"#stream_writable_cork\"><code>writable.cork()</code></a>.</p>" 676 }, 677 { 678 "textRaw": "`writable.write(chunk[, encoding][, callback])`", 679 "type": "method", 680 "name": "write", 681 "meta": { 682 "added": [ 683 "v0.9.4" 684 ], 685 "changes": [ 686 { 687 "version": "v8.0.0", 688 "pr-url": "https://github.com/nodejs/node/pull/11608", 689 "description": "The `chunk` argument can now be a `Uint8Array` instance." 690 }, 691 { 692 "version": "v6.0.0", 693 "pr-url": "https://github.com/nodejs/node/pull/6170", 694 "description": "Passing `null` as the `chunk` parameter will always be considered invalid now, even in object mode." 695 } 696 ] 697 }, 698 "signatures": [ 699 { 700 "return": { 701 "textRaw": "Returns: {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.", 702 "name": "return", 703 "type": "boolean", 704 "desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`." 705 }, 706 "params": [ 707 { 708 "textRaw": "`chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`.", 709 "name": "chunk", 710 "type": "string|Buffer|Uint8Array|any", 711 "desc": "Optional data to write. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value other than `null`." 712 }, 713 { 714 "textRaw": "`encoding` {string|null} The encoding, if `chunk` is a string. **Default:** `'utf8'`", 715 "name": "encoding", 716 "type": "string|null", 717 "default": "`'utf8'`", 718 "desc": "The encoding, if `chunk` is a string." 719 }, 720 { 721 "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed.", 722 "name": "callback", 723 "type": "Function", 724 "desc": "Callback for when this chunk of data is flushed." 725 } 726 ] 727 } 728 ], 729 "desc": "<p>The <code>writable.write()</code> method writes some data to the stream, and calls the\nsupplied <code>callback</code> once the data has been fully handled. If an error\noccurs, the <code>callback</code> <em>may or may not</em> be called with the error as its\nfirst argument. To reliably detect write errors, add a listener for the\n<code>'error'</code> event. The <code>callback</code> is called asynchronously and before <code>'error'</code> is\nemitted.</p>\n<p>The return value is <code>true</code> if the internal buffer is less than the\n<code>highWaterMark</code> configured when the stream was created after admitting <code>chunk</code>.\nIf <code>false</code> is returned, further attempts to write data to the stream should\nstop until the <a href=\"#stream_event_drain\"><code>'drain'</code></a> event is emitted.</p>\n<p>While a stream is not draining, calls to <code>write()</code> will buffer <code>chunk</code>, and\nreturn false. Once all currently buffered chunks are drained (accepted for\ndelivery by the operating system), the <code>'drain'</code> event will be emitted.\nIt is recommended that once <code>write()</code> returns false, no more chunks be written\nuntil the <code>'drain'</code> event is emitted. While calling <code>write()</code> 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.</p>\n<p>Writing data while the stream is not draining is particularly\nproblematic for a <a href=\"#stream_class_stream_transform\"><code>Transform</code></a>, because the <code>Transform</code> streams are paused\nby default until they are piped or a <code>'data'</code> or <code>'readable'</code> event handler\nis added.</p>\n<p>If the data to be written can be generated or fetched on demand, it is\nrecommended to encapsulate the logic into a <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> and use\n<a href=\"#stream_readable_pipe_destination_options\"><code>stream.pipe()</code></a>. However, if calling <code>write()</code> is preferred, it is\npossible to respect backpressure and avoid memory issues using the\n<a href=\"#stream_event_drain\"><code>'drain'</code></a> event:</p>\n<pre><code class=\"language-js\">function write(data, cb) {\n if (!stream.write(data)) {\n stream.once('drain', cb);\n } else {\n process.nextTick(cb);\n }\n}\n\n// Wait for cb to be called before doing any other write.\nwrite('hello', () => {\n console.log('Write completed, do more writes now.');\n});\n</code></pre>\n<p>A <code>Writable</code> stream in object mode will always ignore the <code>encoding</code> argument.</p>" 730 } 731 ], 732 "properties": [ 733 { 734 "textRaw": "`destroyed` {boolean}", 735 "type": "boolean", 736 "name": "destroyed", 737 "meta": { 738 "added": [ 739 "v8.0.0" 740 ], 741 "changes": [] 742 }, 743 "desc": "<p>Is <code>true</code> after <a href=\"#stream_writable_destroy_error\"><code>writable.destroy()</code></a> has been called.</p>\n<pre><code class=\"language-cjs\">const { Writable } = require('stream');\n\nconst myStream = new Writable();\n\nconsole.log(myStream.destroyed); // false\nmyStream.destroy();\nconsole.log(myStream.destroyed); // true\n</code></pre>" 744 }, 745 { 746 "textRaw": "`writable` {boolean}", 747 "type": "boolean", 748 "name": "writable", 749 "meta": { 750 "added": [ 751 "v11.4.0" 752 ], 753 "changes": [] 754 }, 755 "desc": "<p>Is <code>true</code> if it is safe to call <a href=\"#stream_writable_write_chunk_encoding_callback\"><code>writable.write()</code></a>, which means\nthe stream has not been destroyed, errored or ended.</p>" 756 }, 757 { 758 "textRaw": "`writableEnded` {boolean}", 759 "type": "boolean", 760 "name": "writableEnded", 761 "meta": { 762 "added": [ 763 "v12.9.0" 764 ], 765 "changes": [] 766 }, 767 "desc": "<p>Is <code>true</code> after <a href=\"#stream_writable_end_chunk_encoding_callback\"><code>writable.end()</code></a> has been called. This property\ndoes not indicate whether the data has been flushed, for this use\n<a href=\"#stream_writable_writablefinished\"><code>writable.writableFinished</code></a> instead.</p>" 768 }, 769 { 770 "textRaw": "`writableCorked` {integer}", 771 "type": "integer", 772 "name": "writableCorked", 773 "meta": { 774 "added": [ 775 "v13.2.0", 776 "v12.16.0" 777 ], 778 "changes": [] 779 }, 780 "desc": "<p>Number of times <a href=\"#stream_writable_uncork\"><code>writable.uncork()</code></a> needs to be\ncalled in order to fully uncork the stream.</p>" 781 }, 782 { 783 "textRaw": "`writableFinished` {boolean}", 784 "type": "boolean", 785 "name": "writableFinished", 786 "meta": { 787 "added": [ 788 "v12.6.0" 789 ], 790 "changes": [] 791 }, 792 "desc": "<p>Is set to <code>true</code> immediately before the <a href=\"#stream_event_finish\"><code>'finish'</code></a> event is emitted.</p>" 793 }, 794 { 795 "textRaw": "`writableHighWaterMark` {number}", 796 "type": "number", 797 "name": "writableHighWaterMark", 798 "meta": { 799 "added": [ 800 "v9.3.0" 801 ], 802 "changes": [] 803 }, 804 "desc": "<p>Return the value of <code>highWaterMark</code> passed when constructing this\n<code>Writable</code>.</p>" 805 }, 806 { 807 "textRaw": "`writableLength` {number}", 808 "type": "number", 809 "name": "writableLength", 810 "meta": { 811 "added": [ 812 "v9.4.0" 813 ], 814 "changes": [] 815 }, 816 "desc": "<p>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 <code>highWaterMark</code>.</p>" 817 }, 818 { 819 "textRaw": "`writableNeedDrain` {boolean}", 820 "type": "boolean", 821 "name": "writableNeedDrain", 822 "meta": { 823 "added": [ 824 "v14.17.0" 825 ], 826 "changes": [] 827 }, 828 "desc": "<p>Is <code>true</code> if the stream's buffer has been full and stream will emit <code>'drain'</code>.</p>" 829 }, 830 { 831 "textRaw": "`writableObjectMode` {boolean}", 832 "type": "boolean", 833 "name": "writableObjectMode", 834 "meta": { 835 "added": [ 836 "v12.3.0" 837 ], 838 "changes": [] 839 }, 840 "desc": "<p>Getter for the property <code>objectMode</code> of a given <code>Writable</code> stream.</p>" 841 } 842 ] 843 } 844 ], 845 "type": "misc", 846 "displayName": "Writable streams" 847 }, 848 { 849 "textRaw": "Readable streams", 850 "name": "readable_streams", 851 "desc": "<p>Readable streams are an abstraction for a <em>source</em> from which data is\nconsumed.</p>\n<p>Examples of <code>Readable</code> streams include:</p>\n<ul>\n<li><a href=\"http.html#http_class_http_incomingmessage\">HTTP responses, on the client</a></li>\n<li><a href=\"http.html#http_class_http_incomingmessage\">HTTP requests, on the server</a></li>\n<li><a href=\"fs.html#fs_class_fs_readstream\">fs read streams</a></li>\n<li><a href=\"zlib.html\">zlib streams</a></li>\n<li><a href=\"crypto.html\">crypto streams</a></li>\n<li><a href=\"net.html#net_class_net_socket\">TCP sockets</a></li>\n<li><a href=\"child_process.html#child_process_subprocess_stdout\">child process stdout and stderr</a></li>\n<li><a href=\"process.html#process_process_stdin\"><code>process.stdin</code></a></li>\n</ul>\n<p>All <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> streams implement the interface defined by the\n<code>stream.Readable</code> class.</p>", 852 "modules": [ 853 { 854 "textRaw": "Two reading modes", 855 "name": "two_reading_modes", 856 "desc": "<p><code>Readable</code> streams effectively operate in one of two modes: flowing and\npaused. These modes are separate from <a href=\"#stream_object_mode\">object mode</a>.\nA <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> stream can be in object mode or not, regardless of whether\nit is in flowing mode or paused mode.</p>\n<ul>\n<li>\n<p>In flowing mode, data is read from the underlying system automatically\nand provided to an application as quickly as possible using events via the\n<a href=\"events.html#events_class_eventemitter\"><code>EventEmitter</code></a> interface.</p>\n</li>\n<li>\n<p>In paused mode, the <a href=\"#stream_readable_read_size\"><code>stream.read()</code></a> method must be called\nexplicitly to read chunks of data from the stream.</p>\n</li>\n</ul>\n<p>All <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> streams begin in paused mode but can be switched to flowing\nmode in one of the following ways:</p>\n<ul>\n<li>Adding a <a href=\"#stream_event_data\"><code>'data'</code></a> event handler.</li>\n<li>Calling the <a href=\"#stream_readable_resume\"><code>stream.resume()</code></a> method.</li>\n<li>Calling the <a href=\"#stream_readable_pipe_destination_options\"><code>stream.pipe()</code></a> method to send the data to a <a href=\"#stream_class_stream_writable\"><code>Writable</code></a>.</li>\n</ul>\n<p>The <code>Readable</code> can switch back to paused mode using one of the following:</p>\n<ul>\n<li>If there are no pipe destinations, by calling the\n<a href=\"#stream_readable_pause\"><code>stream.pause()</code></a> method.</li>\n<li>If there are pipe destinations, by removing all pipe destinations.\nMultiple pipe destinations may be removed by calling the\n<a href=\"#stream_readable_unpipe_destination\"><code>stream.unpipe()</code></a> method.</li>\n</ul>\n<p>The important concept to remember is that a <code>Readable</code> 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 <code>Readable</code> will <em>attempt</em>\nto stop generating the data.</p>\n<p>For backward compatibility reasons, removing <a href=\"#stream_event_data\"><code>'data'</code></a> event handlers will\n<strong>not</strong> automatically pause the stream. Also, if there are piped destinations,\nthen calling <a href=\"#stream_readable_pause\"><code>stream.pause()</code></a> will not guarantee that the\nstream will <em>remain</em> paused once those destinations drain and ask for more data.</p>\n<p>If a <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> 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 <code>readable.resume()</code> method is called without a listener\nattached to the <code>'data'</code> event, or when a <code>'data'</code> event handler is removed\nfrom the stream.</p>\n<p>Adding a <a href=\"#stream_event_readable\"><code>'readable'</code></a> event handler automatically makes the stream\nstop flowing, and the data has to be consumed via\n<a href=\"#stream_readable_read_size\"><code>readable.read()</code></a>. If the <a href=\"#stream_event_readable\"><code>'readable'</code></a> event handler is\nremoved, then the stream will start flowing again if there is a\n<a href=\"#stream_event_data\"><code>'data'</code></a> event handler.</p>", 857 "type": "module", 858 "displayName": "Two reading modes" 859 }, 860 { 861 "textRaw": "Three states", 862 "name": "three_states", 863 "desc": "<p>The \"two modes\" of operation for a <code>Readable</code> stream are a simplified\nabstraction for the more complicated internal state management that is happening\nwithin the <code>Readable</code> stream implementation.</p>\n<p>Specifically, at any given point in time, every <code>Readable</code> is in one of three\npossible states:</p>\n<ul>\n<li><code>readable.readableFlowing === null</code></li>\n<li><code>readable.readableFlowing === false</code></li>\n<li><code>readable.readableFlowing === true</code></li>\n</ul>\n<p>When <code>readable.readableFlowing</code> is <code>null</code>, 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 <code>'data'</code> event, calling the\n<code>readable.pipe()</code> method, or calling the <code>readable.resume()</code> method will switch\n<code>readable.readableFlowing</code> to <code>true</code>, causing the <code>Readable</code> to begin actively\nemitting events as data is generated.</p>\n<p>Calling <code>readable.pause()</code>, <code>readable.unpipe()</code>, or receiving backpressure\nwill cause the <code>readable.readableFlowing</code> to be set as <code>false</code>,\ntemporarily halting the flowing of events but <em>not</em> halting the generation of\ndata. While in this state, attaching a listener for the <code>'data'</code> event\nwill not switch <code>readable.readableFlowing</code> to <code>true</code>.</p>\n<pre><code class=\"language-js\">const { PassThrough, Writable } = require('stream');\nconst pass = new PassThrough();\nconst writable = new Writable();\n\npass.pipe(writable);\npass.unpipe(writable);\n// readableFlowing is now false.\n\npass.on('data', (chunk) => { console.log(chunk.toString()); });\npass.write('ok'); // Will not emit 'data'.\npass.resume(); // Must be called to make stream emit 'data'.\n</code></pre>\n<p>While <code>readable.readableFlowing</code> is <code>false</code>, data may be accumulating\nwithin the stream's internal buffer.</p>", 864 "type": "module", 865 "displayName": "Three states" 866 }, 867 { 868 "textRaw": "Choose one API style", 869 "name": "choose_one_api_style", 870 "desc": "<p>The <code>Readable</code> stream API evolved across multiple Node.js versions and provides\nmultiple methods of consuming stream data. In general, developers should choose\n<em>one</em> of the methods of consuming data and <em>should never</em> use multiple methods\nto consume data from a single stream. Specifically, using a combination\nof <code>on('data')</code>, <code>on('readable')</code>, <code>pipe()</code>, or async iterators could\nlead to unintuitive behavior.</p>\n<p>Use of the <code>readable.pipe()</code> method is recommended for most users as it has been\nimplemented to provide the easiest way of consuming stream data. Developers that\nrequire more fine-grained control over the transfer and generation of data can\nuse the <a href=\"events.html#events_class_eventemitter\"><code>EventEmitter</code></a> and <code>readable.on('readable')</code>/<code>readable.read()</code>\nor the <code>readable.pause()</code>/<code>readable.resume()</code> APIs.</p>", 871 "type": "module", 872 "displayName": "Choose one API style" 873 } 874 ], 875 "classes": [ 876 { 877 "textRaw": "Class: `stream.Readable`", 878 "type": "class", 879 "name": "stream.Readable", 880 "meta": { 881 "added": [ 882 "v0.9.4" 883 ], 884 "changes": [] 885 }, 886 "events": [ 887 { 888 "textRaw": "Event: `'close'`", 889 "type": "event", 890 "name": "close", 891 "meta": { 892 "added": [ 893 "v0.9.4" 894 ], 895 "changes": [ 896 { 897 "version": "v10.0.0", 898 "pr-url": "https://github.com/nodejs/node/pull/18438", 899 "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." 900 } 901 ] 902 }, 903 "params": [], 904 "desc": "<p>The <code>'close'</code> 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.</p>\n<p>A <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> stream will always emit the <code>'close'</code> event if it is\ncreated with the <code>emitClose</code> option.</p>" 905 }, 906 { 907 "textRaw": "Event: `'data'`", 908 "type": "event", 909 "name": "data", 910 "meta": { 911 "added": [ 912 "v0.9.4" 913 ], 914 "changes": [] 915 }, 916 "params": [ 917 { 918 "textRaw": "`chunk` {Buffer|string|any} The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. For streams that are in object mode, the chunk can be any JavaScript value other than `null`.", 919 "name": "chunk", 920 "type": "Buffer|string|any", 921 "desc": "The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. For streams that are in object mode, the chunk can be any JavaScript value other than `null`." 922 } 923 ], 924 "desc": "<p>The <code>'data'</code> 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 <code>readable.pipe()</code>, <code>readable.resume()</code>, or by\nattaching a listener callback to the <code>'data'</code> event. The <code>'data'</code> event will\nalso be emitted whenever the <code>readable.read()</code> method is called and a chunk of\ndata is available to be returned.</p>\n<p>Attaching a <code>'data'</code> 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.</p>\n<p>The listener callback will be passed the chunk of data as a string if a default\nencoding has been specified for the stream using the\n<code>readable.setEncoding()</code> method; otherwise the data will be passed as a\n<code>Buffer</code>.</p>\n<pre><code class=\"language-js\">const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n});\n</code></pre>" 925 }, 926 { 927 "textRaw": "Event: `'end'`", 928 "type": "event", 929 "name": "end", 930 "meta": { 931 "added": [ 932 "v0.9.4" 933 ], 934 "changes": [] 935 }, 936 "params": [], 937 "desc": "<p>The <code>'end'</code> event is emitted when there is no more data to be consumed from\nthe stream.</p>\n<p>The <code>'end'</code> event <strong>will not be emitted</strong> unless the data is completely\nconsumed. This can be accomplished by switching the stream into flowing mode,\nor by calling <a href=\"#stream_readable_read_size\"><code>stream.read()</code></a> repeatedly until all data has been\nconsumed.</p>\n<pre><code class=\"language-js\">const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n});\nreadable.on('end', () => {\n console.log('There will be no more data.');\n});\n</code></pre>" 938 }, 939 { 940 "textRaw": "Event: `'error'`", 941 "type": "event", 942 "name": "error", 943 "meta": { 944 "added": [ 945 "v0.9.4" 946 ], 947 "changes": [] 948 }, 949 "params": [ 950 { 951 "textRaw": "{Error}", 952 "type": "Error" 953 } 954 ], 955 "desc": "<p>The <code>'error'</code> event may be emitted by a <code>Readable</code> 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.</p>\n<p>The listener callback will be passed a single <code>Error</code> object.</p>" 956 }, 957 { 958 "textRaw": "Event: `'pause'`", 959 "type": "event", 960 "name": "pause", 961 "meta": { 962 "added": [ 963 "v0.9.4" 964 ], 965 "changes": [] 966 }, 967 "params": [], 968 "desc": "<p>The <code>'pause'</code> event is emitted when <a href=\"#stream_readable_pause\"><code>stream.pause()</code></a> is called\nand <code>readableFlowing</code> is not <code>false</code>.</p>" 969 }, 970 { 971 "textRaw": "Event: `'readable'`", 972 "type": "event", 973 "name": "readable", 974 "meta": { 975 "added": [ 976 "v0.9.4" 977 ], 978 "changes": [ 979 { 980 "version": "v10.0.0", 981 "pr-url": "https://github.com/nodejs/node/pull/17979", 982 "description": "The `'readable'` is always emitted in the next tick after `.push()` is called." 983 }, 984 { 985 "version": "v10.0.0", 986 "pr-url": "https://github.com/nodejs/node/pull/18994", 987 "description": "Using `'readable'` requires calling `.read()`." 988 } 989 ] 990 }, 991 "params": [], 992 "desc": "<p>The <code>'readable'</code> event is emitted when there is data available to be read from\nthe stream. In some cases, attaching a listener for the <code>'readable'</code> event will\ncause some amount of data to be read into an internal buffer.</p>\n<pre><code class=\"language-js\">const readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n // There is some data to read now.\n let data;\n\n while (data = this.read()) {\n console.log(data);\n }\n});\n</code></pre>\n<p>The <code>'readable'</code> event will also be emitted once the end of the stream data\nhas been reached but before the <code>'end'</code> event is emitted.</p>\n<p>Effectively, the <code>'readable'</code> event indicates that the stream has new\ninformation: either new data is available or the end of the stream has been\nreached. In the former case, <a href=\"#stream_readable_read_size\"><code>stream.read()</code></a> will return the\navailable data. In the latter case, <a href=\"#stream_readable_read_size\"><code>stream.read()</code></a> will return\n<code>null</code>. For instance, in the following example, <code>foo.txt</code> is an empty file:</p>\n<pre><code class=\"language-js\">const fs = require('fs');\nconst rr = fs.createReadStream('foo.txt');\nrr.on('readable', () => {\n console.log(`readable: ${rr.read()}`);\n});\nrr.on('end', () => {\n console.log('end');\n});\n</code></pre>\n<p>The output of running this script is:</p>\n<pre><code class=\"language-console\">$ node test.js\nreadable: null\nend\n</code></pre>\n<p>In general, the <code>readable.pipe()</code> and <code>'data'</code> event mechanisms are easier to\nunderstand than the <code>'readable'</code> event. However, handling <code>'readable'</code> might\nresult in increased throughput.</p>\n<p>If both <code>'readable'</code> and <a href=\"#stream_event_data\"><code>'data'</code></a> are used at the same time, <code>'readable'</code>\ntakes precedence in controlling the flow, i.e. <code>'data'</code> will be emitted\nonly when <a href=\"#stream_readable_read_size\"><code>stream.read()</code></a> is called. The\n<code>readableFlowing</code> property would become <code>false</code>.\nIf there are <code>'data'</code> listeners when <code>'readable'</code> is removed, the stream\nwill start flowing, i.e. <code>'data'</code> events will be emitted without calling\n<code>.resume()</code>.</p>" 993 }, 994 { 995 "textRaw": "Event: `'resume'`", 996 "type": "event", 997 "name": "resume", 998 "meta": { 999 "added": [ 1000 "v0.9.4" 1001 ], 1002 "changes": [] 1003 }, 1004 "params": [], 1005 "desc": "<p>The <code>'resume'</code> event is emitted when <a href=\"#stream_readable_resume\"><code>stream.resume()</code></a> is\ncalled and <code>readableFlowing</code> is not <code>true</code>.</p>" 1006 } 1007 ], 1008 "methods": [ 1009 { 1010 "textRaw": "`readable.destroy([error])`", 1011 "type": "method", 1012 "name": "destroy", 1013 "meta": { 1014 "added": [ 1015 "v8.0.0" 1016 ], 1017 "changes": [ 1018 { 1019 "version": "v14.0.0", 1020 "pr-url": "https://github.com/nodejs/node/pull/29197", 1021 "description": "Work as a no-op on a stream that has already been destroyed." 1022 } 1023 ] 1024 }, 1025 "signatures": [ 1026 { 1027 "return": { 1028 "textRaw": "Returns: {this}", 1029 "name": "return", 1030 "type": "this" 1031 }, 1032 "params": [ 1033 { 1034 "textRaw": "`error` {Error} Error which will be passed as payload in `'error'` event", 1035 "name": "error", 1036 "type": "Error", 1037 "desc": "Error which will be passed as payload in `'error'` event" 1038 } 1039 ] 1040 } 1041 ], 1042 "desc": "<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code>\nevent (unless <code>emitClose</code> is set to <code>false</code>). After this call, the readable\nstream will release any internal resources and subsequent calls to <code>push()</code>\nwill be ignored.</p>\n<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no\nfurther errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p>\n<p>Implementors should not override this method, but instead implement\n<a href=\"#stream_readable_destroy_err_callback\"><code>readable._destroy()</code></a>.</p>" 1043 }, 1044 { 1045 "textRaw": "`readable.isPaused()`", 1046 "type": "method", 1047 "name": "isPaused", 1048 "meta": { 1049 "added": [ 1050 "v0.11.14" 1051 ], 1052 "changes": [] 1053 }, 1054 "signatures": [ 1055 { 1056 "return": { 1057 "textRaw": "Returns: {boolean}", 1058 "name": "return", 1059 "type": "boolean" 1060 }, 1061 "params": [] 1062 } 1063 ], 1064 "desc": "<p>The <code>readable.isPaused()</code> method returns the current operating state of the\n<code>Readable</code>. This is used primarily by the mechanism that underlies the\n<code>readable.pipe()</code> method. In most typical cases, there will be no reason to\nuse this method directly.</p>\n<pre><code class=\"language-js\">const readable = new stream.Readable();\n\nreadable.isPaused(); // === false\nreadable.pause();\nreadable.isPaused(); // === true\nreadable.resume();\nreadable.isPaused(); // === false\n</code></pre>" 1065 }, 1066 { 1067 "textRaw": "`readable.pause()`", 1068 "type": "method", 1069 "name": "pause", 1070 "meta": { 1071 "added": [ 1072 "v0.9.4" 1073 ], 1074 "changes": [] 1075 }, 1076 "signatures": [ 1077 { 1078 "return": { 1079 "textRaw": "Returns: {this}", 1080 "name": "return", 1081 "type": "this" 1082 }, 1083 "params": [] 1084 } 1085 ], 1086 "desc": "<p>The <code>readable.pause()</code> method will cause a stream in flowing mode to stop\nemitting <a href=\"#stream_event_data\"><code>'data'</code></a> events, switching out of flowing mode. Any data that\nbecomes available will remain in the internal buffer.</p>\n<pre><code class=\"language-js\">const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n readable.pause();\n console.log('There will be no additional data for 1 second.');\n setTimeout(() => {\n console.log('Now data will start flowing again.');\n readable.resume();\n }, 1000);\n});\n</code></pre>\n<p>The <code>readable.pause()</code> method has no effect if there is a <code>'readable'</code>\nevent listener.</p>" 1087 }, 1088 { 1089 "textRaw": "`readable.pipe(destination[, options])`", 1090 "type": "method", 1091 "name": "pipe", 1092 "meta": { 1093 "added": [ 1094 "v0.9.4" 1095 ], 1096 "changes": [] 1097 }, 1098 "signatures": [ 1099 { 1100 "return": { 1101 "textRaw": "Returns: {stream.Writable} The *destination*, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream", 1102 "name": "return", 1103 "type": "stream.Writable", 1104 "desc": "The *destination*, allowing for a chain of pipes if it is a [`Duplex`][] or a [`Transform`][] stream" 1105 }, 1106 "params": [ 1107 { 1108 "textRaw": "`destination` {stream.Writable} The destination for writing data", 1109 "name": "destination", 1110 "type": "stream.Writable", 1111 "desc": "The destination for writing data" 1112 }, 1113 { 1114 "textRaw": "`options` {Object} Pipe options", 1115 "name": "options", 1116 "type": "Object", 1117 "desc": "Pipe options", 1118 "options": [ 1119 { 1120 "textRaw": "`end` {boolean} End the writer when the reader ends. **Default:** `true`.", 1121 "name": "end", 1122 "type": "boolean", 1123 "default": "`true`", 1124 "desc": "End the writer when the reader ends." 1125 } 1126 ] 1127 } 1128 ] 1129 } 1130 ], 1131 "desc": "<p>The <code>readable.pipe()</code> method attaches a <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> stream to the <code>readable</code>,\ncausing it to switch automatically into flowing mode and push all of its data\nto the attached <a href=\"#stream_class_stream_writable\"><code>Writable</code></a>. The flow of data will be automatically managed\nso that the destination <code>Writable</code> stream is not overwhelmed by a faster\n<code>Readable</code> stream.</p>\n<p>The following example pipes all of the data from the <code>readable</code> into a file\nnamed <code>file.txt</code>:</p>\n<pre><code class=\"language-js\">const fs = require('fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'.\nreadable.pipe(writable);\n</code></pre>\n<p>It is possible to attach multiple <code>Writable</code> streams to a single <code>Readable</code>\nstream.</p>\n<p>The <code>readable.pipe()</code> method returns a reference to the <em>destination</em> stream\nmaking it possible to set up chains of piped streams:</p>\n<pre><code class=\"language-js\">const fs = require('fs');\nconst r = fs.createReadStream('file.txt');\nconst z = zlib.createGzip();\nconst w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);\n</code></pre>\n<p>By default, <a href=\"#stream_writable_end_chunk_encoding_callback\"><code>stream.end()</code></a> is called on the destination <code>Writable</code>\nstream when the source <code>Readable</code> stream emits <a href=\"#stream_event_end\"><code>'end'</code></a>, so that the\ndestination is no longer writable. To disable this default behavior, the <code>end</code>\noption can be passed as <code>false</code>, causing the destination stream to remain open:</p>\n<pre><code class=\"language-js\">reader.pipe(writer, { end: false });\nreader.on('end', () => {\n writer.end('Goodbye\\n');\n});\n</code></pre>\n<p>One important caveat is that if the <code>Readable</code> stream emits an error during\nprocessing, the <code>Writable</code> destination <em>is not closed</em> automatically. If an\nerror occurs, it will be necessary to <em>manually</em> close each stream in order\nto prevent memory leaks.</p>\n<p>The <a href=\"process.html#process_process_stderr\"><code>process.stderr</code></a> and <a href=\"process.html#process_process_stdout\"><code>process.stdout</code></a> <code>Writable</code> streams are never\nclosed until the Node.js process exits, regardless of the specified options.</p>" 1132 }, 1133 { 1134 "textRaw": "`readable.read([size])`", 1135 "type": "method", 1136 "name": "read", 1137 "meta": { 1138 "added": [ 1139 "v0.9.4" 1140 ], 1141 "changes": [] 1142 }, 1143 "signatures": [ 1144 { 1145 "return": { 1146 "textRaw": "Returns: {string|Buffer|null|any}", 1147 "name": "return", 1148 "type": "string|Buffer|null|any" 1149 }, 1150 "params": [ 1151 { 1152 "textRaw": "`size` {number} Optional argument to specify how much data to read.", 1153 "name": "size", 1154 "type": "number", 1155 "desc": "Optional argument to specify how much data to read." 1156 } 1157 ] 1158 } 1159 ], 1160 "desc": "<p>The <code>readable.read()</code> method pulls some data out of the internal buffer and\nreturns it. If no data available to be read, <code>null</code> is returned. By default,\nthe data will be returned as a <code>Buffer</code> object unless an encoding has been\nspecified using the <code>readable.setEncoding()</code> method or the stream is operating\nin object mode.</p>\n<p>The optional <code>size</code> argument specifies a specific number of bytes to read. If\n<code>size</code> bytes are not available to be read, <code>null</code> will be returned <em>unless</em>\nthe stream has ended, in which case all of the data remaining in the internal\nbuffer will be returned.</p>\n<p>If the <code>size</code> argument is not specified, all of the data contained in the\ninternal buffer will be returned.</p>\n<p>The <code>size</code> argument must be less than or equal to 1 GiB.</p>\n<p>The <code>readable.read()</code> method should only be called on <code>Readable</code> streams\noperating in paused mode. In flowing mode, <code>readable.read()</code> is called\nautomatically until the internal buffer is fully drained.</p>\n<pre><code class=\"language-js\">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});\n</code></pre>\n<p>Each call to <code>readable.read()</code> returns a chunk of data, or <code>null</code>. The chunks\nare not concatenated. A <code>while</code> loop is necessary to consume all data\ncurrently in the buffer. When reading a large file <code>.read()</code> may return <code>null</code>,\nhaving consumed all buffered content so far, but there is still more data to\ncome not yet buffered. In this case a new <code>'readable'</code> event will be emitted\nwhen there is more data in the buffer. Finally the <code>'end'</code> event will be\nemitted when there is no more data to come.</p>\n<p>Therefore to read a file's whole contents from a <code>readable</code>, it is necessary\nto collect chunks across multiple <code>'readable'</code> events:</p>\n<pre><code class=\"language-js\">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});\n</code></pre>\n<p>A <code>Readable</code> stream in object mode will always return a single item from\na call to <a href=\"#stream_readable_read_size\"><code>readable.read(size)</code></a>, regardless of the value of the\n<code>size</code> argument.</p>\n<p>If the <code>readable.read()</code> method returns a chunk of data, a <code>'data'</code> event will\nalso be emitted.</p>\n<p>Calling <a href=\"#stream_readable_read_size\"><code>stream.read([size])</code></a> after the <a href=\"#stream_event_end\"><code>'end'</code></a> event has\nbeen emitted will return <code>null</code>. No runtime error will be raised.</p>" 1161 }, 1162 { 1163 "textRaw": "`readable.resume()`", 1164 "type": "method", 1165 "name": "resume", 1166 "meta": { 1167 "added": [ 1168 "v0.9.4" 1169 ], 1170 "changes": [ 1171 { 1172 "version": "v10.0.0", 1173 "pr-url": "https://github.com/nodejs/node/pull/18994", 1174 "description": "The `resume()` has no effect if there is a `'readable'` event listening." 1175 } 1176 ] 1177 }, 1178 "signatures": [ 1179 { 1180 "return": { 1181 "textRaw": "Returns: {this}", 1182 "name": "return", 1183 "type": "this" 1184 }, 1185 "params": [] 1186 } 1187 ], 1188 "desc": "<p>The <code>readable.resume()</code> method causes an explicitly paused <code>Readable</code> stream to\nresume emitting <a href=\"#stream_event_data\"><code>'data'</code></a> events, switching the stream into flowing mode.</p>\n<p>The <code>readable.resume()</code> method can be used to fully consume the data from a\nstream without actually processing any of that data:</p>\n<pre><code class=\"language-js\">getReadableStreamSomehow()\n .resume()\n .on('end', () => {\n console.log('Reached the end, but did not read anything.');\n });\n</code></pre>\n<p>The <code>readable.resume()</code> method has no effect if there is a <code>'readable'</code>\nevent listener.</p>" 1189 }, 1190 { 1191 "textRaw": "`readable.setEncoding(encoding)`", 1192 "type": "method", 1193 "name": "setEncoding", 1194 "meta": { 1195 "added": [ 1196 "v0.9.4" 1197 ], 1198 "changes": [] 1199 }, 1200 "signatures": [ 1201 { 1202 "return": { 1203 "textRaw": "Returns: {this}", 1204 "name": "return", 1205 "type": "this" 1206 }, 1207 "params": [ 1208 { 1209 "textRaw": "`encoding` {string} The encoding to use.", 1210 "name": "encoding", 1211 "type": "string", 1212 "desc": "The encoding to use." 1213 } 1214 ] 1215 } 1216 ], 1217 "desc": "<p>The <code>readable.setEncoding()</code> method sets the character encoding for\ndata read from the <code>Readable</code> stream.</p>\n<p>By default, no encoding is assigned and stream data will be returned as\n<code>Buffer</code> objects. Setting an encoding causes the stream data\nto be returned as strings of the specified encoding rather than as <code>Buffer</code>\nobjects. For instance, calling <code>readable.setEncoding('utf8')</code> will cause the\noutput data to be interpreted as UTF-8 data, and passed as strings. Calling\n<code>readable.setEncoding('hex')</code> will cause the data to be encoded in hexadecimal\nstring format.</p>\n<p>The <code>Readable</code> stream will properly handle multi-byte characters delivered\nthrough the stream that would otherwise become improperly decoded if simply\npulled from the stream as <code>Buffer</code> objects.</p>\n<pre><code class=\"language-js\">const readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', (chunk) => {\n assert.equal(typeof chunk, 'string');\n console.log('Got %d characters of string data:', chunk.length);\n});\n</code></pre>" 1218 }, 1219 { 1220 "textRaw": "`readable.unpipe([destination])`", 1221 "type": "method", 1222 "name": "unpipe", 1223 "meta": { 1224 "added": [ 1225 "v0.9.4" 1226 ], 1227 "changes": [] 1228 }, 1229 "signatures": [ 1230 { 1231 "return": { 1232 "textRaw": "Returns: {this}", 1233 "name": "return", 1234 "type": "this" 1235 }, 1236 "params": [ 1237 { 1238 "textRaw": "`destination` {stream.Writable} Optional specific stream to unpipe", 1239 "name": "destination", 1240 "type": "stream.Writable", 1241 "desc": "Optional specific stream to unpipe" 1242 } 1243 ] 1244 } 1245 ], 1246 "desc": "<p>The <code>readable.unpipe()</code> method detaches a <code>Writable</code> stream previously attached\nusing the <a href=\"#stream_readable_pipe_destination_options\"><code>stream.pipe()</code></a> method.</p>\n<p>If the <code>destination</code> is not specified, then <em>all</em> pipes are detached.</p>\n<p>If the <code>destination</code> is specified, but no pipe is set up for it, then\nthe method does nothing.</p>\n<pre><code class=\"language-js\">const fs = require('fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second.\nreadable.pipe(writable);\nsetTimeout(() => {\n console.log('Stop writing to file.txt.');\n readable.unpipe(writable);\n console.log('Manually close the file stream.');\n writable.end();\n}, 1000);\n</code></pre>" 1247 }, 1248 { 1249 "textRaw": "`readable.unshift(chunk[, encoding])`", 1250 "type": "method", 1251 "name": "unshift", 1252 "meta": { 1253 "added": [ 1254 "v0.9.11" 1255 ], 1256 "changes": [ 1257 { 1258 "version": "v8.0.0", 1259 "pr-url": "https://github.com/nodejs/node/pull/11608", 1260 "description": "The `chunk` argument can now be a `Uint8Array` instance." 1261 } 1262 ] 1263 }, 1264 "signatures": [ 1265 { 1266 "params": [ 1267 { 1268 "textRaw": "`chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode streams, `chunk` may be any JavaScript value.", 1269 "name": "chunk", 1270 "type": "Buffer|Uint8Array|string|null|any", 1271 "desc": "Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer`, `Uint8Array` or `null`. For object mode streams, `chunk` may be any JavaScript value." 1272 }, 1273 { 1274 "textRaw": "`encoding` {string} Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.", 1275 "name": "encoding", 1276 "type": "string", 1277 "desc": "Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`." 1278 } 1279 ] 1280 } 1281 ], 1282 "desc": "<p>Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF) and behaves the\nsame as <code>readable.push(null)</code>, 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.</p>\n<p>The <code>readable.unshift()</code> 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.</p>\n<p>The <code>stream.unshift(chunk)</code> method cannot be called after the <a href=\"#stream_event_end\"><code>'end'</code></a> event\nhas been emitted or a runtime error will be thrown.</p>\n<p>Developers using <code>stream.unshift()</code> often should consider switching to\nuse of a <a href=\"#stream_class_stream_transform\"><code>Transform</code></a> stream instead. See the <a href=\"#stream_api_for_stream_implementers\">API for stream implementers</a>\nsection for more information.</p>\n<pre><code class=\"language-js\">// Pull off a header delimited by \\n\\n.\n// Use unshift() if we get too much.\n// Call the callback with (error, header, stream).\nconst { StringDecoder } = require('string_decoder');\nfunction parseHeader(stream, callback) {\n stream.on('error', callback);\n stream.on('readable', onReadable);\n const decoder = new StringDecoder('utf8');\n let header = '';\n function onReadable() {\n let chunk;\n while (null !== (chunk = stream.read())) {\n const str = decoder.write(chunk);\n if (str.match(/\\n\\n/)) {\n // Found the header boundary.\n const split = str.split(/\\n\\n/);\n header += split.shift();\n const remaining = split.join('\\n\\n');\n const buf = Buffer.from(remaining, 'utf8');\n stream.removeListener('error', callback);\n // Remove the 'readable' listener before unshifting.\n stream.removeListener('readable', onReadable);\n if (buf.length)\n stream.unshift(buf);\n // Now the body of the message can be read from the stream.\n callback(null, header, stream);\n } else {\n // Still reading the header.\n header += str;\n }\n }\n }\n}\n</code></pre>\n<p>Unlike <a href=\"#stream_readable_push_chunk_encoding\"><code>stream.push(chunk)</code></a>, <code>stream.unshift(chunk)</code> will not\nend the reading process by resetting the internal reading state of the stream.\nThis can cause unexpected results if <code>readable.unshift()</code> is called during a\nread (i.e. from within a <a href=\"#stream_readable_read_size_1\"><code>stream._read()</code></a> implementation on a\ncustom stream). Following the call to <code>readable.unshift()</code> with an immediate\n<a href=\"#stream_readable_push_chunk_encoding\"><code>stream.push('')</code></a> will reset the reading state appropriately,\nhowever it is best to simply avoid calling <code>readable.unshift()</code> while in the\nprocess of performing a read.</p>" 1283 }, 1284 { 1285 "textRaw": "`readable.wrap(stream)`", 1286 "type": "method", 1287 "name": "wrap", 1288 "meta": { 1289 "added": [ 1290 "v0.9.4" 1291 ], 1292 "changes": [] 1293 }, 1294 "signatures": [ 1295 { 1296 "return": { 1297 "textRaw": "Returns: {this}", 1298 "name": "return", 1299 "type": "this" 1300 }, 1301 "params": [ 1302 { 1303 "textRaw": "`stream` {Stream} An \"old style\" readable stream", 1304 "name": "stream", 1305 "type": "Stream", 1306 "desc": "An \"old style\" readable stream" 1307 } 1308 ] 1309 } 1310 ], 1311 "desc": "<p>Prior to Node.js 0.10, streams did not implement the entire <code>stream</code> module API\nas it is currently defined. (See <a href=\"#stream_compatibility_with_older_node_js_versions\">Compatibility</a> for more information.)</p>\n<p>When using an older Node.js library that emits <a href=\"#stream_event_data\"><code>'data'</code></a> events and has a\n<a href=\"#stream_readable_pause\"><code>stream.pause()</code></a> method that is advisory only, the\n<code>readable.wrap()</code> method can be used to create a <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> stream that uses\nthe old stream as its data source.</p>\n<p>It will rarely be necessary to use <code>readable.wrap()</code> but the method has been\nprovided as a convenience for interacting with older Node.js applications and\nlibraries.</p>\n<pre><code class=\"language-js\">const { OldReader } = require('./old-api-module.js');\nconst { Readable } = require('stream');\nconst oreader = new OldReader();\nconst myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', () => {\n myReader.read(); // etc.\n});\n</code></pre>" 1312 }, 1313 { 1314 "textRaw": "`readable[Symbol.asyncIterator]()`", 1315 "type": "method", 1316 "name": "[Symbol.asyncIterator]", 1317 "meta": { 1318 "added": [ 1319 "v10.0.0" 1320 ], 1321 "changes": [ 1322 { 1323 "version": "v11.14.0", 1324 "pr-url": "https://github.com/nodejs/node/pull/26989", 1325 "description": "Symbol.asyncIterator support is no longer experimental." 1326 } 1327 ] 1328 }, 1329 "signatures": [ 1330 { 1331 "return": { 1332 "textRaw": "Returns: {AsyncIterator} to fully consume the stream.", 1333 "name": "return", 1334 "type": "AsyncIterator", 1335 "desc": "to fully consume the stream." 1336 }, 1337 "params": [] 1338 } 1339 ], 1340 "desc": "<pre><code class=\"language-js\">const fs = require('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</code></pre>\n<p>If the loop terminates with a <code>break</code> or a <code>throw</code>, the stream will be\ndestroyed. In other terms, iterating over a stream will consume the stream\nfully. The stream will be read in chunks of size equal to the <code>highWaterMark</code>\noption. In the code example above, data will be in a single chunk if the file\nhas less then 64KB of data because no <code>highWaterMark</code> option is provided to\n<a href=\"fs.html#fs_fs_createreadstream_path_options\"><code>fs.createReadStream()</code></a>.</p>" 1341 } 1342 ], 1343 "properties": [ 1344 { 1345 "textRaw": "`destroyed` {boolean}", 1346 "type": "boolean", 1347 "name": "destroyed", 1348 "meta": { 1349 "added": [ 1350 "v8.0.0" 1351 ], 1352 "changes": [] 1353 }, 1354 "desc": "<p>Is <code>true</code> after <a href=\"#stream_readable_destroy_error\"><code>readable.destroy()</code></a> has been called.</p>" 1355 }, 1356 { 1357 "textRaw": "`readable` {boolean}", 1358 "type": "boolean", 1359 "name": "readable", 1360 "meta": { 1361 "added": [ 1362 "v11.4.0" 1363 ], 1364 "changes": [] 1365 }, 1366 "desc": "<p>Is <code>true</code> if it is safe to call <a href=\"#stream_readable_read_size\"><code>readable.read()</code></a>, which means\nthe stream has not been destroyed or emitted <code>'error'</code> or <code>'end'</code>.</p>" 1367 }, 1368 { 1369 "textRaw": "`readableDidRead` {boolean}", 1370 "type": "boolean", 1371 "name": "readableDidRead", 1372 "meta": { 1373 "added": [ 1374 "v14.18.0" 1375 ], 1376 "changes": [] 1377 }, 1378 "desc": "<p>Allows determining if the stream has been or is about to be read.\nReturns true if <code>'data'</code>, <code>'end'</code>, <code>'error'</code> or <code>'close'</code> has been\nemitted.</p>" 1379 }, 1380 { 1381 "textRaw": "`readableEncoding` {null|string}", 1382 "type": "null|string", 1383 "name": "readableEncoding", 1384 "meta": { 1385 "added": [ 1386 "v12.7.0" 1387 ], 1388 "changes": [] 1389 }, 1390 "desc": "<p>Getter for the property <code>encoding</code> of a given <code>Readable</code> stream. The <code>encoding</code>\nproperty can be set using the <a href=\"#stream_readable_setencoding_encoding\"><code>readable.setEncoding()</code></a> method.</p>" 1391 }, 1392 { 1393 "textRaw": "`readableEnded` {boolean}", 1394 "type": "boolean", 1395 "name": "readableEnded", 1396 "meta": { 1397 "added": [ 1398 "v12.9.0" 1399 ], 1400 "changes": [] 1401 }, 1402 "desc": "<p>Becomes <code>true</code> when <a href=\"#stream_event_end\"><code>'end'</code></a> event is emitted.</p>" 1403 }, 1404 { 1405 "textRaw": "`readableFlowing` {boolean}", 1406 "type": "boolean", 1407 "name": "readableFlowing", 1408 "meta": { 1409 "added": [ 1410 "v9.4.0" 1411 ], 1412 "changes": [] 1413 }, 1414 "desc": "<p>This property reflects the current state of a <code>Readable</code> stream as described\nin the <a href=\"#stream_three_states\">Three states</a> section.</p>" 1415 }, 1416 { 1417 "textRaw": "`readableHighWaterMark` {number}", 1418 "type": "number", 1419 "name": "readableHighWaterMark", 1420 "meta": { 1421 "added": [ 1422 "v9.3.0" 1423 ], 1424 "changes": [] 1425 }, 1426 "desc": "<p>Returns the value of <code>highWaterMark</code> passed when constructing this\n<code>Readable</code>.</p>" 1427 }, 1428 { 1429 "textRaw": "`readableLength` {number}", 1430 "type": "number", 1431 "name": "readableLength", 1432 "meta": { 1433 "added": [ 1434 "v9.4.0" 1435 ], 1436 "changes": [] 1437 }, 1438 "desc": "<p>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 <code>highWaterMark</code>.</p>" 1439 }, 1440 { 1441 "textRaw": "`readableObjectMode` {boolean}", 1442 "type": "boolean", 1443 "name": "readableObjectMode", 1444 "meta": { 1445 "added": [ 1446 "v12.3.0" 1447 ], 1448 "changes": [] 1449 }, 1450 "desc": "<p>Getter for the property <code>objectMode</code> of a given <code>Readable</code> stream.</p>" 1451 } 1452 ] 1453 } 1454 ], 1455 "type": "misc", 1456 "displayName": "Readable streams" 1457 }, 1458 { 1459 "textRaw": "Duplex and transform streams", 1460 "name": "duplex_and_transform_streams", 1461 "classes": [ 1462 { 1463 "textRaw": "Class: `stream.Duplex`", 1464 "type": "class", 1465 "name": "stream.Duplex", 1466 "meta": { 1467 "added": [ 1468 "v0.9.4" 1469 ], 1470 "changes": [ 1471 { 1472 "version": "v6.8.0", 1473 "pr-url": "https://github.com/nodejs/node/pull/8834", 1474 "description": "Instances of `Duplex` now return `true` when checking `instanceof stream.Writable`." 1475 } 1476 ] 1477 }, 1478 "desc": "<p>Duplex streams are streams that implement both the <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> and\n<a href=\"#stream_class_stream_writable\"><code>Writable</code></a> interfaces.</p>\n<p>Examples of <code>Duplex</code> streams include:</p>\n<ul>\n<li><a href=\"net.html#net_class_net_socket\">TCP sockets</a></li>\n<li><a href=\"zlib.html\">zlib streams</a></li>\n<li><a href=\"crypto.html\">crypto streams</a></li>\n</ul>" 1479 }, 1480 { 1481 "textRaw": "Class: `stream.Transform`", 1482 "type": "class", 1483 "name": "stream.Transform", 1484 "meta": { 1485 "added": [ 1486 "v0.9.4" 1487 ], 1488 "changes": [] 1489 }, 1490 "desc": "<p>Transform streams are <a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a> streams where the output is in some way\nrelated to the input. Like all <a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a> streams, <code>Transform</code> streams\nimplement both the <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> and <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> interfaces.</p>\n<p>Examples of <code>Transform</code> streams include:</p>\n<ul>\n<li><a href=\"zlib.html\">zlib streams</a></li>\n<li><a href=\"crypto.html\">crypto streams</a></li>\n</ul>", 1491 "methods": [ 1492 { 1493 "textRaw": "`transform.destroy([error])`", 1494 "type": "method", 1495 "name": "destroy", 1496 "meta": { 1497 "added": [ 1498 "v8.0.0" 1499 ], 1500 "changes": [ 1501 { 1502 "version": "v14.0.0", 1503 "pr-url": "https://github.com/nodejs/node/pull/29197", 1504 "description": "Work as a no-op on a stream that has already been destroyed." 1505 } 1506 ] 1507 }, 1508 "signatures": [ 1509 { 1510 "return": { 1511 "textRaw": "Returns: {this}", 1512 "name": "return", 1513 "type": "this" 1514 }, 1515 "params": [ 1516 { 1517 "textRaw": "`error` {Error}", 1518 "name": "error", 1519 "type": "Error" 1520 } 1521 ] 1522 } 1523 ], 1524 "desc": "<p>Destroy the stream, and optionally emit an <code>'error'</code> event. After this call, the\ntransform stream would release any internal resources.\nImplementors should not override this method, but instead implement\n<a href=\"#stream_readable_destroy_err_callback\"><code>readable._destroy()</code></a>.\nThe default implementation of <code>_destroy()</code> for <code>Transform</code> also emit <code>'close'</code>\nunless <code>emitClose</code> is set in false.</p>\n<p>Once <code>destroy()</code> has been called, any further calls will be a no-op and no\nfurther errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p>" 1525 } 1526 ] 1527 } 1528 ], 1529 "type": "misc", 1530 "displayName": "Duplex and transform streams" 1531 } 1532 ], 1533 "methods": [ 1534 { 1535 "textRaw": "`stream.finished(stream[, options], callback)`", 1536 "type": "method", 1537 "name": "finished", 1538 "meta": { 1539 "added": [ 1540 "v10.0.0" 1541 ], 1542 "changes": [ 1543 { 1544 "version": "v14.0.0", 1545 "pr-url": "https://github.com/nodejs/node/pull/32158", 1546 "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'`." 1547 }, 1548 { 1549 "version": "v14.0.0", 1550 "pr-url": "https://github.com/nodejs/node/pull/31545", 1551 "description": "Emitting `'close'` before `'end'` on a `Readable` stream will cause an `ERR_STREAM_PREMATURE_CLOSE` error." 1552 }, 1553 { 1554 "version": "v14.0.0", 1555 "pr-url": "https://github.com/nodejs/node/pull/31509", 1556 "description": "Callback will be invoked on streams which have already finished before the call to `finished(stream, cb)`." 1557 } 1558 ] 1559 }, 1560 "signatures": [ 1561 { 1562 "return": { 1563 "textRaw": "Returns: {Function} A cleanup function which removes all registered listeners.", 1564 "name": "return", 1565 "type": "Function", 1566 "desc": "A cleanup function which removes all registered listeners." 1567 }, 1568 "params": [ 1569 { 1570 "textRaw": "`stream` {Stream} A readable and/or writable stream.", 1571 "name": "stream", 1572 "type": "Stream", 1573 "desc": "A readable and/or writable stream." 1574 }, 1575 { 1576 "textRaw": "`options` {Object}", 1577 "name": "options", 1578 "type": "Object", 1579 "options": [ 1580 { 1581 "textRaw": "`error` {boolean} If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`.", 1582 "name": "error", 1583 "type": "boolean", 1584 "desc": "If set to `false`, then a call to `emit('error', err)` is not treated as finished. **Default**: `true`." 1585 }, 1586 { 1587 "textRaw": "`readable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`.", 1588 "name": "readable", 1589 "type": "boolean", 1590 "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be readable. **Default**: `true`." 1591 }, 1592 { 1593 "textRaw": "`writable` {boolean} When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`.", 1594 "name": "writable", 1595 "type": "boolean", 1596 "desc": "When set to `false`, the callback will be called when the stream ends even though the stream might still be writable. **Default**: `true`." 1597 } 1598 ] 1599 }, 1600 { 1601 "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", 1602 "name": "callback", 1603 "type": "Function", 1604 "desc": "A callback function that takes an optional error argument." 1605 } 1606 ] 1607 } 1608 ], 1609 "desc": "<p>A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.</p>\n<pre><code class=\"language-js\">const { finished } = require('stream');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n if (err) {\n console.error('Stream failed.', err);\n } else {\n console.log('Stream is done reading.');\n }\n});\n\nrs.resume(); // Drain the stream.\n</code></pre>\n<p>Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit <code>'end'</code>\nor <code>'finish'</code>.</p>\n<p>The <code>finished</code> API is promisify-able as well;</p>\n<pre><code class=\"language-js\">const finished = util.promisify(stream.finished);\n\nconst rs = fs.createReadStream('archive.tar');\n\nasync function run() {\n await finished(rs);\n console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // Drain the stream.\n</code></pre>\n<p><code>stream.finished()</code> leaves dangling event listeners (in particular\n<code>'error'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code>) after <code>callback</code> has been\ninvoked. The reason for this is so that unexpected <code>'error'</code> 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:</p>\n<pre><code class=\"language-js\">const cleanup = finished(rs, (err) => {\n cleanup();\n // ...\n});\n</code></pre>" 1610 }, 1611 { 1612 "textRaw": "`stream.pipeline(source[, ...transforms], destination, callback)`", 1613 "type": "method", 1614 "name": "pipeline", 1615 "meta": { 1616 "added": [ 1617 "v10.0.0" 1618 ], 1619 "changes": [ 1620 { 1621 "version": "v14.0.0", 1622 "pr-url": "https://github.com/nodejs/node/pull/32158", 1623 "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'`." 1624 }, 1625 { 1626 "version": "v13.10.0", 1627 "pr-url": "https://github.com/nodejs/node/pull/31223", 1628 "description": "Add support for async generators." 1629 } 1630 ] 1631 }, 1632 "signatures": [ 1633 { 1634 "return": { 1635 "textRaw": "Returns: {Stream}", 1636 "name": "return", 1637 "type": "Stream" 1638 }, 1639 "params": [ 1640 { 1641 "textRaw": "`streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]}", 1642 "name": "streams", 1643 "type": "Stream[]|Iterable[]|AsyncIterable[]|Function[]" 1644 }, 1645 { 1646 "textRaw": "`source` {Stream|Iterable|AsyncIterable|Function}", 1647 "name": "source", 1648 "type": "Stream|Iterable|AsyncIterable|Function", 1649 "options": [ 1650 { 1651 "textRaw": "Returns: {Iterable|AsyncIterable}", 1652 "name": "return", 1653 "type": "Iterable|AsyncIterable" 1654 } 1655 ] 1656 }, 1657 { 1658 "textRaw": "`...transforms` {Stream|Function}", 1659 "name": "...transforms", 1660 "type": "Stream|Function", 1661 "options": [ 1662 { 1663 "textRaw": "`source` {AsyncIterable}", 1664 "name": "source", 1665 "type": "AsyncIterable" 1666 }, 1667 { 1668 "textRaw": "Returns: {AsyncIterable}", 1669 "name": "return", 1670 "type": "AsyncIterable" 1671 } 1672 ] 1673 }, 1674 { 1675 "textRaw": "`destination` {Stream|Function}", 1676 "name": "destination", 1677 "type": "Stream|Function", 1678 "options": [ 1679 { 1680 "textRaw": "`source` {AsyncIterable}", 1681 "name": "source", 1682 "type": "AsyncIterable" 1683 }, 1684 { 1685 "textRaw": "Returns: {AsyncIterable|Promise}", 1686 "name": "return", 1687 "type": "AsyncIterable|Promise" 1688 } 1689 ] 1690 }, 1691 { 1692 "textRaw": "`callback` {Function} Called when the pipeline is fully done.", 1693 "name": "callback", 1694 "type": "Function", 1695 "desc": "Called when the pipeline is fully done.", 1696 "options": [ 1697 { 1698 "textRaw": "`err` {Error}", 1699 "name": "err", 1700 "type": "Error" 1701 }, 1702 { 1703 "textRaw": "`val` Resolved value of `Promise` returned by `destination`.", 1704 "name": "val", 1705 "desc": "Resolved value of `Promise` returned by `destination`." 1706 } 1707 ] 1708 } 1709 ] 1710 } 1711 ], 1712 "desc": "<p>A module method to pipe between streams and generators forwarding errors and\nproperly cleaning up and provide a callback when the pipeline is complete.</p>\n<pre><code class=\"language-js\">const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz'),\n (err) => {\n if (err) {\n console.error('Pipeline failed.', err);\n } else {\n console.log('Pipeline succeeded.');\n }\n }\n);\n</code></pre>\n<p>The <code>pipeline</code> API is promisify-able as well:</p>\n<pre><code class=\"language-js\">const pipeline = util.promisify(stream.pipeline);\n\nasync function run() {\n await pipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n</code></pre>\n<p>The <code>pipeline</code> API also supports async generators:</p>\n<pre><code class=\"language-js\">const pipeline = util.promisify(stream.pipeline);\nconst fs = require('fs');\n\nasync function run() {\n await pipeline(\n fs.createReadStream('lowercase.txt'),\n async function* (source) {\n source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.\n for await (const chunk of source) {\n yield chunk.toUpperCase();\n }\n },\n fs.createWriteStream('uppercase.txt')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n</code></pre>\n<p><code>stream.pipeline()</code> will call <code>stream.destroy(err)</code> on all streams except:</p>\n<ul>\n<li><code>Readable</code> streams which have emitted <code>'end'</code> or <code>'close'</code>.</li>\n<li><code>Writable</code> streams which have emitted <code>'finish'</code> or <code>'close'</code>.</li>\n</ul>\n<p><code>stream.pipeline()</code> leaves dangling event listeners on the streams\nafter the <code>callback</code> has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors.</p>" 1713 }, 1714 { 1715 "textRaw": "`stream.pipeline(streams, callback)`", 1716 "type": "method", 1717 "name": "pipeline", 1718 "meta": { 1719 "added": [ 1720 "v10.0.0" 1721 ], 1722 "changes": [ 1723 { 1724 "version": "v14.0.0", 1725 "pr-url": "https://github.com/nodejs/node/pull/32158", 1726 "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'`." 1727 }, 1728 { 1729 "version": "v13.10.0", 1730 "pr-url": "https://github.com/nodejs/node/pull/31223", 1731 "description": "Add support for async generators." 1732 } 1733 ] 1734 }, 1735 "signatures": [ 1736 { 1737 "return": { 1738 "textRaw": "Returns: {Stream}", 1739 "name": "return", 1740 "type": "Stream" 1741 }, 1742 "params": [ 1743 { 1744 "textRaw": "`streams` {Stream[]|Iterable[]|AsyncIterable[]|Function[]}", 1745 "name": "streams", 1746 "type": "Stream[]|Iterable[]|AsyncIterable[]|Function[]" 1747 }, 1748 { 1749 "textRaw": "`source` {Stream|Iterable|AsyncIterable|Function}", 1750 "name": "source", 1751 "type": "Stream|Iterable|AsyncIterable|Function", 1752 "options": [ 1753 { 1754 "textRaw": "Returns: {Iterable|AsyncIterable}", 1755 "name": "return", 1756 "type": "Iterable|AsyncIterable" 1757 } 1758 ] 1759 }, 1760 { 1761 "textRaw": "`...transforms` {Stream|Function}", 1762 "name": "...transforms", 1763 "type": "Stream|Function", 1764 "options": [ 1765 { 1766 "textRaw": "`source` {AsyncIterable}", 1767 "name": "source", 1768 "type": "AsyncIterable" 1769 }, 1770 { 1771 "textRaw": "Returns: {AsyncIterable}", 1772 "name": "return", 1773 "type": "AsyncIterable" 1774 } 1775 ] 1776 }, 1777 { 1778 "textRaw": "`destination` {Stream|Function}", 1779 "name": "destination", 1780 "type": "Stream|Function", 1781 "options": [ 1782 { 1783 "textRaw": "`source` {AsyncIterable}", 1784 "name": "source", 1785 "type": "AsyncIterable" 1786 }, 1787 { 1788 "textRaw": "Returns: {AsyncIterable|Promise}", 1789 "name": "return", 1790 "type": "AsyncIterable|Promise" 1791 } 1792 ] 1793 }, 1794 { 1795 "textRaw": "`callback` {Function} Called when the pipeline is fully done.", 1796 "name": "callback", 1797 "type": "Function", 1798 "desc": "Called when the pipeline is fully done.", 1799 "options": [ 1800 { 1801 "textRaw": "`err` {Error}", 1802 "name": "err", 1803 "type": "Error" 1804 }, 1805 { 1806 "textRaw": "`val` Resolved value of `Promise` returned by `destination`.", 1807 "name": "val", 1808 "desc": "Resolved value of `Promise` returned by `destination`." 1809 } 1810 ] 1811 } 1812 ] 1813 } 1814 ], 1815 "desc": "<p>A module method to pipe between streams and generators forwarding errors and\nproperly cleaning up and provide a callback when the pipeline is complete.</p>\n<pre><code class=\"language-js\">const { pipeline } = require('stream');\nconst fs = require('fs');\nconst zlib = require('zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz'),\n (err) => {\n if (err) {\n console.error('Pipeline failed.', err);\n } else {\n console.log('Pipeline succeeded.');\n }\n }\n);\n</code></pre>\n<p>The <code>pipeline</code> API is promisify-able as well:</p>\n<pre><code class=\"language-js\">const pipeline = util.promisify(stream.pipeline);\n\nasync function run() {\n await pipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n</code></pre>\n<p>The <code>pipeline</code> API also supports async generators:</p>\n<pre><code class=\"language-js\">const pipeline = util.promisify(stream.pipeline);\nconst fs = require('fs');\n\nasync function run() {\n await pipeline(\n fs.createReadStream('lowercase.txt'),\n async function* (source) {\n source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.\n for await (const chunk of source) {\n yield chunk.toUpperCase();\n }\n },\n fs.createWriteStream('uppercase.txt')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n</code></pre>\n<p><code>stream.pipeline()</code> will call <code>stream.destroy(err)</code> on all streams except:</p>\n<ul>\n<li><code>Readable</code> streams which have emitted <code>'end'</code> or <code>'close'</code>.</li>\n<li><code>Writable</code> streams which have emitted <code>'finish'</code> or <code>'close'</code>.</li>\n</ul>\n<p><code>stream.pipeline()</code> leaves dangling event listeners on the streams\nafter the <code>callback</code> has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors.</p>" 1816 }, 1817 { 1818 "textRaw": "`stream.Readable.from(iterable, [options])`", 1819 "type": "method", 1820 "name": "from", 1821 "meta": { 1822 "added": [ 1823 "v12.3.0", 1824 "v10.17.0" 1825 ], 1826 "changes": [] 1827 }, 1828 "signatures": [ 1829 { 1830 "return": { 1831 "textRaw": "Returns: {stream.Readable}", 1832 "name": "return", 1833 "type": "stream.Readable" 1834 }, 1835 "params": [ 1836 { 1837 "textRaw": "`iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed.", 1838 "name": "iterable", 1839 "type": "Iterable", 1840 "desc": "Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed." 1841 }, 1842 { 1843 "textRaw": "`options` {Object} Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`.", 1844 "name": "options", 1845 "type": "Object", 1846 "desc": "Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`." 1847 } 1848 ] 1849 } 1850 ], 1851 "desc": "<p>A utility method for creating readable streams out of iterators.</p>\n<pre><code class=\"language-js\">const { Readable } = require('stream');\n\nasync function * generate() {\n yield 'hello';\n yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n console.log(chunk);\n});\n</code></pre>\n<p>Calling <code>Readable.from(string)</code> or <code>Readable.from(buffer)</code> will not have\nthe strings or buffers be iterated to match the other streams semantics\nfor performance reasons.</p>" 1852 } 1853 ] 1854 }, 1855 { 1856 "textRaw": "API for stream implementers", 1857 "name": "API for stream implementers", 1858 "type": "misc", 1859 "desc": "<p>The <code>stream</code> module API has been designed to make it possible to easily\nimplement streams using JavaScript's prototypal inheritance model.</p>\n<p>First, a stream developer would declare a new JavaScript class that extends one\nof the four basic stream classes (<code>stream.Writable</code>, <code>stream.Readable</code>,\n<code>stream.Duplex</code>, or <code>stream.Transform</code>), making sure they call the appropriate\nparent class constructor:</p>\n<!-- eslint-disable no-useless-constructor -->\n<pre><code class=\"language-js\">const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n constructor({ highWaterMark, ...options }) {\n super({ highWaterMark });\n // ...\n }\n}\n</code></pre>\n<p>When 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<code>autoDestroy</code> and <code>emitClose</code> options, do not allow the\nuser to override these. Be explicit about what\noptions are forwarded instead of implicitly forwarding all options.</p>\n<p>The new stream class must then implement one or more specific methods, depending\non the type of stream being created, as detailed in the chart below:</p>\n<table>\n<thead>\n<tr>\n<th>Use-case</th>\n<th>Class</th>\n<th>Method(s) to implement</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Reading only</td>\n<td><a href=\"#stream_class_stream_readable\"><code>Readable</code></a></td>\n<td><a href=\"#stream_readable_read_size_1\"><code>_read()</code></a></td>\n</tr>\n<tr>\n<td>Writing only</td>\n<td><a href=\"#stream_class_stream_writable\"><code>Writable</code></a></td>\n<td><a href=\"#stream_writable_write_chunk_encoding_callback_1\"><code>_write()</code></a>, <a href=\"#stream_writable_writev_chunks_callback\"><code>_writev()</code></a>, <a href=\"#stream_writable_final_callback\"><code>_final()</code></a></td>\n</tr>\n<tr>\n<td>Reading and writing</td>\n<td><a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a></td>\n<td><a href=\"#stream_readable_read_size_1\"><code>_read()</code></a>, <a href=\"#stream_writable_write_chunk_encoding_callback_1\"><code>_write()</code></a>, <a href=\"#stream_writable_writev_chunks_callback\"><code>_writev()</code></a>, <a href=\"#stream_writable_final_callback\"><code>_final()</code></a></td>\n</tr>\n<tr>\n<td>Operate on written data, then read the result</td>\n<td><a href=\"#stream_class_stream_transform\"><code>Transform</code></a></td>\n<td><a href=\"#stream_transform_transform_chunk_encoding_callback\"><code>_transform()</code></a>, <a href=\"#stream_transform_flush_callback\"><code>_flush()</code></a>, <a href=\"#stream_writable_final_callback\"><code>_final()</code></a></td>\n</tr>\n</tbody>\n</table>\n<p>The implementation code for a stream should <em>never</em> call the \"public\" methods\nof a stream that are intended for use by consumers (as described in the\n<a href=\"#stream_api_for_stream_consumers\">API for stream consumers</a> section). Doing so may lead to adverse side effects\nin application code consuming the stream.</p>\n<p>Avoid overriding public methods such as <code>write()</code>, <code>end()</code>, <code>cork()</code>,\n<code>uncork()</code>, <code>read()</code> and <code>destroy()</code>, or emitting internal events such\nas <code>'error'</code>, <code>'data'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code> through <code>.emit()</code>.\nDoing so can break current and future stream invariants leading to behavior\nand/or compatibility issues with other streams, stream utilities, and user\nexpectations.</p>", 1860 "miscs": [ 1861 { 1862 "textRaw": "Simplified construction", 1863 "name": "simplified_construction", 1864 "meta": { 1865 "added": [ 1866 "v1.2.0" 1867 ], 1868 "changes": [] 1869 }, 1870 "desc": "<p>For many simple cases, it is possible to construct a stream without relying on\ninheritance. This can be accomplished by directly creating instances of the\n<code>stream.Writable</code>, <code>stream.Readable</code>, <code>stream.Duplex</code> or <code>stream.Transform</code>\nobjects and passing appropriate methods as constructor options.</p>\n<pre><code class=\"language-js\">const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n // ...\n }\n});\n</code></pre>", 1871 "type": "misc", 1872 "displayName": "Simplified construction" 1873 }, 1874 { 1875 "textRaw": "Implementing a writable stream", 1876 "name": "implementing_a_writable_stream", 1877 "desc": "<p>The <code>stream.Writable</code> class is extended to implement a <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> stream.</p>\n<p>Custom <code>Writable</code> streams <em>must</em> call the <code>new stream.Writable([options])</code>\nconstructor and implement the <code>writable._write()</code> and/or <code>writable._writev()</code>\nmethod.</p>", 1878 "ctors": [ 1879 { 1880 "textRaw": "`new stream.Writable([options])`", 1881 "type": "ctor", 1882 "name": "stream.Writable", 1883 "meta": { 1884 "changes": [ 1885 { 1886 "version": "v14.0.0", 1887 "pr-url": "https://github.com/nodejs/node/pull/30623", 1888 "description": "Change `autoDestroy` option default to `true`." 1889 }, 1890 { 1891 "version": [ 1892 "v11.2.0", 1893 "v10.16.0" 1894 ], 1895 "pr-url": "https://github.com/nodejs/node/pull/22795", 1896 "description": "Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'finish'` or errors." 1897 }, 1898 { 1899 "version": "v10.0.0", 1900 "pr-url": "https://github.com/nodejs/node/pull/18438", 1901 "description": "Add `emitClose` option to specify if `'close'` is emitted on destroy." 1902 } 1903 ] 1904 }, 1905 "signatures": [ 1906 { 1907 "params": [ 1908 { 1909 "textRaw": "`options` {Object}", 1910 "name": "options", 1911 "type": "Object", 1912 "options": [ 1913 { 1914 "textRaw": "`highWaterMark` {number} Buffer level when [`stream.write()`][stream-write] starts returning `false`. **Default:** `16384` (16KB), or `16` for `objectMode` streams.", 1915 "name": "highWaterMark", 1916 "type": "number", 1917 "default": "`16384` (16KB), or `16` for `objectMode` streams", 1918 "desc": "Buffer level when [`stream.write()`][stream-write] starts returning `false`." 1919 }, 1920 { 1921 "textRaw": "`decodeStrings` {boolean} Whether to encode `string`s passed to [`stream.write()`][stream-write] to `Buffer`s (with the encoding specified in the [`stream.write()`][stream-write] call) before passing them to [`stream._write()`][stream-_write]. Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent `string`s from being converted. **Default:** `true`.", 1922 "name": "decodeStrings", 1923 "type": "boolean", 1924 "default": "`true`", 1925 "desc": "Whether to encode `string`s passed to [`stream.write()`][stream-write] to `Buffer`s (with the encoding specified in the [`stream.write()`][stream-write] call) before passing them to [`stream._write()`][stream-_write]. Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent `string`s from being converted." 1926 }, 1927 { 1928 "textRaw": "`defaultEncoding` {string} The default encoding that is used when no encoding is specified as an argument to [`stream.write()`][stream-write]. **Default:** `'utf8'`.", 1929 "name": "defaultEncoding", 1930 "type": "string", 1931 "default": "`'utf8'`", 1932 "desc": "The default encoding that is used when no encoding is specified as an argument to [`stream.write()`][stream-write]." 1933 }, 1934 { 1935 "textRaw": "`objectMode` {boolean} Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation. **Default:** `false`.", 1936 "name": "objectMode", 1937 "type": "boolean", 1938 "default": "`false`", 1939 "desc": "Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation." 1940 }, 1941 { 1942 "textRaw": "`emitClose` {boolean} Whether or not the stream should emit `'close'` after it has been destroyed. **Default:** `true`.", 1943 "name": "emitClose", 1944 "type": "boolean", 1945 "default": "`true`", 1946 "desc": "Whether or not the stream should emit `'close'` after it has been destroyed." 1947 }, 1948 { 1949 "textRaw": "`write` {Function} Implementation for the [`stream._write()`][stream-_write] method.", 1950 "name": "write", 1951 "type": "Function", 1952 "desc": "Implementation for the [`stream._write()`][stream-_write] method." 1953 }, 1954 { 1955 "textRaw": "`writev` {Function} Implementation for the [`stream._writev()`][stream-_writev] method.", 1956 "name": "writev", 1957 "type": "Function", 1958 "desc": "Implementation for the [`stream._writev()`][stream-_writev] method." 1959 }, 1960 { 1961 "textRaw": "`destroy` {Function} Implementation for the [`stream._destroy()`][writable-_destroy] method.", 1962 "name": "destroy", 1963 "type": "Function", 1964 "desc": "Implementation for the [`stream._destroy()`][writable-_destroy] method." 1965 }, 1966 { 1967 "textRaw": "`final` {Function} Implementation for the [`stream._final()`][stream-_final] method.", 1968 "name": "final", 1969 "type": "Function", 1970 "desc": "Implementation for the [`stream._final()`][stream-_final] method." 1971 }, 1972 { 1973 "textRaw": "`autoDestroy` {boolean} Whether this stream should automatically call `.destroy()` on itself after ending. **Default:** `true`.", 1974 "name": "autoDestroy", 1975 "type": "boolean", 1976 "default": "`true`", 1977 "desc": "Whether this stream should automatically call `.destroy()` on itself after ending." 1978 } 1979 ] 1980 } 1981 ] 1982 } 1983 ], 1984 "desc": "<!-- eslint-disable no-useless-constructor -->\n<pre><code class=\"language-js\">const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n constructor(options) {\n // Calls the stream.Writable() constructor.\n super(options);\n // ...\n }\n}\n</code></pre>\n<p>Or, when using pre-ES6 style constructors:</p>\n<pre><code class=\"language-js\">const { Writable } = require('stream');\nconst util = require('util');\n\nfunction MyWritable(options) {\n if (!(this instanceof MyWritable))\n return new MyWritable(options);\n Writable.call(this, options);\n}\nutil.inherits(MyWritable, Writable);\n</code></pre>\n<p>Or, using the simplified constructor approach:</p>\n<pre><code class=\"language-js\">const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n // ...\n },\n writev(chunks, callback) {\n // ...\n }\n});\n</code></pre>" 1985 } 1986 ], 1987 "methods": [ 1988 { 1989 "textRaw": "`writable._write(chunk, encoding, callback)`", 1990 "type": "method", 1991 "name": "_write", 1992 "meta": { 1993 "changes": [ 1994 { 1995 "version": "v12.11.0", 1996 "pr-url": "https://github.com/nodejs/node/pull/29639", 1997 "description": "_write() is optional when providing _writev()." 1998 } 1999 ] 2000 }, 2001 "signatures": [ 2002 { 2003 "params": [ 2004 { 2005 "textRaw": "`chunk` {Buffer|string|any} The `Buffer` to be written, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write].", 2006 "name": "chunk", 2007 "type": "Buffer|string|any", 2008 "desc": "The `Buffer` to be written, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write]." 2009 }, 2010 { 2011 "textRaw": "`encoding` {string} If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored.", 2012 "name": "encoding", 2013 "type": "string", 2014 "desc": "If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored." 2015 }, 2016 { 2017 "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when processing is complete for the supplied chunk.", 2018 "name": "callback", 2019 "type": "Function", 2020 "desc": "Call this function (optionally with an error argument) when processing is complete for the supplied chunk." 2021 } 2022 ] 2023 } 2024 ], 2025 "desc": "<p>All <code>Writable</code> stream implementations must provide a\n<a href=\"#stream_writable_write_chunk_encoding_callback_1\"><code>writable._write()</code></a> and/or\n<a href=\"#stream_writable_writev_chunks_callback\"><code>writable._writev()</code></a> method to send data to the underlying\nresource.</p>\n<p><a href=\"#stream_class_stream_transform\"><code>Transform</code></a> streams provide their own implementation of the\n<a href=\"#stream_writable_write_chunk_encoding_callback_1\"><code>writable._write()</code></a>.</p>\n<p>This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal <code>Writable</code> class\nmethods only.</p>\n<p>The <code>callback</code> function must be called synchronously inside of\n<code>writable._write()</code> 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 <code>callback</code> must be the <code>Error</code> object if the\ncall failed or <code>null</code> if the write succeeded.</p>\n<p>All calls to <code>writable.write()</code> that occur between the time <code>writable._write()</code>\nis called and the <code>callback</code> is called will cause the written data to be\nbuffered. When the <code>callback</code> is invoked, the stream might emit a <a href=\"#stream_event_drain\"><code>'drain'</code></a>\nevent. If a stream implementation is capable of processing multiple chunks of\ndata at once, the <code>writable._writev()</code> method should be implemented.</p>\n<p>If the <code>decodeStrings</code> property is explicitly set to <code>false</code> in the constructor\noptions, then <code>chunk</code> will remain the same object that is passed to <code>.write()</code>,\nand may be a string rather than a <code>Buffer</code>. This is to support implementations\nthat have an optimized handling for certain string data encodings. In that case,\nthe <code>encoding</code> argument will indicate the character encoding of the string.\nOtherwise, the <code>encoding</code> argument can be safely ignored.</p>\n<p>The <code>writable._write()</code> 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.</p>" 2026 }, 2027 { 2028 "textRaw": "`writable._writev(chunks, callback)`", 2029 "type": "method", 2030 "name": "_writev", 2031 "signatures": [ 2032 { 2033 "params": [ 2034 { 2035 "textRaw": "`chunks` {Object[]} The data to be written. The value is an array of {Object} that each represent a discrete chunk of data to write. The properties of these objects are:", 2036 "name": "chunks", 2037 "type": "Object[]", 2038 "desc": "The data to be written. The value is an array of {Object} that each represent a discrete chunk of data to write. The properties of these objects are:", 2039 "options": [ 2040 { 2041 "textRaw": "`chunk` {Buffer|string} A buffer instance or string containing the data to be written. The `chunk` will be a string if the `Writable` was created with the `decodeStrings` option set to `false` and a string was passed to `write()`.", 2042 "name": "chunk", 2043 "type": "Buffer|string", 2044 "desc": "A buffer instance or string containing the data to be written. The `chunk` will be a string if the `Writable` was created with the `decodeStrings` option set to `false` and a string was passed to `write()`." 2045 }, 2046 { 2047 "textRaw": "`encoding` {string} The character encoding of the `chunk`. If `chunk` is a `Buffer`, the `encoding` will be `'buffer'`.", 2048 "name": "encoding", 2049 "type": "string", 2050 "desc": "The character encoding of the `chunk`. If `chunk` is a `Buffer`, the `encoding` will be `'buffer'`." 2051 } 2052 ] 2053 }, 2054 { 2055 "textRaw": "`callback` {Function} A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks.", 2056 "name": "callback", 2057 "type": "Function", 2058 "desc": "A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks." 2059 } 2060 ] 2061 } 2062 ], 2063 "desc": "<p>This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal <code>Writable</code> class\nmethods only.</p>\n<p>The <code>writable._writev()</code> method may be implemented in addition or alternatively\nto <code>writable._write()</code> 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, <code>_writev()</code> will be called instead of <code>_write()</code>.</p>\n<p>The <code>writable._writev()</code> 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.</p>" 2064 }, 2065 { 2066 "textRaw": "`writable._destroy(err, callback)`", 2067 "type": "method", 2068 "name": "_destroy", 2069 "meta": { 2070 "added": [ 2071 "v8.0.0" 2072 ], 2073 "changes": [] 2074 }, 2075 "signatures": [ 2076 { 2077 "params": [ 2078 { 2079 "textRaw": "`err` {Error} A possible error.", 2080 "name": "err", 2081 "type": "Error", 2082 "desc": "A possible error." 2083 }, 2084 { 2085 "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", 2086 "name": "callback", 2087 "type": "Function", 2088 "desc": "A callback function that takes an optional error argument." 2089 } 2090 ] 2091 } 2092 ], 2093 "desc": "<p>The <code>_destroy()</code> method is called by <a href=\"#stream_writable_destroy_error\"><code>writable.destroy()</code></a>.\nIt can be overridden by child classes but it <strong>must not</strong> be called directly.</p>" 2094 }, 2095 { 2096 "textRaw": "`writable._final(callback)`", 2097 "type": "method", 2098 "name": "_final", 2099 "meta": { 2100 "added": [ 2101 "v8.0.0" 2102 ], 2103 "changes": [] 2104 }, 2105 "signatures": [ 2106 { 2107 "params": [ 2108 { 2109 "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when finished writing any remaining data.", 2110 "name": "callback", 2111 "type": "Function", 2112 "desc": "Call this function (optionally with an error argument) when finished writing any remaining data." 2113 } 2114 ] 2115 } 2116 ], 2117 "desc": "<p>The <code>_final()</code> method <strong>must not</strong> be called directly. It may be implemented\nby child classes, and if so, will be called by the internal <code>Writable</code>\nclass methods only.</p>\n<p>This optional function will be called before the stream closes, delaying the\n<code>'finish'</code> event until <code>callback</code> is called. This is useful to close resources\nor write buffered data before a stream ends.</p>" 2118 } 2119 ], 2120 "modules": [ 2121 { 2122 "textRaw": "Errors while writing", 2123 "name": "errors_while_writing", 2124 "desc": "<p>Errors occurring during the processing of the <a href=\"#stream_writable_write_chunk_encoding_callback_1\"><code>writable._write()</code></a>,\n<a href=\"#stream_writable_writev_chunks_callback\"><code>writable._writev()</code></a> and <a href=\"#stream_writable_final_callback\"><code>writable._final()</code></a> methods must be propagated\nby invoking the callback and passing the error as the first argument.\nThrowing an <code>Error</code> from within these methods or manually emitting an <code>'error'</code>\nevent results in undefined behavior.</p>\n<p>If a <code>Readable</code> stream pipes into a <code>Writable</code> stream when <code>Writable</code> emits an\nerror, the <code>Readable</code> stream will be unpiped.</p>\n<pre><code class=\"language-js\">const { Writable } = require('stream');\n\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n if (chunk.toString().indexOf('a') >= 0) {\n callback(new Error('chunk is invalid'));\n } else {\n callback();\n }\n }\n});\n</code></pre>", 2125 "type": "module", 2126 "displayName": "Errors while writing" 2127 }, 2128 { 2129 "textRaw": "An example writable stream", 2130 "name": "an_example_writable_stream", 2131 "desc": "<p>The following illustrates a rather simplistic (and somewhat pointless) custom\n<code>Writable</code> stream implementation. While this specific <code>Writable</code> stream instance\nis not of any real particular usefulness, the example illustrates each of the\nrequired elements of a custom <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> stream instance:</p>\n<pre><code class=\"language-js\">const { Writable } = require('stream');\n\nclass MyWritable extends Writable {\n _write(chunk, encoding, callback) {\n if (chunk.toString().indexOf('a') >= 0) {\n callback(new Error('chunk is invalid'));\n } else {\n callback();\n }\n }\n}\n</code></pre>", 2132 "type": "module", 2133 "displayName": "An example writable stream" 2134 }, 2135 { 2136 "textRaw": "Decoding buffers in a writable stream", 2137 "name": "decoding_buffers_in_a_writable_stream", 2138 "desc": "<p>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 <code>StringDecoder</code> and <a href=\"#stream_class_stream_writable\"><code>Writable</code></a>.</p>\n<pre><code class=\"language-js\">const { Writable } = require('stream');\nconst { StringDecoder } = require('string_decoder');\n\nclass StringWritable extends Writable {\n constructor(options) {\n super(options);\n this._decoder = new StringDecoder(options && options.defaultEncoding);\n this.data = '';\n }\n _write(chunk, encoding, callback) {\n if (encoding === 'buffer') {\n chunk = this._decoder.write(chunk);\n }\n this.data += chunk;\n callback();\n }\n _final(callback) {\n this.data += this._decoder.end();\n callback();\n }\n}\n\nconst euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);\nconst w = new StringWritable();\n\nw.write('currency: ');\nw.write(euro[0]);\nw.end(euro[1]);\n\nconsole.log(w.data); // currency: €\n</code></pre>", 2139 "type": "module", 2140 "displayName": "Decoding buffers in a writable stream" 2141 } 2142 ], 2143 "type": "misc", 2144 "displayName": "Implementing a writable stream" 2145 }, 2146 { 2147 "textRaw": "Implementing a readable stream", 2148 "name": "implementing_a_readable_stream", 2149 "desc": "<p>The <code>stream.Readable</code> class is extended to implement a <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> stream.</p>\n<p>Custom <code>Readable</code> streams <em>must</em> call the <code>new stream.Readable([options])</code>\nconstructor and implement the <a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> method.</p>", 2150 "ctors": [ 2151 { 2152 "textRaw": "`new stream.Readable([options])`", 2153 "type": "ctor", 2154 "name": "stream.Readable", 2155 "meta": { 2156 "changes": [ 2157 { 2158 "version": "v14.0.0", 2159 "pr-url": "https://github.com/nodejs/node/pull/30623", 2160 "description": "Change `autoDestroy` option default to `true`." 2161 }, 2162 { 2163 "version": [ 2164 "v11.2.0", 2165 "v10.16.0" 2166 ], 2167 "pr-url": "https://github.com/nodejs/node/pull/22795", 2168 "description": "Add `autoDestroy` option to automatically `destroy()` the stream when it emits `'end'` or errors." 2169 } 2170 ] 2171 }, 2172 "signatures": [ 2173 { 2174 "params": [ 2175 { 2176 "textRaw": "`options` {Object}", 2177 "name": "options", 2178 "type": "Object", 2179 "options": [ 2180 { 2181 "textRaw": "`highWaterMark` {number} The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource. **Default:** `16384` (16KB), or `16` for `objectMode` streams.", 2182 "name": "highWaterMark", 2183 "type": "number", 2184 "default": "`16384` (16KB), or `16` for `objectMode` streams", 2185 "desc": "The maximum [number of bytes][hwm-gotcha] to store in the internal buffer before ceasing to read from the underlying resource." 2186 }, 2187 { 2188 "textRaw": "`encoding` {string} If specified, then buffers will be decoded to strings using the specified encoding. **Default:** `null`.", 2189 "name": "encoding", 2190 "type": "string", 2191 "default": "`null`", 2192 "desc": "If specified, then buffers will be decoded to strings using the specified encoding." 2193 }, 2194 { 2195 "textRaw": "`objectMode` {boolean} Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns a single value instead of a `Buffer` of size `n`. **Default:** `false`.", 2196 "name": "objectMode", 2197 "type": "boolean", 2198 "default": "`false`", 2199 "desc": "Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns a single value instead of a `Buffer` of size `n`." 2200 }, 2201 { 2202 "textRaw": "`emitClose` {boolean} Whether or not the stream should emit `'close'` after it has been destroyed. **Default:** `true`.", 2203 "name": "emitClose", 2204 "type": "boolean", 2205 "default": "`true`", 2206 "desc": "Whether or not the stream should emit `'close'` after it has been destroyed." 2207 }, 2208 { 2209 "textRaw": "`read` {Function} Implementation for the [`stream._read()`][stream-_read] method.", 2210 "name": "read", 2211 "type": "Function", 2212 "desc": "Implementation for the [`stream._read()`][stream-_read] method." 2213 }, 2214 { 2215 "textRaw": "`destroy` {Function} Implementation for the [`stream._destroy()`][readable-_destroy] method.", 2216 "name": "destroy", 2217 "type": "Function", 2218 "desc": "Implementation for the [`stream._destroy()`][readable-_destroy] method." 2219 }, 2220 { 2221 "textRaw": "`autoDestroy` {boolean} Whether this stream should automatically call `.destroy()` on itself after ending. **Default:** `true`.", 2222 "name": "autoDestroy", 2223 "type": "boolean", 2224 "default": "`true`", 2225 "desc": "Whether this stream should automatically call `.destroy()` on itself after ending." 2226 } 2227 ] 2228 } 2229 ] 2230 } 2231 ], 2232 "desc": "<!-- eslint-disable no-useless-constructor -->\n<pre><code class=\"language-js\">const { Readable } = require('stream');\n\nclass MyReadable extends Readable {\n constructor(options) {\n // Calls the stream.Readable(options) constructor.\n super(options);\n // ...\n }\n}\n</code></pre>\n<p>Or, when using pre-ES6 style constructors:</p>\n<pre><code class=\"language-js\">const { Readable } = require('stream');\nconst util = require('util');\n\nfunction MyReadable(options) {\n if (!(this instanceof MyReadable))\n return new MyReadable(options);\n Readable.call(this, options);\n}\nutil.inherits(MyReadable, Readable);\n</code></pre>\n<p>Or, using the simplified constructor approach:</p>\n<pre><code class=\"language-js\">const { Readable } = require('stream');\n\nconst myReadable = new Readable({\n read(size) {\n // ...\n }\n});\n</code></pre>" 2233 } 2234 ], 2235 "methods": [ 2236 { 2237 "textRaw": "`readable._read(size)`", 2238 "type": "method", 2239 "name": "_read", 2240 "meta": { 2241 "added": [ 2242 "v0.9.4" 2243 ], 2244 "changes": [] 2245 }, 2246 "signatures": [ 2247 { 2248 "params": [ 2249 { 2250 "textRaw": "`size` {number} Number of bytes to read asynchronously", 2251 "name": "size", 2252 "type": "number", 2253 "desc": "Number of bytes to read asynchronously" 2254 } 2255 ] 2256 } 2257 ], 2258 "desc": "<p>This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal <code>Readable</code> class\nmethods only.</p>\n<p>All <code>Readable</code> stream implementations must provide an implementation of the\n<a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> method to fetch data from the underlying resource.</p>\n<p>When <a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> is called, if data is available from the resource,\nthe implementation should begin pushing that data into the read queue using the\n<a href=\"#stream_readable_push_chunk_encoding\"><code>this.push(dataChunk)</code></a> method. <code>_read()</code> will be called again\nafter each call to <a href=\"#stream_readable_push_chunk_encoding\"><code>this.push(dataChunk)</code></a> once the stream is\nready to accept more data. <code>_read()</code> may continue reading from the resource and\npushing data until <code>readable.push()</code> returns <code>false</code>. Only when <code>_read()</code> is\ncalled again after it has stopped should it resume pushing additional data into\nthe queue.</p>\n<p>Once the <a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> method has been called, it will not be called\nagain until more data is pushed through the <a href=\"#stream_readable_push_chunk_encoding\"><code>readable.push()</code></a>\nmethod. Empty data such as empty buffers and strings will not cause\n<a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> to be called.</p>\n<p>The <code>size</code> argument is advisory. For implementations where a \"read\" is a\nsingle operation that returns data can use the <code>size</code> 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<code>size</code> bytes are available before calling <a href=\"#stream_readable_push_chunk_encoding\"><code>stream.push(chunk)</code></a>.</p>\n<p>The <a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> 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.</p>" 2259 }, 2260 { 2261 "textRaw": "`readable._destroy(err, callback)`", 2262 "type": "method", 2263 "name": "_destroy", 2264 "meta": { 2265 "added": [ 2266 "v8.0.0" 2267 ], 2268 "changes": [] 2269 }, 2270 "signatures": [ 2271 { 2272 "params": [ 2273 { 2274 "textRaw": "`err` {Error} A possible error.", 2275 "name": "err", 2276 "type": "Error", 2277 "desc": "A possible error." 2278 }, 2279 { 2280 "textRaw": "`callback` {Function} A callback function that takes an optional error argument.", 2281 "name": "callback", 2282 "type": "Function", 2283 "desc": "A callback function that takes an optional error argument." 2284 } 2285 ] 2286 } 2287 ], 2288 "desc": "<p>The <code>_destroy()</code> method is called by <a href=\"#stream_readable_destroy_error\"><code>readable.destroy()</code></a>.\nIt can be overridden by child classes but it <strong>must not</strong> be called directly.</p>" 2289 }, 2290 { 2291 "textRaw": "`readable.push(chunk[, encoding])`", 2292 "type": "method", 2293 "name": "push", 2294 "meta": { 2295 "changes": [ 2296 { 2297 "version": "v8.0.0", 2298 "pr-url": "https://github.com/nodejs/node/pull/11608", 2299 "description": "The `chunk` argument can now be a `Uint8Array` instance." 2300 } 2301 ] 2302 }, 2303 "signatures": [ 2304 { 2305 "return": { 2306 "textRaw": "Returns: {boolean} `true` if additional chunks of data may continue to be pushed; `false` otherwise.", 2307 "name": "return", 2308 "type": "boolean", 2309 "desc": "`true` if additional chunks of data may continue to be pushed; `false` otherwise." 2310 }, 2311 "params": [ 2312 { 2313 "textRaw": "`chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value.", 2314 "name": "chunk", 2315 "type": "Buffer|Uint8Array|string|null|any", 2316 "desc": "Chunk of data to push into the read queue. For streams not operating in object mode, `chunk` must be a string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value." 2317 }, 2318 { 2319 "textRaw": "`encoding` {string} Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`.", 2320 "name": "encoding", 2321 "type": "string", 2322 "desc": "Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`." 2323 } 2324 ] 2325 } 2326 ], 2327 "desc": "<p>When <code>chunk</code> is a <code>Buffer</code>, <code>Uint8Array</code> or <code>string</code>, the <code>chunk</code> of data will\nbe added to the internal queue for users of the stream to consume.\nPassing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF), after which no\nmore data can be written.</p>\n<p>When the <code>Readable</code> is operating in paused mode, the data added with\n<code>readable.push()</code> can be read out by calling the\n<a href=\"#stream_readable_read_size\"><code>readable.read()</code></a> method when the <a href=\"#stream_event_readable\"><code>'readable'</code></a> event is\nemitted.</p>\n<p>When the <code>Readable</code> is operating in flowing mode, the data added with\n<code>readable.push()</code> will be delivered by emitting a <code>'data'</code> event.</p>\n<p>The <code>readable.push()</code> 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 <code>Readable</code> instance:</p>\n<pre><code class=\"language-js\">// `_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</code></pre>\n<p>The <code>readable.push()</code> method is used to push the content\ninto the internal buffer. It can be driven by the <a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> method.</p>\n<p>For streams not operating in object mode, if the <code>chunk</code> parameter of\n<code>readable.push()</code> is <code>undefined</code>, it will be treated as empty string or\nbuffer. See <a href=\"#stream_readable_push\"><code>readable.push('')</code></a> for more information.</p>" 2328 } 2329 ], 2330 "modules": [ 2331 { 2332 "textRaw": "Errors while reading", 2333 "name": "errors_while_reading", 2334 "desc": "<p>Errors occurring during processing of the <a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> must be\npropagated through the <a href=\"#stream_readable_destroy_err_callback\"><code>readable.destroy(err)</code></a> method.\nThrowing an <code>Error</code> from within <a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> or manually emitting an\n<code>'error'</code> event results in undefined behavior.</p>\n<pre><code class=\"language-js\">const { Readable } = require('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</code></pre>", 2335 "type": "module", 2336 "displayName": "Errors while reading" 2337 } 2338 ], 2339 "examples": [ 2340 { 2341 "textRaw": "An example counting stream", 2342 "name": "An example counting stream", 2343 "type": "example", 2344 "desc": "<p>The following is a basic example of a <code>Readable</code> stream that emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.</p>\n<pre><code class=\"language-js\">const { Readable } = require('stream');\n\nclass Counter extends Readable {\n constructor(opt) {\n super(opt);\n this._max = 1000000;\n this._index = 1;\n }\n\n _read() {\n const i = this._index++;\n if (i > this._max)\n this.push(null);\n else {\n const str = String(i);\n const buf = Buffer.from(str, 'ascii');\n this.push(buf);\n }\n }\n}\n</code></pre>" 2345 } 2346 ], 2347 "type": "misc", 2348 "displayName": "Implementing a readable stream" 2349 }, 2350 { 2351 "textRaw": "Implementing a duplex stream", 2352 "name": "implementing_a_duplex_stream", 2353 "desc": "<p>A <a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a> stream is one that implements both <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> and\n<a href=\"#stream_class_stream_writable\"><code>Writable</code></a>, such as a TCP socket connection.</p>\n<p>Because JavaScript does not have support for multiple inheritance, the\n<code>stream.Duplex</code> class is extended to implement a <a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a> stream (as opposed\nto extending the <code>stream.Readable</code> <em>and</em> <code>stream.Writable</code> classes).</p>\n<p>The <code>stream.Duplex</code> class prototypically inherits from <code>stream.Readable</code> and\nparasitically from <code>stream.Writable</code>, but <code>instanceof</code> will work properly for\nboth base classes due to overriding <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance\"><code>Symbol.hasInstance</code></a> on\n<code>stream.Writable</code>.</p>\n<p>Custom <code>Duplex</code> streams <em>must</em> call the <code>new stream.Duplex([options])</code>\nconstructor and implement <em>both</em> the <a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> and\n<code>writable._write()</code> methods.</p>", 2354 "ctors": [ 2355 { 2356 "textRaw": "`new stream.Duplex(options)`", 2357 "type": "ctor", 2358 "name": "stream.Duplex", 2359 "meta": { 2360 "changes": [ 2361 { 2362 "version": "v8.4.0", 2363 "pr-url": "https://github.com/nodejs/node/pull/14636", 2364 "description": "The `readableHighWaterMark` and `writableHighWaterMark` options are supported now." 2365 } 2366 ] 2367 }, 2368 "signatures": [ 2369 { 2370 "params": [ 2371 { 2372 "textRaw": "`options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields:", 2373 "name": "options", 2374 "type": "Object", 2375 "desc": "Passed to both `Writable` and `Readable` constructors. Also has the following fields:", 2376 "options": [ 2377 { 2378 "textRaw": "`allowHalfOpen` {boolean} If set to `false`, then the stream will automatically end the writable side when the readable side ends. **Default:** `true`.", 2379 "name": "allowHalfOpen", 2380 "type": "boolean", 2381 "default": "`true`", 2382 "desc": "If set to `false`, then the stream will automatically end the writable side when the readable side ends." 2383 }, 2384 { 2385 "textRaw": "`readable` {boolean} Sets whether the `Duplex` should be readable. **Default:** `true`.", 2386 "name": "readable", 2387 "type": "boolean", 2388 "default": "`true`", 2389 "desc": "Sets whether the `Duplex` should be readable." 2390 }, 2391 { 2392 "textRaw": "`writable` {boolean} Sets whether the `Duplex` should be writable. **Default:** `true`.", 2393 "name": "writable", 2394 "type": "boolean", 2395 "default": "`true`", 2396 "desc": "Sets whether the `Duplex` should be writable." 2397 }, 2398 { 2399 "textRaw": "`readableObjectMode` {boolean} Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`. **Default:** `false`.", 2400 "name": "readableObjectMode", 2401 "type": "boolean", 2402 "default": "`false`", 2403 "desc": "Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`." 2404 }, 2405 { 2406 "textRaw": "`writableObjectMode` {boolean} Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`. **Default:** `false`.", 2407 "name": "writableObjectMode", 2408 "type": "boolean", 2409 "default": "`false`", 2410 "desc": "Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`." 2411 }, 2412 { 2413 "textRaw": "`readableHighWaterMark` {number} Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided.", 2414 "name": "readableHighWaterMark", 2415 "type": "number", 2416 "desc": "Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided." 2417 }, 2418 { 2419 "textRaw": "`writableHighWaterMark` {number} Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided.", 2420 "name": "writableHighWaterMark", 2421 "type": "number", 2422 "desc": "Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided." 2423 } 2424 ] 2425 } 2426 ] 2427 } 2428 ], 2429 "desc": "<!-- eslint-disable no-useless-constructor -->\n<pre><code class=\"language-js\">const { Duplex } = require('stream');\n\nclass MyDuplex extends Duplex {\n constructor(options) {\n super(options);\n // ...\n }\n}\n</code></pre>\n<p>Or, when using pre-ES6 style constructors:</p>\n<pre><code class=\"language-js\">const { Duplex } = require('stream');\nconst util = require('util');\n\nfunction MyDuplex(options) {\n if (!(this instanceof MyDuplex))\n return new MyDuplex(options);\n Duplex.call(this, options);\n}\nutil.inherits(MyDuplex, Duplex);\n</code></pre>\n<p>Or, using the simplified constructor approach:</p>\n<pre><code class=\"language-js\">const { Duplex } = require('stream');\n\nconst myDuplex = new Duplex({\n read(size) {\n // ...\n },\n write(chunk, encoding, callback) {\n // ...\n }\n});\n</code></pre>" 2430 } 2431 ], 2432 "modules": [ 2433 { 2434 "textRaw": "An example duplex stream", 2435 "name": "an_example_duplex_stream", 2436 "desc": "<p>The following illustrates a simple example of a <code>Duplex</code> 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 <code>Duplex</code> stream that buffers\nincoming written data via the <a href=\"#stream_class_stream_writable\"><code>Writable</code></a> interface that is read back out\nvia the <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> interface.</p>\n<pre><code class=\"language-js\">const { Duplex } = require('stream');\nconst kSource = Symbol('source');\n\nclass MyDuplex extends Duplex {\n constructor(source, options) {\n super(options);\n this[kSource] = source;\n }\n\n _write(chunk, encoding, callback) {\n // The underlying source only deals with strings.\n if (Buffer.isBuffer(chunk))\n chunk = chunk.toString();\n this[kSource].writeSomeData(chunk);\n callback();\n }\n\n _read(size) {\n this[kSource].fetchSomeData(size, (data, encoding) => {\n this.push(Buffer.from(data, encoding));\n });\n }\n}\n</code></pre>\n<p>The most important aspect of a <code>Duplex</code> stream is that the <code>Readable</code> and\n<code>Writable</code> sides operate independently of one another despite co-existing within\na single object instance.</p>", 2437 "type": "module", 2438 "displayName": "An example duplex stream" 2439 }, 2440 { 2441 "textRaw": "Object mode duplex streams", 2442 "name": "object_mode_duplex_streams", 2443 "desc": "<p>For <code>Duplex</code> streams, <code>objectMode</code> can be set exclusively for either the\n<code>Readable</code> or <code>Writable</code> side using the <code>readableObjectMode</code> and\n<code>writableObjectMode</code> options respectively.</p>\n<p>In the following example, for instance, a new <code>Transform</code> stream (which is a\ntype of <a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a> stream) is created that has an object mode <code>Writable</code> side\nthat accepts JavaScript numbers that are converted to hexadecimal strings on\nthe <code>Readable</code> side.</p>\n<pre><code class=\"language-js\">const { Transform } = require('stream');\n\n// All Transform streams are also Duplex Streams.\nconst myTransform = new Transform({\n writableObjectMode: true,\n\n transform(chunk, encoding, callback) {\n // Coerce the chunk to a number if necessary.\n chunk |= 0;\n\n // Transform the chunk into something else.\n const data = chunk.toString(16);\n\n // Push the data onto the readable queue.\n callback(null, '0'.repeat(data.length % 2) + data);\n }\n});\n\nmyTransform.setEncoding('ascii');\nmyTransform.on('data', (chunk) => console.log(chunk));\n\nmyTransform.write(1);\n// Prints: 01\nmyTransform.write(10);\n// Prints: 0a\nmyTransform.write(100);\n// Prints: 64\n</code></pre>", 2444 "type": "module", 2445 "displayName": "Object mode duplex streams" 2446 } 2447 ], 2448 "type": "misc", 2449 "displayName": "Implementing a duplex stream" 2450 }, 2451 { 2452 "textRaw": "Implementing a transform stream", 2453 "name": "implementing_a_transform_stream", 2454 "desc": "<p>A <a href=\"#stream_class_stream_transform\"><code>Transform</code></a> stream is a <a href=\"#stream_class_stream_duplex\"><code>Duplex</code></a> stream where the output is computed\nin some way from the input. Examples include <a href=\"zlib.html\">zlib</a> streams or <a href=\"crypto.html\">crypto</a>\nstreams that compress, encrypt, or decrypt data.</p>\n<p>There is no requirement that the output be the same size as the input, the same\nnumber of chunks, or arrive at the same time. For example, a <code>Hash</code> stream will\nonly ever have a single chunk of output which is provided when the input is\nended. A <code>zlib</code> stream will produce output that is either much smaller or much\nlarger than its input.</p>\n<p>The <code>stream.Transform</code> class is extended to implement a <a href=\"#stream_class_stream_transform\"><code>Transform</code></a> stream.</p>\n<p>The <code>stream.Transform</code> class prototypically inherits from <code>stream.Duplex</code> and\nimplements its own versions of the <code>writable._write()</code> and\n<a href=\"#stream_readable_read_size_1\"><code>readable._read()</code></a> methods. Custom <code>Transform</code> implementations <em>must</em>\nimplement the <a href=\"#stream_transform_transform_chunk_encoding_callback\"><code>transform._transform()</code></a> method and <em>may</em>\nalso implement the <a href=\"#stream_transform_flush_callback\"><code>transform._flush()</code></a> method.</p>\n<p>Care must be taken when using <code>Transform</code> streams in that data written to the\nstream can cause the <code>Writable</code> side of the stream to become paused if the\noutput on the <code>Readable</code> side is not consumed.</p>", 2455 "ctors": [ 2456 { 2457 "textRaw": "`new stream.Transform([options])`", 2458 "type": "ctor", 2459 "name": "stream.Transform", 2460 "signatures": [ 2461 { 2462 "params": [ 2463 { 2464 "textRaw": "`options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields:", 2465 "name": "options", 2466 "type": "Object", 2467 "desc": "Passed to both `Writable` and `Readable` constructors. Also has the following fields:", 2468 "options": [ 2469 { 2470 "textRaw": "`transform` {Function} Implementation for the [`stream._transform()`][stream-_transform] method.", 2471 "name": "transform", 2472 "type": "Function", 2473 "desc": "Implementation for the [`stream._transform()`][stream-_transform] method." 2474 }, 2475 { 2476 "textRaw": "`flush` {Function} Implementation for the [`stream._flush()`][stream-_flush] method.", 2477 "name": "flush", 2478 "type": "Function", 2479 "desc": "Implementation for the [`stream._flush()`][stream-_flush] method." 2480 } 2481 ] 2482 } 2483 ] 2484 } 2485 ], 2486 "desc": "<!-- eslint-disable no-useless-constructor -->\n<pre><code class=\"language-js\">const { Transform } = require('stream');\n\nclass MyTransform extends Transform {\n constructor(options) {\n super(options);\n // ...\n }\n}\n</code></pre>\n<p>Or, when using pre-ES6 style constructors:</p>\n<pre><code class=\"language-js\">const { Transform } = require('stream');\nconst util = require('util');\n\nfunction MyTransform(options) {\n if (!(this instanceof MyTransform))\n return new MyTransform(options);\n Transform.call(this, options);\n}\nutil.inherits(MyTransform, Transform);\n</code></pre>\n<p>Or, using the simplified constructor approach:</p>\n<pre><code class=\"language-js\">const { Transform } = require('stream');\n\nconst myTransform = new Transform({\n transform(chunk, encoding, callback) {\n // ...\n }\n});\n</code></pre>" 2487 } 2488 ], 2489 "events": [ 2490 { 2491 "textRaw": "Event: `'end'`", 2492 "type": "event", 2493 "name": "end", 2494 "params": [], 2495 "desc": "<p>The <a href=\"#stream_event_end\"><code>'end'</code></a> event is from the <code>stream.Readable</code> class. The <code>'end'</code> event is\nemitted after all data has been output, which occurs after the callback in\n<a href=\"#stream_transform_flush_callback\"><code>transform._flush()</code></a> has been called. In the case of an error,\n<code>'end'</code> should not be emitted.</p>" 2496 }, 2497 { 2498 "textRaw": "Event: `'finish'`", 2499 "type": "event", 2500 "name": "finish", 2501 "params": [], 2502 "desc": "<p>The <a href=\"#stream_event_finish\"><code>'finish'</code></a> event is from the <code>stream.Writable</code> class. The <code>'finish'</code>\nevent is emitted after <a href=\"#stream_writable_end_chunk_encoding_callback\"><code>stream.end()</code></a> is called and all chunks\nhave been processed by <a href=\"#stream_transform_transform_chunk_encoding_callback\"><code>stream._transform()</code></a>. In the case\nof an error, <code>'finish'</code> should not be emitted.</p>" 2503 } 2504 ], 2505 "methods": [ 2506 { 2507 "textRaw": "`transform._flush(callback)`", 2508 "type": "method", 2509 "name": "_flush", 2510 "signatures": [ 2511 { 2512 "params": [ 2513 { 2514 "textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called when remaining data has been flushed.", 2515 "name": "callback", 2516 "type": "Function", 2517 "desc": "A callback function (optionally with an error argument and data) to be called when remaining data has been flushed." 2518 } 2519 ] 2520 } 2521 ], 2522 "desc": "<p>This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal <code>Readable</code> class\nmethods only.</p>\n<p>In some cases, a transform operation may need to emit an additional bit of\ndata at the end of the stream. For example, a <code>zlib</code> 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.</p>\n<p>Custom <a href=\"#stream_class_stream_transform\"><code>Transform</code></a> implementations <em>may</em> implement the <code>transform._flush()</code>\nmethod. This will be called when there is no more written data to be consumed,\nbut before the <a href=\"#stream_event_end\"><code>'end'</code></a> event is emitted signaling the end of the\n<a href=\"#stream_class_stream_readable\"><code>Readable</code></a> stream.</p>\n<p>Within the <code>transform._flush()</code> implementation, the <code>transform.push()</code> method\nmay be called zero or more times, as appropriate. The <code>callback</code> function must\nbe called when the flush operation is complete.</p>\n<p>The <code>transform._flush()</code> 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.</p>" 2523 }, 2524 { 2525 "textRaw": "`transform._transform(chunk, encoding, callback)`", 2526 "type": "method", 2527 "name": "_transform", 2528 "signatures": [ 2529 { 2530 "params": [ 2531 { 2532 "textRaw": "`chunk` {Buffer|string|any} The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write].", 2533 "name": "chunk", 2534 "type": "Buffer|string|any", 2535 "desc": "The `Buffer` to be transformed, converted from the `string` passed to [`stream.write()`][stream-write]. If the stream's `decodeStrings` option is `false` or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to [`stream.write()`][stream-write]." 2536 }, 2537 { 2538 "textRaw": "`encoding` {string} If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value `'buffer'`. Ignore it in that case.", 2539 "name": "encoding", 2540 "type": "string", 2541 "desc": "If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value `'buffer'`. Ignore it in that case." 2542 }, 2543 { 2544 "textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called after the supplied `chunk` has been processed.", 2545 "name": "callback", 2546 "type": "Function", 2547 "desc": "A callback function (optionally with an error argument and data) to be called after the supplied `chunk` has been processed." 2548 } 2549 ] 2550 } 2551 ], 2552 "desc": "<p>This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal <code>Readable</code> class\nmethods only.</p>\n<p>All <code>Transform</code> stream implementations must provide a <code>_transform()</code>\nmethod to accept input and produce output. The <code>transform._transform()</code>\nimplementation handles the bytes being written, computes an output, then passes\nthat output off to the readable portion using the <code>transform.push()</code> method.</p>\n<p>The <code>transform.push()</code> 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.</p>\n<p>It is possible that no output is generated from any given chunk of input data.</p>\n<p>The <code>callback</code> function must be called only when the current chunk is completely\nconsumed. The first argument passed to the <code>callback</code> must be an <code>Error</code> object\nif an error occurred while processing the input or <code>null</code> otherwise. If a second\nargument is passed to the <code>callback</code>, it will be forwarded on to the\n<code>transform.push()</code> method. In other words, the following are equivalent:</p>\n<pre><code class=\"language-js\">transform.prototype._transform = function(data, encoding, callback) {\n this.push(data);\n callback();\n};\n\ntransform.prototype._transform = function(data, encoding, callback) {\n callback(null, data);\n};\n</code></pre>\n<p>The <code>transform._transform()</code> 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.</p>\n<p><code>transform._transform()</code> is never called in parallel; streams implement a\nqueue mechanism, and to receive the next chunk, <code>callback</code> must be\ncalled, either synchronously or asynchronously.</p>" 2553 } 2554 ], 2555 "classes": [ 2556 { 2557 "textRaw": "Class: `stream.PassThrough`", 2558 "type": "class", 2559 "name": "stream.PassThrough", 2560 "desc": "<p>The <code>stream.PassThrough</code> class is a trivial implementation of a <a href=\"#stream_class_stream_transform\"><code>Transform</code></a>\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<code>stream.PassThrough</code> is useful as a building block for novel sorts of streams.</p>" 2561 } 2562 ], 2563 "type": "misc", 2564 "displayName": "Implementing a transform stream" 2565 } 2566 ] 2567 }, 2568 { 2569 "textRaw": "Additional notes", 2570 "name": "Additional notes", 2571 "type": "misc", 2572 "miscs": [ 2573 { 2574 "textRaw": "Streams compatibility with async generators and async iterators", 2575 "name": "streams_compatibility_with_async_generators_and_async_iterators", 2576 "desc": "<p>With the support of async generators and iterators in JavaScript, async\ngenerators are effectively a first-class language-level stream construct at\nthis point.</p>\n<p>Some common interop cases of using Node.js streams with async generators\nand async iterators are provided below.</p>", 2577 "modules": [ 2578 { 2579 "textRaw": "Consuming readable streams with async iterators", 2580 "name": "consuming_readable_streams_with_async_iterators", 2581 "desc": "<pre><code class=\"language-js\">(async function() {\n for await (const chunk of readable) {\n console.log(chunk);\n }\n})();\n</code></pre>\n<p>Async iterators register a permanent error handler on the stream to prevent any\nunhandled post-destroy errors.</p>", 2582 "type": "module", 2583 "displayName": "Consuming readable streams with async iterators" 2584 }, 2585 { 2586 "textRaw": "Creating readable streams with async generators", 2587 "name": "creating_readable_streams_with_async_generators", 2588 "desc": "<p>We can construct a Node.js readable stream from an asynchronous generator\nusing the <code>Readable.from()</code> utility method:</p>\n<pre><code class=\"language-js\">const { Readable } = require('stream');\n\nasync function * generate() {\n yield 'a';\n yield 'b';\n yield 'c';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n console.log(chunk);\n});\n</code></pre>", 2589 "type": "module", 2590 "displayName": "Creating readable streams with async generators" 2591 } 2592 ], 2593 "miscs": [ 2594 { 2595 "textRaw": "Piping to writable streams from async iterators", 2596 "name": "Piping to writable streams from async iterators", 2597 "type": "misc", 2598 "desc": "<p>When writing to a writable stream from an async iterator, ensure correct\nhandling of backpressure and errors. <a href=\"#stream_stream_pipeline_source_transforms_destination_callback\"><code>stream.pipeline()</code></a> abstracts away\nthe handling of backpressure and backpressure-related errors:</p>\n<pre><code class=\"language-js\">const { pipeline } = require('stream');\nconst util = require('util');\nconst fs = require('fs');\n\nconst writable = fs.createWriteStream('./file');\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});\n\n// Promise Pattern\nconst pipelinePromise = util.promisify(pipeline);\npipelinePromise(iterator, writable)\n .then((value) => {\n console.log(value, 'value returned');\n })\n .catch(console.error);\n</code></pre>" 2599 } 2600 ], 2601 "type": "misc", 2602 "displayName": "Streams compatibility with async generators and async iterators" 2603 }, 2604 { 2605 "textRaw": "Compatibility with older Node.js versions", 2606 "name": "Compatibility with older Node.js versions", 2607 "type": "misc", 2608 "desc": "<p>Prior to Node.js 0.10, the <code>Readable</code> stream interface was simpler, but also\nless powerful and less useful.</p>\n<ul>\n<li>Rather than waiting for calls to the <a href=\"#stream_readable_read_size\"><code>stream.read()</code></a> method,\n<a href=\"#stream_event_data\"><code>'data'</code></a> events would begin emitting immediately. Applications that\nwould need to perform some amount of work to decide how to handle data\nwere required to store read data into buffers so the data would not be lost.</li>\n<li>The <a href=\"#stream_readable_pause\"><code>stream.pause()</code></a> method was advisory, rather than\nguaranteed. This meant that it was still necessary to be prepared to receive\n<a href=\"#stream_event_data\"><code>'data'</code></a> events <em>even when the stream was in a paused state</em>.</li>\n</ul>\n<p>In Node.js 0.10, the <a href=\"#stream_class_stream_readable\"><code>Readable</code></a> class was added. For backward\ncompatibility with older Node.js programs, <code>Readable</code> streams switch into\n\"flowing mode\" when a <a href=\"#stream_event_data\"><code>'data'</code></a> event handler is added, or when the\n<a href=\"#stream_readable_resume\"><code>stream.resume()</code></a> method is called. The effect is that, even\nwhen not using the new <a href=\"#stream_readable_read_size\"><code>stream.read()</code></a> method and\n<a href=\"#stream_event_readable\"><code>'readable'</code></a> event, it is no longer necessary to worry about losing\n<a href=\"#stream_event_data\"><code>'data'</code></a> chunks.</p>\n<p>While most applications will continue to function normally, this introduces an\nedge case in the following conditions:</p>\n<ul>\n<li>No <a href=\"#stream_event_data\"><code>'data'</code></a> event listener is added.</li>\n<li>The <a href=\"#stream_readable_resume\"><code>stream.resume()</code></a> method is never called.</li>\n<li>The stream is not piped to any writable destination.</li>\n</ul>\n<p>For example, consider the following code:</p>\n<pre><code class=\"language-js\">// 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</code></pre>\n<p>Prior to Node.js 0.10, the incoming message data would be simply discarded.\nHowever, in Node.js 0.10 and beyond, the socket remains paused forever.</p>\n<p>The workaround in this situation is to call the\n<a href=\"#stream_readable_resume\"><code>stream.resume()</code></a> method to begin the flow of data:</p>\n<pre><code class=\"language-js\">// 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</code></pre>\n<p>In addition to new <code>Readable</code> streams switching into flowing mode,\npre-0.10 style streams can be wrapped in a <code>Readable</code> class using the\n<a href=\"#stream_readable_wrap_stream\"><code>readable.wrap()</code></a> method.</p>" 2609 }, 2610 { 2611 "textRaw": "`highWaterMark` discrepancy after calling `readable.setEncoding()`", 2612 "name": "`highwatermark`_discrepancy_after_calling_`readable.setencoding()`", 2613 "desc": "<p>The use of <code>readable.setEncoding()</code> will change the behavior of how the\n<code>highWaterMark</code> operates in non-object mode.</p>\n<p>Typically, the size of the current buffer is measured against the\n<code>highWaterMark</code> in <em>bytes</em>. However, after <code>setEncoding()</code> is called, the\ncomparison function will begin to measure the buffer's size in <em>characters</em>.</p>\n<p>This is not a problem in common cases with <code>latin1</code> or <code>ascii</code>. But it is\nadvised to be mindful about this behavior when working with strings that could\ncontain multi-byte characters.</p>", 2614 "type": "misc", 2615 "displayName": "`highWaterMark` discrepancy after calling `readable.setEncoding()`" 2616 } 2617 ], 2618 "methods": [ 2619 { 2620 "textRaw": "`readable.read(0)`", 2621 "type": "method", 2622 "name": "read", 2623 "signatures": [ 2624 { 2625 "params": [] 2626 } 2627 ], 2628 "desc": "<p>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 <code>readable.read(0)</code>, which will\nalways return <code>null</code>.</p>\n<p>If the internal read buffer is below the <code>highWaterMark</code>, and the\nstream is not currently reading, then calling <code>stream.read(0)</code> will trigger\na low-level <a href=\"#stream_readable_read_size_1\"><code>stream._read()</code></a> call.</p>\n<p>While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\n<code>Readable</code> stream class internals.</p>" 2629 }, 2630 { 2631 "textRaw": "`readable.push('')`", 2632 "type": "method", 2633 "name": "push", 2634 "signatures": [ 2635 { 2636 "params": [] 2637 } 2638 ], 2639 "desc": "<p>Use of <code>readable.push('')</code> is not recommended.</p>\n<p>Pushing a zero-byte string, <code>Buffer</code> or <code>Uint8Array</code> to a stream that is not in\nobject mode has an interesting side effect. Because it <em>is</em> a call to\n<a href=\"#stream_readable_push_chunk_encoding\"><code>readable.push()</code></a>, 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.</p>" 2640 } 2641 ] 2642 } 2643 ], 2644 "type": "module", 2645 "displayName": "Stream" 2646 } 2647 ] 2648}