1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width"> 6 <meta name="nodejs.org:node-version" content="v18.20.1"> 7 <title>Stream | Node.js v18.20.1 Documentation</title> 8 <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback"> 9 <link rel="stylesheet" href="assets/style.css"> 10 <link rel="stylesheet" href="assets/hljs.css"> 11 <link rel="canonical" href="https://nodejs.org/api/stream.html"> 12 <script async defer src="assets/api.js" type="text/javascript"></script> 13 <style>@media(max-width:718px){.with-62-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:646px){.with-53-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}@media(max-width:558px){.with-42-chars>.js-flavor-selector{float:none;margin:0 0 1em auto;}}</style> 14</head> 15<body class="alt apidoc" id="api-section-stream"> 16 <div id="content" class="clearfix"> 17 <div id="column2" class="interior"> 18 <div id="intro" class="interior"> 19 <a href="/" title="Go back to the home page"> 20 Node.js 21 </a> 22 </div> 23 <ul> 24<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> 25<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> 26</ul> 27<hr class="line"> 28<ul> 29<li><a href="assert.html" class="nav-assert">Assertion testing</a></li> 30<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> 31<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> 32<li><a href="buffer.html" class="nav-buffer">Buffer</a></li> 33<li><a href="addons.html" class="nav-addons">C++ addons</a></li> 34<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> 35<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> 36<li><a href="child_process.html" class="nav-child_process">Child processes</a></li> 37<li><a href="cluster.html" class="nav-cluster">Cluster</a></li> 38<li><a href="cli.html" class="nav-cli">Command-line options</a></li> 39<li><a href="console.html" class="nav-console">Console</a></li> 40<li><a href="corepack.html" class="nav-corepack">Corepack</a></li> 41<li><a href="crypto.html" class="nav-crypto">Crypto</a></li> 42<li><a href="debugger.html" class="nav-debugger">Debugger</a></li> 43<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> 44<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> 45<li><a href="dns.html" class="nav-dns">DNS</a></li> 46<li><a href="domain.html" class="nav-domain">Domain</a></li> 47<li><a href="errors.html" class="nav-errors">Errors</a></li> 48<li><a href="events.html" class="nav-events">Events</a></li> 49<li><a href="fs.html" class="nav-fs">File system</a></li> 50<li><a href="globals.html" class="nav-globals">Globals</a></li> 51<li><a href="http.html" class="nav-http">HTTP</a></li> 52<li><a href="http2.html" class="nav-http2">HTTP/2</a></li> 53<li><a href="https.html" class="nav-https">HTTPS</a></li> 54<li><a href="inspector.html" class="nav-inspector">Inspector</a></li> 55<li><a href="intl.html" class="nav-intl">Internationalization</a></li> 56<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> 57<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> 58<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li> 59<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> 60<li><a href="net.html" class="nav-net">Net</a></li> 61<li><a href="os.html" class="nav-os">OS</a></li> 62<li><a href="path.html" class="nav-path">Path</a></li> 63<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> 64<li><a href="permissions.html" class="nav-permissions">Permissions</a></li> 65<li><a href="process.html" class="nav-process">Process</a></li> 66<li><a href="punycode.html" class="nav-punycode">Punycode</a></li> 67<li><a href="querystring.html" class="nav-querystring">Query strings</a></li> 68<li><a href="readline.html" class="nav-readline">Readline</a></li> 69<li><a href="repl.html" class="nav-repl">REPL</a></li> 70<li><a href="report.html" class="nav-report">Report</a></li> 71<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> 72<li><a href="stream.html" class="nav-stream active">Stream</a></li> 73<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> 74<li><a href="test.html" class="nav-test">Test runner</a></li> 75<li><a href="timers.html" class="nav-timers">Timers</a></li> 76<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> 77<li><a href="tracing.html" class="nav-tracing">Trace events</a></li> 78<li><a href="tty.html" class="nav-tty">TTY</a></li> 79<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> 80<li><a href="url.html" class="nav-url">URL</a></li> 81<li><a href="util.html" class="nav-util">Utilities</a></li> 82<li><a href="v8.html" class="nav-v8">V8</a></li> 83<li><a href="vm.html" class="nav-vm">VM</a></li> 84<li><a href="wasi.html" class="nav-wasi">WASI</a></li> 85<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> 86<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> 87<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> 88<li><a href="zlib.html" class="nav-zlib">Zlib</a></li> 89</ul> 90<hr class="line"> 91<ul> 92<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> 93</ul> 94 </div> 95 96 <div id="column1" data-id="stream" class="interior"> 97 <header class="header"> 98 <div class="header-container"> 99 <h1>Node.js v18.20.1 documentation</h1> 100 <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> 101 <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> 102 <path fill="none" d="M0 0h24v24H0z" /> 103 <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/> 104 <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/> 105 </svg> 106 <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> 107 <path d="M0 0h24v24H0z" fill="none" /> 108 <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/> 109 </svg> 110 </button> 111 </div> 112 <div id="gtoc"> 113 <ul> 114 <li class="pinned-header">Node.js v18.20.1</li> 115 116 <li class="picker-header"> 117 <a href="#"> 118 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 119 Table of contents 120 </a> 121 122 <div class="picker"><div class="toc"><ul> 123<li><span class="stability_2"><a href="#stream">Stream</a></span> 124<ul> 125<li><a href="#organization-of-this-document">Organization of this document</a></li> 126<li><a href="#types-of-streams">Types of streams</a> 127<ul> 128<li><a href="#streams-promises-api">Streams Promises API</a></li> 129<li><a href="#streampipelinesource-transforms-destination-options"><code>stream.pipeline(source[, ...transforms], destination[, options])</code></a></li> 130<li><a href="#streampipelinestreams-options"><code>stream.pipeline(streams[, options])</code></a></li> 131<li><a href="#streamfinishedstream-options"><code>stream.finished(stream[, options])</code></a></li> 132<li><a href="#object-mode">Object mode</a></li> 133<li><a href="#buffering">Buffering</a></li> 134</ul> 135</li> 136<li><a href="#api-for-stream-consumers">API for stream consumers</a> 137<ul> 138<li><a href="#writable-streams">Writable streams</a> 139<ul> 140<li><a href="#class-streamwritable">Class: <code>stream.Writable</code></a> 141<ul> 142<li><a href="#event-close">Event: <code>'close'</code></a></li> 143<li><a href="#event-drain">Event: <code>'drain'</code></a></li> 144<li><a href="#event-error">Event: <code>'error'</code></a></li> 145<li><a href="#event-finish">Event: <code>'finish'</code></a></li> 146<li><a href="#event-pipe">Event: <code>'pipe'</code></a></li> 147<li><a href="#event-unpipe">Event: <code>'unpipe'</code></a></li> 148<li><a href="#writablecork"><code>writable.cork()</code></a></li> 149<li><a href="#writabledestroyerror"><code>writable.destroy([error])</code></a></li> 150<li><a href="#writableclosed"><code>writable.closed</code></a></li> 151<li><a href="#writabledestroyed"><code>writable.destroyed</code></a></li> 152<li><a href="#writableendchunk-encoding-callback"><code>writable.end([chunk[, encoding]][, callback])</code></a></li> 153<li><a href="#writablesetdefaultencodingencoding"><code>writable.setDefaultEncoding(encoding)</code></a></li> 154<li><a href="#writableuncork"><code>writable.uncork()</code></a></li> 155<li><a href="#writablewritable"><code>writable.writable</code></a></li> 156<li><span class="stability_1"><a href="#writablewritableaborted"><code>writable.writableAborted</code></a></span></li> 157<li><a href="#writablewritableended"><code>writable.writableEnded</code></a></li> 158<li><a href="#writablewritablecorked"><code>writable.writableCorked</code></a></li> 159<li><a href="#writableerrored"><code>writable.errored</code></a></li> 160<li><a href="#writablewritablefinished"><code>writable.writableFinished</code></a></li> 161<li><a href="#writablewritablehighwatermark"><code>writable.writableHighWaterMark</code></a></li> 162<li><a href="#writablewritablelength"><code>writable.writableLength</code></a></li> 163<li><a href="#writablewritableneeddrain"><code>writable.writableNeedDrain</code></a></li> 164<li><a href="#writablewritableobjectmode"><code>writable.writableObjectMode</code></a></li> 165<li><a href="#writablewritechunk-encoding-callback"><code>writable.write(chunk[, encoding][, callback])</code></a></li> 166</ul> 167</li> 168</ul> 169</li> 170<li><a href="#readable-streams">Readable streams</a> 171<ul> 172<li><a href="#two-reading-modes">Two reading modes</a></li> 173<li><a href="#three-states">Three states</a></li> 174<li><a href="#choose-one-api-style">Choose one API style</a></li> 175<li><a href="#class-streamreadable">Class: <code>stream.Readable</code></a> 176<ul> 177<li><a href="#event-close_1">Event: <code>'close'</code></a></li> 178<li><a href="#event-data">Event: <code>'data'</code></a></li> 179<li><a href="#event-end">Event: <code>'end'</code></a></li> 180<li><a href="#event-error_1">Event: <code>'error'</code></a></li> 181<li><a href="#event-pause">Event: <code>'pause'</code></a></li> 182<li><a href="#event-readable">Event: <code>'readable'</code></a></li> 183<li><a href="#event-resume">Event: <code>'resume'</code></a></li> 184<li><a href="#readabledestroyerror"><code>readable.destroy([error])</code></a></li> 185<li><a href="#readableclosed"><code>readable.closed</code></a></li> 186<li><a href="#readabledestroyed"><code>readable.destroyed</code></a></li> 187<li><a href="#readableispaused"><code>readable.isPaused()</code></a></li> 188<li><a href="#readablepause"><code>readable.pause()</code></a></li> 189<li><a href="#readablepipedestination-options"><code>readable.pipe(destination[, options])</code></a></li> 190<li><a href="#readablereadsize"><code>readable.read([size])</code></a></li> 191<li><a href="#readablereadable"><code>readable.readable</code></a></li> 192<li><span class="stability_1"><a href="#readablereadableaborted"><code>readable.readableAborted</code></a></span></li> 193<li><span class="stability_1"><a href="#readablereadabledidread"><code>readable.readableDidRead</code></a></span></li> 194<li><a href="#readablereadableencoding"><code>readable.readableEncoding</code></a></li> 195<li><a href="#readablereadableended"><code>readable.readableEnded</code></a></li> 196<li><a href="#readableerrored"><code>readable.errored</code></a></li> 197<li><a href="#readablereadableflowing"><code>readable.readableFlowing</code></a></li> 198<li><a href="#readablereadablehighwatermark"><code>readable.readableHighWaterMark</code></a></li> 199<li><a href="#readablereadablelength"><code>readable.readableLength</code></a></li> 200<li><a href="#readablereadableobjectmode"><code>readable.readableObjectMode</code></a></li> 201<li><a href="#readableresume"><code>readable.resume()</code></a></li> 202<li><a href="#readablesetencodingencoding"><code>readable.setEncoding(encoding)</code></a></li> 203<li><a href="#readableunpipedestination"><code>readable.unpipe([destination])</code></a></li> 204<li><a href="#readableunshiftchunk-encoding"><code>readable.unshift(chunk[, encoding])</code></a></li> 205<li><a href="#readablewrapstream"><code>readable.wrap(stream)</code></a></li> 206<li><a href="#readablesymbolasynciterator"><code>readable[Symbol.asyncIterator]()</code></a></li> 207<li><span class="stability_1"><a href="#readablesymbolasyncdispose"><code>readable[Symbol.asyncDispose]()</code></a></span></li> 208<li><span class="stability_1"><a href="#readablecomposestream-options"><code>readable.compose(stream[, options])</code></a></span></li> 209<li><span class="stability_1"><a href="#readableiteratoroptions"><code>readable.iterator([options])</code></a></span></li> 210<li><span class="stability_1"><a href="#readablemapfn-options"><code>readable.map(fn[, options])</code></a></span></li> 211<li><span class="stability_1"><a href="#readablefilterfn-options"><code>readable.filter(fn[, options])</code></a></span></li> 212<li><span class="stability_1"><a href="#readableforeachfn-options"><code>readable.forEach(fn[, options])</code></a></span></li> 213<li><span class="stability_1"><a href="#readabletoarrayoptions"><code>readable.toArray([options])</code></a></span></li> 214<li><span class="stability_1"><a href="#readablesomefn-options"><code>readable.some(fn[, options])</code></a></span></li> 215<li><span class="stability_1"><a href="#readablefindfn-options"><code>readable.find(fn[, options])</code></a></span></li> 216<li><span class="stability_1"><a href="#readableeveryfn-options"><code>readable.every(fn[, options])</code></a></span></li> 217<li><span class="stability_1"><a href="#readableflatmapfn-options"><code>readable.flatMap(fn[, options])</code></a></span></li> 218<li><span class="stability_1"><a href="#readabledroplimit-options"><code>readable.drop(limit[, options])</code></a></span></li> 219<li><span class="stability_1"><a href="#readabletakelimit-options"><code>readable.take(limit[, options])</code></a></span></li> 220<li><span class="stability_1"><a href="#readableasindexedpairsoptions"><code>readable.asIndexedPairs([options])</code></a></span></li> 221<li><span class="stability_1"><a href="#readablereducefn-initial-options"><code>readable.reduce(fn[, initial[, options]])</code></a></span></li> 222</ul> 223</li> 224</ul> 225</li> 226<li><a href="#duplex-and-transform-streams">Duplex and transform streams</a> 227<ul> 228<li><a href="#class-streamduplex">Class: <code>stream.Duplex</code></a> 229<ul> 230<li><a href="#duplexallowhalfopen"><code>duplex.allowHalfOpen</code></a></li> 231</ul> 232</li> 233<li><a href="#class-streamtransform">Class: <code>stream.Transform</code></a> 234<ul> 235<li><a href="#transformdestroyerror"><code>transform.destroy([error])</code></a></li> 236</ul> 237</li> 238</ul> 239</li> 240<li><a href="#streamfinishedstream-options-callback"><code>stream.finished(stream[, options], callback)</code></a></li> 241<li><a href="#streampipelinesource-transforms-destination-callback"><code>stream.pipeline(source[, ...transforms], destination, callback)</code></a></li> 242<li><a href="#streampipelinestreams-callback"><code>stream.pipeline(streams, callback)</code></a></li> 243<li><span class="stability_1"><a href="#streamcomposestreams"><code>stream.compose(...streams)</code></a></span></li> 244<li><a href="#streamreadablefromiterable-options"><code>stream.Readable.from(iterable[, options])</code></a></li> 245<li><span class="stability_1"><a href="#streamreadablefromwebreadablestream-options"><code>stream.Readable.fromWeb(readableStream[, options])</code></a></span></li> 246<li><span class="stability_1"><a href="#streamreadableisdisturbedstream"><code>stream.Readable.isDisturbed(stream)</code></a></span></li> 247<li><span class="stability_1"><a href="#streamiserroredstream"><code>stream.isErrored(stream)</code></a></span></li> 248<li><span class="stability_1"><a href="#streamisreadablestream"><code>stream.isReadable(stream)</code></a></span></li> 249<li><span class="stability_1"><a href="#streamreadabletowebstreamreadable-options"><code>stream.Readable.toWeb(streamReadable[, options])</code></a></span></li> 250<li><span class="stability_1"><a href="#streamwritablefromwebwritablestream-options"><code>stream.Writable.fromWeb(writableStream[, options])</code></a></span></li> 251<li><span class="stability_1"><a href="#streamwritabletowebstreamwritable"><code>stream.Writable.toWeb(streamWritable)</code></a></span></li> 252<li><a href="#streamduplexfromsrc"><code>stream.Duplex.from(src)</code></a></li> 253<li><span class="stability_1"><a href="#streamduplexfromwebpair-options"><code>stream.Duplex.fromWeb(pair[, options])</code></a></span></li> 254<li><span class="stability_1"><a href="#streamduplextowebstreamduplex"><code>stream.Duplex.toWeb(streamDuplex)</code></a></span></li> 255<li><a href="#streamaddabortsignalsignal-stream"><code>stream.addAbortSignal(signal, stream)</code></a></li> 256<li><a href="#streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark(objectMode)</code></a></li> 257<li><a href="#streamsetdefaulthighwatermarkobjectmode-value"><code>stream.setDefaultHighWaterMark(objectMode, value)</code></a></li> 258</ul> 259</li> 260<li><a href="#api-for-stream-implementers">API for stream implementers</a> 261<ul> 262<li><a href="#simplified-construction">Simplified construction</a></li> 263<li><a href="#implementing-a-writable-stream">Implementing a writable stream</a> 264<ul> 265<li><a href="#new-streamwritableoptions"><code>new stream.Writable([options])</code></a></li> 266<li><a href="#writable_constructcallback"><code>writable._construct(callback)</code></a></li> 267<li><a href="#writable_writechunk-encoding-callback"><code>writable._write(chunk, encoding, callback)</code></a></li> 268<li><a href="#writable_writevchunks-callback"><code>writable._writev(chunks, callback)</code></a></li> 269<li><a href="#writable_destroyerr-callback"><code>writable._destroy(err, callback)</code></a></li> 270<li><a href="#writable_finalcallback"><code>writable._final(callback)</code></a></li> 271<li><a href="#errors-while-writing">Errors while writing</a></li> 272<li><a href="#an-example-writable-stream">An example writable stream</a></li> 273<li><a href="#decoding-buffers-in-a-writable-stream">Decoding buffers in a writable stream</a></li> 274</ul> 275</li> 276<li><a href="#implementing-a-readable-stream">Implementing a readable stream</a> 277<ul> 278<li><a href="#new-streamreadableoptions"><code>new stream.Readable([options])</code></a></li> 279<li><a href="#readable_constructcallback"><code>readable._construct(callback)</code></a></li> 280<li><a href="#readable_readsize"><code>readable._read(size)</code></a></li> 281<li><a href="#readable_destroyerr-callback"><code>readable._destroy(err, callback)</code></a></li> 282<li><a href="#readablepushchunk-encoding"><code>readable.push(chunk[, encoding])</code></a></li> 283<li><a href="#errors-while-reading">Errors while reading</a></li> 284<li><a href="#an-example-counting-stream">An example counting stream</a></li> 285</ul> 286</li> 287<li><a href="#implementing-a-duplex-stream">Implementing a duplex stream</a> 288<ul> 289<li><a href="#new-streamduplexoptions"><code>new stream.Duplex(options)</code></a></li> 290<li><a href="#an-example-duplex-stream">An example duplex stream</a></li> 291<li><a href="#object-mode-duplex-streams">Object mode duplex streams</a></li> 292</ul> 293</li> 294<li><a href="#implementing-a-transform-stream">Implementing a transform stream</a> 295<ul> 296<li><a href="#new-streamtransformoptions"><code>new stream.Transform([options])</code></a></li> 297<li><a href="#event-end_1">Event: <code>'end'</code></a></li> 298<li><a href="#event-finish_1">Event: <code>'finish'</code></a></li> 299<li><a href="#transform_flushcallback"><code>transform._flush(callback)</code></a></li> 300<li><a href="#transform_transformchunk-encoding-callback"><code>transform._transform(chunk, encoding, callback)</code></a></li> 301<li><a href="#class-streampassthrough">Class: <code>stream.PassThrough</code></a></li> 302</ul> 303</li> 304</ul> 305</li> 306<li><a href="#additional-notes">Additional notes</a> 307<ul> 308<li><a href="#streams-compatibility-with-async-generators-and-async-iterators">Streams compatibility with async generators and async iterators</a> 309<ul> 310<li><a href="#consuming-readable-streams-with-async-iterators">Consuming readable streams with async iterators</a></li> 311<li><a href="#creating-readable-streams-with-async-generators">Creating readable streams with async generators</a></li> 312<li><a href="#piping-to-writable-streams-from-async-iterators">Piping to writable streams from async iterators</a></li> 313</ul> 314</li> 315<li><a href="#compatibility-with-older-nodejs-versions">Compatibility with older Node.js versions</a></li> 316<li><a href="#readableread0"><code>readable.read(0)</code></a></li> 317<li><a href="#readablepush"><code>readable.push('')</code></a></li> 318<li><a href="#highwatermark-discrepancy-after-calling-readablesetencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li> 319</ul> 320</li> 321</ul> 322</li> 323</ul></div></div> 324 </li> 325 326 327 <li class="picker-header"> 328 <a href="#"> 329 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 330 Index 331 </a> 332 333 <div class="picker"><ul> 334<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> 335<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> 336 337 <li> 338 <a href="index.html">Index</a> 339 </li> 340 </ul> 341 342<hr class="line"> 343<ul> 344<li><a href="assert.html" class="nav-assert">Assertion testing</a></li> 345<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</a></li> 346<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> 347<li><a href="buffer.html" class="nav-buffer">Buffer</a></li> 348<li><a href="addons.html" class="nav-addons">C++ addons</a></li> 349<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> 350<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> 351<li><a href="child_process.html" class="nav-child_process">Child processes</a></li> 352<li><a href="cluster.html" class="nav-cluster">Cluster</a></li> 353<li><a href="cli.html" class="nav-cli">Command-line options</a></li> 354<li><a href="console.html" class="nav-console">Console</a></li> 355<li><a href="corepack.html" class="nav-corepack">Corepack</a></li> 356<li><a href="crypto.html" class="nav-crypto">Crypto</a></li> 357<li><a href="debugger.html" class="nav-debugger">Debugger</a></li> 358<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> 359<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> 360<li><a href="dns.html" class="nav-dns">DNS</a></li> 361<li><a href="domain.html" class="nav-domain">Domain</a></li> 362<li><a href="errors.html" class="nav-errors">Errors</a></li> 363<li><a href="events.html" class="nav-events">Events</a></li> 364<li><a href="fs.html" class="nav-fs">File system</a></li> 365<li><a href="globals.html" class="nav-globals">Globals</a></li> 366<li><a href="http.html" class="nav-http">HTTP</a></li> 367<li><a href="http2.html" class="nav-http2">HTTP/2</a></li> 368<li><a href="https.html" class="nav-https">HTTPS</a></li> 369<li><a href="inspector.html" class="nav-inspector">Inspector</a></li> 370<li><a href="intl.html" class="nav-intl">Internationalization</a></li> 371<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> 372<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> 373<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li> 374<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> 375<li><a href="net.html" class="nav-net">Net</a></li> 376<li><a href="os.html" class="nav-os">OS</a></li> 377<li><a href="path.html" class="nav-path">Path</a></li> 378<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> 379<li><a href="permissions.html" class="nav-permissions">Permissions</a></li> 380<li><a href="process.html" class="nav-process">Process</a></li> 381<li><a href="punycode.html" class="nav-punycode">Punycode</a></li> 382<li><a href="querystring.html" class="nav-querystring">Query strings</a></li> 383<li><a href="readline.html" class="nav-readline">Readline</a></li> 384<li><a href="repl.html" class="nav-repl">REPL</a></li> 385<li><a href="report.html" class="nav-report">Report</a></li> 386<li><a href="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</a></li> 387<li><a href="stream.html" class="nav-stream active">Stream</a></li> 388<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> 389<li><a href="test.html" class="nav-test">Test runner</a></li> 390<li><a href="timers.html" class="nav-timers">Timers</a></li> 391<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> 392<li><a href="tracing.html" class="nav-tracing">Trace events</a></li> 393<li><a href="tty.html" class="nav-tty">TTY</a></li> 394<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> 395<li><a href="url.html" class="nav-url">URL</a></li> 396<li><a href="util.html" class="nav-util">Utilities</a></li> 397<li><a href="v8.html" class="nav-v8">V8</a></li> 398<li><a href="vm.html" class="nav-vm">VM</a></li> 399<li><a href="wasi.html" class="nav-wasi">WASI</a></li> 400<li><a href="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li> 401<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</a></li> 402<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> 403<li><a href="zlib.html" class="nav-zlib">Zlib</a></li> 404</ul> 405<hr class="line"> 406<ul> 407<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> 408</ul></div> 409 </li> 410 411 412 <li class="picker-header"> 413 <a href="#"> 414 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 415 Other versions 416 </a> 417 <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v21.x/api/stream.html">21.x</a></li> 418<li><a href="https://nodejs.org/docs/latest-v20.x/api/stream.html">20.x <b>LTS</b></a></li> 419<li><a href="https://nodejs.org/docs/latest-v19.x/api/stream.html">19.x</a></li> 420<li><a href="https://nodejs.org/docs/latest-v18.x/api/stream.html">18.x <b>LTS</b></a></li> 421<li><a href="https://nodejs.org/docs/latest-v17.x/api/stream.html">17.x</a></li> 422<li><a href="https://nodejs.org/docs/latest-v16.x/api/stream.html">16.x</a></li> 423<li><a href="https://nodejs.org/docs/latest-v15.x/api/stream.html">15.x</a></li> 424<li><a href="https://nodejs.org/docs/latest-v14.x/api/stream.html">14.x</a></li> 425<li><a href="https://nodejs.org/docs/latest-v13.x/api/stream.html">13.x</a></li> 426<li><a href="https://nodejs.org/docs/latest-v12.x/api/stream.html">12.x</a></li> 427<li><a href="https://nodejs.org/docs/latest-v11.x/api/stream.html">11.x</a></li> 428<li><a href="https://nodejs.org/docs/latest-v10.x/api/stream.html">10.x</a></li> 429<li><a href="https://nodejs.org/docs/latest-v9.x/api/stream.html">9.x</a></li> 430<li><a href="https://nodejs.org/docs/latest-v8.x/api/stream.html">8.x</a></li> 431<li><a href="https://nodejs.org/docs/latest-v7.x/api/stream.html">7.x</a></li> 432<li><a href="https://nodejs.org/docs/latest-v6.x/api/stream.html">6.x</a></li> 433<li><a href="https://nodejs.org/docs/latest-v5.x/api/stream.html">5.x</a></li> 434<li><a href="https://nodejs.org/docs/latest-v4.x/api/stream.html">4.x</a></li> 435<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/stream.html">0.12.x</a></li> 436<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/stream.html">0.10.x</a></li></ol></div> 437 </li> 438 439 <li class="picker-header"> 440 <a href="#"> 441 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 442 Options 443 </a> 444 445 <div class="picker"> 446 <ul> 447 <li> 448 <a href="all.html">View on single page</a> 449 </li> 450 <li> 451 <a href="stream.json">View as JSON</a> 452 </li> 453 <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/stream.md">Edit on GitHub</a></li> 454 </ul> 455 </div> 456 </li> 457 </ul> 458 </div> 459 <hr> 460 </header> 461 462 <details id="toc" open><summary>Table of contents</summary><ul> 463<li><span class="stability_2"><a href="#stream">Stream</a></span> 464<ul> 465<li><a href="#organization-of-this-document">Organization of this document</a></li> 466<li><a href="#types-of-streams">Types of streams</a> 467<ul> 468<li><a href="#streams-promises-api">Streams Promises API</a></li> 469<li><a href="#streampipelinesource-transforms-destination-options"><code>stream.pipeline(source[, ...transforms], destination[, options])</code></a></li> 470<li><a href="#streampipelinestreams-options"><code>stream.pipeline(streams[, options])</code></a></li> 471<li><a href="#streamfinishedstream-options"><code>stream.finished(stream[, options])</code></a></li> 472<li><a href="#object-mode">Object mode</a></li> 473<li><a href="#buffering">Buffering</a></li> 474</ul> 475</li> 476<li><a href="#api-for-stream-consumers">API for stream consumers</a> 477<ul> 478<li><a href="#writable-streams">Writable streams</a> 479<ul> 480<li><a href="#class-streamwritable">Class: <code>stream.Writable</code></a> 481<ul> 482<li><a href="#event-close">Event: <code>'close'</code></a></li> 483<li><a href="#event-drain">Event: <code>'drain'</code></a></li> 484<li><a href="#event-error">Event: <code>'error'</code></a></li> 485<li><a href="#event-finish">Event: <code>'finish'</code></a></li> 486<li><a href="#event-pipe">Event: <code>'pipe'</code></a></li> 487<li><a href="#event-unpipe">Event: <code>'unpipe'</code></a></li> 488<li><a href="#writablecork"><code>writable.cork()</code></a></li> 489<li><a href="#writabledestroyerror"><code>writable.destroy([error])</code></a></li> 490<li><a href="#writableclosed"><code>writable.closed</code></a></li> 491<li><a href="#writabledestroyed"><code>writable.destroyed</code></a></li> 492<li><a href="#writableendchunk-encoding-callback"><code>writable.end([chunk[, encoding]][, callback])</code></a></li> 493<li><a href="#writablesetdefaultencodingencoding"><code>writable.setDefaultEncoding(encoding)</code></a></li> 494<li><a href="#writableuncork"><code>writable.uncork()</code></a></li> 495<li><a href="#writablewritable"><code>writable.writable</code></a></li> 496<li><span class="stability_1"><a href="#writablewritableaborted"><code>writable.writableAborted</code></a></span></li> 497<li><a href="#writablewritableended"><code>writable.writableEnded</code></a></li> 498<li><a href="#writablewritablecorked"><code>writable.writableCorked</code></a></li> 499<li><a href="#writableerrored"><code>writable.errored</code></a></li> 500<li><a href="#writablewritablefinished"><code>writable.writableFinished</code></a></li> 501<li><a href="#writablewritablehighwatermark"><code>writable.writableHighWaterMark</code></a></li> 502<li><a href="#writablewritablelength"><code>writable.writableLength</code></a></li> 503<li><a href="#writablewritableneeddrain"><code>writable.writableNeedDrain</code></a></li> 504<li><a href="#writablewritableobjectmode"><code>writable.writableObjectMode</code></a></li> 505<li><a href="#writablewritechunk-encoding-callback"><code>writable.write(chunk[, encoding][, callback])</code></a></li> 506</ul> 507</li> 508</ul> 509</li> 510<li><a href="#readable-streams">Readable streams</a> 511<ul> 512<li><a href="#two-reading-modes">Two reading modes</a></li> 513<li><a href="#three-states">Three states</a></li> 514<li><a href="#choose-one-api-style">Choose one API style</a></li> 515<li><a href="#class-streamreadable">Class: <code>stream.Readable</code></a> 516<ul> 517<li><a href="#event-close_1">Event: <code>'close'</code></a></li> 518<li><a href="#event-data">Event: <code>'data'</code></a></li> 519<li><a href="#event-end">Event: <code>'end'</code></a></li> 520<li><a href="#event-error_1">Event: <code>'error'</code></a></li> 521<li><a href="#event-pause">Event: <code>'pause'</code></a></li> 522<li><a href="#event-readable">Event: <code>'readable'</code></a></li> 523<li><a href="#event-resume">Event: <code>'resume'</code></a></li> 524<li><a href="#readabledestroyerror"><code>readable.destroy([error])</code></a></li> 525<li><a href="#readableclosed"><code>readable.closed</code></a></li> 526<li><a href="#readabledestroyed"><code>readable.destroyed</code></a></li> 527<li><a href="#readableispaused"><code>readable.isPaused()</code></a></li> 528<li><a href="#readablepause"><code>readable.pause()</code></a></li> 529<li><a href="#readablepipedestination-options"><code>readable.pipe(destination[, options])</code></a></li> 530<li><a href="#readablereadsize"><code>readable.read([size])</code></a></li> 531<li><a href="#readablereadable"><code>readable.readable</code></a></li> 532<li><span class="stability_1"><a href="#readablereadableaborted"><code>readable.readableAborted</code></a></span></li> 533<li><span class="stability_1"><a href="#readablereadabledidread"><code>readable.readableDidRead</code></a></span></li> 534<li><a href="#readablereadableencoding"><code>readable.readableEncoding</code></a></li> 535<li><a href="#readablereadableended"><code>readable.readableEnded</code></a></li> 536<li><a href="#readableerrored"><code>readable.errored</code></a></li> 537<li><a href="#readablereadableflowing"><code>readable.readableFlowing</code></a></li> 538<li><a href="#readablereadablehighwatermark"><code>readable.readableHighWaterMark</code></a></li> 539<li><a href="#readablereadablelength"><code>readable.readableLength</code></a></li> 540<li><a href="#readablereadableobjectmode"><code>readable.readableObjectMode</code></a></li> 541<li><a href="#readableresume"><code>readable.resume()</code></a></li> 542<li><a href="#readablesetencodingencoding"><code>readable.setEncoding(encoding)</code></a></li> 543<li><a href="#readableunpipedestination"><code>readable.unpipe([destination])</code></a></li> 544<li><a href="#readableunshiftchunk-encoding"><code>readable.unshift(chunk[, encoding])</code></a></li> 545<li><a href="#readablewrapstream"><code>readable.wrap(stream)</code></a></li> 546<li><a href="#readablesymbolasynciterator"><code>readable[Symbol.asyncIterator]()</code></a></li> 547<li><span class="stability_1"><a href="#readablesymbolasyncdispose"><code>readable[Symbol.asyncDispose]()</code></a></span></li> 548<li><span class="stability_1"><a href="#readablecomposestream-options"><code>readable.compose(stream[, options])</code></a></span></li> 549<li><span class="stability_1"><a href="#readableiteratoroptions"><code>readable.iterator([options])</code></a></span></li> 550<li><span class="stability_1"><a href="#readablemapfn-options"><code>readable.map(fn[, options])</code></a></span></li> 551<li><span class="stability_1"><a href="#readablefilterfn-options"><code>readable.filter(fn[, options])</code></a></span></li> 552<li><span class="stability_1"><a href="#readableforeachfn-options"><code>readable.forEach(fn[, options])</code></a></span></li> 553<li><span class="stability_1"><a href="#readabletoarrayoptions"><code>readable.toArray([options])</code></a></span></li> 554<li><span class="stability_1"><a href="#readablesomefn-options"><code>readable.some(fn[, options])</code></a></span></li> 555<li><span class="stability_1"><a href="#readablefindfn-options"><code>readable.find(fn[, options])</code></a></span></li> 556<li><span class="stability_1"><a href="#readableeveryfn-options"><code>readable.every(fn[, options])</code></a></span></li> 557<li><span class="stability_1"><a href="#readableflatmapfn-options"><code>readable.flatMap(fn[, options])</code></a></span></li> 558<li><span class="stability_1"><a href="#readabledroplimit-options"><code>readable.drop(limit[, options])</code></a></span></li> 559<li><span class="stability_1"><a href="#readabletakelimit-options"><code>readable.take(limit[, options])</code></a></span></li> 560<li><span class="stability_1"><a href="#readableasindexedpairsoptions"><code>readable.asIndexedPairs([options])</code></a></span></li> 561<li><span class="stability_1"><a href="#readablereducefn-initial-options"><code>readable.reduce(fn[, initial[, options]])</code></a></span></li> 562</ul> 563</li> 564</ul> 565</li> 566<li><a href="#duplex-and-transform-streams">Duplex and transform streams</a> 567<ul> 568<li><a href="#class-streamduplex">Class: <code>stream.Duplex</code></a> 569<ul> 570<li><a href="#duplexallowhalfopen"><code>duplex.allowHalfOpen</code></a></li> 571</ul> 572</li> 573<li><a href="#class-streamtransform">Class: <code>stream.Transform</code></a> 574<ul> 575<li><a href="#transformdestroyerror"><code>transform.destroy([error])</code></a></li> 576</ul> 577</li> 578</ul> 579</li> 580<li><a href="#streamfinishedstream-options-callback"><code>stream.finished(stream[, options], callback)</code></a></li> 581<li><a href="#streampipelinesource-transforms-destination-callback"><code>stream.pipeline(source[, ...transforms], destination, callback)</code></a></li> 582<li><a href="#streampipelinestreams-callback"><code>stream.pipeline(streams, callback)</code></a></li> 583<li><span class="stability_1"><a href="#streamcomposestreams"><code>stream.compose(...streams)</code></a></span></li> 584<li><a href="#streamreadablefromiterable-options"><code>stream.Readable.from(iterable[, options])</code></a></li> 585<li><span class="stability_1"><a href="#streamreadablefromwebreadablestream-options"><code>stream.Readable.fromWeb(readableStream[, options])</code></a></span></li> 586<li><span class="stability_1"><a href="#streamreadableisdisturbedstream"><code>stream.Readable.isDisturbed(stream)</code></a></span></li> 587<li><span class="stability_1"><a href="#streamiserroredstream"><code>stream.isErrored(stream)</code></a></span></li> 588<li><span class="stability_1"><a href="#streamisreadablestream"><code>stream.isReadable(stream)</code></a></span></li> 589<li><span class="stability_1"><a href="#streamreadabletowebstreamreadable-options"><code>stream.Readable.toWeb(streamReadable[, options])</code></a></span></li> 590<li><span class="stability_1"><a href="#streamwritablefromwebwritablestream-options"><code>stream.Writable.fromWeb(writableStream[, options])</code></a></span></li> 591<li><span class="stability_1"><a href="#streamwritabletowebstreamwritable"><code>stream.Writable.toWeb(streamWritable)</code></a></span></li> 592<li><a href="#streamduplexfromsrc"><code>stream.Duplex.from(src)</code></a></li> 593<li><span class="stability_1"><a href="#streamduplexfromwebpair-options"><code>stream.Duplex.fromWeb(pair[, options])</code></a></span></li> 594<li><span class="stability_1"><a href="#streamduplextowebstreamduplex"><code>stream.Duplex.toWeb(streamDuplex)</code></a></span></li> 595<li><a href="#streamaddabortsignalsignal-stream"><code>stream.addAbortSignal(signal, stream)</code></a></li> 596<li><a href="#streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark(objectMode)</code></a></li> 597<li><a href="#streamsetdefaulthighwatermarkobjectmode-value"><code>stream.setDefaultHighWaterMark(objectMode, value)</code></a></li> 598</ul> 599</li> 600<li><a href="#api-for-stream-implementers">API for stream implementers</a> 601<ul> 602<li><a href="#simplified-construction">Simplified construction</a></li> 603<li><a href="#implementing-a-writable-stream">Implementing a writable stream</a> 604<ul> 605<li><a href="#new-streamwritableoptions"><code>new stream.Writable([options])</code></a></li> 606<li><a href="#writable_constructcallback"><code>writable._construct(callback)</code></a></li> 607<li><a href="#writable_writechunk-encoding-callback"><code>writable._write(chunk, encoding, callback)</code></a></li> 608<li><a href="#writable_writevchunks-callback"><code>writable._writev(chunks, callback)</code></a></li> 609<li><a href="#writable_destroyerr-callback"><code>writable._destroy(err, callback)</code></a></li> 610<li><a href="#writable_finalcallback"><code>writable._final(callback)</code></a></li> 611<li><a href="#errors-while-writing">Errors while writing</a></li> 612<li><a href="#an-example-writable-stream">An example writable stream</a></li> 613<li><a href="#decoding-buffers-in-a-writable-stream">Decoding buffers in a writable stream</a></li> 614</ul> 615</li> 616<li><a href="#implementing-a-readable-stream">Implementing a readable stream</a> 617<ul> 618<li><a href="#new-streamreadableoptions"><code>new stream.Readable([options])</code></a></li> 619<li><a href="#readable_constructcallback"><code>readable._construct(callback)</code></a></li> 620<li><a href="#readable_readsize"><code>readable._read(size)</code></a></li> 621<li><a href="#readable_destroyerr-callback"><code>readable._destroy(err, callback)</code></a></li> 622<li><a href="#readablepushchunk-encoding"><code>readable.push(chunk[, encoding])</code></a></li> 623<li><a href="#errors-while-reading">Errors while reading</a></li> 624<li><a href="#an-example-counting-stream">An example counting stream</a></li> 625</ul> 626</li> 627<li><a href="#implementing-a-duplex-stream">Implementing a duplex stream</a> 628<ul> 629<li><a href="#new-streamduplexoptions"><code>new stream.Duplex(options)</code></a></li> 630<li><a href="#an-example-duplex-stream">An example duplex stream</a></li> 631<li><a href="#object-mode-duplex-streams">Object mode duplex streams</a></li> 632</ul> 633</li> 634<li><a href="#implementing-a-transform-stream">Implementing a transform stream</a> 635<ul> 636<li><a href="#new-streamtransformoptions"><code>new stream.Transform([options])</code></a></li> 637<li><a href="#event-end_1">Event: <code>'end'</code></a></li> 638<li><a href="#event-finish_1">Event: <code>'finish'</code></a></li> 639<li><a href="#transform_flushcallback"><code>transform._flush(callback)</code></a></li> 640<li><a href="#transform_transformchunk-encoding-callback"><code>transform._transform(chunk, encoding, callback)</code></a></li> 641<li><a href="#class-streampassthrough">Class: <code>stream.PassThrough</code></a></li> 642</ul> 643</li> 644</ul> 645</li> 646<li><a href="#additional-notes">Additional notes</a> 647<ul> 648<li><a href="#streams-compatibility-with-async-generators-and-async-iterators">Streams compatibility with async generators and async iterators</a> 649<ul> 650<li><a href="#consuming-readable-streams-with-async-iterators">Consuming readable streams with async iterators</a></li> 651<li><a href="#creating-readable-streams-with-async-generators">Creating readable streams with async generators</a></li> 652<li><a href="#piping-to-writable-streams-from-async-iterators">Piping to writable streams from async iterators</a></li> 653</ul> 654</li> 655<li><a href="#compatibility-with-older-nodejs-versions">Compatibility with older Node.js versions</a></li> 656<li><a href="#readableread0"><code>readable.read(0)</code></a></li> 657<li><a href="#readablepush"><code>readable.push('')</code></a></li> 658<li><a href="#highwatermark-discrepancy-after-calling-readablesetencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li> 659</ul> 660</li> 661</ul> 662</li> 663</ul></details> 664 665 <div id="apicontent"> 666 <h2>Stream<a class="srclink" href="https://github.com/nodejs/node/blob/1d526a47af29d59ad196c4e05606b0ec6f8090d9/lib/stream.js#L54">[src]</a><span><a class="mark" href="#stream" id="stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream"></a></h2> 667 668<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p> 669<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v18.20.1/lib/stream.js">lib/stream.js</a></p> 670<p>A stream is an abstract interface for working with streaming data in Node.js. 671The <code>node:stream</code> module provides an API for implementing the stream interface.</p> 672<p>There are many stream objects provided by Node.js. For instance, a 673<a href="http.html#class-httpincomingmessage">request to an HTTP server</a> and <a href="process.html#processstdout"><code>process.stdout</code></a> 674are both stream instances.</p> 675<p>Streams can be readable, writable, or both. All streams are instances of 676<a href="events.html#class-eventemitter"><code>EventEmitter</code></a>.</p> 677<p>To access the <code>node:stream</code> module:</p> 678<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);</code> <button class="copy-button">copy</button></pre> 679<p>The <code>node:stream</code> module is useful for creating new types of stream instances. 680It is usually not necessary to use the <code>node:stream</code> module to consume streams.</p> 681<section><h3>Organization of this document<span><a class="mark" href="#organization-of-this-document" id="organization-of-this-document">#</a></span><a aria-hidden="true" class="legacy" id="stream_organization_of_this_document"></a></h3> 682<p>This document contains two primary sections and a third section for notes. The 683first section explains how to use existing streams within an application. The 684second section explains how to create new types of streams.</p> 685</section><section><h3>Types of streams<span><a class="mark" href="#types-of-streams" id="types-of-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_types_of_streams"></a></h3> 686<p>There are four fundamental stream types within Node.js:</p> 687<ul> 688<li><a href="#class-streamwritable"><code>Writable</code></a>: streams to which data can be written (for example, 689<a href="fs.html#fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>).</li> 690<li><a href="#class-streamreadable"><code>Readable</code></a>: streams from which data can be read (for example, 691<a href="fs.html#fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>).</li> 692<li><a href="#class-streamduplex"><code>Duplex</code></a>: streams that are both <code>Readable</code> and <code>Writable</code> (for example, 693<a href="net.html#class-netsocket"><code>net.Socket</code></a>).</li> 694<li><a href="#class-streamtransform"><code>Transform</code></a>: <code>Duplex</code> streams that can modify or transform the data as it 695is written and read (for example, <a href="zlib.html#zlibcreatedeflateoptions"><code>zlib.createDeflate()</code></a>).</li> 696</ul> 697<p>Additionally, this module includes the utility functions 698<a href="#streampipelinesource-transforms-destination-callback"><code>stream.pipeline()</code></a>, <a href="#streamfinishedstream-options-callback"><code>stream.finished()</code></a>, <a href="#streamreadablefromiterable-options"><code>stream.Readable.from()</code></a> 699and <a href="#streamaddabortsignalsignal-stream"><code>stream.addAbortSignal()</code></a>.</p> 700<h4>Streams Promises API<span><a class="mark" href="#streams-promises-api" id="streams-promises-api">#</a></span><a aria-hidden="true" class="legacy" id="stream_streams_promises_api"></a></h4> 701<div class="api_metadata"> 702<span>Added in: v15.0.0</span> 703</div> 704<p>The <code>stream/promises</code> API provides an alternative set of asynchronous utility 705functions for streams that return <code>Promise</code> objects rather than using 706callbacks. The API is accessible via <code>require('node:stream/promises')</code> 707or <code>require('node:stream').promises</code>.</p> 708<h4><code>stream.pipeline(source[, ...transforms], destination[, options])</code><span><a class="mark" href="#streampipelinesource-transforms-destination-options" id="streampipelinesource-transforms-destination-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_source_transforms_destination_options"></a></h4> 709<h4><code>stream.pipeline(streams[, options])</code><span><a class="mark" href="#streampipelinestreams-options" id="streampipelinestreams-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_streams_options"></a></h4> 710<div class="api_metadata"> 711<span>Added in: v15.0.0</span> 712</div> 713<ul> 714<li><code>streams</code> <a href="stream.html#stream" class="type"><Stream[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable[]></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a></li> 715<li><code>source</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> 716<ul> 717<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 718</ul> 719</li> 720<li><code>...transforms</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> 721<ul> 722<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 723<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 724</ul> 725</li> 726<li><code>destination</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> 727<ul> 728<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 729<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 730</ul> 731</li> 732<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 733<ul> 734<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li> 735<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 736</ul> 737</li> 738<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills when the pipeline is complete.</li> 739</ul> 740 741<pre class="with-62-chars"><input class="js-flavor-selector" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>); 742<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 743<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>); 744 745<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 746 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 747 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 748 zlib.<span class="hljs-title function_">createGzip</span>(), 749 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 750 ); 751 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 752} 753 754<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>; 755<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 756<span class="hljs-keyword">import</span> { createGzip } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>; 757 758<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 759 <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 760 <span class="hljs-title function_">createGzip</span>(), 761 <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 762); 763<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);</code><button class="copy-button">copy</button></pre> 764<p>To use an <code>AbortSignal</code>, pass it inside an options object, as the last argument. 765When the signal is aborted, <code>destroy</code> will be called on the underlying pipeline, 766with an <code>AbortError</code>.</p> 767 768<pre class="with-62-chars"><input class="js-flavor-selector" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>); 769<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 770<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>); 771 772<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 773 <span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 774 <span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>; 775 776 <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>()); 777 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 778 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 779 zlib.<span class="hljs-title function_">createGzip</span>(), 780 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 781 { signal }, 782 ); 783} 784 785<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>); <span class="hljs-comment">// AbortError</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>; 786<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 787<span class="hljs-keyword">import</span> { createGzip } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>; 788 789<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 790<span class="hljs-keyword">const</span> { signal } = ac; 791<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>()); 792<span class="hljs-keyword">try</span> { 793 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 794 <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 795 <span class="hljs-title function_">createGzip</span>(), 796 <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 797 { signal }, 798 ); 799} <span class="hljs-keyword">catch</span> (err) { 800 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err); <span class="hljs-comment">// AbortError</span> 801}</code><button class="copy-button">copy</button></pre> 802<p>The <code>pipeline</code> API also supports async generators:</p> 803 804<pre class="with-62-chars"><input class="js-flavor-selector" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>); 805<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 806 807<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 808 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 809 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'lowercase.txt'</span>), 810 <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* (source, { signal }) { 811 source.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); <span class="hljs-comment">// Work with strings rather than `Buffer`s.</span> 812 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) { 813 <span class="hljs-keyword">yield</span> <span class="hljs-keyword">await</span> <span class="hljs-title function_">processChunk</span>(chunk, { signal }); 814 } 815 }, 816 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>), 817 ); 818 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 819} 820 821<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>; 822<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 823 824<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 825 <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'lowercase.txt'</span>), 826 <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* (source, { signal }) { 827 source.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); <span class="hljs-comment">// Work with strings rather than `Buffer`s.</span> 828 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) { 829 <span class="hljs-keyword">yield</span> <span class="hljs-keyword">await</span> <span class="hljs-title function_">processChunk</span>(chunk, { signal }); 830 } 831 }, 832 <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>), 833); 834<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);</code><button class="copy-button">copy</button></pre> 835<p>Remember to handle the <code>signal</code> argument passed into the async generator. 836Especially in the case where the async generator is the source for the 837pipeline (i.e. first argument) or the pipeline will never complete.</p> 838 839<pre class="with-53-chars"><input class="js-flavor-selector" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>); 840<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 841 842<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 843 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 844 <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* ({ signal }) { 845 <span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningfn</span>({ signal }); 846 <span class="hljs-keyword">yield</span> <span class="hljs-string">'asd'</span>; 847 }, 848 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>), 849 ); 850 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 851} 852 853<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>; 854<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 855<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 856 <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* ({ signal }) { 857 <span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningfn</span>({ signal }); 858 <span class="hljs-keyword">yield</span> <span class="hljs-string">'asd'</span>; 859 }, 860 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>), 861); 862<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);</code><button class="copy-button">copy</button></pre> 863<p>The <code>pipeline</code> API provides <a href="#streampipelinesource-transforms-destination-callback">callback version</a>:</p> 864<h4><code>stream.finished(stream[, options])</code><span><a class="mark" href="#streamfinishedstream-options" id="streamfinishedstream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_finished_stream_options"></a></h4> 865<div class="api_metadata"> 866<span>Added in: v15.0.0</span> 867</div> 868<ul> 869<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a></li> 870<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 871<ul> 872<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> 873<li><code>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> 874<li><code>writable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> 875<li><code>signal</code>: <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> 876</ul> 877</li> 878<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> Fulfills when the stream is no 879longer readable or writable.</li> 880</ul> 881 882<pre class="with-53-chars"><input class="js-flavor-selector" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { finished } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>); 883<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 884 885<span class="hljs-keyword">const</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>); 886 887<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 888 <span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(rs); 889 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>); 890} 891 892<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>); 893rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { finished } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>; 894<span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 895 896<span class="hljs-keyword">const</span> rs = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>); 897 898<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 899 <span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(rs); 900 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>); 901} 902 903<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>); 904rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code><button class="copy-button">copy</button></pre> 905<p>The <code>finished</code> API also provides a <a href="#streamfinishedstream-options-callback">callback version</a>.</p> 906<h4>Object mode<span><a class="mark" href="#object-mode" id="object-mode">#</a></span><a aria-hidden="true" class="legacy" id="stream_object_mode"></a></h4> 907<p>All streams created by Node.js APIs operate exclusively on strings and <code>Buffer</code> 908(or <code>Uint8Array</code>) objects. It is possible, however, for stream implementations 909to work with other types of JavaScript values (with the exception of <code>null</code>, 910which serves a special purpose within streams). Such streams are considered to 911operate in "object mode".</p> 912<p>Stream instances are switched into object mode using the <code>objectMode</code> option 913when the stream is created. Attempting to switch an existing stream into 914object mode is not safe.</p> 915<h4>Buffering<span><a class="mark" href="#buffering" id="buffering">#</a></span><a aria-hidden="true" class="legacy" id="stream_buffering"></a></h4> 916 917<p>Both <a href="#class-streamwritable"><code>Writable</code></a> and <a href="#class-streamreadable"><code>Readable</code></a> streams will store data in an internal 918buffer.</p> 919<p>The amount of data potentially buffered depends on the <code>highWaterMark</code> option 920passed into the stream's constructor. For normal streams, the <code>highWaterMark</code> 921option specifies a <a href="#highwatermark-discrepancy-after-calling-readablesetencoding">total number of bytes</a>. For streams operating 922in object mode, the <code>highWaterMark</code> specifies a total number of objects.</p> 923<p>Data is buffered in <code>Readable</code> streams when the implementation calls 924<a href="#readablepushchunk-encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not 925call <a href="#readablereadsize"><code>stream.read()</code></a>, the data will sit in the internal 926queue until it is consumed.</p> 927<p>Once the total size of the internal read buffer reaches the threshold specified 928by <code>highWaterMark</code>, the stream will temporarily stop reading data from the 929underlying resource until the data currently buffered can be consumed (that is, 930the stream will stop calling the internal <a href="#readable_readsize"><code>readable._read()</code></a> method that is 931used to fill the read buffer).</p> 932<p>Data is buffered in <code>Writable</code> streams when the 933<a href="#writablewritechunk-encoding-callback"><code>writable.write(chunk)</code></a> method is called repeatedly. While the 934total size of the internal write buffer is below the threshold set by 935<code>highWaterMark</code>, calls to <code>writable.write()</code> will return <code>true</code>. Once 936the size of the internal buffer reaches or exceeds the <code>highWaterMark</code>, <code>false</code> 937will be returned.</p> 938<p>A key goal of the <code>stream</code> API, particularly the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> method, 939is to limit the buffering of data to acceptable levels such that sources and 940destinations of differing speeds will not overwhelm the available memory.</p> 941<p>The <code>highWaterMark</code> option is a threshold, not a limit: it dictates the amount 942of data that a stream buffers before it stops asking for more data. It does not 943enforce a strict memory limitation in general. Specific stream implementations 944may choose to enforce stricter limits but doing so is optional.</p> 945<p>Because <a href="#class-streamduplex"><code>Duplex</code></a> and <a href="#class-streamtransform"><code>Transform</code></a> streams are both <code>Readable</code> and 946<code>Writable</code>, each maintains <em>two</em> separate internal buffers used for reading and 947writing, allowing each side to operate independently of the other while 948maintaining an appropriate and efficient flow of data. For example, 949<a href="net.html#class-netsocket"><code>net.Socket</code></a> instances are <a href="#class-streamduplex"><code>Duplex</code></a> streams whose <code>Readable</code> side allows 950consumption of data received <em>from</em> the socket and whose <code>Writable</code> side allows 951writing data <em>to</em> the socket. Because data may be written to the socket at a 952faster or slower rate than data is received, each side should 953operate (and buffer) independently of the other.</p> 954<p>The mechanics of the internal buffering are an internal implementation detail 955and may be changed at any time. However, for certain advanced implementations, 956the internal buffers can be retrieved using <code>writable.writableBuffer</code> or 957<code>readable.readableBuffer</code>. Use of these undocumented properties is discouraged.</p> 958</section><section><h3>API for stream consumers<span><a class="mark" href="#api-for-stream-consumers" id="api-for-stream-consumers">#</a></span><a aria-hidden="true" class="legacy" id="stream_api_for_stream_consumers"></a></h3> 959 960<p>Almost all Node.js applications, no matter how simple, use streams in some 961manner. The following is an example of using streams in a Node.js application 962that implements an HTTP server:</p> 963<pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>); 964 965<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { 966 <span class="hljs-comment">// `req` is an http.IncomingMessage, which is a readable stream.</span> 967 <span class="hljs-comment">// `res` is an http.ServerResponse, which is a writable stream.</span> 968 969 <span class="hljs-keyword">let</span> body = <span class="hljs-string">''</span>; 970 <span class="hljs-comment">// Get the data as utf8 strings.</span> 971 <span class="hljs-comment">// If an encoding is not set, Buffer objects will be received.</span> 972 req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); 973 974 <span class="hljs-comment">// Readable streams emit 'data' events once a listener is added.</span> 975 req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 976 body += chunk; 977 }); 978 979 <span class="hljs-comment">// The 'end' event indicates that the entire body has been received.</span> 980 req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 981 <span class="hljs-keyword">try</span> { 982 <span class="hljs-keyword">const</span> data = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(body); 983 <span class="hljs-comment">// Write back something interesting to the user:</span> 984 res.<span class="hljs-title function_">write</span>(<span class="hljs-keyword">typeof</span> data); 985 res.<span class="hljs-title function_">end</span>(); 986 } <span class="hljs-keyword">catch</span> (er) { 987 <span class="hljs-comment">// uh oh! bad json!</span> 988 res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">400</span>; 989 <span class="hljs-keyword">return</span> res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`error: <span class="hljs-subst">${er.message}</span>`</span>); 990 } 991 }); 992}); 993 994server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>); 995 996<span class="hljs-comment">// $ curl localhost:1337 -d "{}"</span> 997<span class="hljs-comment">// object</span> 998<span class="hljs-comment">// $ curl localhost:1337 -d "\"foo\""</span> 999<span class="hljs-comment">// string</span> 1000<span class="hljs-comment">// $ curl localhost:1337 -d "not json"</span> 1001<span class="hljs-comment">// error: Unexpected token 'o', "not json" is not valid JSON</span></code> <button class="copy-button">copy</button></pre> 1002<p><a href="#class-streamwritable"><code>Writable</code></a> streams (such as <code>res</code> in the example) expose methods such as 1003<code>write()</code> and <code>end()</code> that are used to write data onto the stream.</p> 1004<p><a href="#class-streamreadable"><code>Readable</code></a> streams use the <a href="events.html#class-eventemitter"><code>EventEmitter</code></a> API for notifying application 1005code when data is available to be read off the stream. That available data can 1006be read from the stream in multiple ways.</p> 1007<p>Both <a href="#class-streamwritable"><code>Writable</code></a> and <a href="#class-streamreadable"><code>Readable</code></a> streams use the <a href="events.html#class-eventemitter"><code>EventEmitter</code></a> API in 1008various ways to communicate the current state of the stream.</p> 1009<p><a href="#class-streamduplex"><code>Duplex</code></a> and <a href="#class-streamtransform"><code>Transform</code></a> streams are both <a href="#class-streamwritable"><code>Writable</code></a> and 1010<a href="#class-streamreadable"><code>Readable</code></a>.</p> 1011<p>Applications that are either writing data to or consuming data from a stream 1012are not required to implement the stream interfaces directly and will generally 1013have no reason to call <code>require('node:stream')</code>.</p> 1014<p>Developers wishing to implement new types of streams should refer to the 1015section <a href="#api-for-stream-implementers">API for stream implementers</a>.</p> 1016<h4>Writable streams<span><a class="mark" href="#writable-streams" id="writable-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_streams"></a></h4> 1017<p>Writable streams are an abstraction for a <em>destination</em> to which data is 1018written.</p> 1019<p>Examples of <a href="#class-streamwritable"><code>Writable</code></a> streams include:</p> 1020<ul> 1021<li><a href="http.html#class-httpclientrequest">HTTP requests, on the client</a></li> 1022<li><a href="http.html#class-httpserverresponse">HTTP responses, on the server</a></li> 1023<li><a href="fs.html#class-fswritestream">fs write streams</a></li> 1024<li><a href="zlib.html">zlib streams</a></li> 1025<li><a href="crypto.html">crypto streams</a></li> 1026<li><a href="net.html#class-netsocket">TCP sockets</a></li> 1027<li><a href="child_process.html#subprocessstdin">child process stdin</a></li> 1028<li><a href="process.html#processstdout"><code>process.stdout</code></a>, <a href="process.html#processstderr"><code>process.stderr</code></a></li> 1029</ul> 1030<p>Some of these examples are actually <a href="#class-streamduplex"><code>Duplex</code></a> streams that implement the 1031<a href="#class-streamwritable"><code>Writable</code></a> interface.</p> 1032<p>All <a href="#class-streamwritable"><code>Writable</code></a> streams implement the interface defined by the 1033<code>stream.Writable</code> class.</p> 1034<p>While specific instances of <a href="#class-streamwritable"><code>Writable</code></a> streams may differ in various ways, 1035all <code>Writable</code> streams follow the same fundamental usage pattern as illustrated 1036in the example below:</p> 1037<pre><code class="language-js"><span class="hljs-keyword">const</span> myStream = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 1038myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data'</span>); 1039myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some more data'</span>); 1040myStream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'done writing data'</span>);</code> <button class="copy-button">copy</button></pre> 1041<h5>Class: <code>stream.Writable</code><span><a class="mark" href="#class-streamwritable" id="class-streamwritable">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_writable"></a></h5> 1042<div class="api_metadata"> 1043<span>Added in: v0.9.4</span> 1044</div> 1045 1046<h6>Event: <code>'close'</code><span><a class="mark" href="#event-close" id="event-close">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_close"></a></h6> 1047<div class="api_metadata"> 1048<details class="changelog"><summary>History</summary> 1049<table> 1050<tbody><tr><th>Version</th><th>Changes</th></tr> 1051<tr><td>v10.0.0</td> 1052<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> 1053<tr><td>v0.9.4</td> 1054<td><p><span>Added in: v0.9.4</span></p></td></tr> 1055</tbody></table> 1056</details> 1057</div> 1058<p>The <code>'close'</code> event is emitted when the stream and any of its underlying 1059resources (a file descriptor, for example) have been closed. The event indicates 1060that no more events will be emitted, and no further computation will occur.</p> 1061<p>A <a href="#class-streamwritable"><code>Writable</code></a> stream will always emit the <code>'close'</code> event if it is 1062created with the <code>emitClose</code> option.</p> 1063<h6>Event: <code>'drain'</code><span><a class="mark" href="#event-drain" id="event-drain">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_drain"></a></h6> 1064<div class="api_metadata"> 1065<span>Added in: v0.9.4</span> 1066</div> 1067<p>If a call to <a href="#writablewritechunk-encoding-callback"><code>stream.write(chunk)</code></a> returns <code>false</code>, the 1068<code>'drain'</code> event will be emitted when it is appropriate to resume writing data 1069to the stream.</p> 1070<pre><code class="language-js"><span class="hljs-comment">// Write the data to the supplied writable stream one million times.</span> 1071<span class="hljs-comment">// Be attentive to back-pressure.</span> 1072<span class="hljs-keyword">function</span> <span class="hljs-title function_">writeOneMillionTimes</span>(<span class="hljs-params">writer, data, encoding, callback</span>) { 1073 <span class="hljs-keyword">let</span> i = <span class="hljs-number">1000000</span>; 1074 <span class="hljs-title function_">write</span>(); 1075 <span class="hljs-keyword">function</span> <span class="hljs-title function_">write</span>(<span class="hljs-params"></span>) { 1076 <span class="hljs-keyword">let</span> ok = <span class="hljs-literal">true</span>; 1077 <span class="hljs-keyword">do</span> { 1078 i--; 1079 <span class="hljs-keyword">if</span> (i === <span class="hljs-number">0</span>) { 1080 <span class="hljs-comment">// Last time!</span> 1081 writer.<span class="hljs-title function_">write</span>(data, encoding, callback); 1082 } <span class="hljs-keyword">else</span> { 1083 <span class="hljs-comment">// See if we should continue, or wait.</span> 1084 <span class="hljs-comment">// Don't pass the callback, because we're not done yet.</span> 1085 ok = writer.<span class="hljs-title function_">write</span>(data, encoding); 1086 } 1087 } <span class="hljs-keyword">while</span> (i > <span class="hljs-number">0</span> && ok); 1088 <span class="hljs-keyword">if</span> (i > <span class="hljs-number">0</span>) { 1089 <span class="hljs-comment">// Had to stop early!</span> 1090 <span class="hljs-comment">// Write some more once it drains.</span> 1091 writer.<span class="hljs-title function_">once</span>(<span class="hljs-string">'drain'</span>, write); 1092 } 1093 } 1094}</code> <button class="copy-button">copy</button></pre> 1095<h6>Event: <code>'error'</code><span><a class="mark" href="#event-error" id="event-error">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_error"></a></h6> 1096<div class="api_metadata"> 1097<span>Added in: v0.9.4</span> 1098</div> 1099<ul> 1100<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1101</ul> 1102<p>The <code>'error'</code> event is emitted if an error occurred while writing or piping 1103data. The listener callback is passed a single <code>Error</code> argument when called.</p> 1104<p>The stream is closed when the <code>'error'</code> event is emitted unless the 1105<a href="#new-streamwritableoptions"><code>autoDestroy</code></a> option was set to <code>false</code> when creating the 1106stream.</p> 1107<p>After <code>'error'</code>, no further events other than <code>'close'</code> <em>should</em> be emitted 1108(including <code>'error'</code> events).</p> 1109<h6>Event: <code>'finish'</code><span><a class="mark" href="#event-finish" id="event-finish">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_finish"></a></h6> 1110<div class="api_metadata"> 1111<span>Added in: v0.9.4</span> 1112</div> 1113<p>The <code>'finish'</code> event is emitted after the <a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> method 1114has been called, and all data has been flushed to the underlying system.</p> 1115<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 1116<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">100</span>; i++) { 1117 writer.<span class="hljs-title function_">write</span>(<span class="hljs-string">`hello, #<span class="hljs-subst">${i}</span>!\n`</span>); 1118} 1119writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'finish'</span>, <span class="hljs-function">() =></span> { 1120 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'All writes are now complete.'</span>); 1121}); 1122writer.<span class="hljs-title function_">end</span>(<span class="hljs-string">'This is the end\n'</span>);</code> <button class="copy-button">copy</button></pre> 1123<h6>Event: <code>'pipe'</code><span><a class="mark" href="#event-pipe" id="event-pipe">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_pipe"></a></h6> 1124<div class="api_metadata"> 1125<span>Added in: v0.9.4</span> 1126</div> 1127<ul> 1128<li><code>src</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a> source stream that is piping to this writable</li> 1129</ul> 1130<p>The <code>'pipe'</code> event is emitted when the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> method is called on 1131a readable stream, adding this writable to its set of destinations.</p> 1132<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 1133<span class="hljs-keyword">const</span> reader = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1134writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'pipe'</span>, <span class="hljs-function">(<span class="hljs-params">src</span>) =></span> { 1135 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Something is piping into the writer.'</span>); 1136 assert.<span class="hljs-title function_">equal</span>(src, reader); 1137}); 1138reader.<span class="hljs-title function_">pipe</span>(writer);</code> <button class="copy-button">copy</button></pre> 1139<h6>Event: <code>'unpipe'</code><span><a class="mark" href="#event-unpipe" id="event-unpipe">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_unpipe"></a></h6> 1140<div class="api_metadata"> 1141<span>Added in: v0.9.4</span> 1142</div> 1143<ul> 1144<li><code>src</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a> The source stream that 1145<a href="#readableunpipedestination">unpiped</a> this writable</li> 1146</ul> 1147<p>The <code>'unpipe'</code> event is emitted when the <a href="#readableunpipedestination"><code>stream.unpipe()</code></a> method is called 1148on a <a href="#class-streamreadable"><code>Readable</code></a> stream, removing this <a href="#class-streamwritable"><code>Writable</code></a> from its set of 1149destinations.</p> 1150<p>This is also emitted in case this <a href="#class-streamwritable"><code>Writable</code></a> stream emits an error when a 1151<a href="#class-streamreadable"><code>Readable</code></a> stream pipes into it.</p> 1152<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 1153<span class="hljs-keyword">const</span> reader = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1154writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unpipe'</span>, <span class="hljs-function">(<span class="hljs-params">src</span>) =></span> { 1155 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Something has stopped piping into the writer.'</span>); 1156 assert.<span class="hljs-title function_">equal</span>(src, reader); 1157}); 1158reader.<span class="hljs-title function_">pipe</span>(writer); 1159reader.<span class="hljs-title function_">unpipe</span>(writer);</code> <button class="copy-button">copy</button></pre> 1160<h6><code>writable.cork()</code><span><a class="mark" href="#writablecork" id="writablecork">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_cork"></a></h6> 1161<div class="api_metadata"> 1162<span>Added in: v0.11.2</span> 1163</div> 1164<p>The <code>writable.cork()</code> method forces all written data to be buffered in memory. 1165The buffered data will be flushed when either the <a href="#writableuncork"><code>stream.uncork()</code></a> or 1166<a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> methods are called.</p> 1167<p>The primary intent of <code>writable.cork()</code> is to accommodate a situation in which 1168several small chunks are written to the stream in rapid succession. Instead of 1169immediately forwarding them to the underlying destination, <code>writable.cork()</code> 1170buffers all the chunks until <code>writable.uncork()</code> is called, which will pass them 1171all to <code>writable._writev()</code>, if present. This prevents a head-of-line blocking 1172situation where data is being buffered while waiting for the first small chunk 1173to be processed. However, use of <code>writable.cork()</code> without implementing 1174<code>writable._writev()</code> may have an adverse effect on throughput.</p> 1175<p>See also: <a href="#writableuncork"><code>writable.uncork()</code></a>, <a href="#writable_writevchunks-callback"><code>writable._writev()</code></a>.</p> 1176<h6><code>writable.destroy([error])</code><span><a class="mark" href="#writabledestroyerror" id="writabledestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_destroy_error"></a></h6> 1177<div class="api_metadata"> 1178<details class="changelog"><summary>History</summary> 1179<table> 1180<tbody><tr><th>Version</th><th>Changes</th></tr> 1181<tr><td>v14.0.0</td> 1182<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr> 1183<tr><td>v8.0.0</td> 1184<td><p><span>Added in: v8.0.0</span></p></td></tr> 1185</tbody></table> 1186</details> 1187</div> 1188<ul> 1189<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Optional, an error to emit with <code>'error'</code> event.</li> 1190<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1191</ul> 1192<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code> 1193event (unless <code>emitClose</code> is set to <code>false</code>). After this call, the writable 1194stream has ended and subsequent calls to <code>write()</code> or <code>end()</code> will result in 1195an <code>ERR_STREAM_DESTROYED</code> error. 1196This is a destructive and immediate way to destroy a stream. Previous calls to 1197<code>write()</code> may not have drained, and may trigger an <code>ERR_STREAM_DESTROYED</code> error. 1198Use <code>end()</code> instead of destroy if data should flush before close, or wait for 1199the <code>'drain'</code> event before destroying the stream.</p> 1200<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 1201 1202<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 1203 1204<span class="hljs-keyword">const</span> fooErr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'foo error'</span>); 1205myStream.<span class="hljs-title function_">destroy</span>(fooErr); 1206myStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">fooErr</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(fooErr.<span class="hljs-property">message</span>)); <span class="hljs-comment">// foo error</span></code> <button class="copy-button">copy</button></pre> 1207<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 1208 1209<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 1210 1211myStream.<span class="hljs-title function_">destroy</span>(); 1212myStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">wontHappen</span>(<span class="hljs-params"></span>) {});</code> <button class="copy-button">copy</button></pre> 1213<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 1214 1215<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 1216myStream.<span class="hljs-title function_">destroy</span>(); 1217 1218myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error.<span class="hljs-property">code</span>)); 1219<span class="hljs-comment">// ERR_STREAM_DESTROYED</span></code> <button class="copy-button">copy</button></pre> 1220<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no 1221further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p> 1222<p>Implementors should not override this method, 1223but instead implement <a href="#writable_destroyerr-callback"><code>writable._destroy()</code></a>.</p> 1224<h6><code>writable.closed</code><span><a class="mark" href="#writableclosed" id="writableclosed">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_closed"></a></h6> 1225<div class="api_metadata"> 1226<span>Added in: v18.0.0</span> 1227</div> 1228<ul> 1229<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1230</ul> 1231<p>Is <code>true</code> after <code>'close'</code> has been emitted.</p> 1232<h6><code>writable.destroyed</code><span><a class="mark" href="#writabledestroyed" id="writabledestroyed">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_destroyed"></a></h6> 1233<div class="api_metadata"> 1234<span>Added in: v8.0.0</span> 1235</div> 1236<ul> 1237<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1238</ul> 1239<p>Is <code>true</code> after <a href="#writabledestroyerror"><code>writable.destroy()</code></a> has been called.</p> 1240<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 1241 1242<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 1243 1244<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myStream.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// false</span> 1245myStream.<span class="hljs-title function_">destroy</span>(); 1246<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myStream.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre> 1247<h6><code>writable.end([chunk[, encoding]][, callback])</code><span><a class="mark" href="#writableendchunk-encoding-callback" id="writableendchunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_end_chunk_encoding_callback"></a></h6> 1248<div class="api_metadata"> 1249<details class="changelog"><summary>History</summary> 1250<table> 1251<tbody><tr><th>Version</th><th>Changes</th></tr> 1252<tr><td>v15.0.0</td> 1253<td><p>The <code>callback</code> is invoked before 'finish' or on error.</p></td></tr> 1254<tr><td>v14.0.0</td> 1255<td><p>The <code>callback</code> is invoked if 'finish' or 'error' is emitted.</p></td></tr> 1256<tr><td>v10.0.0</td> 1257<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr> 1258<tr><td>v8.0.0</td> 1259<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 1260<tr><td>v0.9.4</td> 1261<td><p><span>Added in: v0.9.4</span></p></td></tr> 1262</tbody></table> 1263</details> 1264</div> 1265<ul> 1266<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data to write. For streams 1267not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or 1268<code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value 1269other than <code>null</code>.</li> 1270<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding if <code>chunk</code> is a string</li> 1271<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback for when the stream is finished.</li> 1272<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1273</ul> 1274<p>Calling the <code>writable.end()</code> method signals that no more data will be written 1275to the <a href="#class-streamwritable"><code>Writable</code></a>. The optional <code>chunk</code> and <code>encoding</code> arguments allow one 1276final additional chunk of data to be written immediately before closing the 1277stream.</p> 1278<p>Calling the <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> method after calling 1279<a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> will raise an error.</p> 1280<pre><code class="language-js"><span class="hljs-comment">// Write 'hello, ' and then end with 'world!'.</span> 1281<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 1282<span class="hljs-keyword">const</span> file = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'example.txt'</span>); 1283file.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello, '</span>); 1284file.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world!'</span>); 1285<span class="hljs-comment">// Writing more now is not allowed!</span></code> <button class="copy-button">copy</button></pre> 1286<h6><code>writable.setDefaultEncoding(encoding)</code><span><a class="mark" href="#writablesetdefaultencodingencoding" id="writablesetdefaultencodingencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_setdefaultencoding_encoding"></a></h6> 1287<div class="api_metadata"> 1288<details class="changelog"><summary>History</summary> 1289<table> 1290<tbody><tr><th>Version</th><th>Changes</th></tr> 1291<tr><td>v6.1.0</td> 1292<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr> 1293<tr><td>v0.11.15</td> 1294<td><p><span>Added in: v0.11.15</span></p></td></tr> 1295</tbody></table> 1296</details> 1297</div> 1298<ul> 1299<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The new default encoding</li> 1300<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1301</ul> 1302<p>The <code>writable.setDefaultEncoding()</code> method sets the default <code>encoding</code> for a 1303<a href="#class-streamwritable"><code>Writable</code></a> stream.</p> 1304<h6><code>writable.uncork()</code><span><a class="mark" href="#writableuncork" id="writableuncork">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_uncork"></a></h6> 1305<div class="api_metadata"> 1306<span>Added in: v0.11.2</span> 1307</div> 1308<p>The <code>writable.uncork()</code> method flushes all data buffered since 1309<a href="#writablecork"><code>stream.cork()</code></a> was called.</p> 1310<p>When using <a href="#writablecork"><code>writable.cork()</code></a> and <code>writable.uncork()</code> to manage the buffering 1311of writes to a stream, defer calls to <code>writable.uncork()</code> using 1312<code>process.nextTick()</code>. Doing so allows batching of all 1313<code>writable.write()</code> calls that occur within a given Node.js event loop phase.</p> 1314<pre><code class="language-js">stream.<span class="hljs-title function_">cork</span>(); 1315stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some '</span>); 1316stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'data '</span>); 1317process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> stream.<span class="hljs-title function_">uncork</span>());</code> <button class="copy-button">copy</button></pre> 1318<p>If the <a href="#writablecork"><code>writable.cork()</code></a> method is called multiple times on a stream, the 1319same number of calls to <code>writable.uncork()</code> must be called to flush the buffered 1320data.</p> 1321<pre><code class="language-js">stream.<span class="hljs-title function_">cork</span>(); 1322stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some '</span>); 1323stream.<span class="hljs-title function_">cork</span>(); 1324stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'data '</span>); 1325process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> { 1326 stream.<span class="hljs-title function_">uncork</span>(); 1327 <span class="hljs-comment">// The data will not be flushed until uncork() is called a second time.</span> 1328 stream.<span class="hljs-title function_">uncork</span>(); 1329});</code> <button class="copy-button">copy</button></pre> 1330<p>See also: <a href="#writablecork"><code>writable.cork()</code></a>.</p> 1331<h6><code>writable.writable</code><span><a class="mark" href="#writablewritable" id="writablewritable">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writable"></a></h6> 1332<div class="api_metadata"> 1333<span>Added in: v11.4.0</span> 1334</div> 1335<ul> 1336<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1337</ul> 1338<p>Is <code>true</code> if it is safe to call <a href="#writablewritechunk-encoding-callback"><code>writable.write()</code></a>, which means 1339the stream has not been destroyed, errored, or ended.</p> 1340<h6><code>writable.writableAborted</code><span><a class="mark" href="#writablewritableaborted" id="writablewritableaborted">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableaborted"></a></h6> 1341<div class="api_metadata"> 1342<span>Added in: v18.0.0</span> 1343</div> 1344<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 1345<ul> 1346<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1347</ul> 1348<p>Returns whether the stream was destroyed or errored before emitting <code>'finish'</code>.</p> 1349<h6><code>writable.writableEnded</code><span><a class="mark" href="#writablewritableended" id="writablewritableended">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableended"></a></h6> 1350<div class="api_metadata"> 1351<span>Added in: v12.9.0</span> 1352</div> 1353<ul> 1354<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1355</ul> 1356<p>Is <code>true</code> after <a href="#writableendchunk-encoding-callback"><code>writable.end()</code></a> has been called. This property 1357does not indicate whether the data has been flushed, for this use 1358<a href="#writablewritablefinished"><code>writable.writableFinished</code></a> instead.</p> 1359<h6><code>writable.writableCorked</code><span><a class="mark" href="#writablewritablecorked" id="writablewritablecorked">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablecorked"></a></h6> 1360<div class="api_metadata"> 1361<span>Added in: v13.2.0, v12.16.0</span> 1362</div> 1363<ul> 1364<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 1365</ul> 1366<p>Number of times <a href="#writableuncork"><code>writable.uncork()</code></a> needs to be 1367called in order to fully uncork the stream.</p> 1368<h6><code>writable.errored</code><span><a class="mark" href="#writableerrored" id="writableerrored">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_errored"></a></h6> 1369<div class="api_metadata"> 1370<span>Added in: v18.0.0</span> 1371</div> 1372<ul> 1373<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1374</ul> 1375<p>Returns error if the stream has been destroyed with an error.</p> 1376<h6><code>writable.writableFinished</code><span><a class="mark" href="#writablewritablefinished" id="writablewritablefinished">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablefinished"></a></h6> 1377<div class="api_metadata"> 1378<span>Added in: v12.6.0</span> 1379</div> 1380<ul> 1381<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1382</ul> 1383<p>Is set to <code>true</code> immediately before the <a href="#event-finish"><code>'finish'</code></a> event is emitted.</p> 1384<h6><code>writable.writableHighWaterMark</code><span><a class="mark" href="#writablewritablehighwatermark" id="writablewritablehighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablehighwatermark"></a></h6> 1385<div class="api_metadata"> 1386<span>Added in: v9.3.0</span> 1387</div> 1388<ul> 1389<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1390</ul> 1391<p>Return the value of <code>highWaterMark</code> passed when creating this <code>Writable</code>.</p> 1392<h6><code>writable.writableLength</code><span><a class="mark" href="#writablewritablelength" id="writablewritablelength">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablelength"></a></h6> 1393<div class="api_metadata"> 1394<span>Added in: v9.4.0</span> 1395</div> 1396<ul> 1397<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1398</ul> 1399<p>This property contains the number of bytes (or objects) in the queue 1400ready to be written. The value provides introspection data regarding 1401the status of the <code>highWaterMark</code>.</p> 1402<h6><code>writable.writableNeedDrain</code><span><a class="mark" href="#writablewritableneeddrain" id="writablewritableneeddrain">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableneeddrain"></a></h6> 1403<div class="api_metadata"> 1404<span>Added in: v15.2.0, v14.17.0</span> 1405</div> 1406<ul> 1407<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1408</ul> 1409<p>Is <code>true</code> if the stream's buffer has been full and stream will emit <code>'drain'</code>.</p> 1410<h6><code>writable.writableObjectMode</code><span><a class="mark" href="#writablewritableobjectmode" id="writablewritableobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableobjectmode"></a></h6> 1411<div class="api_metadata"> 1412<span>Added in: v12.3.0</span> 1413</div> 1414<ul> 1415<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1416</ul> 1417<p>Getter for the property <code>objectMode</code> of a given <code>Writable</code> stream.</p> 1418<h6><code>writable.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#writablewritechunk-encoding-callback" id="writablewritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_write_chunk_encoding_callback"></a></h6> 1419<div class="api_metadata"> 1420<details class="changelog"><summary>History</summary> 1421<table> 1422<tbody><tr><th>Version</th><th>Changes</th></tr> 1423<tr><td>v8.0.0</td> 1424<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 1425<tr><td>v6.0.0</td> 1426<td><p>Passing <code>null</code> as the <code>chunk</code> parameter will always be considered invalid now, even in object mode.</p></td></tr> 1427<tr><td>v0.9.4</td> 1428<td><p><span>Added in: v0.9.4</span></p></td></tr> 1429</tbody></table> 1430</details> 1431</div> 1432<ul> 1433<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data to write. For streams 1434not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or 1435<code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value 1436other than <code>null</code>.</li> 1437<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The encoding, if <code>chunk</code> is a string. <strong>Default:</strong> <code>'utf8'</code></li> 1438<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback for when this chunk of data is flushed.</li> 1439<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>false</code> if the stream wishes for the calling code to 1440wait for the <code>'drain'</code> event to be emitted before continuing to write 1441additional data; otherwise <code>true</code>.</li> 1442</ul> 1443<p>The <code>writable.write()</code> method writes some data to the stream, and calls the 1444supplied <code>callback</code> once the data has been fully handled. If an error 1445occurs, the <code>callback</code> will be called with the error as its 1446first argument. The <code>callback</code> is called asynchronously and before <code>'error'</code> is 1447emitted.</p> 1448<p>The return value is <code>true</code> if the internal buffer is less than the 1449<code>highWaterMark</code> configured when the stream was created after admitting <code>chunk</code>. 1450If <code>false</code> is returned, further attempts to write data to the stream should 1451stop until the <a href="#event-drain"><code>'drain'</code></a> event is emitted.</p> 1452<p>While a stream is not draining, calls to <code>write()</code> will buffer <code>chunk</code>, and 1453return false. Once all currently buffered chunks are drained (accepted for 1454delivery by the operating system), the <code>'drain'</code> event will be emitted. 1455Once <code>write()</code> returns false, do not write more chunks 1456until the <code>'drain'</code> event is emitted. While calling <code>write()</code> on a stream that 1457is not draining is allowed, Node.js will buffer all written chunks until 1458maximum memory usage occurs, at which point it will abort unconditionally. 1459Even before it aborts, high memory usage will cause poor garbage collector 1460performance and high RSS (which is not typically released back to the system, 1461even after the memory is no longer required). Since TCP sockets may never 1462drain if the remote peer does not read the data, writing a socket that is 1463not draining may lead to a remotely exploitable vulnerability.</p> 1464<p>Writing data while the stream is not draining is particularly 1465problematic for a <a href="#class-streamtransform"><code>Transform</code></a>, because the <code>Transform</code> streams are paused 1466by default until they are piped or a <code>'data'</code> or <code>'readable'</code> event handler 1467is added.</p> 1468<p>If the data to be written can be generated or fetched on demand, it is 1469recommended to encapsulate the logic into a <a href="#class-streamreadable"><code>Readable</code></a> and use 1470<a href="#readablepipedestination-options"><code>stream.pipe()</code></a>. However, if calling <code>write()</code> is preferred, it is 1471possible to respect backpressure and avoid memory issues using the 1472<a href="#event-drain"><code>'drain'</code></a> event:</p> 1473<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">write</span>(<span class="hljs-params">data, cb</span>) { 1474 <span class="hljs-keyword">if</span> (!stream.<span class="hljs-title function_">write</span>(data)) { 1475 stream.<span class="hljs-title function_">once</span>(<span class="hljs-string">'drain'</span>, cb); 1476 } <span class="hljs-keyword">else</span> { 1477 process.<span class="hljs-title function_">nextTick</span>(cb); 1478 } 1479} 1480 1481<span class="hljs-comment">// Wait for cb to be called before doing any other write.</span> 1482<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-function">() =></span> { 1483 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Write completed, do more writes now.'</span>); 1484});</code> <button class="copy-button">copy</button></pre> 1485<p>A <code>Writable</code> stream in object mode will always ignore the <code>encoding</code> argument.</p> 1486<h4>Readable streams<span><a class="mark" href="#readable-streams" id="readable-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_streams"></a></h4> 1487<p>Readable streams are an abstraction for a <em>source</em> from which data is 1488consumed.</p> 1489<p>Examples of <code>Readable</code> streams include:</p> 1490<ul> 1491<li><a href="http.html#class-httpincomingmessage">HTTP responses, on the client</a></li> 1492<li><a href="http.html#class-httpincomingmessage">HTTP requests, on the server</a></li> 1493<li><a href="fs.html#class-fsreadstream">fs read streams</a></li> 1494<li><a href="zlib.html">zlib streams</a></li> 1495<li><a href="crypto.html">crypto streams</a></li> 1496<li><a href="net.html#class-netsocket">TCP sockets</a></li> 1497<li><a href="child_process.html#subprocessstdout">child process stdout and stderr</a></li> 1498<li><a href="process.html#processstdin"><code>process.stdin</code></a></li> 1499</ul> 1500<p>All <a href="#class-streamreadable"><code>Readable</code></a> streams implement the interface defined by the 1501<code>stream.Readable</code> class.</p> 1502<h5>Two reading modes<span><a class="mark" href="#two-reading-modes" id="two-reading-modes">#</a></span><a aria-hidden="true" class="legacy" id="stream_two_reading_modes"></a></h5> 1503<p><code>Readable</code> streams effectively operate in one of two modes: flowing and 1504paused. These modes are separate from <a href="#object-mode">object mode</a>. 1505A <a href="#class-streamreadable"><code>Readable</code></a> stream can be in object mode or not, regardless of whether 1506it is in flowing mode or paused mode.</p> 1507<ul> 1508<li> 1509<p>In flowing mode, data is read from the underlying system automatically 1510and provided to an application as quickly as possible using events via the 1511<a href="events.html#class-eventemitter"><code>EventEmitter</code></a> interface.</p> 1512</li> 1513<li> 1514<p>In paused mode, the <a href="#readablereadsize"><code>stream.read()</code></a> method must be called 1515explicitly to read chunks of data from the stream.</p> 1516</li> 1517</ul> 1518<p>All <a href="#class-streamreadable"><code>Readable</code></a> streams begin in paused mode but can be switched to flowing 1519mode in one of the following ways:</p> 1520<ul> 1521<li>Adding a <a href="#event-data"><code>'data'</code></a> event handler.</li> 1522<li>Calling the <a href="#readableresume"><code>stream.resume()</code></a> method.</li> 1523<li>Calling the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> method to send the data to a <a href="#class-streamwritable"><code>Writable</code></a>.</li> 1524</ul> 1525<p>The <code>Readable</code> can switch back to paused mode using one of the following:</p> 1526<ul> 1527<li>If there are no pipe destinations, by calling the 1528<a href="#readablepause"><code>stream.pause()</code></a> method.</li> 1529<li>If there are pipe destinations, by removing all pipe destinations. 1530Multiple pipe destinations may be removed by calling the 1531<a href="#readableunpipedestination"><code>stream.unpipe()</code></a> method.</li> 1532</ul> 1533<p>The important concept to remember is that a <code>Readable</code> will not generate data 1534until a mechanism for either consuming or ignoring that data is provided. If 1535the consuming mechanism is disabled or taken away, the <code>Readable</code> will <em>attempt</em> 1536to stop generating the data.</p> 1537<p>For backward compatibility reasons, removing <a href="#event-data"><code>'data'</code></a> event handlers will 1538<strong>not</strong> automatically pause the stream. Also, if there are piped destinations, 1539then calling <a href="#readablepause"><code>stream.pause()</code></a> will not guarantee that the 1540stream will <em>remain</em> paused once those destinations drain and ask for more data.</p> 1541<p>If a <a href="#class-streamreadable"><code>Readable</code></a> is switched into flowing mode and there are no consumers 1542available to handle the data, that data will be lost. This can occur, for 1543instance, when the <code>readable.resume()</code> method is called without a listener 1544attached to the <code>'data'</code> event, or when a <code>'data'</code> event handler is removed 1545from the stream.</p> 1546<p>Adding a <a href="#event-readable"><code>'readable'</code></a> event handler automatically makes the stream 1547stop flowing, and the data has to be consumed via 1548<a href="#readablereadsize"><code>readable.read()</code></a>. If the <a href="#event-readable"><code>'readable'</code></a> event handler is 1549removed, then the stream will start flowing again if there is a 1550<a href="#event-data"><code>'data'</code></a> event handler.</p> 1551<h5>Three states<span><a class="mark" href="#three-states" id="three-states">#</a></span><a aria-hidden="true" class="legacy" id="stream_three_states"></a></h5> 1552<p>The "two modes" of operation for a <code>Readable</code> stream are a simplified 1553abstraction for the more complicated internal state management that is happening 1554within the <code>Readable</code> stream implementation.</p> 1555<p>Specifically, at any given point in time, every <code>Readable</code> is in one of three 1556possible states:</p> 1557<ul> 1558<li><code>readable.readableFlowing === null</code></li> 1559<li><code>readable.readableFlowing === false</code></li> 1560<li><code>readable.readableFlowing === true</code></li> 1561</ul> 1562<p>When <code>readable.readableFlowing</code> is <code>null</code>, no mechanism for consuming the 1563stream's data is provided. Therefore, the stream will not generate data. 1564While in this state, attaching a listener for the <code>'data'</code> event, calling the 1565<code>readable.pipe()</code> method, or calling the <code>readable.resume()</code> method will switch 1566<code>readable.readableFlowing</code> to <code>true</code>, causing the <code>Readable</code> to begin actively 1567emitting events as data is generated.</p> 1568<p>Calling <code>readable.pause()</code>, <code>readable.unpipe()</code>, or receiving backpressure 1569will cause the <code>readable.readableFlowing</code> to be set as <code>false</code>, 1570temporarily halting the flowing of events but <em>not</em> halting the generation of 1571data. While in this state, attaching a listener for the <code>'data'</code> event 1572will not switch <code>readable.readableFlowing</code> to <code>true</code>.</p> 1573<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">PassThrough</span>, <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 1574<span class="hljs-keyword">const</span> pass = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PassThrough</span>(); 1575<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 1576 1577pass.<span class="hljs-title function_">pipe</span>(writable); 1578pass.<span class="hljs-title function_">unpipe</span>(writable); 1579<span class="hljs-comment">// readableFlowing is now false.</span> 1580 1581pass.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk.<span class="hljs-title function_">toString</span>()); }); 1582<span class="hljs-comment">// readableFlowing is still false.</span> 1583pass.<span class="hljs-title function_">write</span>(<span class="hljs-string">'ok'</span>); <span class="hljs-comment">// Will not emit 'data'.</span> 1584pass.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Must be called to make stream emit 'data'.</span> 1585<span class="hljs-comment">// readableFlowing is now true.</span></code> <button class="copy-button">copy</button></pre> 1586<p>While <code>readable.readableFlowing</code> is <code>false</code>, data may be accumulating 1587within the stream's internal buffer.</p> 1588<h5>Choose one API style<span><a class="mark" href="#choose-one-api-style" id="choose-one-api-style">#</a></span><a aria-hidden="true" class="legacy" id="stream_choose_one_api_style"></a></h5> 1589<p>The <code>Readable</code> stream API evolved across multiple Node.js versions and provides 1590multiple methods of consuming stream data. In general, developers should choose 1591<em>one</em> of the methods of consuming data and <em>should never</em> use multiple methods 1592to consume data from a single stream. Specifically, using a combination 1593of <code>on('data')</code>, <code>on('readable')</code>, <code>pipe()</code>, or async iterators could 1594lead to unintuitive behavior.</p> 1595<h5>Class: <code>stream.Readable</code><span><a class="mark" href="#class-streamreadable" id="class-streamreadable">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_readable"></a></h5> 1596<div class="api_metadata"> 1597<span>Added in: v0.9.4</span> 1598</div> 1599 1600<h6>Event: <code>'close'</code><span><a class="mark" href="#event-close_1" id="event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_close_1"></a></h6> 1601<div class="api_metadata"> 1602<details class="changelog"><summary>History</summary> 1603<table> 1604<tbody><tr><th>Version</th><th>Changes</th></tr> 1605<tr><td>v10.0.0</td> 1606<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> 1607<tr><td>v0.9.4</td> 1608<td><p><span>Added in: v0.9.4</span></p></td></tr> 1609</tbody></table> 1610</details> 1611</div> 1612<p>The <code>'close'</code> event is emitted when the stream and any of its underlying 1613resources (a file descriptor, for example) have been closed. The event indicates 1614that no more events will be emitted, and no further computation will occur.</p> 1615<p>A <a href="#class-streamreadable"><code>Readable</code></a> stream will always emit the <code>'close'</code> event if it is 1616created with the <code>emitClose</code> option.</p> 1617<h6>Event: <code>'data'</code><span><a class="mark" href="#event-data" id="event-data">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_data"></a></h6> 1618<div class="api_metadata"> 1619<span>Added in: v0.9.4</span> 1620</div> 1621<ul> 1622<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The chunk of data. For streams that are not 1623operating in object mode, the chunk will be either a string or <code>Buffer</code>. 1624For streams that are in object mode, the chunk can be any JavaScript value 1625other than <code>null</code>.</li> 1626</ul> 1627<p>The <code>'data'</code> event is emitted whenever the stream is relinquishing ownership of 1628a chunk of data to a consumer. This may occur whenever the stream is switched 1629in flowing mode by calling <code>readable.pipe()</code>, <code>readable.resume()</code>, or by 1630attaching a listener callback to the <code>'data'</code> event. The <code>'data'</code> event will 1631also be emitted whenever the <code>readable.read()</code> method is called and a chunk of 1632data is available to be returned.</p> 1633<p>Attaching a <code>'data'</code> event listener to a stream that has not been explicitly 1634paused will switch the stream into flowing mode. Data will then be passed as 1635soon as it is available.</p> 1636<p>The listener callback will be passed the chunk of data as a string if a default 1637encoding has been specified for the stream using the 1638<code>readable.setEncoding()</code> method; otherwise the data will be passed as a 1639<code>Buffer</code>.</p> 1640<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1641readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1642 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>); 1643});</code> <button class="copy-button">copy</button></pre> 1644<h6>Event: <code>'end'</code><span><a class="mark" href="#event-end" id="event-end">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_end"></a></h6> 1645<div class="api_metadata"> 1646<span>Added in: v0.9.4</span> 1647</div> 1648<p>The <code>'end'</code> event is emitted when there is no more data to be consumed from 1649the stream.</p> 1650<p>The <code>'end'</code> event <strong>will not be emitted</strong> unless the data is completely 1651consumed. This can be accomplished by switching the stream into flowing mode, 1652or by calling <a href="#readablereadsize"><code>stream.read()</code></a> repeatedly until all data has been 1653consumed.</p> 1654<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1655readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1656 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>); 1657}); 1658readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1659 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'There will be no more data.'</span>); 1660});</code> <button class="copy-button">copy</button></pre> 1661<h6>Event: <code>'error'</code><span><a class="mark" href="#event-error_1" id="event-error_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_error_1"></a></h6> 1662<div class="api_metadata"> 1663<span>Added in: v0.9.4</span> 1664</div> 1665<ul> 1666<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1667</ul> 1668<p>The <code>'error'</code> event may be emitted by a <code>Readable</code> implementation at any time. 1669Typically, this may occur if the underlying stream is unable to generate data 1670due to an underlying internal failure, or when a stream implementation attempts 1671to push an invalid chunk of data.</p> 1672<p>The listener callback will be passed a single <code>Error</code> object.</p> 1673<h6>Event: <code>'pause'</code><span><a class="mark" href="#event-pause" id="event-pause">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_pause"></a></h6> 1674<div class="api_metadata"> 1675<span>Added in: v0.9.4</span> 1676</div> 1677<p>The <code>'pause'</code> event is emitted when <a href="#readablepause"><code>stream.pause()</code></a> is called 1678and <code>readableFlowing</code> is not <code>false</code>.</p> 1679<h6>Event: <code>'readable'</code><span><a class="mark" href="#event-readable" id="event-readable">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_readable"></a></h6> 1680<div class="api_metadata"> 1681<details class="changelog"><summary>History</summary> 1682<table> 1683<tbody><tr><th>Version</th><th>Changes</th></tr> 1684<tr><td>v10.0.0</td> 1685<td><p>The <code>'readable'</code> is always emitted in the next tick after <code>.push()</code> is called.</p></td></tr> 1686<tr><td>v10.0.0</td> 1687<td><p>Using <code>'readable'</code> requires calling <code>.read()</code>.</p></td></tr> 1688<tr><td>v0.9.4</td> 1689<td><p><span>Added in: v0.9.4</span></p></td></tr> 1690</tbody></table> 1691</details> 1692</div> 1693<p>The <code>'readable'</code> event is emitted when there is data available to be read from 1694the stream or when the end of the stream has been reached. Effectively, the 1695<code>'readable'</code> event indicates that the stream has new information. If data is 1696available, <a href="#readablereadsize"><code>stream.read()</code></a> will return that data.</p> 1697<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1698readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { 1699 <span class="hljs-comment">// There is some data to read now.</span> 1700 <span class="hljs-keyword">let</span> data; 1701 1702 <span class="hljs-keyword">while</span> ((data = <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">read</span>()) !== <span class="hljs-literal">null</span>) { 1703 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data); 1704 } 1705});</code> <button class="copy-button">copy</button></pre> 1706<p>If the end of the stream has been reached, calling 1707<a href="#readablereadsize"><code>stream.read()</code></a> will return <code>null</code> and trigger the <code>'end'</code> 1708event. This is also true if there never was any data to be read. For instance, 1709in the following example, <code>foo.txt</code> is an empty file:</p> 1710<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 1711<span class="hljs-keyword">const</span> rr = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'foo.txt'</span>); 1712rr.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 1713 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`readable: <span class="hljs-subst">${rr.read()}</span>`</span>); 1714}); 1715rr.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1716 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'end'</span>); 1717});</code> <button class="copy-button">copy</button></pre> 1718<p>The output of running this script is:</p> 1719<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node test.js</span> 1720readable: null 1721end</code> <button class="copy-button">copy</button></pre> 1722<p>In some cases, attaching a listener for the <code>'readable'</code> event will cause some 1723amount of data to be read into an internal buffer.</p> 1724<p>In general, the <code>readable.pipe()</code> and <code>'data'</code> event mechanisms are easier to 1725understand than the <code>'readable'</code> event. However, handling <code>'readable'</code> might 1726result in increased throughput.</p> 1727<p>If both <code>'readable'</code> and <a href="#event-data"><code>'data'</code></a> are used at the same time, <code>'readable'</code> 1728takes precedence in controlling the flow, i.e. <code>'data'</code> will be emitted 1729only when <a href="#readablereadsize"><code>stream.read()</code></a> is called. The 1730<code>readableFlowing</code> property would become <code>false</code>. 1731If there are <code>'data'</code> listeners when <code>'readable'</code> is removed, the stream 1732will start flowing, i.e. <code>'data'</code> events will be emitted without calling 1733<code>.resume()</code>.</p> 1734<h6>Event: <code>'resume'</code><span><a class="mark" href="#event-resume" id="event-resume">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_resume"></a></h6> 1735<div class="api_metadata"> 1736<span>Added in: v0.9.4</span> 1737</div> 1738<p>The <code>'resume'</code> event is emitted when <a href="#readableresume"><code>stream.resume()</code></a> is 1739called and <code>readableFlowing</code> is not <code>true</code>.</p> 1740<h6><code>readable.destroy([error])</code><span><a class="mark" href="#readabledestroyerror" id="readabledestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_destroy_error"></a></h6> 1741<div class="api_metadata"> 1742<details class="changelog"><summary>History</summary> 1743<table> 1744<tbody><tr><th>Version</th><th>Changes</th></tr> 1745<tr><td>v14.0.0</td> 1746<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr> 1747<tr><td>v8.0.0</td> 1748<td><p><span>Added in: v8.0.0</span></p></td></tr> 1749</tbody></table> 1750</details> 1751</div> 1752<ul> 1753<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Error which will be passed as payload in <code>'error'</code> event</li> 1754<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1755</ul> 1756<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code> 1757event (unless <code>emitClose</code> is set to <code>false</code>). After this call, the readable 1758stream will release any internal resources and subsequent calls to <code>push()</code> 1759will be ignored.</p> 1760<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no 1761further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p> 1762<p>Implementors should not override this method, but instead implement 1763<a href="#readable_destroyerr-callback"><code>readable._destroy()</code></a>.</p> 1764<h6><code>readable.closed</code><span><a class="mark" href="#readableclosed" id="readableclosed">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_closed"></a></h6> 1765<div class="api_metadata"> 1766<span>Added in: v18.0.0</span> 1767</div> 1768<ul> 1769<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1770</ul> 1771<p>Is <code>true</code> after <code>'close'</code> has been emitted.</p> 1772<h6><code>readable.destroyed</code><span><a class="mark" href="#readabledestroyed" id="readabledestroyed">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_destroyed"></a></h6> 1773<div class="api_metadata"> 1774<span>Added in: v8.0.0</span> 1775</div> 1776<ul> 1777<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1778</ul> 1779<p>Is <code>true</code> after <a href="#readabledestroyerror"><code>readable.destroy()</code></a> has been called.</p> 1780<h6><code>readable.isPaused()</code><span><a class="mark" href="#readableispaused" id="readableispaused">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_ispaused"></a></h6> 1781<div class="api_metadata"> 1782<span>Added in: v0.11.14</span> 1783</div> 1784<ul> 1785<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1786</ul> 1787<p>The <code>readable.isPaused()</code> method returns the current operating state of the 1788<code>Readable</code>. This is used primarily by the mechanism that underlies the 1789<code>readable.pipe()</code> method. In most typical cases, there will be no reason to 1790use this method directly.</p> 1791<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> stream.<span class="hljs-title class_">Readable</span>(); 1792 1793readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === false</span> 1794readable.<span class="hljs-title function_">pause</span>(); 1795readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === true</span> 1796readable.<span class="hljs-title function_">resume</span>(); 1797readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === false</span></code> <button class="copy-button">copy</button></pre> 1798<h6><code>readable.pause()</code><span><a class="mark" href="#readablepause" id="readablepause">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_pause"></a></h6> 1799<div class="api_metadata"> 1800<span>Added in: v0.9.4</span> 1801</div> 1802<ul> 1803<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1804</ul> 1805<p>The <code>readable.pause()</code> method will cause a stream in flowing mode to stop 1806emitting <a href="#event-data"><code>'data'</code></a> events, switching out of flowing mode. Any data that 1807becomes available will remain in the internal buffer.</p> 1808<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1809readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1810 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>); 1811 readable.<span class="hljs-title function_">pause</span>(); 1812 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'There will be no additional data for 1 second.'</span>); 1813 <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { 1814 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Now data will start flowing again.'</span>); 1815 readable.<span class="hljs-title function_">resume</span>(); 1816 }, <span class="hljs-number">1000</span>); 1817});</code> <button class="copy-button">copy</button></pre> 1818<p>The <code>readable.pause()</code> method has no effect if there is a <code>'readable'</code> 1819event listener.</p> 1820<h6><code>readable.pipe(destination[, options])</code><span><a class="mark" href="#readablepipedestination-options" id="readablepipedestination-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_pipe_destination_options"></a></h6> 1821<div class="api_metadata"> 1822<span>Added in: v0.9.4</span> 1823</div> 1824<ul> 1825<li><code>destination</code> <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a> The destination for writing data</li> 1826<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Pipe options 1827<ul> 1828<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> End the writer when the reader ends. <strong>Default:</strong> <code>true</code>.</li> 1829</ul> 1830</li> 1831<li>Returns: <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a> The <em>destination</em>, allowing for a chain of pipes if 1832it is a <a href="#class-streamduplex"><code>Duplex</code></a> or a <a href="#class-streamtransform"><code>Transform</code></a> stream</li> 1833</ul> 1834<p>The <code>readable.pipe()</code> method attaches a <a href="#class-streamwritable"><code>Writable</code></a> stream to the <code>readable</code>, 1835causing it to switch automatically into flowing mode and push all of its data 1836to the attached <a href="#class-streamwritable"><code>Writable</code></a>. The flow of data will be automatically managed 1837so that the destination <code>Writable</code> stream is not overwhelmed by a faster 1838<code>Readable</code> stream.</p> 1839<p>The following example pipes all of the data from the <code>readable</code> into a file 1840named <code>file.txt</code>:</p> 1841<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 1842<span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1843<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt'</span>); 1844<span class="hljs-comment">// All the data from readable goes into 'file.txt'.</span> 1845readable.<span class="hljs-title function_">pipe</span>(writable);</code> <button class="copy-button">copy</button></pre> 1846<p>It is possible to attach multiple <code>Writable</code> streams to a single <code>Readable</code> 1847stream.</p> 1848<p>The <code>readable.pipe()</code> method returns a reference to the <em>destination</em> stream 1849making it possible to set up chains of piped streams:</p> 1850<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 1851<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>); 1852<span class="hljs-keyword">const</span> r = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'file.txt'</span>); 1853<span class="hljs-keyword">const</span> z = zlib.<span class="hljs-title function_">createGzip</span>(); 1854<span class="hljs-keyword">const</span> w = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt.gz'</span>); 1855r.<span class="hljs-title function_">pipe</span>(z).<span class="hljs-title function_">pipe</span>(w);</code> <button class="copy-button">copy</button></pre> 1856<p>By default, <a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> is called on the destination <code>Writable</code> 1857stream when the source <code>Readable</code> stream emits <a href="#event-end"><code>'end'</code></a>, so that the 1858destination is no longer writable. To disable this default behavior, the <code>end</code> 1859option can be passed as <code>false</code>, causing the destination stream to remain open:</p> 1860<pre><code class="language-js">reader.<span class="hljs-title function_">pipe</span>(writer, { <span class="hljs-attr">end</span>: <span class="hljs-literal">false</span> }); 1861reader.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1862 writer.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Goodbye\n'</span>); 1863});</code> <button class="copy-button">copy</button></pre> 1864<p>One important caveat is that if the <code>Readable</code> stream emits an error during 1865processing, the <code>Writable</code> destination <em>is not closed</em> automatically. If an 1866error occurs, it will be necessary to <em>manually</em> close each stream in order 1867to prevent memory leaks.</p> 1868<p>The <a href="process.html#processstderr"><code>process.stderr</code></a> and <a href="process.html#processstdout"><code>process.stdout</code></a> <code>Writable</code> streams are never 1869closed until the Node.js process exits, regardless of the specified options.</p> 1870<h6><code>readable.read([size])</code><span><a class="mark" href="#readablereadsize" id="readablereadsize">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_read_size"></a></h6> 1871<div class="api_metadata"> 1872<span>Added in: v0.9.4</span> 1873</div> 1874<ul> 1875<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optional argument to specify how much data to read.</li> 1876<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> 1877</ul> 1878<p>The <code>readable.read()</code> method reads data out of the internal buffer and 1879returns it. If no data is available to be read, <code>null</code> is returned. By default, 1880the data is returned as a <code>Buffer</code> object unless an encoding has been 1881specified using the <code>readable.setEncoding()</code> method or the stream is operating 1882in object mode.</p> 1883<p>The optional <code>size</code> argument specifies a specific number of bytes to read. If 1884<code>size</code> bytes are not available to be read, <code>null</code> will be returned <em>unless</em> 1885the stream has ended, in which case all of the data remaining in the internal 1886buffer will be returned.</p> 1887<p>If the <code>size</code> argument is not specified, all of the data contained in the 1888internal buffer will be returned.</p> 1889<p>The <code>size</code> argument must be less than or equal to 1 GiB.</p> 1890<p>The <code>readable.read()</code> method should only be called on <code>Readable</code> streams 1891operating in paused mode. In flowing mode, <code>readable.read()</code> is called 1892automatically until the internal buffer is fully drained.</p> 1893<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1894 1895<span class="hljs-comment">// 'readable' may be triggered multiple times as data is buffered in</span> 1896readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 1897 <span class="hljs-keyword">let</span> chunk; 1898 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is readable (new data received in buffer)'</span>); 1899 <span class="hljs-comment">// Use a loop to make sure we read all currently available data</span> 1900 <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = readable.<span class="hljs-title function_">read</span>())) { 1901 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Read <span class="hljs-subst">${chunk.length}</span> bytes of data...`</span>); 1902 } 1903}); 1904 1905<span class="hljs-comment">// 'end' will be triggered once when there is no more data available</span> 1906readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1907 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Reached end of stream.'</span>); 1908});</code> <button class="copy-button">copy</button></pre> 1909<p>Each call to <code>readable.read()</code> returns a chunk of data, or <code>null</code>. The chunks 1910are not concatenated. A <code>while</code> loop is necessary to consume all data 1911currently in the buffer. When reading a large file <code>.read()</code> may return <code>null</code>, 1912having consumed all buffered content so far, but there is still more data to 1913come not yet buffered. In this case a new <code>'readable'</code> event will be emitted 1914when there is more data in the buffer. Finally the <code>'end'</code> event will be 1915emitted when there is no more data to come.</p> 1916<p>Therefore to read a file's whole contents from a <code>readable</code>, it is necessary 1917to collect chunks across multiple <code>'readable'</code> events:</p> 1918<pre><code class="language-js"><span class="hljs-keyword">const</span> chunks = []; 1919 1920readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 1921 <span class="hljs-keyword">let</span> chunk; 1922 <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = readable.<span class="hljs-title function_">read</span>())) { 1923 chunks.<span class="hljs-title function_">push</span>(chunk); 1924 } 1925}); 1926 1927readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1928 <span class="hljs-keyword">const</span> content = chunks.<span class="hljs-title function_">join</span>(<span class="hljs-string">''</span>); 1929});</code> <button class="copy-button">copy</button></pre> 1930<p>A <code>Readable</code> stream in object mode will always return a single item from 1931a call to <a href="#readablereadsize"><code>readable.read(size)</code></a>, regardless of the value of the 1932<code>size</code> argument.</p> 1933<p>If the <code>readable.read()</code> method returns a chunk of data, a <code>'data'</code> event will 1934also be emitted.</p> 1935<p>Calling <a href="#readablereadsize"><code>stream.read([size])</code></a> after the <a href="#event-end"><code>'end'</code></a> event has 1936been emitted will return <code>null</code>. No runtime error will be raised.</p> 1937<h6><code>readable.readable</code><span><a class="mark" href="#readablereadable" id="readablereadable">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readable"></a></h6> 1938<div class="api_metadata"> 1939<span>Added in: v11.4.0</span> 1940</div> 1941<ul> 1942<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1943</ul> 1944<p>Is <code>true</code> if it is safe to call <a href="#readablereadsize"><code>readable.read()</code></a>, which means 1945the stream has not been destroyed or emitted <code>'error'</code> or <code>'end'</code>.</p> 1946<h6><code>readable.readableAborted</code><span><a class="mark" href="#readablereadableaborted" id="readablereadableaborted">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableaborted"></a></h6> 1947<div class="api_metadata"> 1948<span>Added in: v16.8.0</span> 1949</div> 1950<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 1951<ul> 1952<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1953</ul> 1954<p>Returns whether the stream was destroyed or errored before emitting <code>'end'</code>.</p> 1955<h6><code>readable.readableDidRead</code><span><a class="mark" href="#readablereadabledidread" id="readablereadabledidread">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readabledidread"></a></h6> 1956<div class="api_metadata"> 1957<span>Added in: v16.7.0, v14.18.0</span> 1958</div> 1959<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 1960<ul> 1961<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1962</ul> 1963<p>Returns whether <code>'data'</code> has been emitted.</p> 1964<h6><code>readable.readableEncoding</code><span><a class="mark" href="#readablereadableencoding" id="readablereadableencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableencoding"></a></h6> 1965<div class="api_metadata"> 1966<span>Added in: v12.7.0</span> 1967</div> 1968<ul> 1969<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 1970</ul> 1971<p>Getter for the property <code>encoding</code> of a given <code>Readable</code> stream. The <code>encoding</code> 1972property can be set using the <a href="#readablesetencodingencoding"><code>readable.setEncoding()</code></a> method.</p> 1973<h6><code>readable.readableEnded</code><span><a class="mark" href="#readablereadableended" id="readablereadableended">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableended"></a></h6> 1974<div class="api_metadata"> 1975<span>Added in: v12.9.0</span> 1976</div> 1977<ul> 1978<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1979</ul> 1980<p>Becomes <code>true</code> when <a href="#event-end"><code>'end'</code></a> event is emitted.</p> 1981<h6><code>readable.errored</code><span><a class="mark" href="#readableerrored" id="readableerrored">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_errored"></a></h6> 1982<div class="api_metadata"> 1983<span>Added in: v18.0.0</span> 1984</div> 1985<ul> 1986<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1987</ul> 1988<p>Returns error if the stream has been destroyed with an error.</p> 1989<h6><code>readable.readableFlowing</code><span><a class="mark" href="#readablereadableflowing" id="readablereadableflowing">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableflowing"></a></h6> 1990<div class="api_metadata"> 1991<span>Added in: v9.4.0</span> 1992</div> 1993<ul> 1994<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1995</ul> 1996<p>This property reflects the current state of a <code>Readable</code> stream as described 1997in the <a href="#three-states">Three states</a> section.</p> 1998<h6><code>readable.readableHighWaterMark</code><span><a class="mark" href="#readablereadablehighwatermark" id="readablereadablehighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readablehighwatermark"></a></h6> 1999<div class="api_metadata"> 2000<span>Added in: v9.3.0</span> 2001</div> 2002<ul> 2003<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 2004</ul> 2005<p>Returns the value of <code>highWaterMark</code> passed when creating this <code>Readable</code>.</p> 2006<h6><code>readable.readableLength</code><span><a class="mark" href="#readablereadablelength" id="readablereadablelength">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readablelength"></a></h6> 2007<div class="api_metadata"> 2008<span>Added in: v9.4.0</span> 2009</div> 2010<ul> 2011<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 2012</ul> 2013<p>This property contains the number of bytes (or objects) in the queue 2014ready to be read. The value provides introspection data regarding 2015the status of the <code>highWaterMark</code>.</p> 2016<h6><code>readable.readableObjectMode</code><span><a class="mark" href="#readablereadableobjectmode" id="readablereadableobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableobjectmode"></a></h6> 2017<div class="api_metadata"> 2018<span>Added in: v12.3.0</span> 2019</div> 2020<ul> 2021<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 2022</ul> 2023<p>Getter for the property <code>objectMode</code> of a given <code>Readable</code> stream.</p> 2024<h6><code>readable.resume()</code><span><a class="mark" href="#readableresume" id="readableresume">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_resume"></a></h6> 2025<div class="api_metadata"> 2026<details class="changelog"><summary>History</summary> 2027<table> 2028<tbody><tr><th>Version</th><th>Changes</th></tr> 2029<tr><td>v10.0.0</td> 2030<td><p>The <code>resume()</code> has no effect if there is a <code>'readable'</code> event listening.</p></td></tr> 2031<tr><td>v0.9.4</td> 2032<td><p><span>Added in: v0.9.4</span></p></td></tr> 2033</tbody></table> 2034</details> 2035</div> 2036<ul> 2037<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 2038</ul> 2039<p>The <code>readable.resume()</code> method causes an explicitly paused <code>Readable</code> stream to 2040resume emitting <a href="#event-data"><code>'data'</code></a> events, switching the stream into flowing mode.</p> 2041<p>The <code>readable.resume()</code> method can be used to fully consume the data from a 2042stream without actually processing any of that data:</p> 2043<pre><code class="language-js"><span class="hljs-title function_">getReadableStreamSomehow</span>() 2044 .<span class="hljs-title function_">resume</span>() 2045 .<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 2046 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Reached the end, but did not read anything.'</span>); 2047 });</code> <button class="copy-button">copy</button></pre> 2048<p>The <code>readable.resume()</code> method has no effect if there is a <code>'readable'</code> 2049event listener.</p> 2050<h6><code>readable.setEncoding(encoding)</code><span><a class="mark" href="#readablesetencodingencoding" id="readablesetencodingencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_setencoding_encoding"></a></h6> 2051<div class="api_metadata"> 2052<span>Added in: v0.9.4</span> 2053</div> 2054<ul> 2055<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding to use.</li> 2056<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 2057</ul> 2058<p>The <code>readable.setEncoding()</code> method sets the character encoding for 2059data read from the <code>Readable</code> stream.</p> 2060<p>By default, no encoding is assigned and stream data will be returned as 2061<code>Buffer</code> objects. Setting an encoding causes the stream data 2062to be returned as strings of the specified encoding rather than as <code>Buffer</code> 2063objects. For instance, calling <code>readable.setEncoding('utf8')</code> will cause the 2064output data to be interpreted as UTF-8 data, and passed as strings. Calling 2065<code>readable.setEncoding('hex')</code> will cause the data to be encoded in hexadecimal 2066string format.</p> 2067<p>The <code>Readable</code> stream will properly handle multi-byte characters delivered 2068through the stream that would otherwise become improperly decoded if simply 2069pulled from the stream as <code>Buffer</code> objects.</p> 2070<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 2071readable.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); 2072readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 2073 assert.<span class="hljs-title function_">equal</span>(<span class="hljs-keyword">typeof</span> chunk, <span class="hljs-string">'string'</span>); 2074 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Got %d characters of string data:'</span>, chunk.<span class="hljs-property">length</span>); 2075});</code> <button class="copy-button">copy</button></pre> 2076<h6><code>readable.unpipe([destination])</code><span><a class="mark" href="#readableunpipedestination" id="readableunpipedestination">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_unpipe_destination"></a></h6> 2077<div class="api_metadata"> 2078<span>Added in: v0.9.4</span> 2079</div> 2080<ul> 2081<li><code>destination</code> <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a> Optional specific stream to unpipe</li> 2082<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 2083</ul> 2084<p>The <code>readable.unpipe()</code> method detaches a <code>Writable</code> stream previously attached 2085using the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> method.</p> 2086<p>If the <code>destination</code> is not specified, then <em>all</em> pipes are detached.</p> 2087<p>If the <code>destination</code> is specified, but no pipe is set up for it, then 2088the method does nothing.</p> 2089<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 2090<span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 2091<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt'</span>); 2092<span class="hljs-comment">// All the data from readable goes into 'file.txt',</span> 2093<span class="hljs-comment">// but only for the first second.</span> 2094readable.<span class="hljs-title function_">pipe</span>(writable); 2095<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { 2096 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stop writing to file.txt.'</span>); 2097 readable.<span class="hljs-title function_">unpipe</span>(writable); 2098 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Manually close the file stream.'</span>); 2099 writable.<span class="hljs-title function_">end</span>(); 2100}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre> 2101<h6><code>readable.unshift(chunk[, encoding])</code><span><a class="mark" href="#readableunshiftchunk-encoding" id="readableunshiftchunk-encoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_unshift_chunk_encoding"></a></h6> 2102<div class="api_metadata"> 2103<details class="changelog"><summary>History</summary> 2104<table> 2105<tbody><tr><th>Version</th><th>Changes</th></tr> 2106<tr><td>v8.0.0</td> 2107<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 2108<tr><td>v0.9.11</td> 2109<td><p><span>Added in: v0.9.11</span></p></td></tr> 2110</tbody></table> 2111</details> 2112</div> 2113<ul> 2114<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Chunk of data to unshift onto the 2115read queue. For streams not operating in object mode, <code>chunk</code> must be a 2116string, <code>Buffer</code>, <code>Uint8Array</code>, or <code>null</code>. For object mode streams, <code>chunk</code> 2117may be any JavaScript value.</li> 2118<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Encoding of string chunks. Must be a valid 2119<code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li> 2120</ul> 2121<p>Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF) and behaves the 2122same as <code>readable.push(null)</code>, after which no more data can be written. The EOF 2123signal is put at the end of the buffer and any buffered data will still be 2124flushed.</p> 2125<p>The <code>readable.unshift()</code> method pushes a chunk of data back into the internal 2126buffer. This is useful in certain situations where a stream is being consumed by 2127code that needs to "un-consume" some amount of data that it has optimistically 2128pulled out of the source, so that the data can be passed on to some other party.</p> 2129<p>The <code>stream.unshift(chunk)</code> method cannot be called after the <a href="#event-end"><code>'end'</code></a> event 2130has been emitted or a runtime error will be thrown.</p> 2131<p>Developers using <code>stream.unshift()</code> often should consider switching to 2132use of a <a href="#class-streamtransform"><code>Transform</code></a> stream instead. See the <a href="#api-for-stream-implementers">API for stream implementers</a> 2133section for more information.</p> 2134<pre><code class="language-js"><span class="hljs-comment">// Pull off a header delimited by \n\n.</span> 2135<span class="hljs-comment">// Use unshift() if we get too much.</span> 2136<span class="hljs-comment">// Call the callback with (error, header, stream).</span> 2137<span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:string_decoder'</span>); 2138<span class="hljs-keyword">function</span> <span class="hljs-title function_">parseHeader</span>(<span class="hljs-params">stream, callback</span>) { 2139 stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, callback); 2140 stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, onReadable); 2141 <span class="hljs-keyword">const</span> decoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringDecoder</span>(<span class="hljs-string">'utf8'</span>); 2142 <span class="hljs-keyword">let</span> header = <span class="hljs-string">''</span>; 2143 <span class="hljs-keyword">function</span> <span class="hljs-title function_">onReadable</span>(<span class="hljs-params"></span>) { 2144 <span class="hljs-keyword">let</span> chunk; 2145 <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = stream.<span class="hljs-title function_">read</span>())) { 2146 <span class="hljs-keyword">const</span> str = decoder.<span class="hljs-title function_">write</span>(chunk); 2147 <span class="hljs-keyword">if</span> (str.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'\n\n'</span>)) { 2148 <span class="hljs-comment">// Found the header boundary.</span> 2149 <span class="hljs-keyword">const</span> split = str.<span class="hljs-title function_">split</span>(<span class="hljs-regexp">/\n\n/</span>); 2150 header += split.<span class="hljs-title function_">shift</span>(); 2151 <span class="hljs-keyword">const</span> remaining = split.<span class="hljs-title function_">join</span>(<span class="hljs-string">'\n\n'</span>); 2152 <span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(remaining, <span class="hljs-string">'utf8'</span>); 2153 stream.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'error'</span>, callback); 2154 <span class="hljs-comment">// Remove the 'readable' listener before unshifting.</span> 2155 stream.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'readable'</span>, onReadable); 2156 <span class="hljs-keyword">if</span> (buf.<span class="hljs-property">length</span>) 2157 stream.<span class="hljs-title function_">unshift</span>(buf); 2158 <span class="hljs-comment">// Now the body of the message can be read from the stream.</span> 2159 <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, header, stream); 2160 <span class="hljs-keyword">return</span>; 2161 } 2162 <span class="hljs-comment">// Still reading the header.</span> 2163 header += str; 2164 } 2165 } 2166}</code> <button class="copy-button">copy</button></pre> 2167<p>Unlike <a href="#readablepushchunk-encoding"><code>stream.push(chunk)</code></a>, <code>stream.unshift(chunk)</code> will not 2168end the reading process by resetting the internal reading state of the stream. 2169This can cause unexpected results if <code>readable.unshift()</code> is called during a 2170read (i.e. from within a <a href="#readable_readsize"><code>stream._read()</code></a> implementation on a 2171custom stream). Following the call to <code>readable.unshift()</code> with an immediate 2172<a href="#readablepushchunk-encoding"><code>stream.push('')</code></a> will reset the reading state appropriately, 2173however it is best to simply avoid calling <code>readable.unshift()</code> while in the 2174process of performing a read.</p> 2175<h6><code>readable.wrap(stream)</code><span><a class="mark" href="#readablewrapstream" id="readablewrapstream">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_wrap_stream"></a></h6> 2176<div class="api_metadata"> 2177<span>Added in: v0.9.4</span> 2178</div> 2179<ul> 2180<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a> An "old style" readable stream</li> 2181<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 2182</ul> 2183<p>Prior to Node.js 0.10, streams did not implement the entire <code>node:stream</code> 2184module API as it is currently defined. (See <a href="#compatibility-with-older-nodejs-versions">Compatibility</a> for more 2185information.)</p> 2186<p>When using an older Node.js library that emits <a href="#event-data"><code>'data'</code></a> events and has a 2187<a href="#readablepause"><code>stream.pause()</code></a> method that is advisory only, the 2188<code>readable.wrap()</code> method can be used to create a <a href="#class-streamreadable"><code>Readable</code></a> stream that uses 2189the old stream as its data source.</p> 2190<p>It will rarely be necessary to use <code>readable.wrap()</code> but the method has been 2191provided as a convenience for interacting with older Node.js applications and 2192libraries.</p> 2193<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">OldReader</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./old-api-module.js'</span>); 2194<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 2195<span class="hljs-keyword">const</span> oreader = <span class="hljs-keyword">new</span> <span class="hljs-title class_">OldReader</span>(); 2196<span class="hljs-keyword">const</span> myReader = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>().<span class="hljs-title function_">wrap</span>(oreader); 2197 2198myReader.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 2199 myReader.<span class="hljs-title function_">read</span>(); <span class="hljs-comment">// etc.</span> 2200});</code> <button class="copy-button">copy</button></pre> 2201<h6><code>readable[Symbol.asyncIterator]()</code><span><a class="mark" href="#readablesymbolasynciterator" id="readablesymbolasynciterator">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_symbol_asynciterator"></a></h6> 2202<div class="api_metadata"> 2203<details class="changelog"><summary>History</summary> 2204<table> 2205<tbody><tr><th>Version</th><th>Changes</th></tr> 2206<tr><td>v11.14.0</td> 2207<td><p>Symbol.asyncIterator support is no longer experimental.</p></td></tr> 2208<tr><td>v10.0.0</td> 2209<td><p><span>Added in: v10.0.0</span></p></td></tr> 2210</tbody></table> 2211</details> 2212</div> 2213<ul> 2214<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> to fully consume the stream.</li> 2215</ul> 2216<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 2217 2218<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">print</span>(<span class="hljs-params">readable</span>) { 2219 readable.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); 2220 <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>; 2221 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable) { 2222 data += chunk; 2223 } 2224 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data); 2225} 2226 2227<span class="hljs-title function_">print</span>(fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'file'</span>)).<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code> <button class="copy-button">copy</button></pre> 2228<p>If the loop terminates with a <code>break</code>, <code>return</code>, or a <code>throw</code>, the stream will 2229be destroyed. In other terms, iterating over a stream will consume the stream 2230fully. The stream will be read in chunks of size equal to the <code>highWaterMark</code> 2231option. In the code example above, data will be in a single chunk if the file 2232has less then 64 KiB of data because no <code>highWaterMark</code> option is provided to 2233<a href="fs.html#fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>.</p> 2234<h6><code>readable[Symbol.asyncDispose]()</code><span><a class="mark" href="#readablesymbolasyncdispose" id="readablesymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_symbol_asyncdispose"></a></h6> 2235<div class="api_metadata"> 2236<span>Added in: v18.18.0</span> 2237</div> 2238<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2239<p>Calls <a href="#readabledestroyerror"><code>readable.destroy()</code></a> with an <code>AbortError</code> and returns 2240a promise that fulfills when the stream is finished.</p> 2241<h6><code>readable.compose(stream[, options])</code><span><a class="mark" href="#readablecomposestream-options" id="readablecomposestream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_compose_stream_options"></a></h6> 2242<div class="api_metadata"> 2243<span>Added in: v18.13.0</span> 2244</div> 2245<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2246<ul> 2247<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> 2248<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2249<ul> 2250<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2251aborted.</li> 2252</ul> 2253</li> 2254<li>Returns: <a href="stream.html#class-streamduplex" class="type"><Duplex></a> a stream composed with the stream <code>stream</code>.</li> 2255</ul> 2256<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2257 2258<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">splitToWords</span>(<span class="hljs-params">source</span>) { 2259 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) { 2260 <span class="hljs-keyword">const</span> words = <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">split</span>(<span class="hljs-string">' '</span>); 2261 2262 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> word <span class="hljs-keyword">of</span> words) { 2263 <span class="hljs-keyword">yield</span> word; 2264 } 2265 } 2266} 2267 2268<span class="hljs-keyword">const</span> wordsStream = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-string">'this is'</span>, <span class="hljs-string">'compose as operator'</span>]).<span class="hljs-title function_">compose</span>(splitToWords); 2269<span class="hljs-keyword">const</span> words = <span class="hljs-keyword">await</span> wordsStream.<span class="hljs-title function_">toArray</span>(); 2270 2271<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(words); <span class="hljs-comment">// prints ['this', 'is', 'compose', 'as', 'operator']</span></code> <button class="copy-button">copy</button></pre> 2272<p>See <a href="#streamcomposestreams"><code>stream.compose</code></a> for more information.</p> 2273<h6><code>readable.iterator([options])</code><span><a class="mark" href="#readableiteratoroptions" id="readableiteratoroptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_iterator_options"></a></h6> 2274<div class="api_metadata"> 2275<span>Added in: v16.3.0</span> 2276</div> 2277<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2278<ul> 2279<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2280<ul> 2281<li><code>destroyOnReturn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When set to <code>false</code>, calling <code>return</code> on the 2282async iterator, or exiting a <code>for await...of</code> iteration using a <code>break</code>, 2283<code>return</code>, or <code>throw</code> will not destroy the stream. <strong>Default:</strong> <code>true</code>.</li> 2284</ul> 2285</li> 2286<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> to consume the stream.</li> 2287</ul> 2288<p>The iterator created by this method gives users the option to cancel the 2289destruction of the stream if the <code>for await...of</code> loop is exited by <code>return</code>, 2290<code>break</code>, or <code>throw</code>, or if the iterator should destroy the stream if the stream 2291emitted an error during iteration.</p> 2292<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 2293 2294<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">printIterator</span>(<span class="hljs-params">readable</span>) { 2295 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable.<span class="hljs-title function_">iterator</span>({ <span class="hljs-attr">destroyOnReturn</span>: <span class="hljs-literal">false</span> })) { 2296 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1</span> 2297 <span class="hljs-keyword">break</span>; 2298 } 2299 2300 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(readable.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// false</span> 2301 2302 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable.<span class="hljs-title function_">iterator</span>({ <span class="hljs-attr">destroyOnReturn</span>: <span class="hljs-literal">false</span> })) { 2303 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// Will print 2 and then 3</span> 2304 } 2305 2306 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(readable.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// True, stream was totally consumed</span> 2307} 2308 2309<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">printSymbolAsyncIterator</span>(<span class="hljs-params">readable</span>) { 2310 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable) { 2311 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1</span> 2312 <span class="hljs-keyword">break</span>; 2313 } 2314 2315 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(readable.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// true</span> 2316} 2317 2318<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">showBoth</span>(<span class="hljs-params"></span>) { 2319 <span class="hljs-keyword">await</span> <span class="hljs-title function_">printIterator</span>(<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])); 2320 <span class="hljs-keyword">await</span> <span class="hljs-title function_">printSymbolAsyncIterator</span>(<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])); 2321} 2322 2323<span class="hljs-title function_">showBoth</span>();</code> <button class="copy-button">copy</button></pre> 2324<h6><code>readable.map(fn[, options])</code><span><a class="mark" href="#readablemapfn-options" id="readablemapfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_map_fn_options"></a></h6> 2325<div class="api_metadata"> 2326<details class="changelog"><summary>History</summary> 2327<table> 2328<tbody><tr><th>Version</th><th>Changes</th></tr> 2329<tr><td>v18.19.0</td> 2330<td><p>added <code>highWaterMark</code> in options.</p></td></tr> 2331<tr><td>v17.4.0, v16.14.0</td> 2332<td><p><span>Added in: v17.4.0, v16.14.0</span></p></td></tr> 2333</tbody></table> 2334</details> 2335</div> 2336<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2337<ul> 2338<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to map over every chunk in the 2339stream. 2340<ul> 2341<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li> 2342<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2343<ul> 2344<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2345abort the <code>fn</code> call early.</li> 2346</ul> 2347</li> 2348</ul> 2349</li> 2350<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2351<ul> 2352<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call 2353on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2354<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> how many items to buffer while waiting for user 2355consumption of the mapped items. <strong>Default:</strong> <code>concurrency * 2 - 1</code>.</li> 2356<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2357aborted.</li> 2358</ul> 2359</li> 2360<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream mapped with the function <code>fn</code>.</li> 2361</ul> 2362<p>This method allows mapping over the stream. The <code>fn</code> function will be called 2363for every chunk in the stream. If the <code>fn</code> function returns a promise - that 2364promise will be <code>await</code>ed before being passed to the result stream.</p> 2365<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2366<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>; 2367 2368<span class="hljs-comment">// With a synchronous mapper.</span> 2369<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x * <span class="hljs-number">2</span>)) { 2370 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 2, 4, 6, 8</span> 2371} 2372<span class="hljs-comment">// With an asynchronous mapper, making at most 2 queries at a time.</span> 2373<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>(); 2374<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2375 <span class="hljs-string">'nodejs.org'</span>, 2376 <span class="hljs-string">'openjsf.org'</span>, 2377 <span class="hljs-string">'www.linuxfoundation.org'</span>, 2378]).<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">domain</span>) =></span> resolver.<span class="hljs-title function_">resolve4</span>(domain), { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2379<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> result <span class="hljs-keyword">of</span> dnsResults) { 2380 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); <span class="hljs-comment">// Logs the DNS result of resolver.resolve4.</span> 2381}</code> <button class="copy-button">copy</button></pre> 2382<h6><code>readable.filter(fn[, options])</code><span><a class="mark" href="#readablefilterfn-options" id="readablefilterfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_filter_fn_options"></a></h6> 2383<div class="api_metadata"> 2384<details class="changelog"><summary>History</summary> 2385<table> 2386<tbody><tr><th>Version</th><th>Changes</th></tr> 2387<tr><td>v18.19.0</td> 2388<td><p>added <code>highWaterMark</code> in options.</p></td></tr> 2389<tr><td>v17.4.0, v16.14.0</td> 2390<td><p><span>Added in: v17.4.0, v16.14.0</span></p></td></tr> 2391</tbody></table> 2392</details> 2393</div> 2394<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2395<ul> 2396<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to filter chunks from the stream. 2397<ul> 2398<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li> 2399<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2400<ul> 2401<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2402abort the <code>fn</code> call early.</li> 2403</ul> 2404</li> 2405</ul> 2406</li> 2407<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2408<ul> 2409<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call 2410on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2411<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> how many items to buffer while waiting for user 2412consumption of the filtered items. <strong>Default:</strong> <code>concurrency * 2 - 1</code>.</li> 2413<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2414aborted.</li> 2415</ul> 2416</li> 2417<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream filtered with the predicate <code>fn</code>.</li> 2418</ul> 2419<p>This method allows filtering the stream. For each chunk in the stream the <code>fn</code> 2420function will be called and if it returns a truthy value, the chunk will be 2421passed to the result stream. If the <code>fn</code> function returns a promise - that 2422promise will be <code>await</code>ed.</p> 2423<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2424<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>; 2425 2426<span class="hljs-comment">// With a synchronous predicate.</span> 2427<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>)) { 2428 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 3, 4</span> 2429} 2430<span class="hljs-comment">// With an asynchronous predicate, making at most 2 queries at a time.</span> 2431<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>(); 2432<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2433 <span class="hljs-string">'nodejs.org'</span>, 2434 <span class="hljs-string">'openjsf.org'</span>, 2435 <span class="hljs-string">'www.linuxfoundation.org'</span>, 2436]).<span class="hljs-title function_">filter</span>(<span class="hljs-keyword">async</span> (domain) => { 2437 <span class="hljs-keyword">const</span> { address } = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(domain, { <span class="hljs-attr">ttl</span>: <span class="hljs-literal">true</span> }); 2438 <span class="hljs-keyword">return</span> address.<span class="hljs-property">ttl</span> > <span class="hljs-number">60</span>; 2439}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2440<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> result <span class="hljs-keyword">of</span> dnsResults) { 2441 <span class="hljs-comment">// Logs domains with more than 60 seconds on the resolved dns record.</span> 2442 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); 2443}</code> <button class="copy-button">copy</button></pre> 2444<h6><code>readable.forEach(fn[, options])</code><span><a class="mark" href="#readableforeachfn-options" id="readableforeachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_foreach_fn_options"></a></h6> 2445<div class="api_metadata"> 2446<span>Added in: v17.5.0</span> 2447</div> 2448<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2449<ul> 2450<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to call on each chunk of the stream. 2451<ul> 2452<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li> 2453<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2454<ul> 2455<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2456abort the <code>fn</code> call early.</li> 2457</ul> 2458</li> 2459</ul> 2460</li> 2461<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2462<ul> 2463<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call 2464on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2465<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2466aborted.</li> 2467</ul> 2468</li> 2469<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise for when the stream has finished.</li> 2470</ul> 2471<p>This method allows iterating a stream. For each chunk in the stream the 2472<code>fn</code> function will be called. If the <code>fn</code> function returns a promise - that 2473promise will be <code>await</code>ed.</p> 2474<p>This method is different from <code>for await...of</code> loops in that it can optionally 2475process chunks concurrently. In addition, a <code>forEach</code> iteration can only be 2476stopped by having passed a <code>signal</code> option and aborting the related 2477<code>AbortController</code> while <code>for await...of</code> can be stopped with <code>break</code> or 2478<code>return</code>. In either case the stream will be destroyed.</p> 2479<p>This method is different from listening to the <a href="#event-data"><code>'data'</code></a> event in that it 2480uses the <a href="#class-streamreadable"><code>readable</code></a> event in the underlying machinary and can limit the 2481number of concurrent <code>fn</code> calls.</p> 2482<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2483<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>; 2484 2485<span class="hljs-comment">// With a synchronous predicate.</span> 2486<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>)) { 2487 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 3, 4</span> 2488} 2489<span class="hljs-comment">// With an asynchronous predicate, making at most 2 queries at a time.</span> 2490<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>(); 2491<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2492 <span class="hljs-string">'nodejs.org'</span>, 2493 <span class="hljs-string">'openjsf.org'</span>, 2494 <span class="hljs-string">'www.linuxfoundation.org'</span>, 2495]).<span class="hljs-title function_">map</span>(<span class="hljs-keyword">async</span> (domain) => { 2496 <span class="hljs-keyword">const</span> { address } = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(domain, { <span class="hljs-attr">ttl</span>: <span class="hljs-literal">true</span> }); 2497 <span class="hljs-keyword">return</span> address; 2498}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2499<span class="hljs-keyword">await</span> dnsResults.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> { 2500 <span class="hljs-comment">// Logs result, similar to `for await (const result of dnsResults)`</span> 2501 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); 2502}); 2503<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre> 2504<h6><code>readable.toArray([options])</code><span><a class="mark" href="#readabletoarrayoptions" id="readabletoarrayoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_toarray_options"></a></h6> 2505<div class="api_metadata"> 2506<span>Added in: v17.5.0</span> 2507</div> 2508<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2509<ul> 2510<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2511<ul> 2512<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows cancelling the toArray operation if the 2513signal is aborted.</li> 2514</ul> 2515</li> 2516<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise containing an array with the contents of the 2517stream.</li> 2518</ul> 2519<p>This method allows easily obtaining the contents of a stream.</p> 2520<p>As this method reads the entire stream into memory, it negates the benefits of 2521streams. It's intended for interoperability and convenience, not as the primary 2522way to consume streams.</p> 2523<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2524<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>; 2525 2526<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">toArray</span>(); <span class="hljs-comment">// [1, 2, 3, 4]</span> 2527 2528<span class="hljs-comment">// Make dns queries concurrently using .map and collect</span> 2529<span class="hljs-comment">// the results into an array using toArray</span> 2530<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2531 <span class="hljs-string">'nodejs.org'</span>, 2532 <span class="hljs-string">'openjsf.org'</span>, 2533 <span class="hljs-string">'www.linuxfoundation.org'</span>, 2534]).<span class="hljs-title function_">map</span>(<span class="hljs-keyword">async</span> (domain) => { 2535 <span class="hljs-keyword">const</span> { address } = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(domain, { <span class="hljs-attr">ttl</span>: <span class="hljs-literal">true</span> }); 2536 <span class="hljs-keyword">return</span> address; 2537}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }).<span class="hljs-title function_">toArray</span>();</code> <button class="copy-button">copy</button></pre> 2538<h6><code>readable.some(fn[, options])</code><span><a class="mark" href="#readablesomefn-options" id="readablesomefn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_some_fn_options"></a></h6> 2539<div class="api_metadata"> 2540<span>Added in: v17.5.0</span> 2541</div> 2542<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2543<ul> 2544<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to call on each chunk of the stream. 2545<ul> 2546<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li> 2547<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2548<ul> 2549<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2550abort the <code>fn</code> call early.</li> 2551</ul> 2552</li> 2553</ul> 2554</li> 2555<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2556<ul> 2557<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call 2558on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2559<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2560aborted.</li> 2561</ul> 2562</li> 2563<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise evaluating to <code>true</code> if <code>fn</code> returned a truthy 2564value for at least one of the chunks.</li> 2565</ul> 2566<p>This method is similar to <code>Array.prototype.some</code> and calls <code>fn</code> on each chunk 2567in the stream until the awaited return value is <code>true</code> (or any truthy value). 2568Once an <code>fn</code> call on a chunk awaited return value is truthy, the stream is 2569destroyed and the promise is fulfilled with <code>true</code>. If none of the <code>fn</code> 2570calls on the chunks return a truthy value, the promise is fulfilled with 2571<code>false</code>.</p> 2572<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2573<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; 2574 2575<span class="hljs-comment">// With a synchronous predicate.</span> 2576<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">some</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>); <span class="hljs-comment">// true</span> 2577<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">some</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x < <span class="hljs-number">0</span>); <span class="hljs-comment">// false</span> 2578 2579<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span> 2580<span class="hljs-keyword">const</span> anyBigFile = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2581 <span class="hljs-string">'file1'</span>, 2582 <span class="hljs-string">'file2'</span>, 2583 <span class="hljs-string">'file3'</span>, 2584]).<span class="hljs-title function_">some</span>(<span class="hljs-keyword">async</span> (fileName) => { 2585 <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName); 2586 <span class="hljs-keyword">return</span> stats.<span class="hljs-property">size</span> > <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>; 2587}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2588<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(anyBigFile); <span class="hljs-comment">// `true` if any file in the list is bigger than 1MB</span> 2589<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre> 2590<h6><code>readable.find(fn[, options])</code><span><a class="mark" href="#readablefindfn-options" id="readablefindfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_find_fn_options"></a></h6> 2591<div class="api_metadata"> 2592<span>Added in: v17.5.0</span> 2593</div> 2594<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2595<ul> 2596<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to call on each chunk of the stream. 2597<ul> 2598<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li> 2599<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2600<ul> 2601<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2602abort the <code>fn</code> call early.</li> 2603</ul> 2604</li> 2605</ul> 2606</li> 2607<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2608<ul> 2609<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call 2610on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2611<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2612aborted.</li> 2613</ul> 2614</li> 2615<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise evaluating to the first chunk for which <code>fn</code> 2616evaluated with a truthy value, or <code>undefined</code> if no element was found.</li> 2617</ul> 2618<p>This method is similar to <code>Array.prototype.find</code> and calls <code>fn</code> on each chunk 2619in the stream to find a chunk with a truthy value for <code>fn</code>. Once an <code>fn</code> call's 2620awaited return value is truthy, the stream is destroyed and the promise is 2621fulfilled with value for which <code>fn</code> returned a truthy value. If all of the 2622<code>fn</code> calls on the chunks return a falsy value, the promise is fulfilled with 2623<code>undefined</code>.</p> 2624<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2625<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; 2626 2627<span class="hljs-comment">// With a synchronous predicate.</span> 2628<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">find</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>); <span class="hljs-comment">// 3</span> 2629<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">find</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">0</span>); <span class="hljs-comment">// 1</span> 2630<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">find</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">10</span>); <span class="hljs-comment">// undefined</span> 2631 2632<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span> 2633<span class="hljs-keyword">const</span> foundBigFile = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2634 <span class="hljs-string">'file1'</span>, 2635 <span class="hljs-string">'file2'</span>, 2636 <span class="hljs-string">'file3'</span>, 2637]).<span class="hljs-title function_">find</span>(<span class="hljs-keyword">async</span> (fileName) => { 2638 <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName); 2639 <span class="hljs-keyword">return</span> stats.<span class="hljs-property">size</span> > <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>; 2640}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2641<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(foundBigFile); <span class="hljs-comment">// File name of large file, if any file in the list is bigger than 1MB</span> 2642<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre> 2643<h6><code>readable.every(fn[, options])</code><span><a class="mark" href="#readableeveryfn-options" id="readableeveryfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_every_fn_options"></a></h6> 2644<div class="api_metadata"> 2645<span>Added in: v17.5.0</span> 2646</div> 2647<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2648<ul> 2649<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to call on each chunk of the stream. 2650<ul> 2651<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li> 2652<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2653<ul> 2654<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2655abort the <code>fn</code> call early.</li> 2656</ul> 2657</li> 2658</ul> 2659</li> 2660<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2661<ul> 2662<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call 2663on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2664<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2665aborted.</li> 2666</ul> 2667</li> 2668<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise evaluating to <code>true</code> if <code>fn</code> returned a truthy 2669value for all of the chunks.</li> 2670</ul> 2671<p>This method is similar to <code>Array.prototype.every</code> and calls <code>fn</code> on each chunk 2672in the stream to check if all awaited return values are truthy value for <code>fn</code>. 2673Once an <code>fn</code> call on a chunk awaited return value is falsy, the stream is 2674destroyed and the promise is fulfilled with <code>false</code>. If all of the <code>fn</code> calls 2675on the chunks return a truthy value, the promise is fulfilled with <code>true</code>.</p> 2676<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2677<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; 2678 2679<span class="hljs-comment">// With a synchronous predicate.</span> 2680<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">every</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>); <span class="hljs-comment">// false</span> 2681<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">every</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">0</span>); <span class="hljs-comment">// true</span> 2682 2683<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span> 2684<span class="hljs-keyword">const</span> allBigFiles = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2685 <span class="hljs-string">'file1'</span>, 2686 <span class="hljs-string">'file2'</span>, 2687 <span class="hljs-string">'file3'</span>, 2688]).<span class="hljs-title function_">every</span>(<span class="hljs-keyword">async</span> (fileName) => { 2689 <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName); 2690 <span class="hljs-keyword">return</span> stats.<span class="hljs-property">size</span> > <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>; 2691}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2692<span class="hljs-comment">// `true` if all files in the list are bigger than 1MiB</span> 2693<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(allBigFiles); 2694<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre> 2695<h6><code>readable.flatMap(fn[, options])</code><span><a class="mark" href="#readableflatmapfn-options" id="readableflatmapfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_flatmap_fn_options"></a></h6> 2696<div class="api_metadata"> 2697<span>Added in: v17.5.0</span> 2698</div> 2699<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2700<ul> 2701<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor" class="type"><AsyncGeneratorFunction></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a function to map over 2702every chunk in the stream. 2703<ul> 2704<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li> 2705<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2706<ul> 2707<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2708abort the <code>fn</code> call early.</li> 2709</ul> 2710</li> 2711</ul> 2712</li> 2713<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2714<ul> 2715<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the maximum concurrent invocation of <code>fn</code> to call 2716on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2717<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2718aborted.</li> 2719</ul> 2720</li> 2721<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream flat-mapped with the function <code>fn</code>.</li> 2722</ul> 2723<p>This method returns a new stream by applying the given callback to each 2724chunk of the stream and then flattening the result.</p> 2725<p>It is possible to return a stream or another iterable or async iterable from 2726<code>fn</code> and the result streams will be merged (flattened) into the returned 2727stream.</p> 2728<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2729<span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 2730 2731<span class="hljs-comment">// With a synchronous mapper.</span> 2732<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">flatMap</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> [x, x])) { 2733 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1, 1, 2, 2, 3, 3, 4, 4</span> 2734} 2735<span class="hljs-comment">// With an asynchronous mapper, combine the contents of 4 files</span> 2736<span class="hljs-keyword">const</span> concatResult = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2737 <span class="hljs-string">'./1.mjs'</span>, 2738 <span class="hljs-string">'./2.mjs'</span>, 2739 <span class="hljs-string">'./3.mjs'</span>, 2740 <span class="hljs-string">'./4.mjs'</span>, 2741]).<span class="hljs-title function_">flatMap</span>(<span class="hljs-function">(<span class="hljs-params">fileName</span>) =></span> <span class="hljs-title function_">createReadStream</span>(fileName)); 2742<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> result <span class="hljs-keyword">of</span> concatResult) { 2743 <span class="hljs-comment">// This will contain the contents (all chunks) of all 4 files</span> 2744 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); 2745}</code> <button class="copy-button">copy</button></pre> 2746<h6><code>readable.drop(limit[, options])</code><span><a class="mark" href="#readabledroplimit-options" id="readabledroplimit-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_drop_limit_options"></a></h6> 2747<div class="api_metadata"> 2748<span>Added in: v17.5.0</span> 2749</div> 2750<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2751<ul> 2752<li><code>limit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the number of chunks to drop from the readable.</li> 2753<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2754<ul> 2755<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2756aborted.</li> 2757</ul> 2758</li> 2759<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream with <code>limit</code> chunks dropped.</li> 2760</ul> 2761<p>This method returns a new stream with the first <code>limit</code> chunks dropped.</p> 2762<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2763 2764<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">drop</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">toArray</span>(); <span class="hljs-comment">// [3, 4]</span></code> <button class="copy-button">copy</button></pre> 2765<h6><code>readable.take(limit[, options])</code><span><a class="mark" href="#readabletakelimit-options" id="readabletakelimit-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_take_limit_options"></a></h6> 2766<div class="api_metadata"> 2767<span>Added in: v17.5.0</span> 2768</div> 2769<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2770<ul> 2771<li><code>limit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the number of chunks to take from the readable.</li> 2772<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2773<ul> 2774<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2775aborted.</li> 2776</ul> 2777</li> 2778<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream with <code>limit</code> chunks taken.</li> 2779</ul> 2780<p>This method returns a new stream with the first <code>limit</code> chunks.</p> 2781<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2782 2783<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">take</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">toArray</span>(); <span class="hljs-comment">// [1, 2]</span></code> <button class="copy-button">copy</button></pre> 2784<h6><code>readable.asIndexedPairs([options])</code><span><a class="mark" href="#readableasindexedpairsoptions" id="readableasindexedpairsoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_asindexedpairs_options"></a></h6> 2785<div class="api_metadata"> 2786<details class="changelog"><summary>History</summary> 2787<table> 2788<tbody><tr><th>Version</th><th>Changes</th></tr> 2789<tr><td>v18.17.0</td> 2790<td><p>Using the <code>asIndexedPairs</code> method emits a runtime warning that it will be removed in a future version.</p></td></tr> 2791<tr><td>v17.5.0</td> 2792<td><p><span>Added in: v17.5.0</span></p></td></tr> 2793</tbody></table> 2794</details> 2795</div> 2796<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2797<ul> 2798<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2799<ul> 2800<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2801aborted.</li> 2802</ul> 2803</li> 2804<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream of indexed pairs.</li> 2805</ul> 2806<p>This method returns a new stream with chunks of the underlying stream paired 2807with a counter in the form <code>[index, chunk]</code>. The first index value is 0 and it 2808increases by 1 for each chunk produced.</p> 2809<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2810 2811<span class="hljs-keyword">const</span> pairs = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>]).<span class="hljs-title function_">asIndexedPairs</span>().<span class="hljs-title function_">toArray</span>(); 2812<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pairs); <span class="hljs-comment">// [[0, 'a'], [1, 'b'], [2, 'c']]</span></code> <button class="copy-button">copy</button></pre> 2813<h6><code>readable.reduce(fn[, initial[, options]])</code><span><a class="mark" href="#readablereducefn-initial-options" id="readablereducefn-initial-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_reduce_fn_initial_options"></a></h6> 2814<div class="api_metadata"> 2815<span>Added in: v17.5.0</span> 2816</div> 2817<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2818<ul> 2819<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> a reducer function to call over every chunk 2820in the stream. 2821<ul> 2822<li><code>previous</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the value obtained from the last call to <code>fn</code> or the 2823<code>initial</code> value if specified or the first chunk of the stream otherwise.</li> 2824<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> a chunk of data from the stream.</li> 2825<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2826<ul> 2827<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2828abort the <code>fn</code> call early.</li> 2829</ul> 2830</li> 2831</ul> 2832</li> 2833<li><code>initial</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> the initial value to use in the reduction.</li> 2834<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2835<ul> 2836<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2837aborted.</li> 2838</ul> 2839</li> 2840<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> a promise for the final value of the reduction.</li> 2841</ul> 2842<p>This method calls <code>fn</code> on each chunk of the stream in order, passing it the 2843result from the calculation on the previous element. It returns a promise for 2844the final value of the reduction.</p> 2845<p>If no <code>initial</code> value is supplied the first chunk of the stream is used as the 2846initial value. If the stream is empty, the promise is rejected with a 2847<code>TypeError</code> with the <code>ERR_INVALID_ARGS</code> code property.</p> 2848<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2849<span class="hljs-keyword">import</span> { readdir, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; 2850<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>; 2851 2852<span class="hljs-keyword">const</span> directoryPath = <span class="hljs-string">'./src'</span>; 2853<span class="hljs-keyword">const</span> filesInDir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readdir</span>(directoryPath); 2854 2855<span class="hljs-keyword">const</span> folderSize = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(filesInDir) 2856 .<span class="hljs-title function_">reduce</span>(<span class="hljs-keyword">async</span> (totalSize, file) => { 2857 <span class="hljs-keyword">const</span> { size } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(<span class="hljs-title function_">join</span>(directoryPath, file)); 2858 <span class="hljs-keyword">return</span> totalSize + size; 2859 }, <span class="hljs-number">0</span>); 2860 2861<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(folderSize);</code> <button class="copy-button">copy</button></pre> 2862<p>The reducer function iterates the stream element-by-element which means that 2863there is no <code>concurrency</code> parameter or parallelism. To perform a <code>reduce</code> 2864concurrently, you can extract the async function to <a href="#readablemapfn-options"><code>readable.map</code></a> method.</p> 2865<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 2866<span class="hljs-keyword">import</span> { readdir, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; 2867<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>; 2868 2869<span class="hljs-keyword">const</span> directoryPath = <span class="hljs-string">'./src'</span>; 2870<span class="hljs-keyword">const</span> filesInDir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readdir</span>(directoryPath); 2871 2872<span class="hljs-keyword">const</span> folderSize = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(filesInDir) 2873 .<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">file</span>) =></span> <span class="hljs-title function_">stat</span>(<span class="hljs-title function_">join</span>(directoryPath, file)), { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }) 2874 .<span class="hljs-title function_">reduce</span>(<span class="hljs-function">(<span class="hljs-params">totalSize, { size }</span>) =></span> totalSize + size, <span class="hljs-number">0</span>); 2875 2876<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(folderSize);</code> <button class="copy-button">copy</button></pre> 2877<h4>Duplex and transform streams<span><a class="mark" href="#duplex-and-transform-streams" id="duplex-and-transform-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_duplex_and_transform_streams"></a></h4> 2878<h5>Class: <code>stream.Duplex</code><span><a class="mark" href="#class-streamduplex" id="class-streamduplex">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_duplex"></a></h5> 2879<div class="api_metadata"> 2880<details class="changelog"><summary>History</summary> 2881<table> 2882<tbody><tr><th>Version</th><th>Changes</th></tr> 2883<tr><td>v6.8.0</td> 2884<td><p>Instances of <code>Duplex</code> now return <code>true</code> when checking <code>instanceof stream.Writable</code>.</p></td></tr> 2885<tr><td>v0.9.4</td> 2886<td><p><span>Added in: v0.9.4</span></p></td></tr> 2887</tbody></table> 2888</details> 2889</div> 2890 2891<p>Duplex streams are streams that implement both the <a href="#class-streamreadable"><code>Readable</code></a> and 2892<a href="#class-streamwritable"><code>Writable</code></a> interfaces.</p> 2893<p>Examples of <code>Duplex</code> streams include:</p> 2894<ul> 2895<li><a href="net.html#class-netsocket">TCP sockets</a></li> 2896<li><a href="zlib.html">zlib streams</a></li> 2897<li><a href="crypto.html">crypto streams</a></li> 2898</ul> 2899<h6><code>duplex.allowHalfOpen</code><span><a class="mark" href="#duplexallowhalfopen" id="duplexallowhalfopen">#</a></span><a aria-hidden="true" class="legacy" id="stream_duplex_allowhalfopen"></a></h6> 2900<div class="api_metadata"> 2901<span>Added in: v0.9.4</span> 2902</div> 2903<ul> 2904<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 2905</ul> 2906<p>If <code>false</code> then the stream will automatically end the writable side when the 2907readable side ends. Set initially by the <code>allowHalfOpen</code> constructor option, 2908which defaults to <code>true</code>.</p> 2909<p>This can be changed manually to change the half-open behavior of an existing 2910<code>Duplex</code> stream instance, but must be changed before the <code>'end'</code> event is 2911emitted.</p> 2912<h5>Class: <code>stream.Transform</code><span><a class="mark" href="#class-streamtransform" id="class-streamtransform">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_transform"></a></h5> 2913<div class="api_metadata"> 2914<span>Added in: v0.9.4</span> 2915</div> 2916 2917<p>Transform streams are <a href="#class-streamduplex"><code>Duplex</code></a> streams where the output is in some way 2918related to the input. Like all <a href="#class-streamduplex"><code>Duplex</code></a> streams, <code>Transform</code> streams 2919implement both the <a href="#class-streamreadable"><code>Readable</code></a> and <a href="#class-streamwritable"><code>Writable</code></a> interfaces.</p> 2920<p>Examples of <code>Transform</code> streams include:</p> 2921<ul> 2922<li><a href="zlib.html">zlib streams</a></li> 2923<li><a href="crypto.html">crypto streams</a></li> 2924</ul> 2925<h6><code>transform.destroy([error])</code><span><a class="mark" href="#transformdestroyerror" id="transformdestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="stream_transform_destroy_error"></a></h6> 2926<div class="api_metadata"> 2927<details class="changelog"><summary>History</summary> 2928<table> 2929<tbody><tr><th>Version</th><th>Changes</th></tr> 2930<tr><td>v14.0.0</td> 2931<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr> 2932<tr><td>v8.0.0</td> 2933<td><p><span>Added in: v8.0.0</span></p></td></tr> 2934</tbody></table> 2935</details> 2936</div> 2937<ul> 2938<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 2939<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 2940</ul> 2941<p>Destroy the stream, and optionally emit an <code>'error'</code> event. After this call, the 2942transform stream would release any internal resources. 2943Implementors should not override this method, but instead implement 2944<a href="#readable_destroyerr-callback"><code>readable._destroy()</code></a>. 2945The default implementation of <code>_destroy()</code> for <code>Transform</code> also emit <code>'close'</code> 2946unless <code>emitClose</code> is set in false.</p> 2947<p>Once <code>destroy()</code> has been called, any further calls will be a no-op and no 2948further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p> 2949<h4><code>stream.finished(stream[, options], callback)</code><span><a class="mark" href="#streamfinishedstream-options-callback" id="streamfinishedstream-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_finished_stream_options_callback"></a></h4> 2950<div class="api_metadata"> 2951<details class="changelog"><summary>History</summary> 2952<table> 2953<tbody><tr><th>Version</th><th>Changes</th></tr> 2954<tr><td>v18.14.0</td> 2955<td><p>Added support for <code>ReadableStream</code> and <code>WritableStream</code>.</p></td></tr> 2956<tr><td>v15.11.0</td> 2957<td><p>The <code>signal</code> option was added.</p></td></tr> 2958<tr><td>v14.0.0</td> 2959<td><p>The <code>finished(stream, cb)</code> will wait for the <code>'close'</code> event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit <code>'close'</code>.</p></td></tr> 2960<tr><td>v14.0.0</td> 2961<td><p>Emitting <code>'close'</code> before <code>'end'</code> on a <code>Readable</code> stream will cause an <code>ERR_STREAM_PREMATURE_CLOSE</code> error.</p></td></tr> 2962<tr><td>v14.0.0</td> 2963<td><p>Callback will be invoked on streams which have already finished before the call to <code>finished(stream, cb)</code>.</p></td></tr> 2964<tr><td>v10.0.0</td> 2965<td><p><span>Added in: v10.0.0</span></p></td></tr> 2966</tbody></table> 2967</details> 2968</div> 2969<ul> 2970<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 2971</ul> 2972<p>A readable and/or writable stream/webstream.</p> 2973<ul> 2974<li> 2975<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> 2976<ul> 2977<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>false</code>, then a call to <code>emit('error', err)</code> is 2978not treated as finished. <strong>Default:</strong> <code>true</code>.</li> 2979<li><code>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When set to <code>false</code>, the callback will be called when 2980the stream ends even though the stream might still be readable. 2981<strong>Default:</strong> <code>true</code>.</li> 2982<li><code>writable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When set to <code>false</code>, the callback will be called when 2983the stream ends even though the stream might still be writable. 2984<strong>Default:</strong> <code>true</code>.</li> 2985<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows aborting the wait for the stream finish. The 2986underlying stream will <em>not</em> be aborted if the signal is aborted. The 2987callback will get called with an <code>AbortError</code>. All registered 2988listeners added by this function will also be removed.</li> 2989<li><code>cleanup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> remove all registered stream listeners. 2990<strong>Default:</strong> <code>false</code>.</li> 2991</ul> 2992</li> 2993<li> 2994<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that takes an optional error 2995argument.</p> 2996</li> 2997<li> 2998<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A cleanup function which removes all registered 2999listeners.</p> 3000</li> 3001</ul> 3002<p>A function to get notified when a stream is no longer readable, writable 3003or has experienced an error or a premature close event.</p> 3004<pre><code class="language-js"><span class="hljs-keyword">const</span> { finished } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3005<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 3006 3007<span class="hljs-keyword">const</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>); 3008 3009<span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 3010 <span class="hljs-keyword">if</span> (err) { 3011 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Stream failed.'</span>, err); 3012 } <span class="hljs-keyword">else</span> { 3013 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>); 3014 } 3015}); 3016 3017rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code> <button class="copy-button">copy</button></pre> 3018<p>Especially useful in error handling scenarios where a stream is destroyed 3019prematurely (like an aborted HTTP request), and will not emit <code>'end'</code> 3020or <code>'finish'</code>.</p> 3021<p>The <code>finished</code> API provides <a href="#streamfinishedstream-options">promise version</a>.</p> 3022<p><code>stream.finished()</code> leaves dangling event listeners (in particular 3023<code>'error'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code>) after <code>callback</code> has been 3024invoked. The reason for this is so that unexpected <code>'error'</code> events (due to 3025incorrect stream implementations) do not cause unexpected crashes. 3026If this is unwanted behavior then the returned cleanup function needs to be 3027invoked in the callback:</p> 3028<pre><code class="language-js"><span class="hljs-keyword">const</span> cleanup = <span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 3029 <span class="hljs-title function_">cleanup</span>(); 3030 <span class="hljs-comment">// ...</span> 3031});</code> <button class="copy-button">copy</button></pre> 3032<h4><code>stream.pipeline(source[, ...transforms], destination, callback)</code><span><a class="mark" href="#streampipelinesource-transforms-destination-callback" id="streampipelinesource-transforms-destination-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_source_transforms_destination_callback"></a></h4> 3033<h4><code>stream.pipeline(streams, callback)</code><span><a class="mark" href="#streampipelinestreams-callback" id="streampipelinestreams-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_streams_callback"></a></h4> 3034<div class="api_metadata"> 3035<details class="changelog"><summary>History</summary> 3036<table> 3037<tbody><tr><th>Version</th><th>Changes</th></tr> 3038<tr><td>v18.16.0</td> 3039<td><p>Added support for webstreams.</p></td></tr> 3040<tr><td>v18.0.0</td> 3041<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr> 3042<tr><td>v14.0.0</td> 3043<td><p>The <code>pipeline(..., cb)</code> will wait for the <code>'close'</code> event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit <code>'close'</code>.</p></td></tr> 3044<tr><td>v13.10.0</td> 3045<td><p>Add support for async generators.</p></td></tr> 3046<tr><td>v10.0.0</td> 3047<td><p><span>Added in: v10.0.0</span></p></td></tr> 3048</tbody></table> 3049</details> 3050</div> 3051<ul> 3052<li><code>streams</code> <a href="stream.html#stream" class="type"><Stream[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable[]></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream[]></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream[]></a> | <a href="webstreams.html#class-transformstream" class="type"><TransformStream[]></a></li> 3053<li><code>source</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a> 3054<ul> 3055<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 3056</ul> 3057</li> 3058<li><code>...transforms</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="webstreams.html#class-transformstream" class="type"><TransformStream></a> 3059<ul> 3060<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 3061<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 3062</ul> 3063</li> 3064<li><code>destination</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a> 3065<ul> 3066<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 3067<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> 3068</ul> 3069</li> 3070<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when the pipeline is fully done. 3071<ul> 3072<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 3073<li><code>val</code> Resolved value of <code>Promise</code> returned by <code>destination</code>.</li> 3074</ul> 3075</li> 3076<li>Returns: <a href="stream.html#stream" class="type"><Stream></a></li> 3077</ul> 3078<p>A module method to pipe between streams and generators forwarding errors and 3079properly cleaning up and provide a callback when the pipeline is complete.</p> 3080<pre><code class="language-js"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3081<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 3082<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>); 3083 3084<span class="hljs-comment">// Use the pipeline API to easily pipe a series of streams</span> 3085<span class="hljs-comment">// together and get notified when the pipeline is fully done.</span> 3086 3087<span class="hljs-comment">// A pipeline to gzip a potentially huge tar file efficiently:</span> 3088 3089<span class="hljs-title function_">pipeline</span>( 3090 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 3091 zlib.<span class="hljs-title function_">createGzip</span>(), 3092 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 3093 <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 3094 <span class="hljs-keyword">if</span> (err) { 3095 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Pipeline failed.'</span>, err); 3096 } <span class="hljs-keyword">else</span> { 3097 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 3098 } 3099 }, 3100);</code> <button class="copy-button">copy</button></pre> 3101<p>The <code>pipeline</code> API provides a <a href="#streampipelinesource-transforms-destination-options">promise version</a>.</p> 3102<p><code>stream.pipeline()</code> will call <code>stream.destroy(err)</code> on all streams except:</p> 3103<ul> 3104<li><code>Readable</code> streams which have emitted <code>'end'</code> or <code>'close'</code>.</li> 3105<li><code>Writable</code> streams which have emitted <code>'finish'</code> or <code>'close'</code>.</li> 3106</ul> 3107<p><code>stream.pipeline()</code> leaves dangling event listeners on the streams 3108after the <code>callback</code> has been invoked. In the case of reuse of streams after 3109failure, this can cause event listener leaks and swallowed errors. If the last 3110stream is readable, dangling event listeners will be removed so that the last 3111stream can be consumed later.</p> 3112<p><code>stream.pipeline()</code> closes all the streams when an error is raised. 3113The <code>IncomingRequest</code> usage with <code>pipeline</code> could lead to an unexpected behavior 3114once it would destroy the socket without sending the expected response. 3115See the example below:</p> 3116<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 3117<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>); 3118<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3119 3120<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> { 3121 <span class="hljs-keyword">const</span> fileStream = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'./fileNotExist.txt'</span>); 3122 <span class="hljs-title function_">pipeline</span>(fileStream, res, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 3123 <span class="hljs-keyword">if</span> (err) { 3124 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err); <span class="hljs-comment">// No such file</span> 3125 <span class="hljs-comment">// this message can't be sent once `pipeline` already destroyed the socket</span> 3126 <span class="hljs-keyword">return</span> res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'error!!!'</span>); 3127 } 3128 }); 3129});</code> <button class="copy-button">copy</button></pre> 3130<h4><code>stream.compose(...streams)</code><span><a class="mark" href="#streamcomposestreams" id="streamcomposestreams">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_compose_streams"></a></h4> 3131<div class="api_metadata"> 3132<details class="changelog"><summary>History</summary> 3133<table> 3134<tbody><tr><th>Version</th><th>Changes</th></tr> 3135<tr><td>v18.16.0</td> 3136<td><p>Added support for webstreams.</p></td></tr> 3137<tr><td>v16.9.0</td> 3138<td><p><span>Added in: v16.9.0</span></p></td></tr> 3139</tbody></table> 3140</details> 3141</div> 3142<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - <code>stream.compose</code> is experimental.</div><p></p> 3143<ul> 3144<li><code>streams</code> <a href="stream.html#stream" class="type"><Stream[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable[]></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream[]></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream[]></a> | <a href="webstreams.html#class-transformstream" class="type"><TransformStream[]></a></li> 3145<li>Returns: <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li> 3146</ul> 3147<p>Combines two or more streams into a <code>Duplex</code> stream that writes to the 3148first stream and reads from the last. Each provided stream is piped into 3149the next, using <code>stream.pipeline</code>. If any of the streams error then all 3150are destroyed, including the outer <code>Duplex</code> stream.</p> 3151<p>Because <code>stream.compose</code> returns a new stream that in turn can (and 3152should) be piped into other streams, it enables composition. In contrast, 3153when passing streams to <code>stream.pipeline</code>, typically the first stream is 3154a readable stream and the last a writable stream, forming a closed 3155circuit.</p> 3156<p>If passed a <code>Function</code> it must be a factory method taking a <code>source</code> 3157<code>Iterable</code>.</p> 3158<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { compose, <span class="hljs-title class_">Transform</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 3159 3160<span class="hljs-keyword">const</span> removeSpaces = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({ 3161 <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3162 <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">replace</span>(<span class="hljs-string">' '</span>, <span class="hljs-string">''</span>)); 3163 }, 3164}); 3165 3166<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">toUpper</span>(<span class="hljs-params">source</span>) { 3167 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) { 3168 <span class="hljs-keyword">yield</span> <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">toUpperCase</span>(); 3169 } 3170} 3171 3172<span class="hljs-keyword">let</span> res = <span class="hljs-string">''</span>; 3173<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> buf <span class="hljs-keyword">of</span> <span class="hljs-title function_">compose</span>(removeSpaces, toUpper).<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world'</span>)) { 3174 res += buf; 3175} 3176 3177<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res); <span class="hljs-comment">// prints 'HELLOWORLD'</span></code> <button class="copy-button">copy</button></pre> 3178<p><code>stream.compose</code> can be used to convert async iterables, generators and 3179functions into streams.</p> 3180<ul> 3181<li><code>AsyncIterable</code> converts into a readable <code>Duplex</code>. Cannot yield 3182<code>null</code>.</li> 3183<li><code>AsyncGeneratorFunction</code> converts into a readable/writable transform <code>Duplex</code>. 3184Must take a source <code>AsyncIterable</code> as first parameter. Cannot yield 3185<code>null</code>.</li> 3186<li><code>AsyncFunction</code> converts into a writable <code>Duplex</code>. Must return 3187either <code>null</code> or <code>undefined</code>.</li> 3188</ul> 3189<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { compose } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 3190<span class="hljs-keyword">import</span> { finished } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>; 3191 3192<span class="hljs-comment">// Convert AsyncIterable into readable Duplex.</span> 3193<span class="hljs-keyword">const</span> s1 = <span class="hljs-title function_">compose</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>*() { 3194 <span class="hljs-keyword">yield</span> <span class="hljs-string">'Hello'</span>; 3195 <span class="hljs-keyword">yield</span> <span class="hljs-string">'World'</span>; 3196}()); 3197 3198<span class="hljs-comment">// Convert AsyncGenerator into transform Duplex.</span> 3199<span class="hljs-keyword">const</span> s2 = <span class="hljs-title function_">compose</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>*(source) { 3200 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) { 3201 <span class="hljs-keyword">yield</span> <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">toUpperCase</span>(); 3202 } 3203}); 3204 3205<span class="hljs-keyword">let</span> res = <span class="hljs-string">''</span>; 3206 3207<span class="hljs-comment">// Convert AsyncFunction into writable Duplex.</span> 3208<span class="hljs-keyword">const</span> s3 = <span class="hljs-title function_">compose</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params">source</span>) { 3209 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) { 3210 res += chunk; 3211 } 3212}); 3213 3214<span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(<span class="hljs-title function_">compose</span>(s1, s2, s3)); 3215 3216<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res); <span class="hljs-comment">// prints 'HELLOWORLD'</span></code> <button class="copy-button">copy</button></pre> 3217<p>See <a href="#readablecomposestream-options"><code>readable.compose(stream)</code></a> for <code>stream.compose</code> as operator.</p> 3218<h4><code>stream.Readable.from(iterable[, options])</code><span><a class="mark" href="#streamreadablefromiterable-options" id="streamreadablefromiterable-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_from_iterable_options"></a></h4> 3219<div class="api_metadata"> 3220<span>Added in: v12.3.0, v10.17.0</span> 3221</div> 3222<ul> 3223<li><code>iterable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> Object implementing the <code>Symbol.asyncIterator</code> or 3224<code>Symbol.iterator</code> iterable protocol. Emits an 'error' event if a null 3225value is passed.</li> 3226<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Options provided to <code>new stream.Readable([options])</code>. 3227By default, <code>Readable.from()</code> will set <code>options.objectMode</code> to <code>true</code>, unless 3228this is explicitly opted out by setting <code>options.objectMode</code> to <code>false</code>.</li> 3229<li>Returns: <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li> 3230</ul> 3231<p>A utility method for creating readable streams out of iterators.</p> 3232<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3233 3234<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) { 3235 <span class="hljs-keyword">yield</span> <span class="hljs-string">'hello'</span>; 3236 <span class="hljs-keyword">yield</span> <span class="hljs-string">'streams'</span>; 3237} 3238 3239<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">generate</span>()); 3240 3241readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 3242 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); 3243});</code> <button class="copy-button">copy</button></pre> 3244<p>Calling <code>Readable.from(string)</code> or <code>Readable.from(buffer)</code> will not have 3245the strings or buffers be iterated to match the other streams semantics 3246for performance reasons.</p> 3247<p>If an <code>Iterable</code> object containing promises is passed as an argument, 3248it might result in unhandled rejection.</p> 3249<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3250 3251<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 3252 <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'1'</span>), <span class="hljs-number">1500</span>)), 3253 <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">_, reject</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'2'</span>)), <span class="hljs-number">1000</span>)), <span class="hljs-comment">// Unhandled rejection</span> 3254]);</code> <button class="copy-button">copy</button></pre> 3255<h4><code>stream.Readable.fromWeb(readableStream[, options])</code><span><a class="mark" href="#streamreadablefromwebreadablestream-options" id="streamreadablefromwebreadablestream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_fromweb_readablestream_options"></a></h4> 3256<div class="api_metadata"> 3257<span>Added in: v17.0.0</span> 3258</div> 3259<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3260<ul> 3261<li><code>readableStream</code> <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3262<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3263<ul> 3264<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 3265<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 3266<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3267<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li> 3268</ul> 3269</li> 3270<li>Returns: <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li> 3271</ul> 3272<h4><code>stream.Readable.isDisturbed(stream)</code><span><a class="mark" href="#streamreadableisdisturbedstream" id="streamreadableisdisturbedstream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_isdisturbed_stream"></a></h4> 3273<div class="api_metadata"> 3274<span>Added in: v16.8.0</span> 3275</div> 3276<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3277<ul> 3278<li><code>stream</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3279<li>Returns: <code>boolean</code></li> 3280</ul> 3281<p>Returns whether the stream has been read from or cancelled.</p> 3282<h4><code>stream.isErrored(stream)</code><span><a class="mark" href="#streamiserroredstream" id="streamiserroredstream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_iserrored_stream"></a></h4> 3283<div class="api_metadata"> 3284<span>Added in: v17.3.0, v16.14.0</span> 3285</div> 3286<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3287<ul> 3288<li><code>stream</code> <a href="stream.html#class-streamreadable" class="type"><Readable></a> | <a href="stream.html#class-streamwritable" class="type"><Writable></a> | <a href="stream.html#class-streamduplex" class="type"><Duplex></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3289<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3290</ul> 3291<p>Returns whether the stream has encountered an error.</p> 3292<h4><code>stream.isReadable(stream)</code><span><a class="mark" href="#streamisreadablestream" id="streamisreadablestream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_isreadable_stream"></a></h4> 3293<div class="api_metadata"> 3294<span>Added in: v17.4.0, v16.14.0</span> 3295</div> 3296<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3297<ul> 3298<li><code>stream</code> <a href="stream.html#class-streamreadable" class="type"><Readable></a> | <a href="stream.html#class-streamduplex" class="type"><Duplex></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3299<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3300</ul> 3301<p>Returns whether the stream is readable.</p> 3302<h4><code>stream.Readable.toWeb(streamReadable[, options])</code><span><a class="mark" href="#streamreadabletowebstreamreadable-options" id="streamreadabletowebstreamreadable-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_toweb_streamreadable_options"></a></h4> 3303<div class="api_metadata"> 3304<span>Added in: v17.0.0</span> 3305</div> 3306<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3307<ul> 3308<li><code>streamReadable</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li> 3309<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3310<ul> 3311<li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3312<ul> 3313<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum internal queue size (of the created 3314<code>ReadableStream</code>) before backpressure is applied in reading from the given 3315<code>stream.Readable</code>. If no value is provided, it will be taken from the 3316given <code>stream.Readable</code>.</li> 3317<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that size of the given chunk of data. 3318If no value is provided, the size will be <code>1</code> for all the chunks. 3319<ul> 3320<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> 3321<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 3322</ul> 3323</li> 3324</ul> 3325</li> 3326</ul> 3327</li> 3328<li>Returns: <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3329</ul> 3330<h4><code>stream.Writable.fromWeb(writableStream[, options])</code><span><a class="mark" href="#streamwritablefromwebwritablestream-options" id="streamwritablefromwebwritablestream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_writable_fromweb_writablestream_options"></a></h4> 3331<div class="api_metadata"> 3332<span>Added in: v17.0.0</span> 3333</div> 3334<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3335<ul> 3336<li><code>writableStream</code> <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 3337<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3338<ul> 3339<li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3340<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 3341<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3342<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li> 3343</ul> 3344</li> 3345<li>Returns: <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a></li> 3346</ul> 3347<h4><code>stream.Writable.toWeb(streamWritable)</code><span><a class="mark" href="#streamwritabletowebstreamwritable" id="streamwritabletowebstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_writable_toweb_streamwritable"></a></h4> 3348<div class="api_metadata"> 3349<span>Added in: v17.0.0</span> 3350</div> 3351<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3352<ul> 3353<li><code>streamWritable</code> <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a></li> 3354<li>Returns: <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 3355</ul> 3356<h4><code>stream.Duplex.from(src)</code><span><a class="mark" href="#streamduplexfromsrc" id="streamduplexfromsrc">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplex_from_src"></a></h4> 3357<div class="api_metadata"> 3358<details class="changelog"><summary>History</summary> 3359<table> 3360<tbody><tr><th>Version</th><th>Changes</th></tr> 3361<tr><td>v18.17.0</td> 3362<td><p>The <code>src</code> argument can now be a <code>ReadableStream</code> or <code>WritableStream</code>.</p></td></tr> 3363<tr><td>v16.8.0</td> 3364<td><p><span>Added in: v16.8.0</span></p></td></tr> 3365</tbody></table> 3366</details> 3367</div> 3368<ul> 3369<li><code>src</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="buffer.html#class-blob" class="type"><Blob></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a> | <a href="https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor" class="type"><AsyncGeneratorFunction></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type"><AsyncFunction></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 3370</ul> 3371<p>A utility method for creating duplex streams.</p> 3372<ul> 3373<li><code>Stream</code> converts writable stream into writable <code>Duplex</code> and readable stream 3374to <code>Duplex</code>.</li> 3375<li><code>Blob</code> converts into readable <code>Duplex</code>.</li> 3376<li><code>string</code> converts into readable <code>Duplex</code>.</li> 3377<li><code>ArrayBuffer</code> converts into readable <code>Duplex</code>.</li> 3378<li><code>AsyncIterable</code> converts into a readable <code>Duplex</code>. Cannot yield 3379<code>null</code>.</li> 3380<li><code>AsyncGeneratorFunction</code> converts into a readable/writable transform 3381<code>Duplex</code>. Must take a source <code>AsyncIterable</code> as first parameter. Cannot yield 3382<code>null</code>.</li> 3383<li><code>AsyncFunction</code> converts into a writable <code>Duplex</code>. Must return 3384either <code>null</code> or <code>undefined</code></li> 3385<li><code>Object ({ writable, readable })</code> converts <code>readable</code> and 3386<code>writable</code> into <code>Stream</code> and then combines them into <code>Duplex</code> where the 3387<code>Duplex</code> will write to the <code>writable</code> and read from the <code>readable</code>.</li> 3388<li><code>Promise</code> converts into readable <code>Duplex</code>. Value <code>null</code> is ignored.</li> 3389<li><code>ReadableStream</code> converts into readable <code>Duplex</code>.</li> 3390<li><code>WritableStream</code> converts into writable <code>Duplex</code>.</li> 3391<li>Returns: <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li> 3392</ul> 3393<p>If an <code>Iterable</code> object containing promises is passed as an argument, 3394it might result in unhandled rejection.</p> 3395<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3396 3397<span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">from</span>([ 3398 <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'1'</span>), <span class="hljs-number">1500</span>)), 3399 <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">_, reject</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'2'</span>)), <span class="hljs-number">1000</span>)), <span class="hljs-comment">// Unhandled rejection</span> 3400]);</code> <button class="copy-button">copy</button></pre> 3401<h4><code>stream.Duplex.fromWeb(pair[, options])</code><span><a class="mark" href="#streamduplexfromwebpair-options" id="streamduplexfromwebpair-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplex_fromweb_pair_options"></a></h4> 3402<div class="api_metadata"> 3403<span>Added in: v17.0.0</span> 3404</div> 3405<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3406<ul> 3407<li><code>pair</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3408<ul> 3409<li><code>readable</code> <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3410<li><code>writable</code> <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 3411</ul> 3412</li> 3413<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3414<ul> 3415<li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3416<li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3417<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 3418<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 3419<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3420<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li> 3421</ul> 3422</li> 3423<li>Returns: <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li> 3424</ul> 3425 3426<pre class="with-42-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Duplex</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 3427<span class="hljs-keyword">import</span> { 3428 <span class="hljs-title class_">ReadableStream</span>, 3429 <span class="hljs-title class_">WritableStream</span>, 3430} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>; 3431 3432<span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({ 3433 <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) { 3434 controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>); 3435 }, 3436}); 3437 3438<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>({ 3439 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk</span>) { 3440 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk); 3441 }, 3442}); 3443 3444<span class="hljs-keyword">const</span> pair = { 3445 readable, 3446 writable, 3447}; 3448<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">fromWeb</span>(pair, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span>, <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span> }); 3449 3450duplex.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>); 3451 3452<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> duplex) { 3453 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, chunk); 3454}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3455<span class="hljs-keyword">const</span> { 3456 <span class="hljs-title class_">ReadableStream</span>, 3457 <span class="hljs-title class_">WritableStream</span>, 3458} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>); 3459 3460<span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({ 3461 <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) { 3462 controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>); 3463 }, 3464}); 3465 3466<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>({ 3467 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk</span>) { 3468 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk); 3469 }, 3470}); 3471 3472<span class="hljs-keyword">const</span> pair = { 3473 readable, 3474 writable, 3475}; 3476<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">fromWeb</span>(pair, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span>, <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span> }); 3477 3478duplex.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>); 3479duplex.<span class="hljs-title function_">once</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, duplex.<span class="hljs-title function_">read</span>()));</code><button class="copy-button">copy</button></pre> 3480<h4><code>stream.Duplex.toWeb(streamDuplex)</code><span><a class="mark" href="#streamduplextowebstreamduplex" id="streamduplextowebstreamduplex">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplex_toweb_streamduplex"></a></h4> 3481<div class="api_metadata"> 3482<span>Added in: v17.0.0</span> 3483</div> 3484<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3485<ul> 3486<li><code>streamDuplex</code> <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li> 3487<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3488<ul> 3489<li><code>readable</code> <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3490<li><code>writable</code> <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 3491</ul> 3492</li> 3493</ul> 3494 3495<pre class="with-42-chars"><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Duplex</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>; 3496 3497<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>({ 3498 <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span>, 3499 <span class="hljs-title function_">read</span>(<span class="hljs-params"></span>) { 3500 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-string">'world'</span>); 3501 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>); 3502 }, 3503 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3504 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk); 3505 <span class="hljs-title function_">callback</span>(); 3506 }, 3507}); 3508 3509<span class="hljs-keyword">const</span> { readable, writable } = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">toWeb</span>(duplex); 3510writable.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>); 3511 3512<span class="hljs-keyword">const</span> { value } = <span class="hljs-keyword">await</span> readable.<span class="hljs-title function_">getReader</span>().<span class="hljs-title function_">read</span>(); 3513<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, value);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3514 3515<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>({ 3516 <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span>, 3517 <span class="hljs-title function_">read</span>(<span class="hljs-params"></span>) { 3518 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-string">'world'</span>); 3519 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>); 3520 }, 3521 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3522 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk); 3523 <span class="hljs-title function_">callback</span>(); 3524 }, 3525}); 3526 3527<span class="hljs-keyword">const</span> { readable, writable } = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">toWeb</span>(duplex); 3528writable.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>); 3529 3530readable.<span class="hljs-title function_">getReader</span>().<span class="hljs-title function_">read</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> { 3531 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, result.<span class="hljs-property">value</span>); 3532});</code><button class="copy-button">copy</button></pre> 3533<h4><code>stream.addAbortSignal(signal, stream)</code><span><a class="mark" href="#streamaddabortsignalsignal-stream" id="streamaddabortsignalsignal-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_addabortsignal_signal_stream"></a></h4> 3534<div class="api_metadata"> 3535<details class="changelog"><summary>History</summary> 3536<table> 3537<tbody><tr><th>Version</th><th>Changes</th></tr> 3538<tr><td>v18.16.0</td> 3539<td><p>Added support for <code>ReadableStream</code> and <code>WritableStream</code>.</p></td></tr> 3540<tr><td>v15.4.0</td> 3541<td><p><span>Added in: v15.4.0</span></p></td></tr> 3542</tbody></table> 3543</details> 3544</div> 3545<ul> 3546<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> A signal representing possible cancellation</li> 3547<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a> | <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a> | <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 3548</ul> 3549<p>A stream to attach a signal to.</p> 3550<p>Attaches an AbortSignal to a readable or writeable stream. This lets code 3551control stream destruction using an <code>AbortController</code>.</p> 3552<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed 3553<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code> 3554on the stream, and <code>controller.error(new AbortError())</code> for webstreams.</p> 3555<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 3556 3557<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 3558<span class="hljs-keyword">const</span> read = <span class="hljs-title function_">addAbortSignal</span>( 3559 controller.<span class="hljs-property">signal</span>, 3560 fs.<span class="hljs-title function_">createReadStream</span>((<span class="hljs-string">'object.json'</span>)), 3561); 3562<span class="hljs-comment">// Later, abort the operation closing the stream</span> 3563controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre> 3564<p>Or using an <code>AbortSignal</code> with a readable stream as an async iterable:</p> 3565<pre><code class="language-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 3566<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> controller.<span class="hljs-title function_">abort</span>(), <span class="hljs-number">10_000</span>); <span class="hljs-comment">// set a timeout</span> 3567<span class="hljs-keyword">const</span> stream = <span class="hljs-title function_">addAbortSignal</span>( 3568 controller.<span class="hljs-property">signal</span>, 3569 fs.<span class="hljs-title function_">createReadStream</span>((<span class="hljs-string">'object.json'</span>)), 3570); 3571(<span class="hljs-keyword">async</span> () => { 3572 <span class="hljs-keyword">try</span> { 3573 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> stream) { 3574 <span class="hljs-keyword">await</span> <span class="hljs-title function_">process</span>(chunk); 3575 } 3576 } <span class="hljs-keyword">catch</span> (e) { 3577 <span class="hljs-keyword">if</span> (e.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) { 3578 <span class="hljs-comment">// The operation was cancelled</span> 3579 } <span class="hljs-keyword">else</span> { 3580 <span class="hljs-keyword">throw</span> e; 3581 } 3582 } 3583})();</code> <button class="copy-button">copy</button></pre> 3584<p>Or using an <code>AbortSignal</code> with a ReadableStream:</p> 3585<pre><code class="language-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 3586<span class="hljs-keyword">const</span> rs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({ 3587 <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) { 3588 controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'hello'</span>); 3589 controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>); 3590 controller.<span class="hljs-title function_">close</span>(); 3591 }, 3592}); 3593 3594<span class="hljs-title function_">addAbortSignal</span>(controller.<span class="hljs-property">signal</span>, rs); 3595 3596<span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 3597 <span class="hljs-keyword">if</span> (err) { 3598 <span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) { 3599 <span class="hljs-comment">// The operation was cancelled</span> 3600 } 3601 } 3602}); 3603 3604<span class="hljs-keyword">const</span> reader = rs.<span class="hljs-title function_">getReader</span>(); 3605 3606reader.<span class="hljs-title function_">read</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">{ value, done }</span>) =></span> { 3607 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value); <span class="hljs-comment">// hello</span> 3608 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(done); <span class="hljs-comment">// false</span> 3609 controller.<span class="hljs-title function_">abort</span>(); 3610});</code> <button class="copy-button">copy</button></pre> 3611<h4><code>stream.getDefaultHighWaterMark(objectMode)</code><span><a class="mark" href="#streamgetdefaulthighwatermarkobjectmode" id="streamgetdefaulthighwatermarkobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_getdefaulthighwatermark_objectmode"></a></h4> 3612<div class="api_metadata"> 3613<span>Added in: v18.17.0</span> 3614</div> 3615<ul> 3616<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3617<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 3618</ul> 3619<p>Returns the default highWaterMark used by streams. 3620Defaults to <code>16384</code> (16 KiB), or <code>16</code> for <code>objectMode</code>.</p> 3621<h4><code>stream.setDefaultHighWaterMark(objectMode, value)</code><span><a class="mark" href="#streamsetdefaulthighwatermarkobjectmode-value" id="streamsetdefaulthighwatermarkobjectmode-value">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_setdefaulthighwatermark_objectmode_value"></a></h4> 3622<div class="api_metadata"> 3623<span>Added in: v18.17.0</span> 3624</div> 3625<ul> 3626<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3627<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> highWaterMark value</li> 3628</ul> 3629<p>Sets the default highWaterMark used by streams.</p> 3630</section><section><h3>API for stream implementers<span><a class="mark" href="#api-for-stream-implementers" id="api-for-stream-implementers">#</a></span><a aria-hidden="true" class="legacy" id="stream_api_for_stream_implementers"></a></h3> 3631 3632<p>The <code>node:stream</code> module API has been designed to make it possible to easily 3633implement streams using JavaScript's prototypal inheritance model.</p> 3634<p>First, a stream developer would declare a new JavaScript class that extends one 3635of the four basic stream classes (<code>stream.Writable</code>, <code>stream.Readable</code>, 3636<code>stream.Duplex</code>, or <code>stream.Transform</code>), making sure they call the appropriate 3637parent class constructor:</p> 3638<!-- eslint-disable no-useless-constructor --> 3639<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3640 3641<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> { 3642 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">{ highWaterMark, ...options }</span>) { 3643 <span class="hljs-variable language_">super</span>({ highWaterMark }); 3644 <span class="hljs-comment">// ...</span> 3645 } 3646}</code> <button class="copy-button">copy</button></pre> 3647<p>When extending streams, keep in mind what options the user 3648can and should provide before forwarding these to the base constructor. For 3649example, if the implementation makes assumptions in regard to the 3650<code>autoDestroy</code> and <code>emitClose</code> options, do not allow the 3651user to override these. Be explicit about what 3652options are forwarded instead of implicitly forwarding all options.</p> 3653<p>The new stream class must then implement one or more specific methods, depending 3654on the type of stream being created, as detailed in the chart below:</p> 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685<table><thead><tr><th>Use-case</th><th>Class</th><th>Method(s) to implement</th></tr></thead><tbody><tr><td>Reading only</td><td><a href="#class-streamreadable"><code>Readable</code></a></td><td><a href="#readable_readsize"><code>_read()</code></a></td></tr><tr><td>Writing only</td><td><a href="#class-streamwritable"><code>Writable</code></a></td><td><a href="#writable_writechunk-encoding-callback"><code>_write()</code></a>, <a href="#writable_writevchunks-callback"><code>_writev()</code></a>, <a href="#writable_finalcallback"><code>_final()</code></a></td></tr><tr><td>Reading and writing</td><td><a href="#class-streamduplex"><code>Duplex</code></a></td><td><a href="#readable_readsize"><code>_read()</code></a>, <a href="#writable_writechunk-encoding-callback"><code>_write()</code></a>, <a href="#writable_writevchunks-callback"><code>_writev()</code></a>, <a href="#writable_finalcallback"><code>_final()</code></a></td></tr><tr><td>Operate on written data, then read the result</td><td><a href="#class-streamtransform"><code>Transform</code></a></td><td><a href="#transform_transformchunk-encoding-callback"><code>_transform()</code></a>, <a href="#transform_flushcallback"><code>_flush()</code></a>, <a href="#writable_finalcallback"><code>_final()</code></a></td></tr></tbody></table> 3686<p>The implementation code for a stream should <em>never</em> call the "public" methods 3687of a stream that are intended for use by consumers (as described in the 3688<a href="#api-for-stream-consumers">API for stream consumers</a> section). Doing so may lead to adverse side effects 3689in application code consuming the stream.</p> 3690<p>Avoid overriding public methods such as <code>write()</code>, <code>end()</code>, <code>cork()</code>, 3691<code>uncork()</code>, <code>read()</code> and <code>destroy()</code>, or emitting internal events such 3692as <code>'error'</code>, <code>'data'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code> through <code>.emit()</code>. 3693Doing so can break current and future stream invariants leading to behavior 3694and/or compatibility issues with other streams, stream utilities, and user 3695expectations.</p> 3696<h4>Simplified construction<span><a class="mark" href="#simplified-construction" id="simplified-construction">#</a></span><a aria-hidden="true" class="legacy" id="stream_simplified_construction"></a></h4> 3697<div class="api_metadata"> 3698<span>Added in: v1.2.0</span> 3699</div> 3700<p>For many simple cases, it is possible to create a stream without relying on 3701inheritance. This can be accomplished by directly creating instances of the 3702<code>stream.Writable</code>, <code>stream.Readable</code>, <code>stream.Duplex</code>, or <code>stream.Transform</code> 3703objects and passing appropriate methods as constructor options.</p> 3704<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3705 3706<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 3707 <span class="hljs-title function_">construct</span>(<span class="hljs-params">callback</span>) { 3708 <span class="hljs-comment">// Initialize state and load resources...</span> 3709 }, 3710 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3711 <span class="hljs-comment">// ...</span> 3712 }, 3713 <span class="hljs-title function_">destroy</span>(<span class="hljs-params"></span>) { 3714 <span class="hljs-comment">// Free resources...</span> 3715 }, 3716});</code> <button class="copy-button">copy</button></pre> 3717<h4>Implementing a writable stream<span><a class="mark" href="#implementing-a-writable-stream" id="implementing-a-writable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_writable_stream"></a></h4> 3718<p>The <code>stream.Writable</code> class is extended to implement a <a href="#class-streamwritable"><code>Writable</code></a> stream.</p> 3719<p>Custom <code>Writable</code> streams <em>must</em> call the <code>new stream.Writable([options])</code> 3720constructor and implement the <code>writable._write()</code> and/or <code>writable._writev()</code> 3721method.</p> 3722<h5><code>new stream.Writable([options])</code><span><a class="mark" href="#new-streamwritableoptions" id="new-streamwritableoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_writable_options"></a></h5> 3723<div class="api_metadata"> 3724<details class="changelog"><summary>History</summary> 3725<table> 3726<tbody><tr><th>Version</th><th>Changes</th></tr> 3727<tr><td>v15.5.0</td> 3728<td><p>support passing in an AbortSignal.</p></td></tr> 3729<tr><td>v14.0.0</td> 3730<td><p>Change <code>autoDestroy</code> option default to <code>true</code>.</p></td></tr> 3731<tr><td>v11.2.0, v10.16.0</td> 3732<td><p>Add <code>autoDestroy</code> option to automatically <code>destroy()</code> the stream when it emits <code>'finish'</code> or errors.</p></td></tr> 3733<tr><td>v10.0.0</td> 3734<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> 3735</tbody></table> 3736</details> 3737</div> 3738<ul> 3739<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3740<ul> 3741<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Buffer level when 3742<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> starts returning <code>false</code>. <strong>Default:</strong> 3743<code>16384</code> (16 KiB), or <code>16</code> for <code>objectMode</code> streams.</li> 3744<li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether to encode <code>string</code>s passed to 3745<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> to <code>Buffer</code>s (with the encoding 3746specified in the <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> call) before passing 3747them to <a href="#writable_writechunk-encoding-callback"><code>stream._write()</code></a>. Other types of data are not 3748converted (i.e. <code>Buffer</code>s are not decoded into <code>string</code>s). Setting to 3749false will prevent <code>string</code>s from being converted. <strong>Default:</strong> <code>true</code>.</li> 3750<li><code>defaultEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The default encoding that is used when no 3751encoding is specified as an argument to <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>. 3752<strong>Default:</strong> <code>'utf8'</code>.</li> 3753<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not the 3754<a href="#writablewritechunk-encoding-callback"><code>stream.write(anyObj)</code></a> is a valid operation. When set, 3755it becomes possible to write JavaScript values other than string, 3756<code>Buffer</code> or <code>Uint8Array</code> if supported by the stream implementation. 3757<strong>Default:</strong> <code>false</code>.</li> 3758<li><code>emitClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not the stream should emit <code>'close'</code> 3759after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li> 3760<li><code>write</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the 3761<a href="#writable_writechunk-encoding-callback"><code>stream._write()</code></a> method.</li> 3762<li><code>writev</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the 3763<a href="#writable_writevchunks-callback"><code>stream._writev()</code></a> method.</li> 3764<li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the 3765<a href="#writable_destroyerr-callback"><code>stream._destroy()</code></a> method.</li> 3766<li><code>final</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the 3767<a href="#writable_finalcallback"><code>stream._final()</code></a> method.</li> 3768<li><code>construct</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the 3769<a href="#writable_constructcallback"><code>stream._construct()</code></a> method.</li> 3770<li><code>autoDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this stream should automatically call 3771<code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>true</code>.</li> 3772<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> A signal representing possible cancellation.</li> 3773</ul> 3774</li> 3775</ul> 3776<!-- eslint-disable no-useless-constructor --> 3777<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3778 3779<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> { 3780 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 3781 <span class="hljs-comment">// Calls the stream.Writable() constructor.</span> 3782 <span class="hljs-variable language_">super</span>(options); 3783 <span class="hljs-comment">// ...</span> 3784 } 3785}</code> <button class="copy-button">copy</button></pre> 3786<p>Or, when using pre-ES6 style constructors:</p> 3787<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3788<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>); 3789 3790<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyWritable</span>(<span class="hljs-params">options</span>) { 3791 <span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyWritable</span>)) 3792 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyWritable</span>(options); 3793 <span class="hljs-title class_">Writable</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 3794} 3795util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyWritable</span>, <span class="hljs-title class_">Writable</span>);</code> <button class="copy-button">copy</button></pre> 3796<p>Or, using the simplified constructor approach:</p> 3797<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3798 3799<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 3800 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3801 <span class="hljs-comment">// ...</span> 3802 }, 3803 <span class="hljs-title function_">writev</span>(<span class="hljs-params">chunks, callback</span>) { 3804 <span class="hljs-comment">// ...</span> 3805 }, 3806});</code> <button class="copy-button">copy</button></pre> 3807<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed 3808<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code> 3809on the writeable stream.</p> 3810<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3811 3812<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 3813<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 3814 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3815 <span class="hljs-comment">// ...</span> 3816 }, 3817 <span class="hljs-title function_">writev</span>(<span class="hljs-params">chunks, callback</span>) { 3818 <span class="hljs-comment">// ...</span> 3819 }, 3820 <span class="hljs-attr">signal</span>: controller.<span class="hljs-property">signal</span>, 3821}); 3822<span class="hljs-comment">// Later, abort the operation closing the stream</span> 3823controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre> 3824<h5><code>writable._construct(callback)</code><span><a class="mark" href="#writable_constructcallback" id="writable_constructcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_construct_callback"></a></h5> 3825<div class="api_metadata"> 3826<span>Added in: v15.0.0</span> 3827</div> 3828<ul> 3829<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call this function (optionally with an error 3830argument) when the stream has finished initializing.</li> 3831</ul> 3832<p>The <code>_construct()</code> method MUST NOT be called directly. It may be implemented 3833by child classes, and if so, will be called by the internal <code>Writable</code> 3834class methods only.</p> 3835<p>This optional function will be called in a tick after the stream constructor 3836has returned, delaying any <code>_write()</code>, <code>_final()</code> and <code>_destroy()</code> calls until 3837<code>callback</code> is called. This is useful to initialize state or asynchronously 3838initialize resources before the stream can be used.</p> 3839<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3840<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 3841 3842<span class="hljs-keyword">class</span> <span class="hljs-title class_">WriteStream</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> { 3843 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">filename</span>) { 3844 <span class="hljs-variable language_">super</span>(); 3845 <span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span> = filename; 3846 <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = <span class="hljs-literal">null</span>; 3847 } 3848 <span class="hljs-title function_">_construct</span>(<span class="hljs-params">callback</span>) { 3849 fs.<span class="hljs-title function_">open</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> { 3850 <span class="hljs-keyword">if</span> (err) { 3851 <span class="hljs-title function_">callback</span>(err); 3852 } <span class="hljs-keyword">else</span> { 3853 <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = fd; 3854 <span class="hljs-title function_">callback</span>(); 3855 } 3856 }); 3857 } 3858 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3859 fs.<span class="hljs-title function_">write</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, chunk, callback); 3860 } 3861 <span class="hljs-title function_">_destroy</span>(<span class="hljs-params">err, callback</span>) { 3862 <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>) { 3863 fs.<span class="hljs-title function_">close</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> <span class="hljs-title function_">callback</span>(er || err)); 3864 } <span class="hljs-keyword">else</span> { 3865 <span class="hljs-title function_">callback</span>(err); 3866 } 3867 } 3868}</code> <button class="copy-button">copy</button></pre> 3869<h5><code>writable._write(chunk, encoding, callback)</code><span><a class="mark" href="#writable_writechunk-encoding-callback" id="writable_writechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_write_chunk_encoding_callback_1"></a></h5> 3870<div class="api_metadata"> 3871<details class="changelog"><summary>History</summary> 3872<table> 3873<tbody><tr><th>Version</th><th>Changes</th></tr> 3874<tr><td>v12.11.0</td> 3875<td><p>_write() is optional when providing _writev().</p></td></tr> 3876</tbody></table> 3877</details> 3878</div> 3879<ul> 3880<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>Buffer</code> to be written, converted from the 3881<code>string</code> passed to <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>. If the stream's 3882<code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode, 3883the chunk will not be converted & will be whatever was passed to 3884<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>.</li> 3885<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If the chunk is a string, then <code>encoding</code> is the 3886character encoding of that string. If chunk is a <code>Buffer</code>, or if the 3887stream is operating in object mode, <code>encoding</code> may be ignored.</li> 3888<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call this function (optionally with an error 3889argument) when processing is complete for the supplied chunk.</li> 3890</ul> 3891<p>All <code>Writable</code> stream implementations must provide a 3892<a href="#writable_writechunk-encoding-callback"><code>writable._write()</code></a> and/or 3893<a href="#writable_writevchunks-callback"><code>writable._writev()</code></a> method to send data to the underlying 3894resource.</p> 3895<p><a href="#class-streamtransform"><code>Transform</code></a> streams provide their own implementation of the 3896<a href="#writable_writechunk-encoding-callback"><code>writable._write()</code></a>.</p> 3897<p>This function MUST NOT be called by application code directly. It should be 3898implemented by child classes, and called by the internal <code>Writable</code> class 3899methods only.</p> 3900<p>The <code>callback</code> function must be called synchronously inside of 3901<code>writable._write()</code> or asynchronously (i.e. different tick) to signal either 3902that the write completed successfully or failed with an error. 3903The first argument passed to the <code>callback</code> must be the <code>Error</code> object if the 3904call failed or <code>null</code> if the write succeeded.</p> 3905<p>All calls to <code>writable.write()</code> that occur between the time <code>writable._write()</code> 3906is called and the <code>callback</code> is called will cause the written data to be 3907buffered. When the <code>callback</code> is invoked, the stream might emit a <a href="#event-drain"><code>'drain'</code></a> 3908event. If a stream implementation is capable of processing multiple chunks of 3909data at once, the <code>writable._writev()</code> method should be implemented.</p> 3910<p>If the <code>decodeStrings</code> property is explicitly set to <code>false</code> in the constructor 3911options, then <code>chunk</code> will remain the same object that is passed to <code>.write()</code>, 3912and may be a string rather than a <code>Buffer</code>. This is to support implementations 3913that have an optimized handling for certain string data encodings. In that case, 3914the <code>encoding</code> argument will indicate the character encoding of the string. 3915Otherwise, the <code>encoding</code> argument can be safely ignored.</p> 3916<p>The <code>writable._write()</code> method is prefixed with an underscore because it is 3917internal to the class that defines it, and should never be called directly by 3918user programs.</p> 3919<h5><code>writable._writev(chunks, callback)</code><span><a class="mark" href="#writable_writevchunks-callback" id="writable_writevchunks-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writev_chunks_callback"></a></h5> 3920<ul> 3921<li><code>chunks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> The data to be written. The value is an array of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3922that each represent a discrete chunk of data to write. The properties of 3923these objects are: 3924<ul> 3925<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A buffer instance or string containing the data to 3926be written. The <code>chunk</code> will be a string if the <code>Writable</code> was created with 3927the <code>decodeStrings</code> option set to <code>false</code> and a string was passed to <code>write()</code>.</li> 3928<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The character encoding of the <code>chunk</code>. If <code>chunk</code> is 3929a <code>Buffer</code>, the <code>encoding</code> will be <code>'buffer'</code>.</li> 3930</ul> 3931</li> 3932<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function (optionally with an error 3933argument) to be invoked when processing is complete for the supplied chunks.</li> 3934</ul> 3935<p>This function MUST NOT be called by application code directly. It should be 3936implemented by child classes, and called by the internal <code>Writable</code> class 3937methods only.</p> 3938<p>The <code>writable._writev()</code> method may be implemented in addition or alternatively 3939to <code>writable._write()</code> in stream implementations that are capable of processing 3940multiple chunks of data at once. If implemented and if there is buffered data 3941from previous writes, <code>_writev()</code> will be called instead of <code>_write()</code>.</p> 3942<p>The <code>writable._writev()</code> method is prefixed with an underscore because it is 3943internal to the class that defines it, and should never be called directly by 3944user programs.</p> 3945<h5><code>writable._destroy(err, callback)</code><span><a class="mark" href="#writable_destroyerr-callback" id="writable_destroyerr-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_destroy_err_callback"></a></h5> 3946<div class="api_metadata"> 3947<span>Added in: v8.0.0</span> 3948</div> 3949<ul> 3950<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> A possible error.</li> 3951<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that takes an optional error 3952argument.</li> 3953</ul> 3954<p>The <code>_destroy()</code> method is called by <a href="#writabledestroyerror"><code>writable.destroy()</code></a>. 3955It can be overridden by child classes but it <strong>must not</strong> be called directly. 3956Furthermore, the <code>callback</code> should not be mixed with async/await 3957once it is executed when a promise is resolved.</p> 3958<h5><code>writable._final(callback)</code><span><a class="mark" href="#writable_finalcallback" id="writable_finalcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_final_callback"></a></h5> 3959<div class="api_metadata"> 3960<span>Added in: v8.0.0</span> 3961</div> 3962<ul> 3963<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call this function (optionally with an error 3964argument) when finished writing any remaining data.</li> 3965</ul> 3966<p>The <code>_final()</code> method <strong>must not</strong> be called directly. It may be implemented 3967by child classes, and if so, will be called by the internal <code>Writable</code> 3968class methods only.</p> 3969<p>This optional function will be called before the stream closes, delaying the 3970<code>'finish'</code> event until <code>callback</code> is called. This is useful to close resources 3971or write buffered data before a stream ends.</p> 3972<h5>Errors while writing<span><a class="mark" href="#errors-while-writing" id="errors-while-writing">#</a></span><a aria-hidden="true" class="legacy" id="stream_errors_while_writing"></a></h5> 3973<p>Errors occurring during the processing of the <a href="#writable_writechunk-encoding-callback"><code>writable._write()</code></a>, 3974<a href="#writable_writevchunks-callback"><code>writable._writev()</code></a> and <a href="#writable_finalcallback"><code>writable._final()</code></a> methods must be propagated 3975by invoking the callback and passing the error as the first argument. 3976Throwing an <code>Error</code> from within these methods or manually emitting an <code>'error'</code> 3977event results in undefined behavior.</p> 3978<p>If a <code>Readable</code> stream pipes into a <code>Writable</code> stream when <code>Writable</code> emits an 3979error, the <code>Readable</code> stream will be unpiped.</p> 3980<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3981 3982<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 3983 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3984 <span class="hljs-keyword">if</span> (chunk.<span class="hljs-title function_">toString</span>().<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'a'</span>) >= <span class="hljs-number">0</span>) { 3985 <span class="hljs-title function_">callback</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'chunk is invalid'</span>)); 3986 } <span class="hljs-keyword">else</span> { 3987 <span class="hljs-title function_">callback</span>(); 3988 } 3989 }, 3990});</code> <button class="copy-button">copy</button></pre> 3991<h5>An example writable stream<span><a class="mark" href="#an-example-writable-stream" id="an-example-writable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_an_example_writable_stream"></a></h5> 3992<p>The following illustrates a rather simplistic (and somewhat pointless) custom 3993<code>Writable</code> stream implementation. While this specific <code>Writable</code> stream instance 3994is not of any real particular usefulness, the example illustrates each of the 3995required elements of a custom <a href="#class-streamwritable"><code>Writable</code></a> stream instance:</p> 3996<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3997 3998<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> { 3999 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4000 <span class="hljs-keyword">if</span> (chunk.<span class="hljs-title function_">toString</span>().<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'a'</span>) >= <span class="hljs-number">0</span>) { 4001 <span class="hljs-title function_">callback</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'chunk is invalid'</span>)); 4002 } <span class="hljs-keyword">else</span> { 4003 <span class="hljs-title function_">callback</span>(); 4004 } 4005 } 4006}</code> <button class="copy-button">copy</button></pre> 4007<h5>Decoding buffers in a writable stream<span><a class="mark" href="#decoding-buffers-in-a-writable-stream" id="decoding-buffers-in-a-writable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_decoding_buffers_in_a_writable_stream"></a></h5> 4008<p>Decoding buffers is a common task, for instance, when using transformers whose 4009input is a string. This is not a trivial process when using multi-byte 4010characters encoding, such as UTF-8. The following example shows how to decode 4011multi-byte strings using <code>StringDecoder</code> and <a href="#class-streamwritable"><code>Writable</code></a>.</p> 4012<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4013<span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:string_decoder'</span>); 4014 4015<span class="hljs-keyword">class</span> <span class="hljs-title class_">StringWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> { 4016 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 4017 <span class="hljs-variable language_">super</span>(options); 4018 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringDecoder</span>(options && options.<span class="hljs-property">defaultEncoding</span>); 4019 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> = <span class="hljs-string">''</span>; 4020 } 4021 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4022 <span class="hljs-keyword">if</span> (encoding === <span class="hljs-string">'buffer'</span>) { 4023 chunk = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span>.<span class="hljs-title function_">write</span>(chunk); 4024 } 4025 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += chunk; 4026 <span class="hljs-title function_">callback</span>(); 4027 } 4028 <span class="hljs-title function_">_final</span>(<span class="hljs-params">callback</span>) { 4029 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += <span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span>.<span class="hljs-title function_">end</span>(); 4030 <span class="hljs-title function_">callback</span>(); 4031 } 4032} 4033 4034<span class="hljs-keyword">const</span> euro = [[<span class="hljs-number">0xE2</span>, <span class="hljs-number">0x82</span>], [<span class="hljs-number">0xAC</span>]].<span class="hljs-title function_">map</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">from</span>); 4035<span class="hljs-keyword">const</span> w = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringWritable</span>(); 4036 4037w.<span class="hljs-title function_">write</span>(<span class="hljs-string">'currency: '</span>); 4038w.<span class="hljs-title function_">write</span>(euro[<span class="hljs-number">0</span>]); 4039w.<span class="hljs-title function_">end</span>(euro[<span class="hljs-number">1</span>]); 4040 4041<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(w.<span class="hljs-property">data</span>); <span class="hljs-comment">// currency: €</span></code> <button class="copy-button">copy</button></pre> 4042<h4>Implementing a readable stream<span><a class="mark" href="#implementing-a-readable-stream" id="implementing-a-readable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_readable_stream"></a></h4> 4043<p>The <code>stream.Readable</code> class is extended to implement a <a href="#class-streamreadable"><code>Readable</code></a> stream.</p> 4044<p>Custom <code>Readable</code> streams <em>must</em> call the <code>new stream.Readable([options])</code> 4045constructor and implement the <a href="#readable_readsize"><code>readable._read()</code></a> method.</p> 4046<h5><code>new stream.Readable([options])</code><span><a class="mark" href="#new-streamreadableoptions" id="new-streamreadableoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_readable_options"></a></h5> 4047<div class="api_metadata"> 4048<details class="changelog"><summary>History</summary> 4049<table> 4050<tbody><tr><th>Version</th><th>Changes</th></tr> 4051<tr><td>v15.5.0</td> 4052<td><p>support passing in an AbortSignal.</p></td></tr> 4053<tr><td>v14.0.0</td> 4054<td><p>Change <code>autoDestroy</code> option default to <code>true</code>.</p></td></tr> 4055<tr><td>v11.2.0, v10.16.0</td> 4056<td><p>Add <code>autoDestroy</code> option to automatically <code>destroy()</code> the stream when it emits <code>'end'</code> or errors.</p></td></tr> 4057</tbody></table> 4058</details> 4059</div> 4060<ul> 4061<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 4062<ul> 4063<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum <a href="#highwatermark-discrepancy-after-calling-readablesetencoding">number of bytes</a> to store 4064in the internal buffer before ceasing to read from the underlying resource. 4065<strong>Default:</strong> <code>16384</code> (16 KiB), or <code>16</code> for <code>objectMode</code> streams.</li> 4066<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If specified, then buffers will be decoded to 4067strings using the specified encoding. <strong>Default:</strong> <code>null</code>.</li> 4068<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this stream should behave 4069as a stream of objects. Meaning that <a href="#readablereadsize"><code>stream.read(n)</code></a> returns 4070a single value instead of a <code>Buffer</code> of size <code>n</code>. <strong>Default:</strong> <code>false</code>.</li> 4071<li><code>emitClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not the stream should emit <code>'close'</code> 4072after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li> 4073<li><code>read</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#readable_readsize"><code>stream._read()</code></a> 4074method.</li> 4075<li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the 4076<a href="#readable_destroyerr-callback"><code>stream._destroy()</code></a> method.</li> 4077<li><code>construct</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the 4078<a href="#readable_constructcallback"><code>stream._construct()</code></a> method.</li> 4079<li><code>autoDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this stream should automatically call 4080<code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>true</code>.</li> 4081<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> A signal representing possible cancellation.</li> 4082</ul> 4083</li> 4084</ul> 4085<!-- eslint-disable no-useless-constructor --> 4086<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4087 4088<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyReadable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> { 4089 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 4090 <span class="hljs-comment">// Calls the stream.Readable(options) constructor.</span> 4091 <span class="hljs-variable language_">super</span>(options); 4092 <span class="hljs-comment">// ...</span> 4093 } 4094}</code> <button class="copy-button">copy</button></pre> 4095<p>Or, when using pre-ES6 style constructors:</p> 4096<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4097<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>); 4098 4099<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyReadable</span>(<span class="hljs-params">options</span>) { 4100 <span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyReadable</span>)) 4101 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyReadable</span>(options); 4102 <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 4103} 4104util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyReadable</span>, <span class="hljs-title class_">Readable</span>);</code> <button class="copy-button">copy</button></pre> 4105<p>Or, using the simplified constructor approach:</p> 4106<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4107 4108<span class="hljs-keyword">const</span> myReadable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({ 4109 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 4110 <span class="hljs-comment">// ...</span> 4111 }, 4112});</code> <button class="copy-button">copy</button></pre> 4113<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed 4114<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code> 4115on the readable created.</p> 4116<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4117<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 4118<span class="hljs-keyword">const</span> read = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({ 4119 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 4120 <span class="hljs-comment">// ...</span> 4121 }, 4122 <span class="hljs-attr">signal</span>: controller.<span class="hljs-property">signal</span>, 4123}); 4124<span class="hljs-comment">// Later, abort the operation closing the stream</span> 4125controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre> 4126<h5><code>readable._construct(callback)</code><span><a class="mark" href="#readable_constructcallback" id="readable_constructcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_construct_callback"></a></h5> 4127<div class="api_metadata"> 4128<span>Added in: v15.0.0</span> 4129</div> 4130<ul> 4131<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call this function (optionally with an error 4132argument) when the stream has finished initializing.</li> 4133</ul> 4134<p>The <code>_construct()</code> method MUST NOT be called directly. It may be implemented 4135by child classes, and if so, will be called by the internal <code>Readable</code> 4136class methods only.</p> 4137<p>This optional function will be scheduled in the next tick by the stream 4138constructor, delaying any <code>_read()</code> and <code>_destroy()</code> calls until <code>callback</code> is 4139called. This is useful to initialize state or asynchronously initialize 4140resources before the stream can be used.</p> 4141<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4142<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 4143 4144<span class="hljs-keyword">class</span> <span class="hljs-title class_">ReadStream</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> { 4145 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">filename</span>) { 4146 <span class="hljs-variable language_">super</span>(); 4147 <span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span> = filename; 4148 <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = <span class="hljs-literal">null</span>; 4149 } 4150 <span class="hljs-title function_">_construct</span>(<span class="hljs-params">callback</span>) { 4151 fs.<span class="hljs-title function_">open</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> { 4152 <span class="hljs-keyword">if</span> (err) { 4153 <span class="hljs-title function_">callback</span>(err); 4154 } <span class="hljs-keyword">else</span> { 4155 <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = fd; 4156 <span class="hljs-title function_">callback</span>(); 4157 } 4158 }); 4159 } 4160 <span class="hljs-title function_">_read</span>(<span class="hljs-params">n</span>) { 4161 <span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(n); 4162 fs.<span class="hljs-title function_">read</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, buf, <span class="hljs-number">0</span>, n, <span class="hljs-literal">null</span>, <span class="hljs-function">(<span class="hljs-params">err, bytesRead</span>) =></span> { 4163 <span class="hljs-keyword">if</span> (err) { 4164 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err); 4165 } <span class="hljs-keyword">else</span> { 4166 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(bytesRead > <span class="hljs-number">0</span> ? buf.<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, bytesRead) : <span class="hljs-literal">null</span>); 4167 } 4168 }); 4169 } 4170 <span class="hljs-title function_">_destroy</span>(<span class="hljs-params">err, callback</span>) { 4171 <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>) { 4172 fs.<span class="hljs-title function_">close</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> <span class="hljs-title function_">callback</span>(er || err)); 4173 } <span class="hljs-keyword">else</span> { 4174 <span class="hljs-title function_">callback</span>(err); 4175 } 4176 } 4177}</code> <button class="copy-button">copy</button></pre> 4178<h5><code>readable._read(size)</code><span><a class="mark" href="#readable_readsize" id="readable_readsize">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_read_size_1"></a></h5> 4179<div class="api_metadata"> 4180<span>Added in: v0.9.4</span> 4181</div> 4182<ul> 4183<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of bytes to read asynchronously</li> 4184</ul> 4185<p>This function MUST NOT be called by application code directly. It should be 4186implemented by child classes, and called by the internal <code>Readable</code> class 4187methods only.</p> 4188<p>All <code>Readable</code> stream implementations must provide an implementation of the 4189<a href="#readable_readsize"><code>readable._read()</code></a> method to fetch data from the underlying resource.</p> 4190<p>When <a href="#readable_readsize"><code>readable._read()</code></a> is called, if data is available from the resource, 4191the implementation should begin pushing that data into the read queue using the 4192<a href="#readablepushchunk-encoding"><code>this.push(dataChunk)</code></a> method. <code>_read()</code> will be called again 4193after each call to <a href="#readablepushchunk-encoding"><code>this.push(dataChunk)</code></a> once the stream is 4194ready to accept more data. <code>_read()</code> may continue reading from the resource and 4195pushing data until <code>readable.push()</code> returns <code>false</code>. Only when <code>_read()</code> is 4196called again after it has stopped should it resume pushing additional data into 4197the queue.</p> 4198<p>Once the <a href="#readable_readsize"><code>readable._read()</code></a> method has been called, it will not be called 4199again until more data is pushed through the <a href="#readablepushchunk-encoding"><code>readable.push()</code></a> 4200method. Empty data such as empty buffers and strings will not cause 4201<a href="#readable_readsize"><code>readable._read()</code></a> to be called.</p> 4202<p>The <code>size</code> argument is advisory. For implementations where a "read" is a 4203single operation that returns data can use the <code>size</code> argument to determine how 4204much data to fetch. Other implementations may ignore this argument and simply 4205provide data whenever it becomes available. There is no need to "wait" until 4206<code>size</code> bytes are available before calling <a href="#readablepushchunk-encoding"><code>stream.push(chunk)</code></a>.</p> 4207<p>The <a href="#readable_readsize"><code>readable._read()</code></a> method is prefixed with an underscore because it is 4208internal to the class that defines it, and should never be called directly by 4209user programs.</p> 4210<h5><code>readable._destroy(err, callback)</code><span><a class="mark" href="#readable_destroyerr-callback" id="readable_destroyerr-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_destroy_err_callback"></a></h5> 4211<div class="api_metadata"> 4212<span>Added in: v8.0.0</span> 4213</div> 4214<ul> 4215<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> A possible error.</li> 4216<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that takes an optional error 4217argument.</li> 4218</ul> 4219<p>The <code>_destroy()</code> method is called by <a href="#readabledestroyerror"><code>readable.destroy()</code></a>. 4220It can be overridden by child classes but it <strong>must not</strong> be called directly.</p> 4221<h5><code>readable.push(chunk[, encoding])</code><span><a class="mark" href="#readablepushchunk-encoding" id="readablepushchunk-encoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_push_chunk_encoding"></a></h5> 4222<div class="api_metadata"> 4223<details class="changelog"><summary>History</summary> 4224<table> 4225<tbody><tr><th>Version</th><th>Changes</th></tr> 4226<tr><td>v8.0.0</td> 4227<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 4228</tbody></table> 4229</details> 4230</div> 4231<ul> 4232<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Chunk of data to push into the 4233read queue. For streams not operating in object mode, <code>chunk</code> must be a 4234string, <code>Buffer</code> or <code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be 4235any JavaScript value.</li> 4236<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Encoding of string chunks. Must be a valid 4237<code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li> 4238<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if additional chunks of data may continue to be 4239pushed; <code>false</code> otherwise.</li> 4240</ul> 4241<p>When <code>chunk</code> is a <code>Buffer</code>, <code>Uint8Array</code>, or <code>string</code>, the <code>chunk</code> of data will 4242be added to the internal queue for users of the stream to consume. 4243Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF), after which no 4244more data can be written.</p> 4245<p>When the <code>Readable</code> is operating in paused mode, the data added with 4246<code>readable.push()</code> can be read out by calling the 4247<a href="#readablereadsize"><code>readable.read()</code></a> method when the <a href="#event-readable"><code>'readable'</code></a> event is 4248emitted.</p> 4249<p>When the <code>Readable</code> is operating in flowing mode, the data added with 4250<code>readable.push()</code> will be delivered by emitting a <code>'data'</code> event.</p> 4251<p>The <code>readable.push()</code> method is designed to be as flexible as possible. For 4252example, when wrapping a lower-level source that provides some form of 4253pause/resume mechanism, and a data callback, the low-level source can be wrapped 4254by the custom <code>Readable</code> instance:</p> 4255<pre><code class="language-js"><span class="hljs-comment">// `_source` is an object with readStop() and readStart() methods,</span> 4256<span class="hljs-comment">// and an `ondata` member that gets called when it has data, and</span> 4257<span class="hljs-comment">// an `onend` member that gets called when the data is over.</span> 4258 4259<span class="hljs-keyword">class</span> <span class="hljs-title class_">SourceWrapper</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> { 4260 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 4261 <span class="hljs-variable language_">super</span>(options); 4262 4263 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span> = <span class="hljs-title function_">getLowLevelSourceObject</span>(); 4264 4265 <span class="hljs-comment">// Every time there's data, push it into the internal buffer.</span> 4266 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-property">ondata</span> = <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 4267 <span class="hljs-comment">// If push() returns false, then stop reading from source.</span> 4268 <span class="hljs-keyword">if</span> (!<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(chunk)) 4269 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-title function_">readStop</span>(); 4270 }; 4271 4272 <span class="hljs-comment">// When the source ends, push the EOF-signaling `null` chunk.</span> 4273 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-property">onend</span> = <span class="hljs-function">() =></span> { 4274 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>); 4275 }; 4276 } 4277 <span class="hljs-comment">// _read() will be called when the stream wants to pull more data in.</span> 4278 <span class="hljs-comment">// The advisory size argument is ignored in this case.</span> 4279 <span class="hljs-title function_">_read</span>(<span class="hljs-params">size</span>) { 4280 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-title function_">readStart</span>(); 4281 } 4282}</code> <button class="copy-button">copy</button></pre> 4283<p>The <code>readable.push()</code> method is used to push the content 4284into the internal buffer. It can be driven by the <a href="#readable_readsize"><code>readable._read()</code></a> method.</p> 4285<p>For streams not operating in object mode, if the <code>chunk</code> parameter of 4286<code>readable.push()</code> is <code>undefined</code>, it will be treated as empty string or 4287buffer. See <a href="#readablepush"><code>readable.push('')</code></a> for more information.</p> 4288<h5>Errors while reading<span><a class="mark" href="#errors-while-reading" id="errors-while-reading">#</a></span><a aria-hidden="true" class="legacy" id="stream_errors_while_reading"></a></h5> 4289<p>Errors occurring during processing of the <a href="#readable_readsize"><code>readable._read()</code></a> must be 4290propagated through the <a href="#readable_destroyerr-callback"><code>readable.destroy(err)</code></a> method. 4291Throwing an <code>Error</code> from within <a href="#readable_readsize"><code>readable._read()</code></a> or manually emitting an 4292<code>'error'</code> event results in undefined behavior.</p> 4293<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4294 4295<span class="hljs-keyword">const</span> myReadable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({ 4296 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 4297 <span class="hljs-keyword">const</span> err = <span class="hljs-title function_">checkSomeErrorCondition</span>(); 4298 <span class="hljs-keyword">if</span> (err) { 4299 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err); 4300 } <span class="hljs-keyword">else</span> { 4301 <span class="hljs-comment">// Do some work.</span> 4302 } 4303 }, 4304});</code> <button class="copy-button">copy</button></pre> 4305<h5>An example counting stream<span><a class="mark" href="#an-example-counting-stream" id="an-example-counting-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_an_example_counting_stream"></a></h5> 4306 4307<p>The following is a basic example of a <code>Readable</code> stream that emits the numerals 4308from 1 to 1,000,000 in ascending order, and then ends.</p> 4309<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4310 4311<span class="hljs-keyword">class</span> <span class="hljs-title class_">Counter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> { 4312 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">opt</span>) { 4313 <span class="hljs-variable language_">super</span>(opt); 4314 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_max</span> = <span class="hljs-number">1000000</span>; 4315 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_index</span> = <span class="hljs-number">1</span>; 4316 } 4317 4318 <span class="hljs-title function_">_read</span>(<span class="hljs-params"></span>) { 4319 <span class="hljs-keyword">const</span> i = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_index</span>++; 4320 <span class="hljs-keyword">if</span> (i > <span class="hljs-variable language_">this</span>.<span class="hljs-property">_max</span>) 4321 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>); 4322 <span class="hljs-keyword">else</span> { 4323 <span class="hljs-keyword">const</span> str = <span class="hljs-title class_">String</span>(i); 4324 <span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(str, <span class="hljs-string">'ascii'</span>); 4325 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(buf); 4326 } 4327 } 4328}</code> <button class="copy-button">copy</button></pre> 4329<h4>Implementing a duplex stream<span><a class="mark" href="#implementing-a-duplex-stream" id="implementing-a-duplex-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_duplex_stream"></a></h4> 4330<p>A <a href="#class-streamduplex"><code>Duplex</code></a> stream is one that implements both <a href="#class-streamreadable"><code>Readable</code></a> and 4331<a href="#class-streamwritable"><code>Writable</code></a>, such as a TCP socket connection.</p> 4332<p>Because JavaScript does not have support for multiple inheritance, the 4333<code>stream.Duplex</code> class is extended to implement a <a href="#class-streamduplex"><code>Duplex</code></a> stream (as opposed 4334to extending the <code>stream.Readable</code> <em>and</em> <code>stream.Writable</code> classes).</p> 4335<p>The <code>stream.Duplex</code> class prototypically inherits from <code>stream.Readable</code> and 4336parasitically from <code>stream.Writable</code>, but <code>instanceof</code> will work properly for 4337both 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 4338<code>stream.Writable</code>.</p> 4339<p>Custom <code>Duplex</code> streams <em>must</em> call the <code>new stream.Duplex([options])</code> 4340constructor and implement <em>both</em> the <a href="#readable_readsize"><code>readable._read()</code></a> and 4341<code>writable._write()</code> methods.</p> 4342<h5><code>new stream.Duplex(options)</code><span><a class="mark" href="#new-streamduplexoptions" id="new-streamduplexoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_duplex_options"></a></h5> 4343<div class="api_metadata"> 4344<details class="changelog"><summary>History</summary> 4345<table> 4346<tbody><tr><th>Version</th><th>Changes</th></tr> 4347<tr><td>v8.4.0</td> 4348<td><p>The <code>readableHighWaterMark</code> and <code>writableHighWaterMark</code> options are supported now.</p></td></tr> 4349</tbody></table> 4350</details> 4351</div> 4352<ul> 4353<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Passed to both <code>Writable</code> and <code>Readable</code> 4354constructors. Also has the following fields: 4355<ul> 4356<li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>false</code>, then the stream will 4357automatically end the writable side when the readable side ends. 4358<strong>Default:</strong> <code>true</code>.</li> 4359<li><code>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Sets whether the <code>Duplex</code> should be readable. 4360<strong>Default:</strong> <code>true</code>.</li> 4361<li><code>writable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Sets whether the <code>Duplex</code> should be writable. 4362<strong>Default:</strong> <code>true</code>.</li> 4363<li><code>readableObjectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Sets <code>objectMode</code> for readable side of the 4364stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li> 4365<li><code>writableObjectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Sets <code>objectMode</code> for writable side of the 4366stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li> 4367<li><code>readableHighWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets <code>highWaterMark</code> for the readable side 4368of the stream. Has no effect if <code>highWaterMark</code> is provided.</li> 4369<li><code>writableHighWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets <code>highWaterMark</code> for the writable side 4370of the stream. Has no effect if <code>highWaterMark</code> is provided.</li> 4371</ul> 4372</li> 4373</ul> 4374<!-- eslint-disable no-useless-constructor --> 4375<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4376 4377<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyDuplex</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Duplex</span> { 4378 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 4379 <span class="hljs-variable language_">super</span>(options); 4380 <span class="hljs-comment">// ...</span> 4381 } 4382}</code> <button class="copy-button">copy</button></pre> 4383<p>Or, when using pre-ES6 style constructors:</p> 4384<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4385<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>); 4386 4387<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyDuplex</span>(<span class="hljs-params">options</span>) { 4388 <span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyDuplex</span>)) 4389 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyDuplex</span>(options); 4390 <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 4391} 4392util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyDuplex</span>, <span class="hljs-title class_">Duplex</span>);</code> <button class="copy-button">copy</button></pre> 4393<p>Or, using the simplified constructor approach:</p> 4394<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4395 4396<span class="hljs-keyword">const</span> myDuplex = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Duplex</span>({ 4397 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 4398 <span class="hljs-comment">// ...</span> 4399 }, 4400 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4401 <span class="hljs-comment">// ...</span> 4402 }, 4403});</code> <button class="copy-button">copy</button></pre> 4404<p>When using pipeline:</p> 4405<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span>, pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4406<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 4407 4408<span class="hljs-title function_">pipeline</span>( 4409 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'object.json'</span>) 4410 .<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>), 4411 <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({ 4412 <span class="hljs-attr">decodeStrings</span>: <span class="hljs-literal">false</span>, <span class="hljs-comment">// Accept string input rather than Buffers</span> 4413 <span class="hljs-title function_">construct</span>(<span class="hljs-params">callback</span>) { 4414 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> = <span class="hljs-string">''</span>; 4415 <span class="hljs-title function_">callback</span>(); 4416 }, 4417 <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4418 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += chunk; 4419 <span class="hljs-title function_">callback</span>(); 4420 }, 4421 <span class="hljs-title function_">flush</span>(<span class="hljs-params">callback</span>) { 4422 <span class="hljs-keyword">try</span> { 4423 <span class="hljs-comment">// Make sure is valid json.</span> 4424 <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span>); 4425 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span>); 4426 <span class="hljs-title function_">callback</span>(); 4427 } <span class="hljs-keyword">catch</span> (err) { 4428 <span class="hljs-title function_">callback</span>(err); 4429 } 4430 }, 4431 }), 4432 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'valid-object.json'</span>), 4433 <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 4434 <span class="hljs-keyword">if</span> (err) { 4435 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'failed'</span>, err); 4436 } <span class="hljs-keyword">else</span> { 4437 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'completed'</span>); 4438 } 4439 }, 4440);</code> <button class="copy-button">copy</button></pre> 4441<h5>An example duplex stream<span><a class="mark" href="#an-example-duplex-stream" id="an-example-duplex-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_an_example_duplex_stream"></a></h5> 4442<p>The following illustrates a simple example of a <code>Duplex</code> stream that wraps a 4443hypothetical lower-level source object to which data can be written, and 4444from which data can be read, albeit using an API that is not compatible with 4445Node.js streams. 4446The following illustrates a simple example of a <code>Duplex</code> stream that buffers 4447incoming written data via the <a href="#class-streamwritable"><code>Writable</code></a> interface that is read back out 4448via the <a href="#class-streamreadable"><code>Readable</code></a> interface.</p> 4449<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4450<span class="hljs-keyword">const</span> kSource = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'source'</span>); 4451 4452<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyDuplex</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Duplex</span> { 4453 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">source, options</span>) { 4454 <span class="hljs-variable language_">super</span>(options); 4455 <span class="hljs-variable language_">this</span>[kSource] = source; 4456 } 4457 4458 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4459 <span class="hljs-comment">// The underlying source only deals with strings.</span> 4460 <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(chunk)) 4461 chunk = chunk.<span class="hljs-title function_">toString</span>(); 4462 <span class="hljs-variable language_">this</span>[kSource].<span class="hljs-title function_">writeSomeData</span>(chunk); 4463 <span class="hljs-title function_">callback</span>(); 4464 } 4465 4466 <span class="hljs-title function_">_read</span>(<span class="hljs-params">size</span>) { 4467 <span class="hljs-variable language_">this</span>[kSource].<span class="hljs-title function_">fetchSomeData</span>(size, <span class="hljs-function">(<span class="hljs-params">data, encoding</span>) =></span> { 4468 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(data, encoding)); 4469 }); 4470 } 4471}</code> <button class="copy-button">copy</button></pre> 4472<p>The most important aspect of a <code>Duplex</code> stream is that the <code>Readable</code> and 4473<code>Writable</code> sides operate independently of one another despite co-existing within 4474a single object instance.</p> 4475<h5>Object mode duplex streams<span><a class="mark" href="#object-mode-duplex-streams" id="object-mode-duplex-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_object_mode_duplex_streams"></a></h5> 4476<p>For <code>Duplex</code> streams, <code>objectMode</code> can be set exclusively for either the 4477<code>Readable</code> or <code>Writable</code> side using the <code>readableObjectMode</code> and 4478<code>writableObjectMode</code> options respectively.</p> 4479<p>In the following example, for instance, a new <code>Transform</code> stream (which is a 4480type of <a href="#class-streamduplex"><code>Duplex</code></a> stream) is created that has an object mode <code>Writable</code> side 4481that accepts JavaScript numbers that are converted to hexadecimal strings on 4482the <code>Readable</code> side.</p> 4483<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4484 4485<span class="hljs-comment">// All Transform streams are also Duplex Streams.</span> 4486<span class="hljs-keyword">const</span> myTransform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({ 4487 <span class="hljs-attr">writableObjectMode</span>: <span class="hljs-literal">true</span>, 4488 4489 <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4490 <span class="hljs-comment">// Coerce the chunk to a number if necessary.</span> 4491 chunk |= <span class="hljs-number">0</span>; 4492 4493 <span class="hljs-comment">// Transform the chunk into something else.</span> 4494 <span class="hljs-keyword">const</span> data = chunk.<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>); 4495 4496 <span class="hljs-comment">// Push the data onto the readable queue.</span> 4497 <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'0'</span>.<span class="hljs-title function_">repeat</span>(data.<span class="hljs-property">length</span> % <span class="hljs-number">2</span>) + data); 4498 }, 4499}); 4500 4501myTransform.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'ascii'</span>); 4502myTransform.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk)); 4503 4504myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">1</span>); 4505<span class="hljs-comment">// Prints: 01</span> 4506myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">10</span>); 4507<span class="hljs-comment">// Prints: 0a</span> 4508myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">100</span>); 4509<span class="hljs-comment">// Prints: 64</span></code> <button class="copy-button">copy</button></pre> 4510<h4>Implementing a transform stream<span><a class="mark" href="#implementing-a-transform-stream" id="implementing-a-transform-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_transform_stream"></a></h4> 4511<p>A <a href="#class-streamtransform"><code>Transform</code></a> stream is a <a href="#class-streamduplex"><code>Duplex</code></a> stream where the output is computed 4512in some way from the input. Examples include <a href="zlib.html">zlib</a> streams or <a href="crypto.html">crypto</a> 4513streams that compress, encrypt, or decrypt data.</p> 4514<p>There is no requirement that the output be the same size as the input, the same 4515number of chunks, or arrive at the same time. For example, a <code>Hash</code> stream will 4516only ever have a single chunk of output which is provided when the input is 4517ended. A <code>zlib</code> stream will produce output that is either much smaller or much 4518larger than its input.</p> 4519<p>The <code>stream.Transform</code> class is extended to implement a <a href="#class-streamtransform"><code>Transform</code></a> stream.</p> 4520<p>The <code>stream.Transform</code> class prototypically inherits from <code>stream.Duplex</code> and 4521implements its own versions of the <code>writable._write()</code> and 4522<a href="#readable_readsize"><code>readable._read()</code></a> methods. Custom <code>Transform</code> implementations <em>must</em> 4523implement the <a href="#transform_transformchunk-encoding-callback"><code>transform._transform()</code></a> method and <em>may</em> 4524also implement the <a href="#transform_flushcallback"><code>transform._flush()</code></a> method.</p> 4525<p>Care must be taken when using <code>Transform</code> streams in that data written to the 4526stream can cause the <code>Writable</code> side of the stream to become paused if the 4527output on the <code>Readable</code> side is not consumed.</p> 4528<h5><code>new stream.Transform([options])</code><span><a class="mark" href="#new-streamtransformoptions" id="new-streamtransformoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_transform_options"></a></h5> 4529<ul> 4530<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Passed to both <code>Writable</code> and <code>Readable</code> 4531constructors. Also has the following fields: 4532<ul> 4533<li><code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the 4534<a href="#transform_transformchunk-encoding-callback"><code>stream._transform()</code></a> method.</li> 4535<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#transform_flushcallback"><code>stream._flush()</code></a> 4536method.</li> 4537</ul> 4538</li> 4539</ul> 4540<!-- eslint-disable no-useless-constructor --> 4541<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4542 4543<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyTransform</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Transform</span> { 4544 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 4545 <span class="hljs-variable language_">super</span>(options); 4546 <span class="hljs-comment">// ...</span> 4547 } 4548}</code> <button class="copy-button">copy</button></pre> 4549<p>Or, when using pre-ES6 style constructors:</p> 4550<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4551<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>); 4552 4553<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyTransform</span>(<span class="hljs-params">options</span>) { 4554 <span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyTransform</span>)) 4555 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyTransform</span>(options); 4556 <span class="hljs-title class_">Transform</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 4557} 4558util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyTransform</span>, <span class="hljs-title class_">Transform</span>);</code> <button class="copy-button">copy</button></pre> 4559<p>Or, using the simplified constructor approach:</p> 4560<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4561 4562<span class="hljs-keyword">const</span> myTransform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({ 4563 <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4564 <span class="hljs-comment">// ...</span> 4565 }, 4566});</code> <button class="copy-button">copy</button></pre> 4567<h5>Event: <code>'end'</code><span><a class="mark" href="#event-end_1" id="event-end_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_end_1"></a></h5> 4568<p>The <a href="#event-end"><code>'end'</code></a> event is from the <code>stream.Readable</code> class. The <code>'end'</code> event is 4569emitted after all data has been output, which occurs after the callback in 4570<a href="#transform_flushcallback"><code>transform._flush()</code></a> has been called. In the case of an error, 4571<code>'end'</code> should not be emitted.</p> 4572<h5>Event: <code>'finish'</code><span><a class="mark" href="#event-finish_1" id="event-finish_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_finish_1"></a></h5> 4573<p>The <a href="#event-finish"><code>'finish'</code></a> event is from the <code>stream.Writable</code> class. The <code>'finish'</code> 4574event is emitted after <a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> is called and all chunks 4575have been processed by <a href="#transform_transformchunk-encoding-callback"><code>stream._transform()</code></a>. In the case 4576of an error, <code>'finish'</code> should not be emitted.</p> 4577<h5><code>transform._flush(callback)</code><span><a class="mark" href="#transform_flushcallback" id="transform_flushcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_transform_flush_callback"></a></h5> 4578<ul> 4579<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function (optionally with an error 4580argument and data) to be called when remaining data has been flushed.</li> 4581</ul> 4582<p>This function MUST NOT be called by application code directly. It should be 4583implemented by child classes, and called by the internal <code>Readable</code> class 4584methods only.</p> 4585<p>In some cases, a transform operation may need to emit an additional bit of 4586data at the end of the stream. For example, a <code>zlib</code> compression stream will 4587store an amount of internal state used to optimally compress the output. When 4588the stream ends, however, that additional data needs to be flushed so that the 4589compressed data will be complete.</p> 4590<p>Custom <a href="#class-streamtransform"><code>Transform</code></a> implementations <em>may</em> implement the <code>transform._flush()</code> 4591method. This will be called when there is no more written data to be consumed, 4592but before the <a href="#event-end"><code>'end'</code></a> event is emitted signaling the end of the 4593<a href="#class-streamreadable"><code>Readable</code></a> stream.</p> 4594<p>Within the <code>transform._flush()</code> implementation, the <code>transform.push()</code> method 4595may be called zero or more times, as appropriate. The <code>callback</code> function must 4596be called when the flush operation is complete.</p> 4597<p>The <code>transform._flush()</code> method is prefixed with an underscore because it is 4598internal to the class that defines it, and should never be called directly by 4599user programs.</p> 4600<h5><code>transform._transform(chunk, encoding, callback)</code><span><a class="mark" href="#transform_transformchunk-encoding-callback" id="transform_transformchunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_transform_transform_chunk_encoding_callback"></a></h5> 4601<ul> 4602<li><code>chunk</code> <a href="buffer.html#class-buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>Buffer</code> to be transformed, converted from 4603the <code>string</code> passed to <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>. If the stream's 4604<code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode, 4605the chunk will not be converted & will be whatever was passed to 4606<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>.</li> 4607<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If the chunk is a string, then this is the 4608encoding type. If chunk is a buffer, then this is the special 4609value <code>'buffer'</code>. Ignore it in that case.</li> 4610<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function (optionally with an error 4611argument and data) to be called after the supplied <code>chunk</code> has been 4612processed.</li> 4613</ul> 4614<p>This function MUST NOT be called by application code directly. It should be 4615implemented by child classes, and called by the internal <code>Readable</code> class 4616methods only.</p> 4617<p>All <code>Transform</code> stream implementations must provide a <code>_transform()</code> 4618method to accept input and produce output. The <code>transform._transform()</code> 4619implementation handles the bytes being written, computes an output, then passes 4620that output off to the readable portion using the <code>transform.push()</code> method.</p> 4621<p>The <code>transform.push()</code> method may be called zero or more times to generate 4622output from a single input chunk, depending on how much is to be output 4623as a result of the chunk.</p> 4624<p>It is possible that no output is generated from any given chunk of input data.</p> 4625<p>The <code>callback</code> function must be called only when the current chunk is completely 4626consumed. The first argument passed to the <code>callback</code> must be an <code>Error</code> object 4627if an error occurred while processing the input or <code>null</code> otherwise. If a second 4628argument is passed to the <code>callback</code>, it will be forwarded on to the 4629<code>transform.push()</code> method, but only if the first argument is falsy. In other 4630words, the following are equivalent:</p> 4631<pre><code class="language-js">transform.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">_transform</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">data, encoding, callback</span>) { 4632 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(data); 4633 <span class="hljs-title function_">callback</span>(); 4634}; 4635 4636transform.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">_transform</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">data, encoding, callback</span>) { 4637 <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, data); 4638};</code> <button class="copy-button">copy</button></pre> 4639<p>The <code>transform._transform()</code> method is prefixed with an underscore because it 4640is internal to the class that defines it, and should never be called directly by 4641user programs.</p> 4642<p><code>transform._transform()</code> is never called in parallel; streams implement a 4643queue mechanism, and to receive the next chunk, <code>callback</code> must be 4644called, either synchronously or asynchronously.</p> 4645<h5>Class: <code>stream.PassThrough</code><span><a class="mark" href="#class-streampassthrough" id="class-streampassthrough">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_passthrough"></a></h5> 4646<p>The <code>stream.PassThrough</code> class is a trivial implementation of a <a href="#class-streamtransform"><code>Transform</code></a> 4647stream that simply passes the input bytes across to the output. Its purpose is 4648primarily for examples and testing, but there are some use cases where 4649<code>stream.PassThrough</code> is useful as a building block for novel sorts of streams.</p> 4650</section><section><h3>Additional notes<span><a class="mark" href="#additional-notes" id="additional-notes">#</a></span><a aria-hidden="true" class="legacy" id="stream_additional_notes"></a></h3> 4651 4652<h4>Streams compatibility with async generators and async iterators<span><a class="mark" href="#streams-compatibility-with-async-generators-and-async-iterators" id="streams-compatibility-with-async-generators-and-async-iterators">#</a></span><a aria-hidden="true" class="legacy" id="stream_streams_compatibility_with_async_generators_and_async_iterators"></a></h4> 4653<p>With the support of async generators and iterators in JavaScript, async 4654generators are effectively a first-class language-level stream construct at 4655this point.</p> 4656<p>Some common interop cases of using Node.js streams with async generators 4657and async iterators are provided below.</p> 4658<h5>Consuming readable streams with async iterators<span><a class="mark" href="#consuming-readable-streams-with-async-iterators" id="consuming-readable-streams-with-async-iterators">#</a></span><a aria-hidden="true" class="legacy" id="stream_consuming_readable_streams_with_async_iterators"></a></h5> 4659<pre><code class="language-js">(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { 4660 <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable) { 4661 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); 4662 } 4663})();</code> <button class="copy-button">copy</button></pre> 4664<p>Async iterators register a permanent error handler on the stream to prevent any 4665unhandled post-destroy errors.</p> 4666<h5>Creating readable streams with async generators<span><a class="mark" href="#creating-readable-streams-with-async-generators" id="creating-readable-streams-with-async-generators">#</a></span><a aria-hidden="true" class="legacy" id="stream_creating_readable_streams_with_async_generators"></a></h5> 4667<p>A Node.js readable stream can be created from an asynchronous generator using 4668the <code>Readable.from()</code> utility method:</p> 4669<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4670 4671<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 4672<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>; 4673 4674<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) { 4675 <span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>; 4676 <span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningFn</span>({ signal }); 4677 <span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>; 4678 <span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>; 4679} 4680 4681<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">generate</span>()); 4682readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> { 4683 ac.<span class="hljs-title function_">abort</span>(); 4684}); 4685 4686readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 4687 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); 4688});</code> <button class="copy-button">copy</button></pre> 4689<h5>Piping to writable streams from async iterators<span><a class="mark" href="#piping-to-writable-streams-from-async-iterators" id="piping-to-writable-streams-from-async-iterators">#</a></span><a aria-hidden="true" class="legacy" id="stream_piping_to_writable_streams_from_async_iterators"></a></h5> 4690<p>When writing to a writable stream from an async iterator, ensure correct 4691handling of backpressure and errors. <a href="#streampipelinesource-transforms-destination-callback"><code>stream.pipeline()</code></a> abstracts away 4692the handling of backpressure and backpressure-related errors:</p> 4693<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 4694<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4695<span class="hljs-keyword">const</span> { <span class="hljs-attr">pipeline</span>: pipelinePromise } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>); 4696 4697<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./file'</span>); 4698 4699<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 4700<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>; 4701 4702<span class="hljs-keyword">const</span> iterator = <span class="hljs-title function_">createIterator</span>({ signal }); 4703 4704<span class="hljs-comment">// Callback Pattern</span> 4705<span class="hljs-title function_">pipeline</span>(iterator, writable, <span class="hljs-function">(<span class="hljs-params">err, value</span>) =></span> { 4706 <span class="hljs-keyword">if</span> (err) { 4707 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err); 4708 } <span class="hljs-keyword">else</span> { 4709 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value, <span class="hljs-string">'value returned'</span>); 4710 } 4711}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> { 4712 ac.<span class="hljs-title function_">abort</span>(); 4713}); 4714 4715<span class="hljs-comment">// Promise Pattern</span> 4716<span class="hljs-title function_">pipelinePromise</span>(iterator, writable) 4717 .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">value</span>) =></span> { 4718 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value, <span class="hljs-string">'value returned'</span>); 4719 }) 4720 .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 4721 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err); 4722 ac.<span class="hljs-title function_">abort</span>(); 4723 });</code> <button class="copy-button">copy</button></pre> 4724 4725<h4>Compatibility with older Node.js versions<span><a class="mark" href="#compatibility-with-older-nodejs-versions" id="compatibility-with-older-nodejs-versions">#</a></span><a aria-hidden="true" class="legacy" id="stream_compatibility_with_older_node_js_versions"></a></h4> 4726 4727<p>Prior to Node.js 0.10, the <code>Readable</code> stream interface was simpler, but also 4728less powerful and less useful.</p> 4729<ul> 4730<li>Rather than waiting for calls to the <a href="#readablereadsize"><code>stream.read()</code></a> method, 4731<a href="#event-data"><code>'data'</code></a> events would begin emitting immediately. Applications that 4732would need to perform some amount of work to decide how to handle data 4733were required to store read data into buffers so the data would not be lost.</li> 4734<li>The <a href="#readablepause"><code>stream.pause()</code></a> method was advisory, rather than 4735guaranteed. This meant that it was still necessary to be prepared to receive 4736<a href="#event-data"><code>'data'</code></a> events <em>even when the stream was in a paused state</em>.</li> 4737</ul> 4738<p>In Node.js 0.10, the <a href="#class-streamreadable"><code>Readable</code></a> class was added. For backward 4739compatibility with older Node.js programs, <code>Readable</code> streams switch into 4740"flowing mode" when a <a href="#event-data"><code>'data'</code></a> event handler is added, or when the 4741<a href="#readableresume"><code>stream.resume()</code></a> method is called. The effect is that, even 4742when not using the new <a href="#readablereadsize"><code>stream.read()</code></a> method and 4743<a href="#event-readable"><code>'readable'</code></a> event, it is no longer necessary to worry about losing 4744<a href="#event-data"><code>'data'</code></a> chunks.</p> 4745<p>While most applications will continue to function normally, this introduces an 4746edge case in the following conditions:</p> 4747<ul> 4748<li>No <a href="#event-data"><code>'data'</code></a> event listener is added.</li> 4749<li>The <a href="#readableresume"><code>stream.resume()</code></a> method is never called.</li> 4750<li>The stream is not piped to any writable destination.</li> 4751</ul> 4752<p>For example, consider the following code:</p> 4753<pre><code class="language-js"><span class="hljs-comment">// WARNING! BROKEN!</span> 4754net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> { 4755 4756 <span class="hljs-comment">// We add an 'end' listener, but never consume the data.</span> 4757 socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 4758 <span class="hljs-comment">// It will never get here.</span> 4759 socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'The message was received but was not processed.\n'</span>); 4760 }); 4761 4762}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code> <button class="copy-button">copy</button></pre> 4763<p>Prior to Node.js 0.10, the incoming message data would be simply discarded. 4764However, in Node.js 0.10 and beyond, the socket remains paused forever.</p> 4765<p>The workaround in this situation is to call the 4766<a href="#readableresume"><code>stream.resume()</code></a> method to begin the flow of data:</p> 4767<pre><code class="language-js"><span class="hljs-comment">// Workaround.</span> 4768net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> { 4769 socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 4770 socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'The message was received but was not processed.\n'</span>); 4771 }); 4772 4773 <span class="hljs-comment">// Start the flow of data, discarding it.</span> 4774 socket.<span class="hljs-title function_">resume</span>(); 4775}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code> <button class="copy-button">copy</button></pre> 4776<p>In addition to new <code>Readable</code> streams switching into flowing mode, 4777pre-0.10 style streams can be wrapped in a <code>Readable</code> class using the 4778<a href="#readablewrapstream"><code>readable.wrap()</code></a> method.</p> 4779<h4><code>readable.read(0)</code><span><a class="mark" href="#readableread0" id="readableread0">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_read_0"></a></h4> 4780<p>There are some cases where it is necessary to trigger a refresh of the 4781underlying readable stream mechanisms, without actually consuming any 4782data. In such cases, it is possible to call <code>readable.read(0)</code>, which will 4783always return <code>null</code>.</p> 4784<p>If the internal read buffer is below the <code>highWaterMark</code>, and the 4785stream is not currently reading, then calling <code>stream.read(0)</code> will trigger 4786a low-level <a href="#readable_readsize"><code>stream._read()</code></a> call.</p> 4787<p>While most applications will almost never need to do this, there are 4788situations within Node.js where this is done, particularly in the 4789<code>Readable</code> stream class internals.</p> 4790<h4><code>readable.push('')</code><span><a class="mark" href="#readablepush" id="readablepush">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_push"></a></h4> 4791<p>Use of <code>readable.push('')</code> is not recommended.</p> 4792<p>Pushing a zero-byte string, <code>Buffer</code>, or <code>Uint8Array</code> to a stream that is not in 4793object mode has an interesting side effect. Because it <em>is</em> a call to 4794<a href="#readablepushchunk-encoding"><code>readable.push()</code></a>, the call will end the reading process. 4795However, because the argument is an empty string, no data is added to the 4796readable buffer so there is nothing for a user to consume.</p> 4797<h4><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code><span><a class="mark" href="#highwatermark-discrepancy-after-calling-readablesetencoding" id="highwatermark-discrepancy-after-calling-readablesetencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_highwatermark_discrepancy_after_calling_readable_setencoding"></a></h4> 4798<p>The use of <code>readable.setEncoding()</code> will change the behavior of how the 4799<code>highWaterMark</code> operates in non-object mode.</p> 4800<p>Typically, the size of the current buffer is measured against the 4801<code>highWaterMark</code> in <em>bytes</em>. However, after <code>setEncoding()</code> is called, the 4802comparison function will begin to measure the buffer's size in <em>characters</em>.</p> 4803<p>This is not a problem in common cases with <code>latin1</code> or <code>ascii</code>. But it is 4804advised to be mindful about this behavior when working with strings that could 4805contain multi-byte characters.</p></section> 4806 <!-- API END --> 4807 </div> 4808 </div> 4809 </div> 4810</body> 4811</html> 4812