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.18.2"> 7 <title>Stream | Node.js v18.18.2 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.18.2 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.18.2</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-v20.x/api/stream.html">20.x</a></li> 418<li><a href="https://nodejs.org/docs/latest-v19.x/api/stream.html">19.x</a></li> 419<li><a href="https://nodejs.org/docs/latest-v18.x/api/stream.html">18.x <b>LTS</b></a></li> 420<li><a href="https://nodejs.org/docs/latest-v17.x/api/stream.html">17.x</a></li> 421<li><a href="https://nodejs.org/docs/latest-v16.x/api/stream.html">16.x</a></li> 422<li><a href="https://nodejs.org/docs/latest-v15.x/api/stream.html">15.x</a></li> 423<li><a href="https://nodejs.org/docs/latest-v14.x/api/stream.html">14.x</a></li> 424<li><a href="https://nodejs.org/docs/latest-v13.x/api/stream.html">13.x</a></li> 425<li><a href="https://nodejs.org/docs/latest-v12.x/api/stream.html">12.x</a></li> 426<li><a href="https://nodejs.org/docs/latest-v11.x/api/stream.html">11.x</a></li> 427<li><a href="https://nodejs.org/docs/latest-v10.x/api/stream.html">10.x</a></li> 428<li><a href="https://nodejs.org/docs/latest-v9.x/api/stream.html">9.x</a></li> 429<li><a href="https://nodejs.org/docs/latest-v8.x/api/stream.html">8.x</a></li> 430<li><a href="https://nodejs.org/docs/latest-v7.x/api/stream.html">7.x</a></li> 431<li><a href="https://nodejs.org/docs/latest-v6.x/api/stream.html">6.x</a></li> 432<li><a href="https://nodejs.org/docs/latest-v5.x/api/stream.html">5.x</a></li> 433<li><a href="https://nodejs.org/docs/latest-v4.x/api/stream.html">4.x</a></li> 434<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/stream.html">0.12.x</a></li> 435<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/stream.html">0.10.x</a></li></ol></div> 436 </li> 437 438 <li class="picker-header"> 439 <a href="#"> 440 <span class="collapsed-arrow">►</span><span class="expanded-arrow">▼</span> 441 Options 442 </a> 443 444 <div class="picker"> 445 <ul> 446 <li> 447 <a href="all.html">View on single page</a> 448 </li> 449 <li> 450 <a href="stream.json">View as JSON</a> 451 </li> 452 <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/main/doc/api/stream.md">Edit on GitHub</a></li> 453 </ul> 454 </div> 455 </li> 456 </ul> 457 </div> 458 <hr> 459 </header> 460 461 <details id="toc" open><summary>Table of contents</summary><ul> 462<li><span class="stability_2"><a href="#stream">Stream</a></span> 463<ul> 464<li><a href="#organization-of-this-document">Organization of this document</a></li> 465<li><a href="#types-of-streams">Types of streams</a> 466<ul> 467<li><a href="#streams-promises-api">Streams Promises API</a></li> 468<li><a href="#streampipelinesource-transforms-destination-options"><code>stream.pipeline(source[, ...transforms], destination[, options])</code></a></li> 469<li><a href="#streampipelinestreams-options"><code>stream.pipeline(streams[, options])</code></a></li> 470<li><a href="#streamfinishedstream-options"><code>stream.finished(stream[, options])</code></a></li> 471<li><a href="#object-mode">Object mode</a></li> 472<li><a href="#buffering">Buffering</a></li> 473</ul> 474</li> 475<li><a href="#api-for-stream-consumers">API for stream consumers</a> 476<ul> 477<li><a href="#writable-streams">Writable streams</a> 478<ul> 479<li><a href="#class-streamwritable">Class: <code>stream.Writable</code></a> 480<ul> 481<li><a href="#event-close">Event: <code>'close'</code></a></li> 482<li><a href="#event-drain">Event: <code>'drain'</code></a></li> 483<li><a href="#event-error">Event: <code>'error'</code></a></li> 484<li><a href="#event-finish">Event: <code>'finish'</code></a></li> 485<li><a href="#event-pipe">Event: <code>'pipe'</code></a></li> 486<li><a href="#event-unpipe">Event: <code>'unpipe'</code></a></li> 487<li><a href="#writablecork"><code>writable.cork()</code></a></li> 488<li><a href="#writabledestroyerror"><code>writable.destroy([error])</code></a></li> 489<li><a href="#writableclosed"><code>writable.closed</code></a></li> 490<li><a href="#writabledestroyed"><code>writable.destroyed</code></a></li> 491<li><a href="#writableendchunk-encoding-callback"><code>writable.end([chunk[, encoding]][, callback])</code></a></li> 492<li><a href="#writablesetdefaultencodingencoding"><code>writable.setDefaultEncoding(encoding)</code></a></li> 493<li><a href="#writableuncork"><code>writable.uncork()</code></a></li> 494<li><a href="#writablewritable"><code>writable.writable</code></a></li> 495<li><span class="stability_1"><a href="#writablewritableaborted"><code>writable.writableAborted</code></a></span></li> 496<li><a href="#writablewritableended"><code>writable.writableEnded</code></a></li> 497<li><a href="#writablewritablecorked"><code>writable.writableCorked</code></a></li> 498<li><a href="#writableerrored"><code>writable.errored</code></a></li> 499<li><a href="#writablewritablefinished"><code>writable.writableFinished</code></a></li> 500<li><a href="#writablewritablehighwatermark"><code>writable.writableHighWaterMark</code></a></li> 501<li><a href="#writablewritablelength"><code>writable.writableLength</code></a></li> 502<li><a href="#writablewritableneeddrain"><code>writable.writableNeedDrain</code></a></li> 503<li><a href="#writablewritableobjectmode"><code>writable.writableObjectMode</code></a></li> 504<li><a href="#writablewritechunk-encoding-callback"><code>writable.write(chunk[, encoding][, callback])</code></a></li> 505</ul> 506</li> 507</ul> 508</li> 509<li><a href="#readable-streams">Readable streams</a> 510<ul> 511<li><a href="#two-reading-modes">Two reading modes</a></li> 512<li><a href="#three-states">Three states</a></li> 513<li><a href="#choose-one-api-style">Choose one API style</a></li> 514<li><a href="#class-streamreadable">Class: <code>stream.Readable</code></a> 515<ul> 516<li><a href="#event-close_1">Event: <code>'close'</code></a></li> 517<li><a href="#event-data">Event: <code>'data'</code></a></li> 518<li><a href="#event-end">Event: <code>'end'</code></a></li> 519<li><a href="#event-error_1">Event: <code>'error'</code></a></li> 520<li><a href="#event-pause">Event: <code>'pause'</code></a></li> 521<li><a href="#event-readable">Event: <code>'readable'</code></a></li> 522<li><a href="#event-resume">Event: <code>'resume'</code></a></li> 523<li><a href="#readabledestroyerror"><code>readable.destroy([error])</code></a></li> 524<li><a href="#readableclosed"><code>readable.closed</code></a></li> 525<li><a href="#readabledestroyed"><code>readable.destroyed</code></a></li> 526<li><a href="#readableispaused"><code>readable.isPaused()</code></a></li> 527<li><a href="#readablepause"><code>readable.pause()</code></a></li> 528<li><a href="#readablepipedestination-options"><code>readable.pipe(destination[, options])</code></a></li> 529<li><a href="#readablereadsize"><code>readable.read([size])</code></a></li> 530<li><a href="#readablereadable"><code>readable.readable</code></a></li> 531<li><span class="stability_1"><a href="#readablereadableaborted"><code>readable.readableAborted</code></a></span></li> 532<li><span class="stability_1"><a href="#readablereadabledidread"><code>readable.readableDidRead</code></a></span></li> 533<li><a href="#readablereadableencoding"><code>readable.readableEncoding</code></a></li> 534<li><a href="#readablereadableended"><code>readable.readableEnded</code></a></li> 535<li><a href="#readableerrored"><code>readable.errored</code></a></li> 536<li><a href="#readablereadableflowing"><code>readable.readableFlowing</code></a></li> 537<li><a href="#readablereadablehighwatermark"><code>readable.readableHighWaterMark</code></a></li> 538<li><a href="#readablereadablelength"><code>readable.readableLength</code></a></li> 539<li><a href="#readablereadableobjectmode"><code>readable.readableObjectMode</code></a></li> 540<li><a href="#readableresume"><code>readable.resume()</code></a></li> 541<li><a href="#readablesetencodingencoding"><code>readable.setEncoding(encoding)</code></a></li> 542<li><a href="#readableunpipedestination"><code>readable.unpipe([destination])</code></a></li> 543<li><a href="#readableunshiftchunk-encoding"><code>readable.unshift(chunk[, encoding])</code></a></li> 544<li><a href="#readablewrapstream"><code>readable.wrap(stream)</code></a></li> 545<li><a href="#readablesymbolasynciterator"><code>readable[Symbol.asyncIterator]()</code></a></li> 546<li><span class="stability_1"><a href="#readablesymbolasyncdispose"><code>readable[Symbol.asyncDispose]()</code></a></span></li> 547<li><span class="stability_1"><a href="#readablecomposestream-options"><code>readable.compose(stream[, options])</code></a></span></li> 548<li><span class="stability_1"><a href="#readableiteratoroptions"><code>readable.iterator([options])</code></a></span></li> 549<li><span class="stability_1"><a href="#readablemapfn-options"><code>readable.map(fn[, options])</code></a></span></li> 550<li><span class="stability_1"><a href="#readablefilterfn-options"><code>readable.filter(fn[, options])</code></a></span></li> 551<li><span class="stability_1"><a href="#readableforeachfn-options"><code>readable.forEach(fn[, options])</code></a></span></li> 552<li><span class="stability_1"><a href="#readabletoarrayoptions"><code>readable.toArray([options])</code></a></span></li> 553<li><span class="stability_1"><a href="#readablesomefn-options"><code>readable.some(fn[, options])</code></a></span></li> 554<li><span class="stability_1"><a href="#readablefindfn-options"><code>readable.find(fn[, options])</code></a></span></li> 555<li><span class="stability_1"><a href="#readableeveryfn-options"><code>readable.every(fn[, options])</code></a></span></li> 556<li><span class="stability_1"><a href="#readableflatmapfn-options"><code>readable.flatMap(fn[, options])</code></a></span></li> 557<li><span class="stability_1"><a href="#readabledroplimit-options"><code>readable.drop(limit[, options])</code></a></span></li> 558<li><span class="stability_1"><a href="#readabletakelimit-options"><code>readable.take(limit[, options])</code></a></span></li> 559<li><span class="stability_1"><a href="#readableasindexedpairsoptions"><code>readable.asIndexedPairs([options])</code></a></span></li> 560<li><span class="stability_1"><a href="#readablereducefn-initial-options"><code>readable.reduce(fn[, initial[, options]])</code></a></span></li> 561</ul> 562</li> 563</ul> 564</li> 565<li><a href="#duplex-and-transform-streams">Duplex and transform streams</a> 566<ul> 567<li><a href="#class-streamduplex">Class: <code>stream.Duplex</code></a> 568<ul> 569<li><a href="#duplexallowhalfopen"><code>duplex.allowHalfOpen</code></a></li> 570</ul> 571</li> 572<li><a href="#class-streamtransform">Class: <code>stream.Transform</code></a> 573<ul> 574<li><a href="#transformdestroyerror"><code>transform.destroy([error])</code></a></li> 575</ul> 576</li> 577</ul> 578</li> 579<li><a href="#streamfinishedstream-options-callback"><code>stream.finished(stream[, options], callback)</code></a></li> 580<li><a href="#streampipelinesource-transforms-destination-callback"><code>stream.pipeline(source[, ...transforms], destination, callback)</code></a></li> 581<li><a href="#streampipelinestreams-callback"><code>stream.pipeline(streams, callback)</code></a></li> 582<li><span class="stability_1"><a href="#streamcomposestreams"><code>stream.compose(...streams)</code></a></span></li> 583<li><a href="#streamreadablefromiterable-options"><code>stream.Readable.from(iterable[, options])</code></a></li> 584<li><span class="stability_1"><a href="#streamreadablefromwebreadablestream-options"><code>stream.Readable.fromWeb(readableStream[, options])</code></a></span></li> 585<li><span class="stability_1"><a href="#streamreadableisdisturbedstream"><code>stream.Readable.isDisturbed(stream)</code></a></span></li> 586<li><span class="stability_1"><a href="#streamiserroredstream"><code>stream.isErrored(stream)</code></a></span></li> 587<li><span class="stability_1"><a href="#streamisreadablestream"><code>stream.isReadable(stream)</code></a></span></li> 588<li><span class="stability_1"><a href="#streamreadabletowebstreamreadable-options"><code>stream.Readable.toWeb(streamReadable[, options])</code></a></span></li> 589<li><span class="stability_1"><a href="#streamwritablefromwebwritablestream-options"><code>stream.Writable.fromWeb(writableStream[, options])</code></a></span></li> 590<li><span class="stability_1"><a href="#streamwritabletowebstreamwritable"><code>stream.Writable.toWeb(streamWritable)</code></a></span></li> 591<li><a href="#streamduplexfromsrc"><code>stream.Duplex.from(src)</code></a></li> 592<li><span class="stability_1"><a href="#streamduplexfromwebpair-options"><code>stream.Duplex.fromWeb(pair[, options])</code></a></span></li> 593<li><span class="stability_1"><a href="#streamduplextowebstreamduplex"><code>stream.Duplex.toWeb(streamDuplex)</code></a></span></li> 594<li><a href="#streamaddabortsignalsignal-stream"><code>stream.addAbortSignal(signal, stream)</code></a></li> 595<li><a href="#streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark(objectMode)</code></a></li> 596<li><a href="#streamsetdefaulthighwatermarkobjectmode-value"><code>stream.setDefaultHighWaterMark(objectMode, value)</code></a></li> 597</ul> 598</li> 599<li><a href="#api-for-stream-implementers">API for stream implementers</a> 600<ul> 601<li><a href="#simplified-construction">Simplified construction</a></li> 602<li><a href="#implementing-a-writable-stream">Implementing a writable stream</a> 603<ul> 604<li><a href="#new-streamwritableoptions"><code>new stream.Writable([options])</code></a></li> 605<li><a href="#writable_constructcallback"><code>writable._construct(callback)</code></a></li> 606<li><a href="#writable_writechunk-encoding-callback"><code>writable._write(chunk, encoding, callback)</code></a></li> 607<li><a href="#writable_writevchunks-callback"><code>writable._writev(chunks, callback)</code></a></li> 608<li><a href="#writable_destroyerr-callback"><code>writable._destroy(err, callback)</code></a></li> 609<li><a href="#writable_finalcallback"><code>writable._final(callback)</code></a></li> 610<li><a href="#errors-while-writing">Errors while writing</a></li> 611<li><a href="#an-example-writable-stream">An example writable stream</a></li> 612<li><a href="#decoding-buffers-in-a-writable-stream">Decoding buffers in a writable stream</a></li> 613</ul> 614</li> 615<li><a href="#implementing-a-readable-stream">Implementing a readable stream</a> 616<ul> 617<li><a href="#new-streamreadableoptions"><code>new stream.Readable([options])</code></a></li> 618<li><a href="#readable_constructcallback"><code>readable._construct(callback)</code></a></li> 619<li><a href="#readable_readsize"><code>readable._read(size)</code></a></li> 620<li><a href="#readable_destroyerr-callback"><code>readable._destroy(err, callback)</code></a></li> 621<li><a href="#readablepushchunk-encoding"><code>readable.push(chunk[, encoding])</code></a></li> 622<li><a href="#errors-while-reading">Errors while reading</a></li> 623<li><a href="#an-example-counting-stream">An example counting stream</a></li> 624</ul> 625</li> 626<li><a href="#implementing-a-duplex-stream">Implementing a duplex stream</a> 627<ul> 628<li><a href="#new-streamduplexoptions"><code>new stream.Duplex(options)</code></a></li> 629<li><a href="#an-example-duplex-stream">An example duplex stream</a></li> 630<li><a href="#object-mode-duplex-streams">Object mode duplex streams</a></li> 631</ul> 632</li> 633<li><a href="#implementing-a-transform-stream">Implementing a transform stream</a> 634<ul> 635<li><a href="#new-streamtransformoptions"><code>new stream.Transform([options])</code></a></li> 636<li><a href="#event-end_1">Event: <code>'end'</code></a></li> 637<li><a href="#event-finish_1">Event: <code>'finish'</code></a></li> 638<li><a href="#transform_flushcallback"><code>transform._flush(callback)</code></a></li> 639<li><a href="#transform_transformchunk-encoding-callback"><code>transform._transform(chunk, encoding, callback)</code></a></li> 640<li><a href="#class-streampassthrough">Class: <code>stream.PassThrough</code></a></li> 641</ul> 642</li> 643</ul> 644</li> 645<li><a href="#additional-notes">Additional notes</a> 646<ul> 647<li><a href="#streams-compatibility-with-async-generators-and-async-iterators">Streams compatibility with async generators and async iterators</a> 648<ul> 649<li><a href="#consuming-readable-streams-with-async-iterators">Consuming readable streams with async iterators</a></li> 650<li><a href="#creating-readable-streams-with-async-generators">Creating readable streams with async generators</a></li> 651<li><a href="#piping-to-writable-streams-from-async-iterators">Piping to writable streams from async iterators</a></li> 652</ul> 653</li> 654<li><a href="#compatibility-with-older-nodejs-versions">Compatibility with older Node.js versions</a></li> 655<li><a href="#readableread0"><code>readable.read(0)</code></a></li> 656<li><a href="#readablepush"><code>readable.push('')</code></a></li> 657<li><a href="#highwatermark-discrepancy-after-calling-readablesetencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li> 658</ul> 659</li> 660</ul> 661</li> 662</ul></details> 663 664 <div id="apicontent"> 665 <h2>Stream<a class="srclink" href="https://github.com/nodejs/node/blob/8a01b3dcb7d08a48bfd3e6bf85ef49faa1454839/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> 666 667<p></p><div class="api_stability api_stability_2"><a href="documentation.html#stability-index">Stability: 2</a> - Stable</div><p></p> 668<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v18.18.2/lib/stream.js">lib/stream.js</a></p> 669<p>A stream is an abstract interface for working with streaming data in Node.js. 670The <code>node:stream</code> module provides an API for implementing the stream interface.</p> 671<p>There are many stream objects provided by Node.js. For instance, a 672<a href="http.html#class-httpincomingmessage">request to an HTTP server</a> and <a href="process.html#processstdout"><code>process.stdout</code></a> 673are both stream instances.</p> 674<p>Streams can be readable, writable, or both. All streams are instances of 675<a href="events.html#class-eventemitter"><code>EventEmitter</code></a>.</p> 676<p>To access the <code>node:stream</code> module:</p> 677<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> 678<p>The <code>node:stream</code> module is useful for creating new types of stream instances. 679It is usually not necessary to use the <code>node:stream</code> module to consume streams.</p> 680<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> 681<p>This document contains two primary sections and a third section for notes. The 682first section explains how to use existing streams within an application. The 683second section explains how to create new types of streams.</p> 684</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> 685<p>There are four fundamental stream types within Node.js:</p> 686<ul> 687<li><a href="#class-streamwritable"><code>Writable</code></a>: streams to which data can be written (for example, 688<a href="fs.html#fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>).</li> 689<li><a href="#class-streamreadable"><code>Readable</code></a>: streams from which data can be read (for example, 690<a href="fs.html#fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>).</li> 691<li><a href="#class-streamduplex"><code>Duplex</code></a>: streams that are both <code>Readable</code> and <code>Writable</code> (for example, 692<a href="net.html#class-netsocket"><code>net.Socket</code></a>).</li> 693<li><a href="#class-streamtransform"><code>Transform</code></a>: <code>Duplex</code> streams that can modify or transform the data as it 694is written and read (for example, <a href="zlib.html#zlibcreatedeflateoptions"><code>zlib.createDeflate()</code></a>).</li> 695</ul> 696<p>Additionally, this module includes the utility functions 697<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> 698and <a href="#streamaddabortsignalsignal-stream"><code>stream.addAbortSignal()</code></a>.</p> 699<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> 700<div class="api_metadata"> 701<span>Added in: v15.0.0</span> 702</div> 703<p>The <code>stream/promises</code> API provides an alternative set of asynchronous utility 704functions for streams that return <code>Promise</code> objects rather than using 705callbacks. The API is accessible via <code>require('node:stream/promises')</code> 706or <code>require('node:stream').promises</code>.</p> 707<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> 708<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> 709<div class="api_metadata"> 710<span>Added in: v15.0.0</span> 711</div> 712<ul> 713<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> 714<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> 715<ul> 716<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> 717</ul> 718</li> 719<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> 720<ul> 721<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 722<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> 723</ul> 724</li> 725<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> 726<ul> 727<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 728<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> 729</ul> 730</li> 731<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 732<ul> 733<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li> 734<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 735</ul> 736</li> 737<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> 738</ul> 739 740<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>); 741<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 742<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>); 743 744<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 745 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 746 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 747 zlib.<span class="hljs-title function_">createGzip</span>(), 748 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 749 ); 750 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 751} 752 753<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>; 754<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 755<span class="hljs-keyword">import</span> { createGzip } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>; 756 757<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 758 <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 759 <span class="hljs-title function_">createGzip</span>(), 760 <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 761); 762<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> 763<p>To use an <code>AbortSignal</code>, pass it inside an options object, as the last argument. 764When the signal is aborted, <code>destroy</code> will be called on the underlying pipeline, 765with an <code>AbortError</code>.</p> 766 767<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>); 768<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 769<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>); 770 771<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 772 <span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 773 <span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>; 774 775 <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>()); 776 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 777 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 778 zlib.<span class="hljs-title function_">createGzip</span>(), 779 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 780 { signal }, 781 ); 782} 783 784<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>; 785<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 786<span class="hljs-keyword">import</span> { createGzip } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>; 787 788<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 789<span class="hljs-keyword">const</span> { signal } = ac; 790<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>()); 791<span class="hljs-keyword">try</span> { 792 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 793 <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 794 <span class="hljs-title function_">createGzip</span>(), 795 <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 796 { signal }, 797 ); 798} <span class="hljs-keyword">catch</span> (err) { 799 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err); <span class="hljs-comment">// AbortError</span> 800}</code><button class="copy-button">copy</button></pre> 801<p>The <code>pipeline</code> API also supports async generators:</p> 802 803<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>); 804<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 805 806<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 807 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 808 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'lowercase.txt'</span>), 809 <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* (source, { signal }) { 810 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> 811 <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) { 812 <span class="hljs-keyword">yield</span> <span class="hljs-keyword">await</span> <span class="hljs-title function_">processChunk</span>(chunk, { signal }); 813 } 814 }, 815 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>), 816 ); 817 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 818} 819 820<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>; 821<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 822 823<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 824 <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'lowercase.txt'</span>), 825 <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* (source, { signal }) { 826 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> 827 <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) { 828 <span class="hljs-keyword">yield</span> <span class="hljs-keyword">await</span> <span class="hljs-title function_">processChunk</span>(chunk, { signal }); 829 } 830 }, 831 <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>), 832); 833<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> 834<p>Remember to handle the <code>signal</code> argument passed into the async generator. 835Especially in the case where the async generator is the source for the 836pipeline (i.e. first argument) or the pipeline will never complete.</p> 837 838<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>); 839<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 840 841<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 842 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 843 <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* ({ signal }) { 844 <span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningfn</span>({ signal }); 845 <span class="hljs-keyword">yield</span> <span class="hljs-string">'asd'</span>; 846 }, 847 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>), 848 ); 849 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 850} 851 852<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>; 853<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 854<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 855 <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* ({ signal }) { 856 <span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningfn</span>({ signal }); 857 <span class="hljs-keyword">yield</span> <span class="hljs-string">'asd'</span>; 858 }, 859 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>), 860); 861<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> 862<p>The <code>pipeline</code> API provides <a href="#streampipelinesource-transforms-destination-callback">callback version</a>:</p> 863<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> 864<div class="api_metadata"> 865<span>Added in: v15.0.0</span> 866</div> 867<ul> 868<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a></li> 869<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 870<ul> 871<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> 872<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> 873<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> 874<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> 875</ul> 876</li> 877<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 878longer readable or writable.</li> 879</ul> 880 881<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>); 882<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 883 884<span class="hljs-keyword">const</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>); 885 886<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 887 <span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(rs); 888 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>); 889} 890 891<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>); 892rs.<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>; 893<span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 894 895<span class="hljs-keyword">const</span> rs = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>); 896 897<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 898 <span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(rs); 899 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>); 900} 901 902<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>); 903rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code><button class="copy-button">copy</button></pre> 904<p>The <code>finished</code> API provides <a href="#streamfinishedstream-options-callback">callback version</a>:</p> 905<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> 906<p>All streams created by Node.js APIs operate exclusively on strings and <code>Buffer</code> 907(or <code>Uint8Array</code>) objects. It is possible, however, for stream implementations 908to work with other types of JavaScript values (with the exception of <code>null</code>, 909which serves a special purpose within streams). Such streams are considered to 910operate in "object mode".</p> 911<p>Stream instances are switched into object mode using the <code>objectMode</code> option 912when the stream is created. Attempting to switch an existing stream into 913object mode is not safe.</p> 914<h4>Buffering<span><a class="mark" href="#buffering" id="buffering">#</a></span><a aria-hidden="true" class="legacy" id="stream_buffering"></a></h4> 915 916<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 917buffer.</p> 918<p>The amount of data potentially buffered depends on the <code>highWaterMark</code> option 919passed into the stream's constructor. For normal streams, the <code>highWaterMark</code> 920option specifies a <a href="#highwatermark-discrepancy-after-calling-readablesetencoding">total number of bytes</a>. For streams operating 921in object mode, the <code>highWaterMark</code> specifies a total number of objects.</p> 922<p>Data is buffered in <code>Readable</code> streams when the implementation calls 923<a href="#readablepushchunk-encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not 924call <a href="#readablereadsize"><code>stream.read()</code></a>, the data will sit in the internal 925queue until it is consumed.</p> 926<p>Once the total size of the internal read buffer reaches the threshold specified 927by <code>highWaterMark</code>, the stream will temporarily stop reading data from the 928underlying resource until the data currently buffered can be consumed (that is, 929the stream will stop calling the internal <a href="#readable_readsize"><code>readable._read()</code></a> method that is 930used to fill the read buffer).</p> 931<p>Data is buffered in <code>Writable</code> streams when the 932<a href="#writablewritechunk-encoding-callback"><code>writable.write(chunk)</code></a> method is called repeatedly. While the 933total size of the internal write buffer is below the threshold set by 934<code>highWaterMark</code>, calls to <code>writable.write()</code> will return <code>true</code>. Once 935the size of the internal buffer reaches or exceeds the <code>highWaterMark</code>, <code>false</code> 936will be returned.</p> 937<p>A key goal of the <code>stream</code> API, particularly the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> method, 938is to limit the buffering of data to acceptable levels such that sources and 939destinations of differing speeds will not overwhelm the available memory.</p> 940<p>The <code>highWaterMark</code> option is a threshold, not a limit: it dictates the amount 941of data that a stream buffers before it stops asking for more data. It does not 942enforce a strict memory limitation in general. Specific stream implementations 943may choose to enforce stricter limits but doing so is optional.</p> 944<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 945<code>Writable</code>, each maintains <em>two</em> separate internal buffers used for reading and 946writing, allowing each side to operate independently of the other while 947maintaining an appropriate and efficient flow of data. For example, 948<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 949consumption of data received <em>from</em> the socket and whose <code>Writable</code> side allows 950writing data <em>to</em> the socket. Because data may be written to the socket at a 951faster or slower rate than data is received, each side should 952operate (and buffer) independently of the other.</p> 953<p>The mechanics of the internal buffering are an internal implementation detail 954and may be changed at any time. However, for certain advanced implementations, 955the internal buffers can be retrieved using <code>writable.writableBuffer</code> or 956<code>readable.readableBuffer</code>. Use of these undocumented properties is discouraged.</p> 957</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> 958 959<p>Almost all Node.js applications, no matter how simple, use streams in some 960manner. The following is an example of using streams in a Node.js application 961that implements an HTTP server:</p> 962<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>); 963 964<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> { 965 <span class="hljs-comment">// `req` is an http.IncomingMessage, which is a readable stream.</span> 966 <span class="hljs-comment">// `res` is an http.ServerResponse, which is a writable stream.</span> 967 968 <span class="hljs-keyword">let</span> body = <span class="hljs-string">''</span>; 969 <span class="hljs-comment">// Get the data as utf8 strings.</span> 970 <span class="hljs-comment">// If an encoding is not set, Buffer objects will be received.</span> 971 req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); 972 973 <span class="hljs-comment">// Readable streams emit 'data' events once a listener is added.</span> 974 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> { 975 body += chunk; 976 }); 977 978 <span class="hljs-comment">// The 'end' event indicates that the entire body has been received.</span> 979 req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 980 <span class="hljs-keyword">try</span> { 981 <span class="hljs-keyword">const</span> data = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(body); 982 <span class="hljs-comment">// Write back something interesting to the user:</span> 983 res.<span class="hljs-title function_">write</span>(<span class="hljs-keyword">typeof</span> data); 984 res.<span class="hljs-title function_">end</span>(); 985 } <span class="hljs-keyword">catch</span> (er) { 986 <span class="hljs-comment">// uh oh! bad json!</span> 987 res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">400</span>; 988 <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>); 989 } 990 }); 991}); 992 993server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>); 994 995<span class="hljs-comment">// $ curl localhost:1337 -d "{}"</span> 996<span class="hljs-comment">// object</span> 997<span class="hljs-comment">// $ curl localhost:1337 -d "\"foo\""</span> 998<span class="hljs-comment">// string</span> 999<span class="hljs-comment">// $ curl localhost:1337 -d "not json"</span> 1000<span class="hljs-comment">// error: Unexpected token 'o', "not json" is not valid JSON</span></code> <button class="copy-button">copy</button></pre> 1001<p><a href="#class-streamwritable"><code>Writable</code></a> streams (such as <code>res</code> in the example) expose methods such as 1002<code>write()</code> and <code>end()</code> that are used to write data onto the stream.</p> 1003<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 1004code when data is available to be read off the stream. That available data can 1005be read from the stream in multiple ways.</p> 1006<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 1007various ways to communicate the current state of the stream.</p> 1008<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 1009<a href="#class-streamreadable"><code>Readable</code></a>.</p> 1010<p>Applications that are either writing data to or consuming data from a stream 1011are not required to implement the stream interfaces directly and will generally 1012have no reason to call <code>require('node:stream')</code>.</p> 1013<p>Developers wishing to implement new types of streams should refer to the 1014section <a href="#api-for-stream-implementers">API for stream implementers</a>.</p> 1015<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> 1016<p>Writable streams are an abstraction for a <em>destination</em> to which data is 1017written.</p> 1018<p>Examples of <a href="#class-streamwritable"><code>Writable</code></a> streams include:</p> 1019<ul> 1020<li><a href="http.html#class-httpclientrequest">HTTP requests, on the client</a></li> 1021<li><a href="http.html#class-httpserverresponse">HTTP responses, on the server</a></li> 1022<li><a href="fs.html#class-fswritestream">fs write streams</a></li> 1023<li><a href="zlib.html">zlib streams</a></li> 1024<li><a href="crypto.html">crypto streams</a></li> 1025<li><a href="net.html#class-netsocket">TCP sockets</a></li> 1026<li><a href="child_process.html#subprocessstdin">child process stdin</a></li> 1027<li><a href="process.html#processstdout"><code>process.stdout</code></a>, <a href="process.html#processstderr"><code>process.stderr</code></a></li> 1028</ul> 1029<p>Some of these examples are actually <a href="#class-streamduplex"><code>Duplex</code></a> streams that implement the 1030<a href="#class-streamwritable"><code>Writable</code></a> interface.</p> 1031<p>All <a href="#class-streamwritable"><code>Writable</code></a> streams implement the interface defined by the 1032<code>stream.Writable</code> class.</p> 1033<p>While specific instances of <a href="#class-streamwritable"><code>Writable</code></a> streams may differ in various ways, 1034all <code>Writable</code> streams follow the same fundamental usage pattern as illustrated 1035in the example below:</p> 1036<pre><code class="language-js"><span class="hljs-keyword">const</span> myStream = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 1037myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data'</span>); 1038myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some more data'</span>); 1039myStream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'done writing data'</span>);</code> <button class="copy-button">copy</button></pre> 1040<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> 1041<div class="api_metadata"> 1042<span>Added in: v0.9.4</span> 1043</div> 1044 1045<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> 1046<div class="api_metadata"> 1047<details class="changelog"><summary>History</summary> 1048<table> 1049<tbody><tr><th>Version</th><th>Changes</th></tr> 1050<tr><td>v10.0.0</td> 1051<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> 1052<tr><td>v0.9.4</td> 1053<td><p><span>Added in: v0.9.4</span></p></td></tr> 1054</tbody></table> 1055</details> 1056</div> 1057<p>The <code>'close'</code> event is emitted when the stream and any of its underlying 1058resources (a file descriptor, for example) have been closed. The event indicates 1059that no more events will be emitted, and no further computation will occur.</p> 1060<p>A <a href="#class-streamwritable"><code>Writable</code></a> stream will always emit the <code>'close'</code> event if it is 1061created with the <code>emitClose</code> option.</p> 1062<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> 1063<div class="api_metadata"> 1064<span>Added in: v0.9.4</span> 1065</div> 1066<p>If a call to <a href="#writablewritechunk-encoding-callback"><code>stream.write(chunk)</code></a> returns <code>false</code>, the 1067<code>'drain'</code> event will be emitted when it is appropriate to resume writing data 1068to the stream.</p> 1069<pre><code class="language-js"><span class="hljs-comment">// Write the data to the supplied writable stream one million times.</span> 1070<span class="hljs-comment">// Be attentive to back-pressure.</span> 1071<span class="hljs-keyword">function</span> <span class="hljs-title function_">writeOneMillionTimes</span>(<span class="hljs-params">writer, data, encoding, callback</span>) { 1072 <span class="hljs-keyword">let</span> i = <span class="hljs-number">1000000</span>; 1073 <span class="hljs-title function_">write</span>(); 1074 <span class="hljs-keyword">function</span> <span class="hljs-title function_">write</span>(<span class="hljs-params"></span>) { 1075 <span class="hljs-keyword">let</span> ok = <span class="hljs-literal">true</span>; 1076 <span class="hljs-keyword">do</span> { 1077 i--; 1078 <span class="hljs-keyword">if</span> (i === <span class="hljs-number">0</span>) { 1079 <span class="hljs-comment">// Last time!</span> 1080 writer.<span class="hljs-title function_">write</span>(data, encoding, callback); 1081 } <span class="hljs-keyword">else</span> { 1082 <span class="hljs-comment">// See if we should continue, or wait.</span> 1083 <span class="hljs-comment">// Don't pass the callback, because we're not done yet.</span> 1084 ok = writer.<span class="hljs-title function_">write</span>(data, encoding); 1085 } 1086 } <span class="hljs-keyword">while</span> (i > <span class="hljs-number">0</span> && ok); 1087 <span class="hljs-keyword">if</span> (i > <span class="hljs-number">0</span>) { 1088 <span class="hljs-comment">// Had to stop early!</span> 1089 <span class="hljs-comment">// Write some more once it drains.</span> 1090 writer.<span class="hljs-title function_">once</span>(<span class="hljs-string">'drain'</span>, write); 1091 } 1092 } 1093}</code> <button class="copy-button">copy</button></pre> 1094<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> 1095<div class="api_metadata"> 1096<span>Added in: v0.9.4</span> 1097</div> 1098<ul> 1099<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1100</ul> 1101<p>The <code>'error'</code> event is emitted if an error occurred while writing or piping 1102data. The listener callback is passed a single <code>Error</code> argument when called.</p> 1103<p>The stream is closed when the <code>'error'</code> event is emitted unless the 1104<a href="#new-streamwritableoptions"><code>autoDestroy</code></a> option was set to <code>false</code> when creating the 1105stream.</p> 1106<p>After <code>'error'</code>, no further events other than <code>'close'</code> <em>should</em> be emitted 1107(including <code>'error'</code> events).</p> 1108<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> 1109<div class="api_metadata"> 1110<span>Added in: v0.9.4</span> 1111</div> 1112<p>The <code>'finish'</code> event is emitted after the <a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> method 1113has been called, and all data has been flushed to the underlying system.</p> 1114<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 1115<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++) { 1116 writer.<span class="hljs-title function_">write</span>(<span class="hljs-string">`hello, #<span class="hljs-subst">${i}</span>!\n`</span>); 1117} 1118writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'finish'</span>, <span class="hljs-function">() =></span> { 1119 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'All writes are now complete.'</span>); 1120}); 1121writer.<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> 1122<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> 1123<div class="api_metadata"> 1124<span>Added in: v0.9.4</span> 1125</div> 1126<ul> 1127<li><code>src</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a> source stream that is piping to this writable</li> 1128</ul> 1129<p>The <code>'pipe'</code> event is emitted when the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> method is called on 1130a readable stream, adding this writable to its set of destinations.</p> 1131<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 1132<span class="hljs-keyword">const</span> reader = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1133writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'pipe'</span>, <span class="hljs-function">(<span class="hljs-params">src</span>) =></span> { 1134 <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>); 1135 assert.<span class="hljs-title function_">equal</span>(src, reader); 1136}); 1137reader.<span class="hljs-title function_">pipe</span>(writer);</code> <button class="copy-button">copy</button></pre> 1138<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> 1139<div class="api_metadata"> 1140<span>Added in: v0.9.4</span> 1141</div> 1142<ul> 1143<li><code>src</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a> The source stream that 1144<a href="#readableunpipedestination">unpiped</a> this writable</li> 1145</ul> 1146<p>The <code>'unpipe'</code> event is emitted when the <a href="#readableunpipedestination"><code>stream.unpipe()</code></a> method is called 1147on a <a href="#class-streamreadable"><code>Readable</code></a> stream, removing this <a href="#class-streamwritable"><code>Writable</code></a> from its set of 1148destinations.</p> 1149<p>This is also emitted in case this <a href="#class-streamwritable"><code>Writable</code></a> stream emits an error when a 1150<a href="#class-streamreadable"><code>Readable</code></a> stream pipes into it.</p> 1151<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 1152<span class="hljs-keyword">const</span> reader = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1153writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unpipe'</span>, <span class="hljs-function">(<span class="hljs-params">src</span>) =></span> { 1154 <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>); 1155 assert.<span class="hljs-title function_">equal</span>(src, reader); 1156}); 1157reader.<span class="hljs-title function_">pipe</span>(writer); 1158reader.<span class="hljs-title function_">unpipe</span>(writer);</code> <button class="copy-button">copy</button></pre> 1159<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> 1160<div class="api_metadata"> 1161<span>Added in: v0.11.2</span> 1162</div> 1163<p>The <code>writable.cork()</code> method forces all written data to be buffered in memory. 1164The buffered data will be flushed when either the <a href="#writableuncork"><code>stream.uncork()</code></a> or 1165<a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> methods are called.</p> 1166<p>The primary intent of <code>writable.cork()</code> is to accommodate a situation in which 1167several small chunks are written to the stream in rapid succession. Instead of 1168immediately forwarding them to the underlying destination, <code>writable.cork()</code> 1169buffers all the chunks until <code>writable.uncork()</code> is called, which will pass them 1170all to <code>writable._writev()</code>, if present. This prevents a head-of-line blocking 1171situation where data is being buffered while waiting for the first small chunk 1172to be processed. However, use of <code>writable.cork()</code> without implementing 1173<code>writable._writev()</code> may have an adverse effect on throughput.</p> 1174<p>See also: <a href="#writableuncork"><code>writable.uncork()</code></a>, <a href="#writable_writevchunks-callback"><code>writable._writev()</code></a>.</p> 1175<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> 1176<div class="api_metadata"> 1177<details class="changelog"><summary>History</summary> 1178<table> 1179<tbody><tr><th>Version</th><th>Changes</th></tr> 1180<tr><td>v14.0.0</td> 1181<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr> 1182<tr><td>v8.0.0</td> 1183<td><p><span>Added in: v8.0.0</span></p></td></tr> 1184</tbody></table> 1185</details> 1186</div> 1187<ul> 1188<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> 1189<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1190</ul> 1191<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code> 1192event (unless <code>emitClose</code> is set to <code>false</code>). After this call, the writable 1193stream has ended and subsequent calls to <code>write()</code> or <code>end()</code> will result in 1194an <code>ERR_STREAM_DESTROYED</code> error. 1195This is a destructive and immediate way to destroy a stream. Previous calls to 1196<code>write()</code> may not have drained, and may trigger an <code>ERR_STREAM_DESTROYED</code> error. 1197Use <code>end()</code> instead of destroy if data should flush before close, or wait for 1198the <code>'drain'</code> event before destroying the stream.</p> 1199<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>); 1200 1201<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 1202 1203<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>); 1204myStream.<span class="hljs-title function_">destroy</span>(fooErr); 1205myStream.<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> 1206<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>); 1207 1208<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 1209 1210myStream.<span class="hljs-title function_">destroy</span>(); 1211myStream.<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> 1212<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>); 1213 1214<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 1215myStream.<span class="hljs-title function_">destroy</span>(); 1216 1217myStream.<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>)); 1218<span class="hljs-comment">// ERR_STREAM_DESTROYED</span></code> <button class="copy-button">copy</button></pre> 1219<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no 1220further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p> 1221<p>Implementors should not override this method, 1222but instead implement <a href="#writable_destroyerr-callback"><code>writable._destroy()</code></a>.</p> 1223<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> 1224<div class="api_metadata"> 1225<span>Added in: v18.0.0</span> 1226</div> 1227<ul> 1228<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1229</ul> 1230<p>Is <code>true</code> after <code>'close'</code> has been emitted.</p> 1231<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> 1232<div class="api_metadata"> 1233<span>Added in: v8.0.0</span> 1234</div> 1235<ul> 1236<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1237</ul> 1238<p>Is <code>true</code> after <a href="#writabledestroyerror"><code>writable.destroy()</code></a> has been called.</p> 1239<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>); 1240 1241<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 1242 1243<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> 1244myStream.<span class="hljs-title function_">destroy</span>(); 1245<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> 1246<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> 1247<div class="api_metadata"> 1248<details class="changelog"><summary>History</summary> 1249<table> 1250<tbody><tr><th>Version</th><th>Changes</th></tr> 1251<tr><td>v15.0.0</td> 1252<td><p>The <code>callback</code> is invoked before 'finish' or on error.</p></td></tr> 1253<tr><td>v14.0.0</td> 1254<td><p>The <code>callback</code> is invoked if 'finish' or 'error' is emitted.</p></td></tr> 1255<tr><td>v10.0.0</td> 1256<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr> 1257<tr><td>v8.0.0</td> 1258<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 1259<tr><td>v0.9.4</td> 1260<td><p><span>Added in: v0.9.4</span></p></td></tr> 1261</tbody></table> 1262</details> 1263</div> 1264<ul> 1265<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 1266not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or 1267<code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value 1268other than <code>null</code>.</li> 1269<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> 1270<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> 1271<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1272</ul> 1273<p>Calling the <code>writable.end()</code> method signals that no more data will be written 1274to the <a href="#class-streamwritable"><code>Writable</code></a>. The optional <code>chunk</code> and <code>encoding</code> arguments allow one 1275final additional chunk of data to be written immediately before closing the 1276stream.</p> 1277<p>Calling the <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> method after calling 1278<a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> will raise an error.</p> 1279<pre><code class="language-js"><span class="hljs-comment">// Write 'hello, ' and then end with 'world!'.</span> 1280<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 1281<span class="hljs-keyword">const</span> file = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'example.txt'</span>); 1282file.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello, '</span>); 1283file.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world!'</span>); 1284<span class="hljs-comment">// Writing more now is not allowed!</span></code> <button class="copy-button">copy</button></pre> 1285<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> 1286<div class="api_metadata"> 1287<details class="changelog"><summary>History</summary> 1288<table> 1289<tbody><tr><th>Version</th><th>Changes</th></tr> 1290<tr><td>v6.1.0</td> 1291<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr> 1292<tr><td>v0.11.15</td> 1293<td><p><span>Added in: v0.11.15</span></p></td></tr> 1294</tbody></table> 1295</details> 1296</div> 1297<ul> 1298<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> 1299<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1300</ul> 1301<p>The <code>writable.setDefaultEncoding()</code> method sets the default <code>encoding</code> for a 1302<a href="#class-streamwritable"><code>Writable</code></a> stream.</p> 1303<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> 1304<div class="api_metadata"> 1305<span>Added in: v0.11.2</span> 1306</div> 1307<p>The <code>writable.uncork()</code> method flushes all data buffered since 1308<a href="#writablecork"><code>stream.cork()</code></a> was called.</p> 1309<p>When using <a href="#writablecork"><code>writable.cork()</code></a> and <code>writable.uncork()</code> to manage the buffering 1310of writes to a stream, defer calls to <code>writable.uncork()</code> using 1311<code>process.nextTick()</code>. Doing so allows batching of all 1312<code>writable.write()</code> calls that occur within a given Node.js event loop phase.</p> 1313<pre><code class="language-js">stream.<span class="hljs-title function_">cork</span>(); 1314stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some '</span>); 1315stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'data '</span>); 1316process.<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> 1317<p>If the <a href="#writablecork"><code>writable.cork()</code></a> method is called multiple times on a stream, the 1318same number of calls to <code>writable.uncork()</code> must be called to flush the buffered 1319data.</p> 1320<pre><code class="language-js">stream.<span class="hljs-title function_">cork</span>(); 1321stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some '</span>); 1322stream.<span class="hljs-title function_">cork</span>(); 1323stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'data '</span>); 1324process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> { 1325 stream.<span class="hljs-title function_">uncork</span>(); 1326 <span class="hljs-comment">// The data will not be flushed until uncork() is called a second time.</span> 1327 stream.<span class="hljs-title function_">uncork</span>(); 1328});</code> <button class="copy-button">copy</button></pre> 1329<p>See also: <a href="#writablecork"><code>writable.cork()</code></a>.</p> 1330<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> 1331<div class="api_metadata"> 1332<span>Added in: v11.4.0</span> 1333</div> 1334<ul> 1335<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1336</ul> 1337<p>Is <code>true</code> if it is safe to call <a href="#writablewritechunk-encoding-callback"><code>writable.write()</code></a>, which means 1338the stream has not been destroyed, errored, or ended.</p> 1339<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> 1340<div class="api_metadata"> 1341<span>Added in: v18.0.0</span> 1342</div> 1343<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 1344<ul> 1345<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1346</ul> 1347<p>Returns whether the stream was destroyed or errored before emitting <code>'finish'</code>.</p> 1348<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> 1349<div class="api_metadata"> 1350<span>Added in: v12.9.0</span> 1351</div> 1352<ul> 1353<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1354</ul> 1355<p>Is <code>true</code> after <a href="#writableendchunk-encoding-callback"><code>writable.end()</code></a> has been called. This property 1356does not indicate whether the data has been flushed, for this use 1357<a href="#writablewritablefinished"><code>writable.writableFinished</code></a> instead.</p> 1358<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> 1359<div class="api_metadata"> 1360<span>Added in: v13.2.0, v12.16.0</span> 1361</div> 1362<ul> 1363<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 1364</ul> 1365<p>Number of times <a href="#writableuncork"><code>writable.uncork()</code></a> needs to be 1366called in order to fully uncork the stream.</p> 1367<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> 1368<div class="api_metadata"> 1369<span>Added in: v18.0.0</span> 1370</div> 1371<ul> 1372<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1373</ul> 1374<p>Returns error if the stream has been destroyed with an error.</p> 1375<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> 1376<div class="api_metadata"> 1377<span>Added in: v12.6.0</span> 1378</div> 1379<ul> 1380<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1381</ul> 1382<p>Is set to <code>true</code> immediately before the <a href="#event-finish"><code>'finish'</code></a> event is emitted.</p> 1383<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> 1384<div class="api_metadata"> 1385<span>Added in: v9.3.0</span> 1386</div> 1387<ul> 1388<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1389</ul> 1390<p>Return the value of <code>highWaterMark</code> passed when creating this <code>Writable</code>.</p> 1391<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> 1392<div class="api_metadata"> 1393<span>Added in: v9.4.0</span> 1394</div> 1395<ul> 1396<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1397</ul> 1398<p>This property contains the number of bytes (or objects) in the queue 1399ready to be written. The value provides introspection data regarding 1400the status of the <code>highWaterMark</code>.</p> 1401<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> 1402<div class="api_metadata"> 1403<span>Added in: v15.2.0, v14.17.0</span> 1404</div> 1405<ul> 1406<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1407</ul> 1408<p>Is <code>true</code> if the stream's buffer has been full and stream will emit <code>'drain'</code>.</p> 1409<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> 1410<div class="api_metadata"> 1411<span>Added in: v12.3.0</span> 1412</div> 1413<ul> 1414<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1415</ul> 1416<p>Getter for the property <code>objectMode</code> of a given <code>Writable</code> stream.</p> 1417<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> 1418<div class="api_metadata"> 1419<details class="changelog"><summary>History</summary> 1420<table> 1421<tbody><tr><th>Version</th><th>Changes</th></tr> 1422<tr><td>v8.0.0</td> 1423<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 1424<tr><td>v6.0.0</td> 1425<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> 1426<tr><td>v0.9.4</td> 1427<td><p><span>Added in: v0.9.4</span></p></td></tr> 1428</tbody></table> 1429</details> 1430</div> 1431<ul> 1432<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 1433not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or 1434<code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value 1435other than <code>null</code>.</li> 1436<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> 1437<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> 1438<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 1439wait for the <code>'drain'</code> event to be emitted before continuing to write 1440additional data; otherwise <code>true</code>.</li> 1441</ul> 1442<p>The <code>writable.write()</code> method writes some data to the stream, and calls the 1443supplied <code>callback</code> once the data has been fully handled. If an error 1444occurs, the <code>callback</code> will be called with the error as its 1445first argument. The <code>callback</code> is called asynchronously and before <code>'error'</code> is 1446emitted.</p> 1447<p>The return value is <code>true</code> if the internal buffer is less than the 1448<code>highWaterMark</code> configured when the stream was created after admitting <code>chunk</code>. 1449If <code>false</code> is returned, further attempts to write data to the stream should 1450stop until the <a href="#event-drain"><code>'drain'</code></a> event is emitted.</p> 1451<p>While a stream is not draining, calls to <code>write()</code> will buffer <code>chunk</code>, and 1452return false. Once all currently buffered chunks are drained (accepted for 1453delivery by the operating system), the <code>'drain'</code> event will be emitted. 1454Once <code>write()</code> returns false, do not write more chunks 1455until the <code>'drain'</code> event is emitted. While calling <code>write()</code> on a stream that 1456is not draining is allowed, Node.js will buffer all written chunks until 1457maximum memory usage occurs, at which point it will abort unconditionally. 1458Even before it aborts, high memory usage will cause poor garbage collector 1459performance and high RSS (which is not typically released back to the system, 1460even after the memory is no longer required). Since TCP sockets may never 1461drain if the remote peer does not read the data, writing a socket that is 1462not draining may lead to a remotely exploitable vulnerability.</p> 1463<p>Writing data while the stream is not draining is particularly 1464problematic for a <a href="#class-streamtransform"><code>Transform</code></a>, because the <code>Transform</code> streams are paused 1465by default until they are piped or a <code>'data'</code> or <code>'readable'</code> event handler 1466is added.</p> 1467<p>If the data to be written can be generated or fetched on demand, it is 1468recommended to encapsulate the logic into a <a href="#class-streamreadable"><code>Readable</code></a> and use 1469<a href="#readablepipedestination-options"><code>stream.pipe()</code></a>. However, if calling <code>write()</code> is preferred, it is 1470possible to respect backpressure and avoid memory issues using the 1471<a href="#event-drain"><code>'drain'</code></a> event:</p> 1472<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>) { 1473 <span class="hljs-keyword">if</span> (!stream.<span class="hljs-title function_">write</span>(data)) { 1474 stream.<span class="hljs-title function_">once</span>(<span class="hljs-string">'drain'</span>, cb); 1475 } <span class="hljs-keyword">else</span> { 1476 process.<span class="hljs-title function_">nextTick</span>(cb); 1477 } 1478} 1479 1480<span class="hljs-comment">// Wait for cb to be called before doing any other write.</span> 1481<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-function">() =></span> { 1482 <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>); 1483});</code> <button class="copy-button">copy</button></pre> 1484<p>A <code>Writable</code> stream in object mode will always ignore the <code>encoding</code> argument.</p> 1485<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> 1486<p>Readable streams are an abstraction for a <em>source</em> from which data is 1487consumed.</p> 1488<p>Examples of <code>Readable</code> streams include:</p> 1489<ul> 1490<li><a href="http.html#class-httpincomingmessage">HTTP responses, on the client</a></li> 1491<li><a href="http.html#class-httpincomingmessage">HTTP requests, on the server</a></li> 1492<li><a href="fs.html#class-fsreadstream">fs read streams</a></li> 1493<li><a href="zlib.html">zlib streams</a></li> 1494<li><a href="crypto.html">crypto streams</a></li> 1495<li><a href="net.html#class-netsocket">TCP sockets</a></li> 1496<li><a href="child_process.html#subprocessstdout">child process stdout and stderr</a></li> 1497<li><a href="process.html#processstdin"><code>process.stdin</code></a></li> 1498</ul> 1499<p>All <a href="#class-streamreadable"><code>Readable</code></a> streams implement the interface defined by the 1500<code>stream.Readable</code> class.</p> 1501<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> 1502<p><code>Readable</code> streams effectively operate in one of two modes: flowing and 1503paused. These modes are separate from <a href="#object-mode">object mode</a>. 1504A <a href="#class-streamreadable"><code>Readable</code></a> stream can be in object mode or not, regardless of whether 1505it is in flowing mode or paused mode.</p> 1506<ul> 1507<li> 1508<p>In flowing mode, data is read from the underlying system automatically 1509and provided to an application as quickly as possible using events via the 1510<a href="events.html#class-eventemitter"><code>EventEmitter</code></a> interface.</p> 1511</li> 1512<li> 1513<p>In paused mode, the <a href="#readablereadsize"><code>stream.read()</code></a> method must be called 1514explicitly to read chunks of data from the stream.</p> 1515</li> 1516</ul> 1517<p>All <a href="#class-streamreadable"><code>Readable</code></a> streams begin in paused mode but can be switched to flowing 1518mode in one of the following ways:</p> 1519<ul> 1520<li>Adding a <a href="#event-data"><code>'data'</code></a> event handler.</li> 1521<li>Calling the <a href="#readableresume"><code>stream.resume()</code></a> method.</li> 1522<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> 1523</ul> 1524<p>The <code>Readable</code> can switch back to paused mode using one of the following:</p> 1525<ul> 1526<li>If there are no pipe destinations, by calling the 1527<a href="#readablepause"><code>stream.pause()</code></a> method.</li> 1528<li>If there are pipe destinations, by removing all pipe destinations. 1529Multiple pipe destinations may be removed by calling the 1530<a href="#readableunpipedestination"><code>stream.unpipe()</code></a> method.</li> 1531</ul> 1532<p>The important concept to remember is that a <code>Readable</code> will not generate data 1533until a mechanism for either consuming or ignoring that data is provided. If 1534the consuming mechanism is disabled or taken away, the <code>Readable</code> will <em>attempt</em> 1535to stop generating the data.</p> 1536<p>For backward compatibility reasons, removing <a href="#event-data"><code>'data'</code></a> event handlers will 1537<strong>not</strong> automatically pause the stream. Also, if there are piped destinations, 1538then calling <a href="#readablepause"><code>stream.pause()</code></a> will not guarantee that the 1539stream will <em>remain</em> paused once those destinations drain and ask for more data.</p> 1540<p>If a <a href="#class-streamreadable"><code>Readable</code></a> is switched into flowing mode and there are no consumers 1541available to handle the data, that data will be lost. This can occur, for 1542instance, when the <code>readable.resume()</code> method is called without a listener 1543attached to the <code>'data'</code> event, or when a <code>'data'</code> event handler is removed 1544from the stream.</p> 1545<p>Adding a <a href="#event-readable"><code>'readable'</code></a> event handler automatically makes the stream 1546stop flowing, and the data has to be consumed via 1547<a href="#readablereadsize"><code>readable.read()</code></a>. If the <a href="#event-readable"><code>'readable'</code></a> event handler is 1548removed, then the stream will start flowing again if there is a 1549<a href="#event-data"><code>'data'</code></a> event handler.</p> 1550<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> 1551<p>The "two modes" of operation for a <code>Readable</code> stream are a simplified 1552abstraction for the more complicated internal state management that is happening 1553within the <code>Readable</code> stream implementation.</p> 1554<p>Specifically, at any given point in time, every <code>Readable</code> is in one of three 1555possible states:</p> 1556<ul> 1557<li><code>readable.readableFlowing === null</code></li> 1558<li><code>readable.readableFlowing === false</code></li> 1559<li><code>readable.readableFlowing === true</code></li> 1560</ul> 1561<p>When <code>readable.readableFlowing</code> is <code>null</code>, no mechanism for consuming the 1562stream's data is provided. Therefore, the stream will not generate data. 1563While in this state, attaching a listener for the <code>'data'</code> event, calling the 1564<code>readable.pipe()</code> method, or calling the <code>readable.resume()</code> method will switch 1565<code>readable.readableFlowing</code> to <code>true</code>, causing the <code>Readable</code> to begin actively 1566emitting events as data is generated.</p> 1567<p>Calling <code>readable.pause()</code>, <code>readable.unpipe()</code>, or receiving backpressure 1568will cause the <code>readable.readableFlowing</code> to be set as <code>false</code>, 1569temporarily halting the flowing of events but <em>not</em> halting the generation of 1570data. While in this state, attaching a listener for the <code>'data'</code> event 1571will not switch <code>readable.readableFlowing</code> to <code>true</code>.</p> 1572<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>); 1573<span class="hljs-keyword">const</span> pass = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PassThrough</span>(); 1574<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 1575 1576pass.<span class="hljs-title function_">pipe</span>(writable); 1577pass.<span class="hljs-title function_">unpipe</span>(writable); 1578<span class="hljs-comment">// readableFlowing is now false.</span> 1579 1580pass.<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>()); }); 1581<span class="hljs-comment">// readableFlowing is still false.</span> 1582pass.<span class="hljs-title function_">write</span>(<span class="hljs-string">'ok'</span>); <span class="hljs-comment">// Will not emit 'data'.</span> 1583pass.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Must be called to make stream emit 'data'.</span> 1584<span class="hljs-comment">// readableFlowing is now true.</span></code> <button class="copy-button">copy</button></pre> 1585<p>While <code>readable.readableFlowing</code> is <code>false</code>, data may be accumulating 1586within the stream's internal buffer.</p> 1587<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> 1588<p>The <code>Readable</code> stream API evolved across multiple Node.js versions and provides 1589multiple methods of consuming stream data. In general, developers should choose 1590<em>one</em> of the methods of consuming data and <em>should never</em> use multiple methods 1591to consume data from a single stream. Specifically, using a combination 1592of <code>on('data')</code>, <code>on('readable')</code>, <code>pipe()</code>, or async iterators could 1593lead to unintuitive behavior.</p> 1594<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> 1595<div class="api_metadata"> 1596<span>Added in: v0.9.4</span> 1597</div> 1598 1599<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> 1600<div class="api_metadata"> 1601<details class="changelog"><summary>History</summary> 1602<table> 1603<tbody><tr><th>Version</th><th>Changes</th></tr> 1604<tr><td>v10.0.0</td> 1605<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> 1606<tr><td>v0.9.4</td> 1607<td><p><span>Added in: v0.9.4</span></p></td></tr> 1608</tbody></table> 1609</details> 1610</div> 1611<p>The <code>'close'</code> event is emitted when the stream and any of its underlying 1612resources (a file descriptor, for example) have been closed. The event indicates 1613that no more events will be emitted, and no further computation will occur.</p> 1614<p>A <a href="#class-streamreadable"><code>Readable</code></a> stream will always emit the <code>'close'</code> event if it is 1615created with the <code>emitClose</code> option.</p> 1616<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> 1617<div class="api_metadata"> 1618<span>Added in: v0.9.4</span> 1619</div> 1620<ul> 1621<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 1622operating in object mode, the chunk will be either a string or <code>Buffer</code>. 1623For streams that are in object mode, the chunk can be any JavaScript value 1624other than <code>null</code>.</li> 1625</ul> 1626<p>The <code>'data'</code> event is emitted whenever the stream is relinquishing ownership of 1627a chunk of data to a consumer. This may occur whenever the stream is switched 1628in flowing mode by calling <code>readable.pipe()</code>, <code>readable.resume()</code>, or by 1629attaching a listener callback to the <code>'data'</code> event. The <code>'data'</code> event will 1630also be emitted whenever the <code>readable.read()</code> method is called and a chunk of 1631data is available to be returned.</p> 1632<p>Attaching a <code>'data'</code> event listener to a stream that has not been explicitly 1633paused will switch the stream into flowing mode. Data will then be passed as 1634soon as it is available.</p> 1635<p>The listener callback will be passed the chunk of data as a string if a default 1636encoding has been specified for the stream using the 1637<code>readable.setEncoding()</code> method; otherwise the data will be passed as a 1638<code>Buffer</code>.</p> 1639<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1640readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1641 <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>); 1642});</code> <button class="copy-button">copy</button></pre> 1643<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> 1644<div class="api_metadata"> 1645<span>Added in: v0.9.4</span> 1646</div> 1647<p>The <code>'end'</code> event is emitted when there is no more data to be consumed from 1648the stream.</p> 1649<p>The <code>'end'</code> event <strong>will not be emitted</strong> unless the data is completely 1650consumed. This can be accomplished by switching the stream into flowing mode, 1651or by calling <a href="#readablereadsize"><code>stream.read()</code></a> repeatedly until all data has been 1652consumed.</p> 1653<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1654readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1655 <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>); 1656}); 1657readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1658 <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>); 1659});</code> <button class="copy-button">copy</button></pre> 1660<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> 1661<div class="api_metadata"> 1662<span>Added in: v0.9.4</span> 1663</div> 1664<ul> 1665<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1666</ul> 1667<p>The <code>'error'</code> event may be emitted by a <code>Readable</code> implementation at any time. 1668Typically, this may occur if the underlying stream is unable to generate data 1669due to an underlying internal failure, or when a stream implementation attempts 1670to push an invalid chunk of data.</p> 1671<p>The listener callback will be passed a single <code>Error</code> object.</p> 1672<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> 1673<div class="api_metadata"> 1674<span>Added in: v0.9.4</span> 1675</div> 1676<p>The <code>'pause'</code> event is emitted when <a href="#readablepause"><code>stream.pause()</code></a> is called 1677and <code>readableFlowing</code> is not <code>false</code>.</p> 1678<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> 1679<div class="api_metadata"> 1680<details class="changelog"><summary>History</summary> 1681<table> 1682<tbody><tr><th>Version</th><th>Changes</th></tr> 1683<tr><td>v10.0.0</td> 1684<td><p>The <code>'readable'</code> is always emitted in the next tick after <code>.push()</code> is called.</p></td></tr> 1685<tr><td>v10.0.0</td> 1686<td><p>Using <code>'readable'</code> requires calling <code>.read()</code>.</p></td></tr> 1687<tr><td>v0.9.4</td> 1688<td><p><span>Added in: v0.9.4</span></p></td></tr> 1689</tbody></table> 1690</details> 1691</div> 1692<p>The <code>'readable'</code> event is emitted when there is data available to be read from 1693the stream or when the end of the stream has been reached. Effectively, the 1694<code>'readable'</code> event indicates that the stream has new information. If data is 1695available, <a href="#readablereadsize"><code>stream.read()</code></a> will return that data.</p> 1696<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1697readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { 1698 <span class="hljs-comment">// There is some data to read now.</span> 1699 <span class="hljs-keyword">let</span> data; 1700 1701 <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>) { 1702 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data); 1703 } 1704});</code> <button class="copy-button">copy</button></pre> 1705<p>If the end of the stream has been reached, calling 1706<a href="#readablereadsize"><code>stream.read()</code></a> will return <code>null</code> and trigger the <code>'end'</code> 1707event. This is also true if there never was any data to be read. For instance, 1708in the following example, <code>foo.txt</code> is an empty file:</p> 1709<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>); 1710<span class="hljs-keyword">const</span> rr = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'foo.txt'</span>); 1711rr.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 1712 <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>); 1713}); 1714rr.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1715 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'end'</span>); 1716});</code> <button class="copy-button">copy</button></pre> 1717<p>The output of running this script is:</p> 1718<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node test.js</span> 1719readable: null 1720end</code> <button class="copy-button">copy</button></pre> 1721<p>In some cases, attaching a listener for the <code>'readable'</code> event will cause some 1722amount of data to be read into an internal buffer.</p> 1723<p>In general, the <code>readable.pipe()</code> and <code>'data'</code> event mechanisms are easier to 1724understand than the <code>'readable'</code> event. However, handling <code>'readable'</code> might 1725result in increased throughput.</p> 1726<p>If both <code>'readable'</code> and <a href="#event-data"><code>'data'</code></a> are used at the same time, <code>'readable'</code> 1727takes precedence in controlling the flow, i.e. <code>'data'</code> will be emitted 1728only when <a href="#readablereadsize"><code>stream.read()</code></a> is called. The 1729<code>readableFlowing</code> property would become <code>false</code>. 1730If there are <code>'data'</code> listeners when <code>'readable'</code> is removed, the stream 1731will start flowing, i.e. <code>'data'</code> events will be emitted without calling 1732<code>.resume()</code>.</p> 1733<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> 1734<div class="api_metadata"> 1735<span>Added in: v0.9.4</span> 1736</div> 1737<p>The <code>'resume'</code> event is emitted when <a href="#readableresume"><code>stream.resume()</code></a> is 1738called and <code>readableFlowing</code> is not <code>true</code>.</p> 1739<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> 1740<div class="api_metadata"> 1741<details class="changelog"><summary>History</summary> 1742<table> 1743<tbody><tr><th>Version</th><th>Changes</th></tr> 1744<tr><td>v14.0.0</td> 1745<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr> 1746<tr><td>v8.0.0</td> 1747<td><p><span>Added in: v8.0.0</span></p></td></tr> 1748</tbody></table> 1749</details> 1750</div> 1751<ul> 1752<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> 1753<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1754</ul> 1755<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code> 1756event (unless <code>emitClose</code> is set to <code>false</code>). After this call, the readable 1757stream will release any internal resources and subsequent calls to <code>push()</code> 1758will be ignored.</p> 1759<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no 1760further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p> 1761<p>Implementors should not override this method, but instead implement 1762<a href="#readable_destroyerr-callback"><code>readable._destroy()</code></a>.</p> 1763<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> 1764<div class="api_metadata"> 1765<span>Added in: v18.0.0</span> 1766</div> 1767<ul> 1768<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1769</ul> 1770<p>Is <code>true</code> after <code>'close'</code> has been emitted.</p> 1771<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> 1772<div class="api_metadata"> 1773<span>Added in: v8.0.0</span> 1774</div> 1775<ul> 1776<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1777</ul> 1778<p>Is <code>true</code> after <a href="#readabledestroyerror"><code>readable.destroy()</code></a> has been called.</p> 1779<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> 1780<div class="api_metadata"> 1781<span>Added in: v0.11.14</span> 1782</div> 1783<ul> 1784<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1785</ul> 1786<p>The <code>readable.isPaused()</code> method returns the current operating state of the 1787<code>Readable</code>. This is used primarily by the mechanism that underlies the 1788<code>readable.pipe()</code> method. In most typical cases, there will be no reason to 1789use this method directly.</p> 1790<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>(); 1791 1792readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === false</span> 1793readable.<span class="hljs-title function_">pause</span>(); 1794readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === true</span> 1795readable.<span class="hljs-title function_">resume</span>(); 1796readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === false</span></code> <button class="copy-button">copy</button></pre> 1797<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> 1798<div class="api_metadata"> 1799<span>Added in: v0.9.4</span> 1800</div> 1801<ul> 1802<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1803</ul> 1804<p>The <code>readable.pause()</code> method will cause a stream in flowing mode to stop 1805emitting <a href="#event-data"><code>'data'</code></a> events, switching out of flowing mode. Any data that 1806becomes available will remain in the internal buffer.</p> 1807<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1808readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1809 <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>); 1810 readable.<span class="hljs-title function_">pause</span>(); 1811 <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>); 1812 <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { 1813 <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>); 1814 readable.<span class="hljs-title function_">resume</span>(); 1815 }, <span class="hljs-number">1000</span>); 1816});</code> <button class="copy-button">copy</button></pre> 1817<p>The <code>readable.pause()</code> method has no effect if there is a <code>'readable'</code> 1818event listener.</p> 1819<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> 1820<div class="api_metadata"> 1821<span>Added in: v0.9.4</span> 1822</div> 1823<ul> 1824<li><code>destination</code> <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a> The destination for writing data</li> 1825<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 1826<ul> 1827<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> 1828</ul> 1829</li> 1830<li>Returns: <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a> The <em>destination</em>, allowing for a chain of pipes if 1831it is a <a href="#class-streamduplex"><code>Duplex</code></a> or a <a href="#class-streamtransform"><code>Transform</code></a> stream</li> 1832</ul> 1833<p>The <code>readable.pipe()</code> method attaches a <a href="#class-streamwritable"><code>Writable</code></a> stream to the <code>readable</code>, 1834causing it to switch automatically into flowing mode and push all of its data 1835to the attached <a href="#class-streamwritable"><code>Writable</code></a>. The flow of data will be automatically managed 1836so that the destination <code>Writable</code> stream is not overwhelmed by a faster 1837<code>Readable</code> stream.</p> 1838<p>The following example pipes all of the data from the <code>readable</code> into a file 1839named <code>file.txt</code>:</p> 1840<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>); 1841<span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1842<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt'</span>); 1843<span class="hljs-comment">// All the data from readable goes into 'file.txt'.</span> 1844readable.<span class="hljs-title function_">pipe</span>(writable);</code> <button class="copy-button">copy</button></pre> 1845<p>It is possible to attach multiple <code>Writable</code> streams to a single <code>Readable</code> 1846stream.</p> 1847<p>The <code>readable.pipe()</code> method returns a reference to the <em>destination</em> stream 1848making it possible to set up chains of piped streams:</p> 1849<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>); 1850<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>); 1851<span class="hljs-keyword">const</span> r = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'file.txt'</span>); 1852<span class="hljs-keyword">const</span> z = zlib.<span class="hljs-title function_">createGzip</span>(); 1853<span class="hljs-keyword">const</span> w = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt.gz'</span>); 1854r.<span class="hljs-title function_">pipe</span>(z).<span class="hljs-title function_">pipe</span>(w);</code> <button class="copy-button">copy</button></pre> 1855<p>By default, <a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> is called on the destination <code>Writable</code> 1856stream when the source <code>Readable</code> stream emits <a href="#event-end"><code>'end'</code></a>, so that the 1857destination is no longer writable. To disable this default behavior, the <code>end</code> 1858option can be passed as <code>false</code>, causing the destination stream to remain open:</p> 1859<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> }); 1860reader.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1861 writer.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Goodbye\n'</span>); 1862});</code> <button class="copy-button">copy</button></pre> 1863<p>One important caveat is that if the <code>Readable</code> stream emits an error during 1864processing, the <code>Writable</code> destination <em>is not closed</em> automatically. If an 1865error occurs, it will be necessary to <em>manually</em> close each stream in order 1866to prevent memory leaks.</p> 1867<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 1868closed until the Node.js process exits, regardless of the specified options.</p> 1869<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> 1870<div class="api_metadata"> 1871<span>Added in: v0.9.4</span> 1872</div> 1873<ul> 1874<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> 1875<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> 1876</ul> 1877<p>The <code>readable.read()</code> method reads data out of the internal buffer and 1878returns it. If no data is available to be read, <code>null</code> is returned. By default, 1879the data is returned as a <code>Buffer</code> object unless an encoding has been 1880specified using the <code>readable.setEncoding()</code> method or the stream is operating 1881in object mode.</p> 1882<p>The optional <code>size</code> argument specifies a specific number of bytes to read. If 1883<code>size</code> bytes are not available to be read, <code>null</code> will be returned <em>unless</em> 1884the stream has ended, in which case all of the data remaining in the internal 1885buffer will be returned.</p> 1886<p>If the <code>size</code> argument is not specified, all of the data contained in the 1887internal buffer will be returned.</p> 1888<p>The <code>size</code> argument must be less than or equal to 1 GiB.</p> 1889<p>The <code>readable.read()</code> method should only be called on <code>Readable</code> streams 1890operating in paused mode. In flowing mode, <code>readable.read()</code> is called 1891automatically until the internal buffer is fully drained.</p> 1892<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1893 1894<span class="hljs-comment">// 'readable' may be triggered multiple times as data is buffered in</span> 1895readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 1896 <span class="hljs-keyword">let</span> chunk; 1897 <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>); 1898 <span class="hljs-comment">// Use a loop to make sure we read all currently available data</span> 1899 <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = readable.<span class="hljs-title function_">read</span>())) { 1900 <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>); 1901 } 1902}); 1903 1904<span class="hljs-comment">// 'end' will be triggered once when there is no more data available</span> 1905readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1906 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Reached end of stream.'</span>); 1907});</code> <button class="copy-button">copy</button></pre> 1908<p>Each call to <code>readable.read()</code> returns a chunk of data, or <code>null</code>. The chunks 1909are not concatenated. A <code>while</code> loop is necessary to consume all data 1910currently in the buffer. When reading a large file <code>.read()</code> may return <code>null</code>, 1911having consumed all buffered content so far, but there is still more data to 1912come not yet buffered. In this case a new <code>'readable'</code> event will be emitted 1913when there is more data in the buffer. Finally the <code>'end'</code> event will be 1914emitted when there is no more data to come.</p> 1915<p>Therefore to read a file's whole contents from a <code>readable</code>, it is necessary 1916to collect chunks across multiple <code>'readable'</code> events:</p> 1917<pre><code class="language-js"><span class="hljs-keyword">const</span> chunks = []; 1918 1919readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 1920 <span class="hljs-keyword">let</span> chunk; 1921 <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = readable.<span class="hljs-title function_">read</span>())) { 1922 chunks.<span class="hljs-title function_">push</span>(chunk); 1923 } 1924}); 1925 1926readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1927 <span class="hljs-keyword">const</span> content = chunks.<span class="hljs-title function_">join</span>(<span class="hljs-string">''</span>); 1928});</code> <button class="copy-button">copy</button></pre> 1929<p>A <code>Readable</code> stream in object mode will always return a single item from 1930a call to <a href="#readablereadsize"><code>readable.read(size)</code></a>, regardless of the value of the 1931<code>size</code> argument.</p> 1932<p>If the <code>readable.read()</code> method returns a chunk of data, a <code>'data'</code> event will 1933also be emitted.</p> 1934<p>Calling <a href="#readablereadsize"><code>stream.read([size])</code></a> after the <a href="#event-end"><code>'end'</code></a> event has 1935been emitted will return <code>null</code>. No runtime error will be raised.</p> 1936<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> 1937<div class="api_metadata"> 1938<span>Added in: v11.4.0</span> 1939</div> 1940<ul> 1941<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1942</ul> 1943<p>Is <code>true</code> if it is safe to call <a href="#readablereadsize"><code>readable.read()</code></a>, which means 1944the stream has not been destroyed or emitted <code>'error'</code> or <code>'end'</code>.</p> 1945<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> 1946<div class="api_metadata"> 1947<span>Added in: v16.8.0</span> 1948</div> 1949<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 1950<ul> 1951<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1952</ul> 1953<p>Returns whether the stream was destroyed or errored before emitting <code>'end'</code>.</p> 1954<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> 1955<div class="api_metadata"> 1956<span>Added in: v16.7.0, v14.18.0</span> 1957</div> 1958<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 1959<ul> 1960<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1961</ul> 1962<p>Returns whether <code>'data'</code> has been emitted.</p> 1963<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> 1964<div class="api_metadata"> 1965<span>Added in: v12.7.0</span> 1966</div> 1967<ul> 1968<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> 1969</ul> 1970<p>Getter for the property <code>encoding</code> of a given <code>Readable</code> stream. The <code>encoding</code> 1971property can be set using the <a href="#readablesetencodingencoding"><code>readable.setEncoding()</code></a> method.</p> 1972<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> 1973<div class="api_metadata"> 1974<span>Added in: v12.9.0</span> 1975</div> 1976<ul> 1977<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1978</ul> 1979<p>Becomes <code>true</code> when <a href="#event-end"><code>'end'</code></a> event is emitted.</p> 1980<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> 1981<div class="api_metadata"> 1982<span>Added in: v18.0.0</span> 1983</div> 1984<ul> 1985<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1986</ul> 1987<p>Returns error if the stream has been destroyed with an error.</p> 1988<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> 1989<div class="api_metadata"> 1990<span>Added in: v9.4.0</span> 1991</div> 1992<ul> 1993<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1994</ul> 1995<p>This property reflects the current state of a <code>Readable</code> stream as described 1996in the <a href="#three-states">Three states</a> section.</p> 1997<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> 1998<div class="api_metadata"> 1999<span>Added in: v9.3.0</span> 2000</div> 2001<ul> 2002<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 2003</ul> 2004<p>Returns the value of <code>highWaterMark</code> passed when creating this <code>Readable</code>.</p> 2005<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> 2006<div class="api_metadata"> 2007<span>Added in: v9.4.0</span> 2008</div> 2009<ul> 2010<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 2011</ul> 2012<p>This property contains the number of bytes (or objects) in the queue 2013ready to be read. The value provides introspection data regarding 2014the status of the <code>highWaterMark</code>.</p> 2015<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> 2016<div class="api_metadata"> 2017<span>Added in: v12.3.0</span> 2018</div> 2019<ul> 2020<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 2021</ul> 2022<p>Getter for the property <code>objectMode</code> of a given <code>Readable</code> stream.</p> 2023<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> 2024<div class="api_metadata"> 2025<details class="changelog"><summary>History</summary> 2026<table> 2027<tbody><tr><th>Version</th><th>Changes</th></tr> 2028<tr><td>v10.0.0</td> 2029<td><p>The <code>resume()</code> has no effect if there is a <code>'readable'</code> event listening.</p></td></tr> 2030<tr><td>v0.9.4</td> 2031<td><p><span>Added in: v0.9.4</span></p></td></tr> 2032</tbody></table> 2033</details> 2034</div> 2035<ul> 2036<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 2037</ul> 2038<p>The <code>readable.resume()</code> method causes an explicitly paused <code>Readable</code> stream to 2039resume emitting <a href="#event-data"><code>'data'</code></a> events, switching the stream into flowing mode.</p> 2040<p>The <code>readable.resume()</code> method can be used to fully consume the data from a 2041stream without actually processing any of that data:</p> 2042<pre><code class="language-js"><span class="hljs-title function_">getReadableStreamSomehow</span>() 2043 .<span class="hljs-title function_">resume</span>() 2044 .<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 2045 <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>); 2046 });</code> <button class="copy-button">copy</button></pre> 2047<p>The <code>readable.resume()</code> method has no effect if there is a <code>'readable'</code> 2048event listener.</p> 2049<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> 2050<div class="api_metadata"> 2051<span>Added in: v0.9.4</span> 2052</div> 2053<ul> 2054<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> 2055<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 2056</ul> 2057<p>The <code>readable.setEncoding()</code> method sets the character encoding for 2058data read from the <code>Readable</code> stream.</p> 2059<p>By default, no encoding is assigned and stream data will be returned as 2060<code>Buffer</code> objects. Setting an encoding causes the stream data 2061to be returned as strings of the specified encoding rather than as <code>Buffer</code> 2062objects. For instance, calling <code>readable.setEncoding('utf8')</code> will cause the 2063output data to be interpreted as UTF-8 data, and passed as strings. Calling 2064<code>readable.setEncoding('hex')</code> will cause the data to be encoded in hexadecimal 2065string format.</p> 2066<p>The <code>Readable</code> stream will properly handle multi-byte characters delivered 2067through the stream that would otherwise become improperly decoded if simply 2068pulled from the stream as <code>Buffer</code> objects.</p> 2069<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 2070readable.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); 2071readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 2072 assert.<span class="hljs-title function_">equal</span>(<span class="hljs-keyword">typeof</span> chunk, <span class="hljs-string">'string'</span>); 2073 <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>); 2074});</code> <button class="copy-button">copy</button></pre> 2075<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> 2076<div class="api_metadata"> 2077<span>Added in: v0.9.4</span> 2078</div> 2079<ul> 2080<li><code>destination</code> <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a> Optional specific stream to unpipe</li> 2081<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 2082</ul> 2083<p>The <code>readable.unpipe()</code> method detaches a <code>Writable</code> stream previously attached 2084using the <a href="#readablepipedestination-options"><code>stream.pipe()</code></a> method.</p> 2085<p>If the <code>destination</code> is not specified, then <em>all</em> pipes are detached.</p> 2086<p>If the <code>destination</code> is specified, but no pipe is set up for it, then 2087the method does nothing.</p> 2088<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>); 2089<span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 2090<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt'</span>); 2091<span class="hljs-comment">// All the data from readable goes into 'file.txt',</span> 2092<span class="hljs-comment">// but only for the first second.</span> 2093readable.<span class="hljs-title function_">pipe</span>(writable); 2094<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { 2095 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stop writing to file.txt.'</span>); 2096 readable.<span class="hljs-title function_">unpipe</span>(writable); 2097 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Manually close the file stream.'</span>); 2098 writable.<span class="hljs-title function_">end</span>(); 2099}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre> 2100<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> 2101<div class="api_metadata"> 2102<details class="changelog"><summary>History</summary> 2103<table> 2104<tbody><tr><th>Version</th><th>Changes</th></tr> 2105<tr><td>v8.0.0</td> 2106<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 2107<tr><td>v0.9.11</td> 2108<td><p><span>Added in: v0.9.11</span></p></td></tr> 2109</tbody></table> 2110</details> 2111</div> 2112<ul> 2113<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 2114read queue. For streams not operating in object mode, <code>chunk</code> must be a 2115string, <code>Buffer</code>, <code>Uint8Array</code>, or <code>null</code>. For object mode streams, <code>chunk</code> 2116may be any JavaScript value.</li> 2117<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 2118<code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li> 2119</ul> 2120<p>Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF) and behaves the 2121same as <code>readable.push(null)</code>, after which no more data can be written. The EOF 2122signal is put at the end of the buffer and any buffered data will still be 2123flushed.</p> 2124<p>The <code>readable.unshift()</code> method pushes a chunk of data back into the internal 2125buffer. This is useful in certain situations where a stream is being consumed by 2126code that needs to "un-consume" some amount of data that it has optimistically 2127pulled out of the source, so that the data can be passed on to some other party.</p> 2128<p>The <code>stream.unshift(chunk)</code> method cannot be called after the <a href="#event-end"><code>'end'</code></a> event 2129has been emitted or a runtime error will be thrown.</p> 2130<p>Developers using <code>stream.unshift()</code> often should consider switching to 2131use 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> 2132section for more information.</p> 2133<pre><code class="language-js"><span class="hljs-comment">// Pull off a header delimited by \n\n.</span> 2134<span class="hljs-comment">// Use unshift() if we get too much.</span> 2135<span class="hljs-comment">// Call the callback with (error, header, stream).</span> 2136<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>); 2137<span class="hljs-keyword">function</span> <span class="hljs-title function_">parseHeader</span>(<span class="hljs-params">stream, callback</span>) { 2138 stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, callback); 2139 stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, onReadable); 2140 <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>); 2141 <span class="hljs-keyword">let</span> header = <span class="hljs-string">''</span>; 2142 <span class="hljs-keyword">function</span> <span class="hljs-title function_">onReadable</span>(<span class="hljs-params"></span>) { 2143 <span class="hljs-keyword">let</span> chunk; 2144 <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = stream.<span class="hljs-title function_">read</span>())) { 2145 <span class="hljs-keyword">const</span> str = decoder.<span class="hljs-title function_">write</span>(chunk); 2146 <span class="hljs-keyword">if</span> (str.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'\n\n'</span>)) { 2147 <span class="hljs-comment">// Found the header boundary.</span> 2148 <span class="hljs-keyword">const</span> split = str.<span class="hljs-title function_">split</span>(<span class="hljs-regexp">/\n\n/</span>); 2149 header += split.<span class="hljs-title function_">shift</span>(); 2150 <span class="hljs-keyword">const</span> remaining = split.<span class="hljs-title function_">join</span>(<span class="hljs-string">'\n\n'</span>); 2151 <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>); 2152 stream.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'error'</span>, callback); 2153 <span class="hljs-comment">// Remove the 'readable' listener before unshifting.</span> 2154 stream.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'readable'</span>, onReadable); 2155 <span class="hljs-keyword">if</span> (buf.<span class="hljs-property">length</span>) 2156 stream.<span class="hljs-title function_">unshift</span>(buf); 2157 <span class="hljs-comment">// Now the body of the message can be read from the stream.</span> 2158 <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, header, stream); 2159 <span class="hljs-keyword">return</span>; 2160 } 2161 <span class="hljs-comment">// Still reading the header.</span> 2162 header += str; 2163 } 2164 } 2165}</code> <button class="copy-button">copy</button></pre> 2166<p>Unlike <a href="#readablepushchunk-encoding"><code>stream.push(chunk)</code></a>, <code>stream.unshift(chunk)</code> will not 2167end the reading process by resetting the internal reading state of the stream. 2168This can cause unexpected results if <code>readable.unshift()</code> is called during a 2169read (i.e. from within a <a href="#readable_readsize"><code>stream._read()</code></a> implementation on a 2170custom stream). Following the call to <code>readable.unshift()</code> with an immediate 2171<a href="#readablepushchunk-encoding"><code>stream.push('')</code></a> will reset the reading state appropriately, 2172however it is best to simply avoid calling <code>readable.unshift()</code> while in the 2173process of performing a read.</p> 2174<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> 2175<div class="api_metadata"> 2176<span>Added in: v0.9.4</span> 2177</div> 2178<ul> 2179<li><code>stream</code> <a href="stream.html#stream" class="type"><Stream></a> An "old style" readable stream</li> 2180<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 2181</ul> 2182<p>Prior to Node.js 0.10, streams did not implement the entire <code>node:stream</code> 2183module API as it is currently defined. (See <a href="#compatibility-with-older-nodejs-versions">Compatibility</a> for more 2184information.)</p> 2185<p>When using an older Node.js library that emits <a href="#event-data"><code>'data'</code></a> events and has a 2186<a href="#readablepause"><code>stream.pause()</code></a> method that is advisory only, the 2187<code>readable.wrap()</code> method can be used to create a <a href="#class-streamreadable"><code>Readable</code></a> stream that uses 2188the old stream as its data source.</p> 2189<p>It will rarely be necessary to use <code>readable.wrap()</code> but the method has been 2190provided as a convenience for interacting with older Node.js applications and 2191libraries.</p> 2192<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>); 2193<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>); 2194<span class="hljs-keyword">const</span> oreader = <span class="hljs-keyword">new</span> <span class="hljs-title class_">OldReader</span>(); 2195<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); 2196 2197myReader.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 2198 myReader.<span class="hljs-title function_">read</span>(); <span class="hljs-comment">// etc.</span> 2199});</code> <button class="copy-button">copy</button></pre> 2200<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> 2201<div class="api_metadata"> 2202<details class="changelog"><summary>History</summary> 2203<table> 2204<tbody><tr><th>Version</th><th>Changes</th></tr> 2205<tr><td>v11.14.0</td> 2206<td><p>Symbol.asyncIterator support is no longer experimental.</p></td></tr> 2207<tr><td>v10.0.0</td> 2208<td><p><span>Added in: v10.0.0</span></p></td></tr> 2209</tbody></table> 2210</details> 2211</div> 2212<ul> 2213<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> to fully consume the stream.</li> 2214</ul> 2215<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>); 2216 2217<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>) { 2218 readable.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); 2219 <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>; 2220 <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) { 2221 data += chunk; 2222 } 2223 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data); 2224} 2225 2226<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> 2227<p>If the loop terminates with a <code>break</code>, <code>return</code>, or a <code>throw</code>, the stream will 2228be destroyed. In other terms, iterating over a stream will consume the stream 2229fully. The stream will be read in chunks of size equal to the <code>highWaterMark</code> 2230option. In the code example above, data will be in a single chunk if the file 2231has less then 64 KiB of data because no <code>highWaterMark</code> option is provided to 2232<a href="fs.html#fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>.</p> 2233<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> 2234<div class="api_metadata"> 2235<span>Added in: v18.18.0</span> 2236</div> 2237<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2238<p>Calls <a href="#readabledestroyerror"><code>readable.destroy()</code></a> with an <code>AbortError</code> and returns 2239a promise that fulfills when the stream is finished.</p> 2240<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> 2241<div class="api_metadata"> 2242<span>Added in: v18.13.0</span> 2243</div> 2244<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2245<ul> 2246<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> 2247<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2248<ul> 2249<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2250aborted.</li> 2251</ul> 2252</li> 2253<li>Returns: <a href="stream.html#class-streamduplex" class="type"><Duplex></a> a stream composed with the stream <code>stream</code>.</li> 2254</ul> 2255<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>; 2256 2257<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>) { 2258 <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) { 2259 <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>); 2260 2261 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> word <span class="hljs-keyword">of</span> words) { 2262 <span class="hljs-keyword">yield</span> word; 2263 } 2264 } 2265} 2266 2267<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); 2268<span class="hljs-keyword">const</span> words = <span class="hljs-keyword">await</span> wordsStream.<span class="hljs-title function_">toArray</span>(); 2269 2270<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> 2271<p>See <a href="#streamcomposestreams"><code>stream.compose</code></a> for more information.</p> 2272<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> 2273<div class="api_metadata"> 2274<span>Added in: v16.3.0</span> 2275</div> 2276<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2277<ul> 2278<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2279<ul> 2280<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 2281async iterator, or exiting a <code>for await...of</code> iteration using a <code>break</code>, 2282<code>return</code>, or <code>throw</code> will not destroy the stream. <strong>Default:</strong> <code>true</code>.</li> 2283</ul> 2284</li> 2285<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> to consume the stream.</li> 2286</ul> 2287<p>The iterator created by this method gives users the option to cancel the 2288destruction of the stream if the <code>for await...of</code> loop is exited by <code>return</code>, 2289<code>break</code>, or <code>throw</code>, or if the iterator should destroy the stream if the stream 2290emitted an error during iteration.</p> 2291<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>); 2292 2293<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>) { 2294 <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> })) { 2295 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1</span> 2296 <span class="hljs-keyword">break</span>; 2297 } 2298 2299 <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> 2300 2301 <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> })) { 2302 <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> 2303 } 2304 2305 <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> 2306} 2307 2308<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>) { 2309 <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) { 2310 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1</span> 2311 <span class="hljs-keyword">break</span>; 2312 } 2313 2314 <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> 2315} 2316 2317<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">showBoth</span>(<span class="hljs-params"></span>) { 2318 <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>])); 2319 <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>])); 2320} 2321 2322<span class="hljs-title function_">showBoth</span>();</code> <button class="copy-button">copy</button></pre> 2323<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> 2324<div class="api_metadata"> 2325<span>Added in: v17.4.0, v16.14.0</span> 2326</div> 2327<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2328<ul> 2329<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 2330stream. 2331<ul> 2332<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> 2333<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2334<ul> 2335<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2336abort the <code>fn</code> call early.</li> 2337</ul> 2338</li> 2339</ul> 2340</li> 2341<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2342<ul> 2343<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 2344on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2345<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2346aborted.</li> 2347</ul> 2348</li> 2349<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream mapped with the function <code>fn</code>.</li> 2350</ul> 2351<p>This method allows mapping over the stream. The <code>fn</code> function will be called 2352for every chunk in the stream. If the <code>fn</code> function returns a promise - that 2353promise will be <code>await</code>ed before being passed to the result stream.</p> 2354<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>; 2355<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>; 2356 2357<span class="hljs-comment">// With a synchronous mapper.</span> 2358<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>)) { 2359 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 2, 4, 6, 8</span> 2360} 2361<span class="hljs-comment">// With an asynchronous mapper, making at most 2 queries at a time.</span> 2362<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>(); 2363<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2364 <span class="hljs-string">'nodejs.org'</span>, 2365 <span class="hljs-string">'openjsf.org'</span>, 2366 <span class="hljs-string">'www.linuxfoundation.org'</span>, 2367]).<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> }); 2368<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) { 2369 <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> 2370}</code> <button class="copy-button">copy</button></pre> 2371<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> 2372<div class="api_metadata"> 2373<span>Added in: v17.4.0, v16.14.0</span> 2374</div> 2375<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2376<ul> 2377<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. 2378<ul> 2379<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> 2380<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2381<ul> 2382<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2383abort the <code>fn</code> call early.</li> 2384</ul> 2385</li> 2386</ul> 2387</li> 2388<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2389<ul> 2390<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 2391on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2392<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2393aborted.</li> 2394</ul> 2395</li> 2396<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream filtered with the predicate <code>fn</code>.</li> 2397</ul> 2398<p>This method allows filtering the stream. For each chunk in the stream the <code>fn</code> 2399function will be called and if it returns a truthy value, the chunk will be 2400passed to the result stream. If the <code>fn</code> function returns a promise - that 2401promise will be <code>await</code>ed.</p> 2402<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>; 2403<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>; 2404 2405<span class="hljs-comment">// With a synchronous predicate.</span> 2406<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>)) { 2407 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 3, 4</span> 2408} 2409<span class="hljs-comment">// With an asynchronous predicate, making at most 2 queries at a time.</span> 2410<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>(); 2411<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2412 <span class="hljs-string">'nodejs.org'</span>, 2413 <span class="hljs-string">'openjsf.org'</span>, 2414 <span class="hljs-string">'www.linuxfoundation.org'</span>, 2415]).<span class="hljs-title function_">filter</span>(<span class="hljs-keyword">async</span> (domain) => { 2416 <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> }); 2417 <span class="hljs-keyword">return</span> address.<span class="hljs-property">ttl</span> > <span class="hljs-number">60</span>; 2418}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2419<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) { 2420 <span class="hljs-comment">// Logs domains with more than 60 seconds on the resolved dns record.</span> 2421 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); 2422}</code> <button class="copy-button">copy</button></pre> 2423<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> 2424<div class="api_metadata"> 2425<span>Added in: v17.5.0</span> 2426</div> 2427<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2428<ul> 2429<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. 2430<ul> 2431<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> 2432<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2433<ul> 2434<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2435abort the <code>fn</code> call early.</li> 2436</ul> 2437</li> 2438</ul> 2439</li> 2440<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2441<ul> 2442<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 2443on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2444<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2445aborted.</li> 2446</ul> 2447</li> 2448<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> 2449</ul> 2450<p>This method allows iterating a stream. For each chunk in the stream the 2451<code>fn</code> function will be called. If the <code>fn</code> function returns a promise - that 2452promise will be <code>await</code>ed.</p> 2453<p>This method is different from <code>for await...of</code> loops in that it can optionally 2454process chunks concurrently. In addition, a <code>forEach</code> iteration can only be 2455stopped by having passed a <code>signal</code> option and aborting the related 2456<code>AbortController</code> while <code>for await...of</code> can be stopped with <code>break</code> or 2457<code>return</code>. In either case the stream will be destroyed.</p> 2458<p>This method is different from listening to the <a href="#event-data"><code>'data'</code></a> event in that it 2459uses the <a href="#class-streamreadable"><code>readable</code></a> event in the underlying machinary and can limit the 2460number of concurrent <code>fn</code> calls.</p> 2461<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>; 2462<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>; 2463 2464<span class="hljs-comment">// With a synchronous predicate.</span> 2465<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>)) { 2466 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 3, 4</span> 2467} 2468<span class="hljs-comment">// With an asynchronous predicate, making at most 2 queries at a time.</span> 2469<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>(); 2470<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2471 <span class="hljs-string">'nodejs.org'</span>, 2472 <span class="hljs-string">'openjsf.org'</span>, 2473 <span class="hljs-string">'www.linuxfoundation.org'</span>, 2474]).<span class="hljs-title function_">map</span>(<span class="hljs-keyword">async</span> (domain) => { 2475 <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> }); 2476 <span class="hljs-keyword">return</span> address; 2477}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2478<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> { 2479 <span class="hljs-comment">// Logs result, similar to `for await (const result of dnsResults)`</span> 2480 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); 2481}); 2482<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> 2483<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> 2484<div class="api_metadata"> 2485<span>Added in: v17.5.0</span> 2486</div> 2487<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2488<ul> 2489<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2490<ul> 2491<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows cancelling the toArray operation if the 2492signal is aborted.</li> 2493</ul> 2494</li> 2495<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 2496stream.</li> 2497</ul> 2498<p>This method allows easily obtaining the contents of a stream.</p> 2499<p>As this method reads the entire stream into memory, it negates the benefits of 2500streams. It's intended for interoperability and convenience, not as the primary 2501way to consume streams.</p> 2502<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>; 2503<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>; 2504 2505<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> 2506 2507<span class="hljs-comment">// Make dns queries concurrently using .map and collect</span> 2508<span class="hljs-comment">// the results into an array using toArray</span> 2509<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>([ 2510 <span class="hljs-string">'nodejs.org'</span>, 2511 <span class="hljs-string">'openjsf.org'</span>, 2512 <span class="hljs-string">'www.linuxfoundation.org'</span>, 2513]).<span class="hljs-title function_">map</span>(<span class="hljs-keyword">async</span> (domain) => { 2514 <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> }); 2515 <span class="hljs-keyword">return</span> address; 2516}, { <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> 2517<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> 2518<div class="api_metadata"> 2519<span>Added in: v17.5.0</span> 2520</div> 2521<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2522<ul> 2523<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. 2524<ul> 2525<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> 2526<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2527<ul> 2528<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2529abort the <code>fn</code> call early.</li> 2530</ul> 2531</li> 2532</ul> 2533</li> 2534<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2535<ul> 2536<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 2537on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2538<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2539aborted.</li> 2540</ul> 2541</li> 2542<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 2543value for at least one of the chunks.</li> 2544</ul> 2545<p>This method is similar to <code>Array.prototype.some</code> and calls <code>fn</code> on each chunk 2546in the stream until the awaited return value is <code>true</code> (or any truthy value). 2547Once an <code>fn</code> call on a chunk awaited return value is truthy, the stream is 2548destroyed and the promise is fulfilled with <code>true</code>. If none of the <code>fn</code> 2549calls on the chunks return a truthy value, the promise is fulfilled with 2550<code>false</code>.</p> 2551<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>; 2552<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; 2553 2554<span class="hljs-comment">// With a synchronous predicate.</span> 2555<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> 2556<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> 2557 2558<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span> 2559<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>([ 2560 <span class="hljs-string">'file1'</span>, 2561 <span class="hljs-string">'file2'</span>, 2562 <span class="hljs-string">'file3'</span>, 2563]).<span class="hljs-title function_">some</span>(<span class="hljs-keyword">async</span> (fileName) => { 2564 <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName); 2565 <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>; 2566}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2567<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> 2568<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> 2569<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> 2570<div class="api_metadata"> 2571<span>Added in: v17.5.0</span> 2572</div> 2573<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2574<ul> 2575<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. 2576<ul> 2577<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> 2578<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2579<ul> 2580<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2581abort the <code>fn</code> call early.</li> 2582</ul> 2583</li> 2584</ul> 2585</li> 2586<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2587<ul> 2588<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 2589on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2590<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2591aborted.</li> 2592</ul> 2593</li> 2594<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> 2595evaluated with a truthy value, or <code>undefined</code> if no element was found.</li> 2596</ul> 2597<p>This method is similar to <code>Array.prototype.find</code> and calls <code>fn</code> on each chunk 2598in the stream to find a chunk with a truthy value for <code>fn</code>. Once an <code>fn</code> call's 2599awaited return value is truthy, the stream is destroyed and the promise is 2600fulfilled with value for which <code>fn</code> returned a truthy value. If all of the 2601<code>fn</code> calls on the chunks return a falsy value, the promise is fulfilled with 2602<code>undefined</code>.</p> 2603<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>; 2604<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; 2605 2606<span class="hljs-comment">// With a synchronous predicate.</span> 2607<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> 2608<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> 2609<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> 2610 2611<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span> 2612<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>([ 2613 <span class="hljs-string">'file1'</span>, 2614 <span class="hljs-string">'file2'</span>, 2615 <span class="hljs-string">'file3'</span>, 2616]).<span class="hljs-title function_">find</span>(<span class="hljs-keyword">async</span> (fileName) => { 2617 <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName); 2618 <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>; 2619}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2620<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> 2621<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> 2622<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> 2623<div class="api_metadata"> 2624<span>Added in: v17.5.0</span> 2625</div> 2626<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2627<ul> 2628<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. 2629<ul> 2630<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> 2631<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2632<ul> 2633<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2634abort the <code>fn</code> call early.</li> 2635</ul> 2636</li> 2637</ul> 2638</li> 2639<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2640<ul> 2641<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 2642on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2643<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2644aborted.</li> 2645</ul> 2646</li> 2647<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 2648value for all of the chunks.</li> 2649</ul> 2650<p>This method is similar to <code>Array.prototype.every</code> and calls <code>fn</code> on each chunk 2651in the stream to check if all awaited return values are truthy value for <code>fn</code>. 2652Once an <code>fn</code> call on a chunk awaited return value is falsy, the stream is 2653destroyed and the promise is fulfilled with <code>false</code>. If all of the <code>fn</code> calls 2654on the chunks return a truthy value, the promise is fulfilled with <code>true</code>.</p> 2655<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>; 2656<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; 2657 2658<span class="hljs-comment">// With a synchronous predicate.</span> 2659<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> 2660<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> 2661 2662<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span> 2663<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>([ 2664 <span class="hljs-string">'file1'</span>, 2665 <span class="hljs-string">'file2'</span>, 2666 <span class="hljs-string">'file3'</span>, 2667]).<span class="hljs-title function_">every</span>(<span class="hljs-keyword">async</span> (fileName) => { 2668 <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName); 2669 <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>; 2670}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }); 2671<span class="hljs-comment">// `true` if all files in the list are bigger than 1MiB</span> 2672<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(allBigFiles); 2673<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> 2674<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> 2675<div class="api_metadata"> 2676<span>Added in: v17.5.0</span> 2677</div> 2678<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2679<ul> 2680<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 2681every chunk in the stream. 2682<ul> 2683<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> 2684<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2685<ul> 2686<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2687abort the <code>fn</code> call early.</li> 2688</ul> 2689</li> 2690</ul> 2691</li> 2692<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2693<ul> 2694<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 2695on the stream at once. <strong>Default:</strong> <code>1</code>.</li> 2696<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2697aborted.</li> 2698</ul> 2699</li> 2700<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream flat-mapped with the function <code>fn</code>.</li> 2701</ul> 2702<p>This method returns a new stream by applying the given callback to each 2703chunk of the stream and then flattening the result.</p> 2704<p>It is possible to return a stream or another iterable or async iterable from 2705<code>fn</code> and the result streams will be merged (flattened) into the returned 2706stream.</p> 2707<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>; 2708<span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>; 2709 2710<span class="hljs-comment">// With a synchronous mapper.</span> 2711<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])) { 2712 <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> 2713} 2714<span class="hljs-comment">// With an asynchronous mapper, combine the contents of 4 files</span> 2715<span class="hljs-keyword">const</span> concatResult = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 2716 <span class="hljs-string">'./1.mjs'</span>, 2717 <span class="hljs-string">'./2.mjs'</span>, 2718 <span class="hljs-string">'./3.mjs'</span>, 2719 <span class="hljs-string">'./4.mjs'</span>, 2720]).<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)); 2721<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) { 2722 <span class="hljs-comment">// This will contain the contents (all chunks) of all 4 files</span> 2723 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); 2724}</code> <button class="copy-button">copy</button></pre> 2725<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> 2726<div class="api_metadata"> 2727<span>Added in: v17.5.0</span> 2728</div> 2729<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2730<ul> 2731<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> 2732<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2733<ul> 2734<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2735aborted.</li> 2736</ul> 2737</li> 2738<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream with <code>limit</code> chunks dropped.</li> 2739</ul> 2740<p>This method returns a new stream with the first <code>limit</code> chunks dropped.</p> 2741<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>; 2742 2743<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> 2744<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> 2745<div class="api_metadata"> 2746<span>Added in: v17.5.0</span> 2747</div> 2748<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2749<ul> 2750<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> 2751<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2752<ul> 2753<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2754aborted.</li> 2755</ul> 2756</li> 2757<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream with <code>limit</code> chunks taken.</li> 2758</ul> 2759<p>This method returns a new stream with the first <code>limit</code> chunks.</p> 2760<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>; 2761 2762<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> 2763<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> 2764<div class="api_metadata"> 2765<details class="changelog"><summary>History</summary> 2766<table> 2767<tbody><tr><th>Version</th><th>Changes</th></tr> 2768<tr><td>v18.17.0</td> 2769<td><p>Using the <code>asIndexedPairs</code> method emits a runtime warning that it will be removed in a future version.</p></td></tr> 2770<tr><td>v17.5.0</td> 2771<td><p><span>Added in: v17.5.0</span></p></td></tr> 2772</tbody></table> 2773</details> 2774</div> 2775<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 2776<ul> 2777<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2778<ul> 2779<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2780aborted.</li> 2781</ul> 2782</li> 2783<li>Returns: <a href="stream.html#class-streamreadable" class="type"><Readable></a> a stream of indexed pairs.</li> 2784</ul> 2785<p>This method returns a new stream with chunks of the underlying stream paired 2786with a counter in the form <code>[index, chunk]</code>. The first index value is 0 and it 2787increases by 1 for each chunk produced.</p> 2788<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>; 2789 2790<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>(); 2791<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> 2792<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> 2793<div class="api_metadata"> 2794<span>Added in: v17.5.0</span> 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>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 2799in the stream. 2800<ul> 2801<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 2802<code>initial</code> value if specified or the first chunk of the stream otherwise.</li> 2803<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> 2804<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2805<ul> 2806<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> aborted if the stream is destroyed allowing to 2807abort the <code>fn</code> call early.</li> 2808</ul> 2809</li> 2810</ul> 2811</li> 2812<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> 2813<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2814<ul> 2815<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows destroying the stream if the signal is 2816aborted.</li> 2817</ul> 2818</li> 2819<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> 2820</ul> 2821<p>This method calls <code>fn</code> on each chunk of the stream in order, passing it the 2822result from the calculation on the previous element. It returns a promise for 2823the final value of the reduction.</p> 2824<p>If no <code>initial</code> value is supplied the first chunk of the stream is used as the 2825initial value. If the stream is empty, the promise is rejected with a 2826<code>TypeError</code> with the <code>ERR_INVALID_ARGS</code> code property.</p> 2827<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>; 2828<span class="hljs-keyword">import</span> { readdir, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; 2829<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>; 2830 2831<span class="hljs-keyword">const</span> directoryPath = <span class="hljs-string">'./src'</span>; 2832<span class="hljs-keyword">const</span> filesInDir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readdir</span>(directoryPath); 2833 2834<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) 2835 .<span class="hljs-title function_">reduce</span>(<span class="hljs-keyword">async</span> (totalSize, file) => { 2836 <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)); 2837 <span class="hljs-keyword">return</span> totalSize + size; 2838 }, <span class="hljs-number">0</span>); 2839 2840<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(folderSize);</code> <button class="copy-button">copy</button></pre> 2841<p>The reducer function iterates the stream element-by-element which means that 2842there is no <code>concurrency</code> parameter or parallelism. To perform a <code>reduce</code> 2843concurrently, you can extract the async function to <a href="#readablemapfn-options"><code>readable.map</code></a> method.</p> 2844<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>; 2845<span class="hljs-keyword">import</span> { readdir, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>; 2846<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>; 2847 2848<span class="hljs-keyword">const</span> directoryPath = <span class="hljs-string">'./src'</span>; 2849<span class="hljs-keyword">const</span> filesInDir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readdir</span>(directoryPath); 2850 2851<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) 2852 .<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> }) 2853 .<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>); 2854 2855<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(folderSize);</code> <button class="copy-button">copy</button></pre> 2856<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> 2857<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> 2858<div class="api_metadata"> 2859<details class="changelog"><summary>History</summary> 2860<table> 2861<tbody><tr><th>Version</th><th>Changes</th></tr> 2862<tr><td>v6.8.0</td> 2863<td><p>Instances of <code>Duplex</code> now return <code>true</code> when checking <code>instanceof stream.Writable</code>.</p></td></tr> 2864<tr><td>v0.9.4</td> 2865<td><p><span>Added in: v0.9.4</span></p></td></tr> 2866</tbody></table> 2867</details> 2868</div> 2869 2870<p>Duplex streams are streams that implement both the <a href="#class-streamreadable"><code>Readable</code></a> and 2871<a href="#class-streamwritable"><code>Writable</code></a> interfaces.</p> 2872<p>Examples of <code>Duplex</code> streams include:</p> 2873<ul> 2874<li><a href="net.html#class-netsocket">TCP sockets</a></li> 2875<li><a href="zlib.html">zlib streams</a></li> 2876<li><a href="crypto.html">crypto streams</a></li> 2877</ul> 2878<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> 2879<div class="api_metadata"> 2880<span>Added in: v0.9.4</span> 2881</div> 2882<ul> 2883<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 2884</ul> 2885<p>If <code>false</code> then the stream will automatically end the writable side when the 2886readable side ends. Set initially by the <code>allowHalfOpen</code> constructor option, 2887which defaults to <code>true</code>.</p> 2888<p>This can be changed manually to change the half-open behavior of an existing 2889<code>Duplex</code> stream instance, but must be changed before the <code>'end'</code> event is 2890emitted.</p> 2891<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> 2892<div class="api_metadata"> 2893<span>Added in: v0.9.4</span> 2894</div> 2895 2896<p>Transform streams are <a href="#class-streamduplex"><code>Duplex</code></a> streams where the output is in some way 2897related to the input. Like all <a href="#class-streamduplex"><code>Duplex</code></a> streams, <code>Transform</code> streams 2898implement both the <a href="#class-streamreadable"><code>Readable</code></a> and <a href="#class-streamwritable"><code>Writable</code></a> interfaces.</p> 2899<p>Examples of <code>Transform</code> streams include:</p> 2900<ul> 2901<li><a href="zlib.html">zlib streams</a></li> 2902<li><a href="crypto.html">crypto streams</a></li> 2903</ul> 2904<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> 2905<div class="api_metadata"> 2906<details class="changelog"><summary>History</summary> 2907<table> 2908<tbody><tr><th>Version</th><th>Changes</th></tr> 2909<tr><td>v14.0.0</td> 2910<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr> 2911<tr><td>v8.0.0</td> 2912<td><p><span>Added in: v8.0.0</span></p></td></tr> 2913</tbody></table> 2914</details> 2915</div> 2916<ul> 2917<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 2918<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 2919</ul> 2920<p>Destroy the stream, and optionally emit an <code>'error'</code> event. After this call, the 2921transform stream would release any internal resources. 2922Implementors should not override this method, but instead implement 2923<a href="#readable_destroyerr-callback"><code>readable._destroy()</code></a>. 2924The default implementation of <code>_destroy()</code> for <code>Transform</code> also emit <code>'close'</code> 2925unless <code>emitClose</code> is set in false.</p> 2926<p>Once <code>destroy()</code> has been called, any further calls will be a no-op and no 2927further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p> 2928<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> 2929<div class="api_metadata"> 2930<details class="changelog"><summary>History</summary> 2931<table> 2932<tbody><tr><th>Version</th><th>Changes</th></tr> 2933<tr><td>v18.14.0</td> 2934<td><p>Added support for <code>ReadableStream</code> and <code>WritableStream</code>.</p></td></tr> 2935<tr><td>v15.11.0</td> 2936<td><p>The <code>signal</code> option was added.</p></td></tr> 2937<tr><td>v14.0.0</td> 2938<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> 2939<tr><td>v14.0.0</td> 2940<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> 2941<tr><td>v14.0.0</td> 2942<td><p>Callback will be invoked on streams which have already finished before the call to <code>finished(stream, cb)</code>.</p></td></tr> 2943<tr><td>v10.0.0</td> 2944<td><p><span>Added in: v10.0.0</span></p></td></tr> 2945</tbody></table> 2946</details> 2947</div> 2948<ul> 2949<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> 2950</ul> 2951<p>A readable and/or writable stream/webstream.</p> 2952<ul> 2953<li> 2954<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> 2955<ul> 2956<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 2957not treated as finished. <strong>Default:</strong> <code>true</code>.</li> 2958<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 2959the stream ends even though the stream might still be readable. 2960<strong>Default:</strong> <code>true</code>.</li> 2961<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 2962the stream ends even though the stream might still be writable. 2963<strong>Default:</strong> <code>true</code>.</li> 2964<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> allows aborting the wait for the stream finish. The 2965underlying stream will <em>not</em> be aborted if the signal is aborted. The 2966callback will get called with an <code>AbortError</code>. All registered 2967listeners added by this function will also be removed.</li> 2968<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. 2969<strong>Default:</strong> <code>false</code>.</li> 2970</ul> 2971</li> 2972<li> 2973<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 2974argument.</p> 2975</li> 2976<li> 2977<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 2978listeners.</p> 2979</li> 2980</ul> 2981<p>A function to get notified when a stream is no longer readable, writable 2982or has experienced an error or a premature close event.</p> 2983<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>); 2984<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 2985 2986<span class="hljs-keyword">const</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>); 2987 2988<span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 2989 <span class="hljs-keyword">if</span> (err) { 2990 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Stream failed.'</span>, err); 2991 } <span class="hljs-keyword">else</span> { 2992 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>); 2993 } 2994}); 2995 2996rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code> <button class="copy-button">copy</button></pre> 2997<p>Especially useful in error handling scenarios where a stream is destroyed 2998prematurely (like an aborted HTTP request), and will not emit <code>'end'</code> 2999or <code>'finish'</code>.</p> 3000<p>The <code>finished</code> API provides <a href="#streamfinishedstream-options">promise version</a>.</p> 3001<p><code>stream.finished()</code> leaves dangling event listeners (in particular 3002<code>'error'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code>) after <code>callback</code> has been 3003invoked. The reason for this is so that unexpected <code>'error'</code> events (due to 3004incorrect stream implementations) do not cause unexpected crashes. 3005If this is unwanted behavior then the returned cleanup function needs to be 3006invoked in the callback:</p> 3007<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> { 3008 <span class="hljs-title function_">cleanup</span>(); 3009 <span class="hljs-comment">// ...</span> 3010});</code> <button class="copy-button">copy</button></pre> 3011<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> 3012<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> 3013<div class="api_metadata"> 3014<details class="changelog"><summary>History</summary> 3015<table> 3016<tbody><tr><th>Version</th><th>Changes</th></tr> 3017<tr><td>v18.16.0</td> 3018<td><p>Added support for webstreams.</p></td></tr> 3019<tr><td>v18.0.0</td> 3020<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> 3021<tr><td>v14.0.0</td> 3022<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> 3023<tr><td>v13.10.0</td> 3024<td><p>Add support for async generators.</p></td></tr> 3025<tr><td>v10.0.0</td> 3026<td><p><span>Added in: v10.0.0</span></p></td></tr> 3027</tbody></table> 3028</details> 3029</div> 3030<ul> 3031<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> 3032<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> 3033<ul> 3034<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> 3035</ul> 3036</li> 3037<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> 3038<ul> 3039<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 3040<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 3041</ul> 3042</li> 3043<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> 3044<ul> 3045<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 3046<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> 3047</ul> 3048</li> 3049<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. 3050<ul> 3051<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 3052<li><code>val</code> Resolved value of <code>Promise</code> returned by <code>destination</code>.</li> 3053</ul> 3054</li> 3055<li>Returns: <a href="stream.html#stream" class="type"><Stream></a></li> 3056</ul> 3057<p>A module method to pipe between streams and generators forwarding errors and 3058properly cleaning up and provide a callback when the pipeline is complete.</p> 3059<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>); 3060<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 3061<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>); 3062 3063<span class="hljs-comment">// Use the pipeline API to easily pipe a series of streams</span> 3064<span class="hljs-comment">// together and get notified when the pipeline is fully done.</span> 3065 3066<span class="hljs-comment">// A pipeline to gzip a potentially huge tar file efficiently:</span> 3067 3068<span class="hljs-title function_">pipeline</span>( 3069 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 3070 zlib.<span class="hljs-title function_">createGzip</span>(), 3071 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 3072 <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 3073 <span class="hljs-keyword">if</span> (err) { 3074 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Pipeline failed.'</span>, err); 3075 } <span class="hljs-keyword">else</span> { 3076 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 3077 } 3078 }, 3079);</code> <button class="copy-button">copy</button></pre> 3080<p>The <code>pipeline</code> API provides a <a href="#streampipelinesource-transforms-destination-options">promise version</a>.</p> 3081<p><code>stream.pipeline()</code> will call <code>stream.destroy(err)</code> on all streams except:</p> 3082<ul> 3083<li><code>Readable</code> streams which have emitted <code>'end'</code> or <code>'close'</code>.</li> 3084<li><code>Writable</code> streams which have emitted <code>'finish'</code> or <code>'close'</code>.</li> 3085</ul> 3086<p><code>stream.pipeline()</code> leaves dangling event listeners on the streams 3087after the <code>callback</code> has been invoked. In the case of reuse of streams after 3088failure, this can cause event listener leaks and swallowed errors. If the last 3089stream is readable, dangling event listeners will be removed so that the last 3090stream can be consumed later.</p> 3091<p><code>stream.pipeline()</code> closes all the streams when an error is raised. 3092The <code>IncomingRequest</code> usage with <code>pipeline</code> could lead to an unexpected behavior 3093once it would destroy the socket without sending the expected response. 3094See the example below:</p> 3095<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>); 3096<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>); 3097<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 3098 3099<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> { 3100 <span class="hljs-keyword">const</span> fileStream = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'./fileNotExist.txt'</span>); 3101 <span class="hljs-title function_">pipeline</span>(fileStream, res, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 3102 <span class="hljs-keyword">if</span> (err) { 3103 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err); <span class="hljs-comment">// No such file</span> 3104 <span class="hljs-comment">// this message can't be sent once `pipeline` already destroyed the socket</span> 3105 <span class="hljs-keyword">return</span> res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'error!!!'</span>); 3106 } 3107 }); 3108});</code> <button class="copy-button">copy</button></pre> 3109<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> 3110<div class="api_metadata"> 3111<details class="changelog"><summary>History</summary> 3112<table> 3113<tbody><tr><th>Version</th><th>Changes</th></tr> 3114<tr><td>v18.16.0</td> 3115<td><p>Added support for webstreams.</p></td></tr> 3116<tr><td>v16.9.0</td> 3117<td><p><span>Added in: v16.9.0</span></p></td></tr> 3118</tbody></table> 3119</details> 3120</div> 3121<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> 3122<ul> 3123<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> 3124<li>Returns: <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li> 3125</ul> 3126<p>Combines two or more streams into a <code>Duplex</code> stream that writes to the 3127first stream and reads from the last. Each provided stream is piped into 3128the next, using <code>stream.pipeline</code>. If any of the streams error then all 3129are destroyed, including the outer <code>Duplex</code> stream.</p> 3130<p>Because <code>stream.compose</code> returns a new stream that in turn can (and 3131should) be piped into other streams, it enables composition. In contrast, 3132when passing streams to <code>stream.pipeline</code>, typically the first stream is 3133a readable stream and the last a writable stream, forming a closed 3134circuit.</p> 3135<p>If passed a <code>Function</code> it must be a factory method taking a <code>source</code> 3136<code>Iterable</code>.</p> 3137<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>; 3138 3139<span class="hljs-keyword">const</span> removeSpaces = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({ 3140 <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3141 <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>)); 3142 }, 3143}); 3144 3145<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>) { 3146 <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) { 3147 <span class="hljs-keyword">yield</span> <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">toUpperCase</span>(); 3148 } 3149} 3150 3151<span class="hljs-keyword">let</span> res = <span class="hljs-string">''</span>; 3152<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>)) { 3153 res += buf; 3154} 3155 3156<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> 3157<p><code>stream.compose</code> can be used to convert async iterables, generators and 3158functions into streams.</p> 3159<ul> 3160<li><code>AsyncIterable</code> converts into a readable <code>Duplex</code>. Cannot yield 3161<code>null</code>.</li> 3162<li><code>AsyncGeneratorFunction</code> converts into a readable/writable transform <code>Duplex</code>. 3163Must take a source <code>AsyncIterable</code> as first parameter. Cannot yield 3164<code>null</code>.</li> 3165<li><code>AsyncFunction</code> converts into a writable <code>Duplex</code>. Must return 3166either <code>null</code> or <code>undefined</code>.</li> 3167</ul> 3168<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>; 3169<span class="hljs-keyword">import</span> { finished } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>; 3170 3171<span class="hljs-comment">// Convert AsyncIterable into readable Duplex.</span> 3172<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>*() { 3173 <span class="hljs-keyword">yield</span> <span class="hljs-string">'Hello'</span>; 3174 <span class="hljs-keyword">yield</span> <span class="hljs-string">'World'</span>; 3175}()); 3176 3177<span class="hljs-comment">// Convert AsyncGenerator into transform Duplex.</span> 3178<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) { 3179 <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) { 3180 <span class="hljs-keyword">yield</span> <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">toUpperCase</span>(); 3181 } 3182}); 3183 3184<span class="hljs-keyword">let</span> res = <span class="hljs-string">''</span>; 3185 3186<span class="hljs-comment">// Convert AsyncFunction into writable Duplex.</span> 3187<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>) { 3188 <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) { 3189 res += chunk; 3190 } 3191}); 3192 3193<span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(<span class="hljs-title function_">compose</span>(s1, s2, s3)); 3194 3195<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> 3196<p>See <a href="#readablecomposestream-options"><code>readable.compose(stream)</code></a> for <code>stream.compose</code> as operator.</p> 3197<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> 3198<div class="api_metadata"> 3199<span>Added in: v12.3.0, v10.17.0</span> 3200</div> 3201<ul> 3202<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 3203<code>Symbol.iterator</code> iterable protocol. Emits an 'error' event if a null 3204value is passed.</li> 3205<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>. 3206By default, <code>Readable.from()</code> will set <code>options.objectMode</code> to <code>true</code>, unless 3207this is explicitly opted out by setting <code>options.objectMode</code> to <code>false</code>.</li> 3208<li>Returns: <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li> 3209</ul> 3210<p>A utility method for creating readable streams out of iterators.</p> 3211<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>); 3212 3213<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) { 3214 <span class="hljs-keyword">yield</span> <span class="hljs-string">'hello'</span>; 3215 <span class="hljs-keyword">yield</span> <span class="hljs-string">'streams'</span>; 3216} 3217 3218<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>()); 3219 3220readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 3221 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); 3222});</code> <button class="copy-button">copy</button></pre> 3223<p>Calling <code>Readable.from(string)</code> or <code>Readable.from(buffer)</code> will not have 3224the strings or buffers be iterated to match the other streams semantics 3225for performance reasons.</p> 3226<p>If an <code>Iterable</code> object containing promises is passed as an argument, 3227it might result in unhandled rejection.</p> 3228<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>); 3229 3230<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([ 3231 <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>)), 3232 <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> 3233]);</code> <button class="copy-button">copy</button></pre> 3234<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> 3235<div class="api_metadata"> 3236<span>Added in: v17.0.0</span> 3237</div> 3238<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3239<ul> 3240<li><code>readableStream</code> <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3241<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3242<ul> 3243<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 3244<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 3245<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3246<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li> 3247</ul> 3248</li> 3249<li>Returns: <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li> 3250</ul> 3251<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> 3252<div class="api_metadata"> 3253<span>Added in: v16.8.0</span> 3254</div> 3255<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3256<ul> 3257<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> 3258<li>Returns: <code>boolean</code></li> 3259</ul> 3260<p>Returns whether the stream has been read from or cancelled.</p> 3261<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> 3262<div class="api_metadata"> 3263<span>Added in: v17.3.0, v16.14.0</span> 3264</div> 3265<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3266<ul> 3267<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> 3268<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3269</ul> 3270<p>Returns whether the stream has encountered an error.</p> 3271<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> 3272<div class="api_metadata"> 3273<span>Added in: v17.4.0, v16.14.0</span> 3274</div> 3275<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3276<ul> 3277<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> 3278<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3279</ul> 3280<p>Returns whether the stream is readable.</p> 3281<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> 3282<div class="api_metadata"> 3283<span>Added in: v17.0.0</span> 3284</div> 3285<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3286<ul> 3287<li><code>streamReadable</code> <a href="stream.html#class-streamreadable" class="type"><stream.Readable></a></li> 3288<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3289<ul> 3290<li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3291<ul> 3292<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 3293<code>ReadableStream</code>) before backpressure is applied in reading from the given 3294<code>stream.Readable</code>. If no value is provided, it will be taken from the 3295given <code>stream.Readable</code>.</li> 3296<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. 3297If no value is provided, the size will be <code>1</code> for all the chunks. 3298<ul> 3299<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> 3300<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 3301</ul> 3302</li> 3303</ul> 3304</li> 3305</ul> 3306</li> 3307<li>Returns: <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3308</ul> 3309<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> 3310<div class="api_metadata"> 3311<span>Added in: v17.0.0</span> 3312</div> 3313<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3314<ul> 3315<li><code>writableStream</code> <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 3316<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3317<ul> 3318<li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3319<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 3320<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3321<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li> 3322</ul> 3323</li> 3324<li>Returns: <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a></li> 3325</ul> 3326<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> 3327<div class="api_metadata"> 3328<span>Added in: v17.0.0</span> 3329</div> 3330<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3331<ul> 3332<li><code>streamWritable</code> <a href="stream.html#class-streamwritable" class="type"><stream.Writable></a></li> 3333<li>Returns: <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 3334</ul> 3335<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> 3336<div class="api_metadata"> 3337<details class="changelog"><summary>History</summary> 3338<table> 3339<tbody><tr><th>Version</th><th>Changes</th></tr> 3340<tr><td>v18.17.0</td> 3341<td><p>The <code>src</code> argument can now be a <code>ReadableStream</code> or <code>WritableStream</code>.</p></td></tr> 3342<tr><td>v16.8.0</td> 3343<td><p><span>Added in: v16.8.0</span></p></td></tr> 3344</tbody></table> 3345</details> 3346</div> 3347<ul> 3348<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> 3349</ul> 3350<p>A utility method for creating duplex streams.</p> 3351<ul> 3352<li><code>Stream</code> converts writable stream into writable <code>Duplex</code> and readable stream 3353to <code>Duplex</code>.</li> 3354<li><code>Blob</code> converts into readable <code>Duplex</code>.</li> 3355<li><code>string</code> converts into readable <code>Duplex</code>.</li> 3356<li><code>ArrayBuffer</code> converts into readable <code>Duplex</code>.</li> 3357<li><code>AsyncIterable</code> converts into a readable <code>Duplex</code>. Cannot yield 3358<code>null</code>.</li> 3359<li><code>AsyncGeneratorFunction</code> converts into a readable/writable transform 3360<code>Duplex</code>. Must take a source <code>AsyncIterable</code> as first parameter. Cannot yield 3361<code>null</code>.</li> 3362<li><code>AsyncFunction</code> converts into a writable <code>Duplex</code>. Must return 3363either <code>null</code> or <code>undefined</code></li> 3364<li><code>Object ({ writable, readable })</code> converts <code>readable</code> and 3365<code>writable</code> into <code>Stream</code> and then combines them into <code>Duplex</code> where the 3366<code>Duplex</code> will write to the <code>writable</code> and read from the <code>readable</code>.</li> 3367<li><code>Promise</code> converts into readable <code>Duplex</code>. Value <code>null</code> is ignored.</li> 3368<li><code>ReadableStream</code> converts into readable <code>Duplex</code>.</li> 3369<li><code>WritableStream</code> converts into writable <code>Duplex</code>.</li> 3370<li>Returns: <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li> 3371</ul> 3372<p>If an <code>Iterable</code> object containing promises is passed as an argument, 3373it might result in unhandled rejection.</p> 3374<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>); 3375 3376<span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">from</span>([ 3377 <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>)), 3378 <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> 3379]);</code> <button class="copy-button">copy</button></pre> 3380<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> 3381<div class="api_metadata"> 3382<span>Added in: v17.0.0</span> 3383</div> 3384<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3385<ul> 3386<li><code>pair</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3387<ul> 3388<li><code>readable</code> <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3389<li><code>writable</code> <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 3390</ul> 3391</li> 3392<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3393<ul> 3394<li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3395<li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3396<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> 3397<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 3398<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3399<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a></li> 3400</ul> 3401</li> 3402<li>Returns: <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li> 3403</ul> 3404 3405<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>; 3406<span class="hljs-keyword">import</span> { 3407 <span class="hljs-title class_">ReadableStream</span>, 3408 <span class="hljs-title class_">WritableStream</span>, 3409} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>; 3410 3411<span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({ 3412 <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) { 3413 controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>); 3414 }, 3415}); 3416 3417<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>({ 3418 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk</span>) { 3419 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk); 3420 }, 3421}); 3422 3423<span class="hljs-keyword">const</span> pair = { 3424 readable, 3425 writable, 3426}; 3427<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> }); 3428 3429duplex.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>); 3430 3431<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) { 3432 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, chunk); 3433}</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>); 3434<span class="hljs-keyword">const</span> { 3435 <span class="hljs-title class_">ReadableStream</span>, 3436 <span class="hljs-title class_">WritableStream</span>, 3437} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>); 3438 3439<span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({ 3440 <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) { 3441 controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>); 3442 }, 3443}); 3444 3445<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>({ 3446 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk</span>) { 3447 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk); 3448 }, 3449}); 3450 3451<span class="hljs-keyword">const</span> pair = { 3452 readable, 3453 writable, 3454}; 3455<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> }); 3456 3457duplex.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>); 3458duplex.<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> 3459<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> 3460<div class="api_metadata"> 3461<span>Added in: v17.0.0</span> 3462</div> 3463<p></p><div class="api_stability api_stability_1"><a href="documentation.html#stability-index">Stability: 1</a> - Experimental</div><p></p> 3464<ul> 3465<li><code>streamDuplex</code> <a href="stream.html#class-streamduplex" class="type"><stream.Duplex></a></li> 3466<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3467<ul> 3468<li><code>readable</code> <a href="webstreams.html#class-readablestream" class="type"><ReadableStream></a></li> 3469<li><code>writable</code> <a href="webstreams.html#class-writablestream" class="type"><WritableStream></a></li> 3470</ul> 3471</li> 3472</ul> 3473 3474<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>; 3475 3476<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>({ 3477 <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span>, 3478 <span class="hljs-title function_">read</span>(<span class="hljs-params"></span>) { 3479 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-string">'world'</span>); 3480 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>); 3481 }, 3482 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3483 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk); 3484 <span class="hljs-title function_">callback</span>(); 3485 }, 3486}); 3487 3488<span class="hljs-keyword">const</span> { readable, writable } = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">toWeb</span>(duplex); 3489writable.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>); 3490 3491<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>(); 3492<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>); 3493 3494<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>({ 3495 <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span>, 3496 <span class="hljs-title function_">read</span>(<span class="hljs-params"></span>) { 3497 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-string">'world'</span>); 3498 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>); 3499 }, 3500 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3501 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk); 3502 <span class="hljs-title function_">callback</span>(); 3503 }, 3504}); 3505 3506<span class="hljs-keyword">const</span> { readable, writable } = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">toWeb</span>(duplex); 3507writable.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>); 3508 3509readable.<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> { 3510 <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>); 3511});</code><button class="copy-button">copy</button></pre> 3512<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> 3513<div class="api_metadata"> 3514<details class="changelog"><summary>History</summary> 3515<table> 3516<tbody><tr><th>Version</th><th>Changes</th></tr> 3517<tr><td>v18.16.0</td> 3518<td><p>Added support for <code>ReadableStream</code> and <code>WritableStream</code>.</p></td></tr> 3519<tr><td>v15.4.0</td> 3520<td><p><span>Added in: v15.4.0</span></p></td></tr> 3521</tbody></table> 3522</details> 3523</div> 3524<ul> 3525<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> A signal representing possible cancellation</li> 3526<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> 3527</ul> 3528<p>A stream to attach a signal to.</p> 3529<p>Attaches an AbortSignal to a readable or writeable stream. This lets code 3530control stream destruction using an <code>AbortController</code>.</p> 3531<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed 3532<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code> 3533on the stream, and <code>controller.error(new AbortError())</code> for webstreams.</p> 3534<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>); 3535 3536<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 3537<span class="hljs-keyword">const</span> read = <span class="hljs-title function_">addAbortSignal</span>( 3538 controller.<span class="hljs-property">signal</span>, 3539 fs.<span class="hljs-title function_">createReadStream</span>((<span class="hljs-string">'object.json'</span>)), 3540); 3541<span class="hljs-comment">// Later, abort the operation closing the stream</span> 3542controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre> 3543<p>Or using an <code>AbortSignal</code> with a readable stream as an async iterable:</p> 3544<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>(); 3545<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> 3546<span class="hljs-keyword">const</span> stream = <span class="hljs-title function_">addAbortSignal</span>( 3547 controller.<span class="hljs-property">signal</span>, 3548 fs.<span class="hljs-title function_">createReadStream</span>((<span class="hljs-string">'object.json'</span>)), 3549); 3550(<span class="hljs-keyword">async</span> () => { 3551 <span class="hljs-keyword">try</span> { 3552 <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) { 3553 <span class="hljs-keyword">await</span> <span class="hljs-title function_">process</span>(chunk); 3554 } 3555 } <span class="hljs-keyword">catch</span> (e) { 3556 <span class="hljs-keyword">if</span> (e.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) { 3557 <span class="hljs-comment">// The operation was cancelled</span> 3558 } <span class="hljs-keyword">else</span> { 3559 <span class="hljs-keyword">throw</span> e; 3560 } 3561 } 3562})();</code> <button class="copy-button">copy</button></pre> 3563<p>Or using an <code>AbortSignal</code> with a ReadableStream:</p> 3564<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>(); 3565<span class="hljs-keyword">const</span> rs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({ 3566 <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) { 3567 controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'hello'</span>); 3568 controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>); 3569 controller.<span class="hljs-title function_">close</span>(); 3570 }, 3571}); 3572 3573<span class="hljs-title function_">addAbortSignal</span>(controller.<span class="hljs-property">signal</span>, rs); 3574 3575<span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 3576 <span class="hljs-keyword">if</span> (err) { 3577 <span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) { 3578 <span class="hljs-comment">// The operation was cancelled</span> 3579 } 3580 } 3581}); 3582 3583<span class="hljs-keyword">const</span> reader = rs.<span class="hljs-title function_">getReader</span>(); 3584 3585reader.<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> { 3586 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value); <span class="hljs-comment">// hello</span> 3587 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(done); <span class="hljs-comment">// false</span> 3588 controller.<span class="hljs-title function_">abort</span>(); 3589});</code> <button class="copy-button">copy</button></pre> 3590<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> 3591<div class="api_metadata"> 3592<span>Added in: v18.17.0</span> 3593</div> 3594<ul> 3595<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3596<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 3597</ul> 3598<p>Returns the default highWaterMark used by streams. 3599Defaults to <code>16384</code> (16 KiB), or <code>16</code> for <code>objectMode</code>.</p> 3600<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> 3601<div class="api_metadata"> 3602<span>Added in: v18.17.0</span> 3603</div> 3604<ul> 3605<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 3606<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> 3607</ul> 3608<p>Sets the default highWaterMark used by streams.</p> 3609</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> 3610 3611<p>The <code>node:stream</code> module API has been designed to make it possible to easily 3612implement streams using JavaScript's prototypal inheritance model.</p> 3613<p>First, a stream developer would declare a new JavaScript class that extends one 3614of the four basic stream classes (<code>stream.Writable</code>, <code>stream.Readable</code>, 3615<code>stream.Duplex</code>, or <code>stream.Transform</code>), making sure they call the appropriate 3616parent class constructor:</p> 3617<!-- eslint-disable no-useless-constructor --> 3618<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>); 3619 3620<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> { 3621 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">{ highWaterMark, ...options }</span>) { 3622 <span class="hljs-variable language_">super</span>({ highWaterMark }); 3623 <span class="hljs-comment">// ...</span> 3624 } 3625}</code> <button class="copy-button">copy</button></pre> 3626<p>When extending streams, keep in mind what options the user 3627can and should provide before forwarding these to the base constructor. For 3628example, if the implementation makes assumptions in regard to the 3629<code>autoDestroy</code> and <code>emitClose</code> options, do not allow the 3630user to override these. Be explicit about what 3631options are forwarded instead of implicitly forwarding all options.</p> 3632<p>The new stream class must then implement one or more specific methods, depending 3633on the type of stream being created, as detailed in the chart below:</p> 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664<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> 3665<p>The implementation code for a stream should <em>never</em> call the "public" methods 3666of a stream that are intended for use by consumers (as described in the 3667<a href="#api-for-stream-consumers">API for stream consumers</a> section). Doing so may lead to adverse side effects 3668in application code consuming the stream.</p> 3669<p>Avoid overriding public methods such as <code>write()</code>, <code>end()</code>, <code>cork()</code>, 3670<code>uncork()</code>, <code>read()</code> and <code>destroy()</code>, or emitting internal events such 3671as <code>'error'</code>, <code>'data'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code> through <code>.emit()</code>. 3672Doing so can break current and future stream invariants leading to behavior 3673and/or compatibility issues with other streams, stream utilities, and user 3674expectations.</p> 3675<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> 3676<div class="api_metadata"> 3677<span>Added in: v1.2.0</span> 3678</div> 3679<p>For many simple cases, it is possible to create a stream without relying on 3680inheritance. This can be accomplished by directly creating instances of the 3681<code>stream.Writable</code>, <code>stream.Readable</code>, <code>stream.Duplex</code>, or <code>stream.Transform</code> 3682objects and passing appropriate methods as constructor options.</p> 3683<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>); 3684 3685<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 3686 <span class="hljs-title function_">construct</span>(<span class="hljs-params">callback</span>) { 3687 <span class="hljs-comment">// Initialize state and load resources...</span> 3688 }, 3689 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3690 <span class="hljs-comment">// ...</span> 3691 }, 3692 <span class="hljs-title function_">destroy</span>(<span class="hljs-params"></span>) { 3693 <span class="hljs-comment">// Free resources...</span> 3694 }, 3695});</code> <button class="copy-button">copy</button></pre> 3696<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> 3697<p>The <code>stream.Writable</code> class is extended to implement a <a href="#class-streamwritable"><code>Writable</code></a> stream.</p> 3698<p>Custom <code>Writable</code> streams <em>must</em> call the <code>new stream.Writable([options])</code> 3699constructor and implement the <code>writable._write()</code> and/or <code>writable._writev()</code> 3700method.</p> 3701<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> 3702<div class="api_metadata"> 3703<details class="changelog"><summary>History</summary> 3704<table> 3705<tbody><tr><th>Version</th><th>Changes</th></tr> 3706<tr><td>v15.5.0</td> 3707<td><p>support passing in an AbortSignal.</p></td></tr> 3708<tr><td>v14.0.0</td> 3709<td><p>Change <code>autoDestroy</code> option default to <code>true</code>.</p></td></tr> 3710<tr><td>v11.2.0, v10.16.0</td> 3711<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> 3712<tr><td>v10.0.0</td> 3713<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> 3714</tbody></table> 3715</details> 3716</div> 3717<ul> 3718<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 3719<ul> 3720<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 3721<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> starts returning <code>false</code>. <strong>Default:</strong> 3722<code>16384</code> (16 KiB), or <code>16</code> for <code>objectMode</code> streams.</li> 3723<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 3724<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> to <code>Buffer</code>s (with the encoding 3725specified in the <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a> call) before passing 3726them to <a href="#writable_writechunk-encoding-callback"><code>stream._write()</code></a>. Other types of data are not 3727converted (i.e. <code>Buffer</code>s are not decoded into <code>string</code>s). Setting to 3728false will prevent <code>string</code>s from being converted. <strong>Default:</strong> <code>true</code>.</li> 3729<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 3730encoding is specified as an argument to <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>. 3731<strong>Default:</strong> <code>'utf8'</code>.</li> 3732<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 3733<a href="#writablewritechunk-encoding-callback"><code>stream.write(anyObj)</code></a> is a valid operation. When set, 3734it becomes possible to write JavaScript values other than string, 3735<code>Buffer</code> or <code>Uint8Array</code> if supported by the stream implementation. 3736<strong>Default:</strong> <code>false</code>.</li> 3737<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> 3738after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li> 3739<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 3740<a href="#writable_writechunk-encoding-callback"><code>stream._write()</code></a> method.</li> 3741<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 3742<a href="#writable_writevchunks-callback"><code>stream._writev()</code></a> method.</li> 3743<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 3744<a href="#writable_destroyerr-callback"><code>stream._destroy()</code></a> method.</li> 3745<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 3746<a href="#writable_finalcallback"><code>stream._final()</code></a> method.</li> 3747<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 3748<a href="#writable_constructcallback"><code>stream._construct()</code></a> method.</li> 3749<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 3750<code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>true</code>.</li> 3751<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> A signal representing possible cancellation.</li> 3752</ul> 3753</li> 3754</ul> 3755<!-- eslint-disable no-useless-constructor --> 3756<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>); 3757 3758<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> { 3759 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 3760 <span class="hljs-comment">// Calls the stream.Writable() constructor.</span> 3761 <span class="hljs-variable language_">super</span>(options); 3762 <span class="hljs-comment">// ...</span> 3763 } 3764}</code> <button class="copy-button">copy</button></pre> 3765<p>Or, when using pre-ES6 style constructors:</p> 3766<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>); 3767<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>); 3768 3769<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyWritable</span>(<span class="hljs-params">options</span>) { 3770 <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>)) 3771 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyWritable</span>(options); 3772 <span class="hljs-title class_">Writable</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 3773} 3774util.<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> 3775<p>Or, using the simplified constructor approach:</p> 3776<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>); 3777 3778<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 3779 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3780 <span class="hljs-comment">// ...</span> 3781 }, 3782 <span class="hljs-title function_">writev</span>(<span class="hljs-params">chunks, callback</span>) { 3783 <span class="hljs-comment">// ...</span> 3784 }, 3785});</code> <button class="copy-button">copy</button></pre> 3786<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed 3787<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code> 3788on the writeable stream.</p> 3789<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>); 3790 3791<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 3792<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 3793 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3794 <span class="hljs-comment">// ...</span> 3795 }, 3796 <span class="hljs-title function_">writev</span>(<span class="hljs-params">chunks, callback</span>) { 3797 <span class="hljs-comment">// ...</span> 3798 }, 3799 <span class="hljs-attr">signal</span>: controller.<span class="hljs-property">signal</span>, 3800}); 3801<span class="hljs-comment">// Later, abort the operation closing the stream</span> 3802controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre> 3803<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> 3804<div class="api_metadata"> 3805<span>Added in: v15.0.0</span> 3806</div> 3807<ul> 3808<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 3809argument) when the stream has finished initializing.</li> 3810</ul> 3811<p>The <code>_construct()</code> method MUST NOT be called directly. It may be implemented 3812by child classes, and if so, will be called by the internal <code>Writable</code> 3813class methods only.</p> 3814<p>This optional function will be called in a tick after the stream constructor 3815has returned, delaying any <code>_write()</code>, <code>_final()</code> and <code>_destroy()</code> calls until 3816<code>callback</code> is called. This is useful to initialize state or asynchronously 3817initialize resources before the stream can be used.</p> 3818<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>); 3819<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 3820 3821<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> { 3822 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">filename</span>) { 3823 <span class="hljs-variable language_">super</span>(); 3824 <span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span> = filename; 3825 <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = <span class="hljs-literal">null</span>; 3826 } 3827 <span class="hljs-title function_">_construct</span>(<span class="hljs-params">callback</span>) { 3828 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> { 3829 <span class="hljs-keyword">if</span> (err) { 3830 <span class="hljs-title function_">callback</span>(err); 3831 } <span class="hljs-keyword">else</span> { 3832 <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = fd; 3833 <span class="hljs-title function_">callback</span>(); 3834 } 3835 }); 3836 } 3837 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3838 fs.<span class="hljs-title function_">write</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, chunk, callback); 3839 } 3840 <span class="hljs-title function_">_destroy</span>(<span class="hljs-params">err, callback</span>) { 3841 <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>) { 3842 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)); 3843 } <span class="hljs-keyword">else</span> { 3844 <span class="hljs-title function_">callback</span>(err); 3845 } 3846 } 3847}</code> <button class="copy-button">copy</button></pre> 3848<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> 3849<div class="api_metadata"> 3850<details class="changelog"><summary>History</summary> 3851<table> 3852<tbody><tr><th>Version</th><th>Changes</th></tr> 3853<tr><td>v12.11.0</td> 3854<td><p>_write() is optional when providing _writev().</p></td></tr> 3855</tbody></table> 3856</details> 3857</div> 3858<ul> 3859<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 3860<code>string</code> passed to <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>. If the stream's 3861<code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode, 3862the chunk will not be converted & will be whatever was passed to 3863<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>.</li> 3864<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 3865character encoding of that string. If chunk is a <code>Buffer</code>, or if the 3866stream is operating in object mode, <code>encoding</code> may be ignored.</li> 3867<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 3868argument) when processing is complete for the supplied chunk.</li> 3869</ul> 3870<p>All <code>Writable</code> stream implementations must provide a 3871<a href="#writable_writechunk-encoding-callback"><code>writable._write()</code></a> and/or 3872<a href="#writable_writevchunks-callback"><code>writable._writev()</code></a> method to send data to the underlying 3873resource.</p> 3874<p><a href="#class-streamtransform"><code>Transform</code></a> streams provide their own implementation of the 3875<a href="#writable_writechunk-encoding-callback"><code>writable._write()</code></a>.</p> 3876<p>This function MUST NOT be called by application code directly. It should be 3877implemented by child classes, and called by the internal <code>Writable</code> class 3878methods only.</p> 3879<p>The <code>callback</code> function must be called synchronously inside of 3880<code>writable._write()</code> or asynchronously (i.e. different tick) to signal either 3881that the write completed successfully or failed with an error. 3882The first argument passed to the <code>callback</code> must be the <code>Error</code> object if the 3883call failed or <code>null</code> if the write succeeded.</p> 3884<p>All calls to <code>writable.write()</code> that occur between the time <code>writable._write()</code> 3885is called and the <code>callback</code> is called will cause the written data to be 3886buffered. When the <code>callback</code> is invoked, the stream might emit a <a href="#event-drain"><code>'drain'</code></a> 3887event. If a stream implementation is capable of processing multiple chunks of 3888data at once, the <code>writable._writev()</code> method should be implemented.</p> 3889<p>If the <code>decodeStrings</code> property is explicitly set to <code>false</code> in the constructor 3890options, then <code>chunk</code> will remain the same object that is passed to <code>.write()</code>, 3891and may be a string rather than a <code>Buffer</code>. This is to support implementations 3892that have an optimized handling for certain string data encodings. In that case, 3893the <code>encoding</code> argument will indicate the character encoding of the string. 3894Otherwise, the <code>encoding</code> argument can be safely ignored.</p> 3895<p>The <code>writable._write()</code> method is prefixed with an underscore because it is 3896internal to the class that defines it, and should never be called directly by 3897user programs.</p> 3898<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> 3899<ul> 3900<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> 3901that each represent a discrete chunk of data to write. The properties of 3902these objects are: 3903<ul> 3904<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 3905be written. The <code>chunk</code> will be a string if the <code>Writable</code> was created with 3906the <code>decodeStrings</code> option set to <code>false</code> and a string was passed to <code>write()</code>.</li> 3907<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 3908a <code>Buffer</code>, the <code>encoding</code> will be <code>'buffer'</code>.</li> 3909</ul> 3910</li> 3911<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 3912argument) to be invoked when processing is complete for the supplied chunks.</li> 3913</ul> 3914<p>This function MUST NOT be called by application code directly. It should be 3915implemented by child classes, and called by the internal <code>Writable</code> class 3916methods only.</p> 3917<p>The <code>writable._writev()</code> method may be implemented in addition or alternatively 3918to <code>writable._write()</code> in stream implementations that are capable of processing 3919multiple chunks of data at once. If implemented and if there is buffered data 3920from previous writes, <code>_writev()</code> will be called instead of <code>_write()</code>.</p> 3921<p>The <code>writable._writev()</code> method is prefixed with an underscore because it is 3922internal to the class that defines it, and should never be called directly by 3923user programs.</p> 3924<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> 3925<div class="api_metadata"> 3926<span>Added in: v8.0.0</span> 3927</div> 3928<ul> 3929<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> 3930<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 3931argument.</li> 3932</ul> 3933<p>The <code>_destroy()</code> method is called by <a href="#writabledestroyerror"><code>writable.destroy()</code></a>. 3934It can be overridden by child classes but it <strong>must not</strong> be called directly. 3935Furthermore, the <code>callback</code> should not be mixed with async/await 3936once it is executed when a promise is resolved.</p> 3937<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> 3938<div class="api_metadata"> 3939<span>Added in: v8.0.0</span> 3940</div> 3941<ul> 3942<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 3943argument) when finished writing any remaining data.</li> 3944</ul> 3945<p>The <code>_final()</code> method <strong>must not</strong> be called directly. It may be implemented 3946by child classes, and if so, will be called by the internal <code>Writable</code> 3947class methods only.</p> 3948<p>This optional function will be called before the stream closes, delaying the 3949<code>'finish'</code> event until <code>callback</code> is called. This is useful to close resources 3950or write buffered data before a stream ends.</p> 3951<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> 3952<p>Errors occurring during the processing of the <a href="#writable_writechunk-encoding-callback"><code>writable._write()</code></a>, 3953<a href="#writable_writevchunks-callback"><code>writable._writev()</code></a> and <a href="#writable_finalcallback"><code>writable._final()</code></a> methods must be propagated 3954by invoking the callback and passing the error as the first argument. 3955Throwing an <code>Error</code> from within these methods or manually emitting an <code>'error'</code> 3956event results in undefined behavior.</p> 3957<p>If a <code>Readable</code> stream pipes into a <code>Writable</code> stream when <code>Writable</code> emits an 3958error, the <code>Readable</code> stream will be unpiped.</p> 3959<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>); 3960 3961<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 3962 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3963 <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>) { 3964 <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>)); 3965 } <span class="hljs-keyword">else</span> { 3966 <span class="hljs-title function_">callback</span>(); 3967 } 3968 }, 3969});</code> <button class="copy-button">copy</button></pre> 3970<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> 3971<p>The following illustrates a rather simplistic (and somewhat pointless) custom 3972<code>Writable</code> stream implementation. While this specific <code>Writable</code> stream instance 3973is not of any real particular usefulness, the example illustrates each of the 3974required elements of a custom <a href="#class-streamwritable"><code>Writable</code></a> stream instance:</p> 3975<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>); 3976 3977<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> { 3978 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 3979 <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>) { 3980 <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>)); 3981 } <span class="hljs-keyword">else</span> { 3982 <span class="hljs-title function_">callback</span>(); 3983 } 3984 } 3985}</code> <button class="copy-button">copy</button></pre> 3986<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> 3987<p>Decoding buffers is a common task, for instance, when using transformers whose 3988input is a string. This is not a trivial process when using multi-byte 3989characters encoding, such as UTF-8. The following example shows how to decode 3990multi-byte strings using <code>StringDecoder</code> and <a href="#class-streamwritable"><code>Writable</code></a>.</p> 3991<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>); 3992<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>); 3993 3994<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> { 3995 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 3996 <span class="hljs-variable language_">super</span>(options); 3997 <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>); 3998 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> = <span class="hljs-string">''</span>; 3999 } 4000 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4001 <span class="hljs-keyword">if</span> (encoding === <span class="hljs-string">'buffer'</span>) { 4002 chunk = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span>.<span class="hljs-title function_">write</span>(chunk); 4003 } 4004 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += chunk; 4005 <span class="hljs-title function_">callback</span>(); 4006 } 4007 <span class="hljs-title function_">_final</span>(<span class="hljs-params">callback</span>) { 4008 <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>(); 4009 <span class="hljs-title function_">callback</span>(); 4010 } 4011} 4012 4013<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>); 4014<span class="hljs-keyword">const</span> w = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringWritable</span>(); 4015 4016w.<span class="hljs-title function_">write</span>(<span class="hljs-string">'currency: '</span>); 4017w.<span class="hljs-title function_">write</span>(euro[<span class="hljs-number">0</span>]); 4018w.<span class="hljs-title function_">end</span>(euro[<span class="hljs-number">1</span>]); 4019 4020<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> 4021<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> 4022<p>The <code>stream.Readable</code> class is extended to implement a <a href="#class-streamreadable"><code>Readable</code></a> stream.</p> 4023<p>Custom <code>Readable</code> streams <em>must</em> call the <code>new stream.Readable([options])</code> 4024constructor and implement the <a href="#readable_readsize"><code>readable._read()</code></a> method.</p> 4025<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> 4026<div class="api_metadata"> 4027<details class="changelog"><summary>History</summary> 4028<table> 4029<tbody><tr><th>Version</th><th>Changes</th></tr> 4030<tr><td>v15.5.0</td> 4031<td><p>support passing in an AbortSignal.</p></td></tr> 4032<tr><td>v14.0.0</td> 4033<td><p>Change <code>autoDestroy</code> option default to <code>true</code>.</p></td></tr> 4034<tr><td>v11.2.0, v10.16.0</td> 4035<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> 4036</tbody></table> 4037</details> 4038</div> 4039<ul> 4040<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 4041<ul> 4042<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 4043in the internal buffer before ceasing to read from the underlying resource. 4044<strong>Default:</strong> <code>16384</code> (16 KiB), or <code>16</code> for <code>objectMode</code> streams.</li> 4045<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 4046strings using the specified encoding. <strong>Default:</strong> <code>null</code>.</li> 4047<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 4048as a stream of objects. Meaning that <a href="#readablereadsize"><code>stream.read(n)</code></a> returns 4049a single value instead of a <code>Buffer</code> of size <code>n</code>. <strong>Default:</strong> <code>false</code>.</li> 4050<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> 4051after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li> 4052<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> 4053method.</li> 4054<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 4055<a href="#readable_destroyerr-callback"><code>stream._destroy()</code></a> method.</li> 4056<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 4057<a href="#readable_constructcallback"><code>stream._construct()</code></a> method.</li> 4058<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 4059<code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>true</code>.</li> 4060<li><code>signal</code> <a href="globals.html#class-abortsignal" class="type"><AbortSignal></a> A signal representing possible cancellation.</li> 4061</ul> 4062</li> 4063</ul> 4064<!-- eslint-disable no-useless-constructor --> 4065<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>); 4066 4067<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> { 4068 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 4069 <span class="hljs-comment">// Calls the stream.Readable(options) constructor.</span> 4070 <span class="hljs-variable language_">super</span>(options); 4071 <span class="hljs-comment">// ...</span> 4072 } 4073}</code> <button class="copy-button">copy</button></pre> 4074<p>Or, when using pre-ES6 style constructors:</p> 4075<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>); 4076<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>); 4077 4078<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyReadable</span>(<span class="hljs-params">options</span>) { 4079 <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>)) 4080 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyReadable</span>(options); 4081 <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 4082} 4083util.<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> 4084<p>Or, using the simplified constructor approach:</p> 4085<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>); 4086 4087<span class="hljs-keyword">const</span> myReadable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({ 4088 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 4089 <span class="hljs-comment">// ...</span> 4090 }, 4091});</code> <button class="copy-button">copy</button></pre> 4092<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed 4093<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code> 4094on the readable created.</p> 4095<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>); 4096<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 4097<span class="hljs-keyword">const</span> read = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({ 4098 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 4099 <span class="hljs-comment">// ...</span> 4100 }, 4101 <span class="hljs-attr">signal</span>: controller.<span class="hljs-property">signal</span>, 4102}); 4103<span class="hljs-comment">// Later, abort the operation closing the stream</span> 4104controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre> 4105<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> 4106<div class="api_metadata"> 4107<span>Added in: v15.0.0</span> 4108</div> 4109<ul> 4110<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 4111argument) when the stream has finished initializing.</li> 4112</ul> 4113<p>The <code>_construct()</code> method MUST NOT be called directly. It may be implemented 4114by child classes, and if so, will be called by the internal <code>Readable</code> 4115class methods only.</p> 4116<p>This optional function will be scheduled in the next tick by the stream 4117constructor, delaying any <code>_read()</code> and <code>_destroy()</code> calls until <code>callback</code> is 4118called. This is useful to initialize state or asynchronously initialize 4119resources before the stream can be used.</p> 4120<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>); 4121<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 4122 4123<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> { 4124 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">filename</span>) { 4125 <span class="hljs-variable language_">super</span>(); 4126 <span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span> = filename; 4127 <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = <span class="hljs-literal">null</span>; 4128 } 4129 <span class="hljs-title function_">_construct</span>(<span class="hljs-params">callback</span>) { 4130 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> { 4131 <span class="hljs-keyword">if</span> (err) { 4132 <span class="hljs-title function_">callback</span>(err); 4133 } <span class="hljs-keyword">else</span> { 4134 <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = fd; 4135 <span class="hljs-title function_">callback</span>(); 4136 } 4137 }); 4138 } 4139 <span class="hljs-title function_">_read</span>(<span class="hljs-params">n</span>) { 4140 <span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(n); 4141 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> { 4142 <span class="hljs-keyword">if</span> (err) { 4143 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err); 4144 } <span class="hljs-keyword">else</span> { 4145 <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>); 4146 } 4147 }); 4148 } 4149 <span class="hljs-title function_">_destroy</span>(<span class="hljs-params">err, callback</span>) { 4150 <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>) { 4151 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)); 4152 } <span class="hljs-keyword">else</span> { 4153 <span class="hljs-title function_">callback</span>(err); 4154 } 4155 } 4156}</code> <button class="copy-button">copy</button></pre> 4157<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> 4158<div class="api_metadata"> 4159<span>Added in: v0.9.4</span> 4160</div> 4161<ul> 4162<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> 4163</ul> 4164<p>This function MUST NOT be called by application code directly. It should be 4165implemented by child classes, and called by the internal <code>Readable</code> class 4166methods only.</p> 4167<p>All <code>Readable</code> stream implementations must provide an implementation of the 4168<a href="#readable_readsize"><code>readable._read()</code></a> method to fetch data from the underlying resource.</p> 4169<p>When <a href="#readable_readsize"><code>readable._read()</code></a> is called, if data is available from the resource, 4170the implementation should begin pushing that data into the read queue using the 4171<a href="#readablepushchunk-encoding"><code>this.push(dataChunk)</code></a> method. <code>_read()</code> will be called again 4172after each call to <a href="#readablepushchunk-encoding"><code>this.push(dataChunk)</code></a> once the stream is 4173ready to accept more data. <code>_read()</code> may continue reading from the resource and 4174pushing data until <code>readable.push()</code> returns <code>false</code>. Only when <code>_read()</code> is 4175called again after it has stopped should it resume pushing additional data into 4176the queue.</p> 4177<p>Once the <a href="#readable_readsize"><code>readable._read()</code></a> method has been called, it will not be called 4178again until more data is pushed through the <a href="#readablepushchunk-encoding"><code>readable.push()</code></a> 4179method. Empty data such as empty buffers and strings will not cause 4180<a href="#readable_readsize"><code>readable._read()</code></a> to be called.</p> 4181<p>The <code>size</code> argument is advisory. For implementations where a "read" is a 4182single operation that returns data can use the <code>size</code> argument to determine how 4183much data to fetch. Other implementations may ignore this argument and simply 4184provide data whenever it becomes available. There is no need to "wait" until 4185<code>size</code> bytes are available before calling <a href="#readablepushchunk-encoding"><code>stream.push(chunk)</code></a>.</p> 4186<p>The <a href="#readable_readsize"><code>readable._read()</code></a> method is prefixed with an underscore because it is 4187internal to the class that defines it, and should never be called directly by 4188user programs.</p> 4189<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> 4190<div class="api_metadata"> 4191<span>Added in: v8.0.0</span> 4192</div> 4193<ul> 4194<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> 4195<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 4196argument.</li> 4197</ul> 4198<p>The <code>_destroy()</code> method is called by <a href="#readabledestroyerror"><code>readable.destroy()</code></a>. 4199It can be overridden by child classes but it <strong>must not</strong> be called directly.</p> 4200<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> 4201<div class="api_metadata"> 4202<details class="changelog"><summary>History</summary> 4203<table> 4204<tbody><tr><th>Version</th><th>Changes</th></tr> 4205<tr><td>v8.0.0</td> 4206<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 4207</tbody></table> 4208</details> 4209</div> 4210<ul> 4211<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 4212read queue. For streams not operating in object mode, <code>chunk</code> must be a 4213string, <code>Buffer</code> or <code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be 4214any JavaScript value.</li> 4215<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 4216<code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li> 4217<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 4218pushed; <code>false</code> otherwise.</li> 4219</ul> 4220<p>When <code>chunk</code> is a <code>Buffer</code>, <code>Uint8Array</code>, or <code>string</code>, the <code>chunk</code> of data will 4221be added to the internal queue for users of the stream to consume. 4222Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF), after which no 4223more data can be written.</p> 4224<p>When the <code>Readable</code> is operating in paused mode, the data added with 4225<code>readable.push()</code> can be read out by calling the 4226<a href="#readablereadsize"><code>readable.read()</code></a> method when the <a href="#event-readable"><code>'readable'</code></a> event is 4227emitted.</p> 4228<p>When the <code>Readable</code> is operating in flowing mode, the data added with 4229<code>readable.push()</code> will be delivered by emitting a <code>'data'</code> event.</p> 4230<p>The <code>readable.push()</code> method is designed to be as flexible as possible. For 4231example, when wrapping a lower-level source that provides some form of 4232pause/resume mechanism, and a data callback, the low-level source can be wrapped 4233by the custom <code>Readable</code> instance:</p> 4234<pre><code class="language-js"><span class="hljs-comment">// `_source` is an object with readStop() and readStart() methods,</span> 4235<span class="hljs-comment">// and an `ondata` member that gets called when it has data, and</span> 4236<span class="hljs-comment">// an `onend` member that gets called when the data is over.</span> 4237 4238<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> { 4239 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 4240 <span class="hljs-variable language_">super</span>(options); 4241 4242 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span> = <span class="hljs-title function_">getLowLevelSourceObject</span>(); 4243 4244 <span class="hljs-comment">// Every time there's data, push it into the internal buffer.</span> 4245 <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> { 4246 <span class="hljs-comment">// If push() returns false, then stop reading from source.</span> 4247 <span class="hljs-keyword">if</span> (!<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(chunk)) 4248 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-title function_">readStop</span>(); 4249 }; 4250 4251 <span class="hljs-comment">// When the source ends, push the EOF-signaling `null` chunk.</span> 4252 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-property">onend</span> = <span class="hljs-function">() =></span> { 4253 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>); 4254 }; 4255 } 4256 <span class="hljs-comment">// _read() will be called when the stream wants to pull more data in.</span> 4257 <span class="hljs-comment">// The advisory size argument is ignored in this case.</span> 4258 <span class="hljs-title function_">_read</span>(<span class="hljs-params">size</span>) { 4259 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-title function_">readStart</span>(); 4260 } 4261}</code> <button class="copy-button">copy</button></pre> 4262<p>The <code>readable.push()</code> method is used to push the content 4263into the internal buffer. It can be driven by the <a href="#readable_readsize"><code>readable._read()</code></a> method.</p> 4264<p>For streams not operating in object mode, if the <code>chunk</code> parameter of 4265<code>readable.push()</code> is <code>undefined</code>, it will be treated as empty string or 4266buffer. See <a href="#readablepush"><code>readable.push('')</code></a> for more information.</p> 4267<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> 4268<p>Errors occurring during processing of the <a href="#readable_readsize"><code>readable._read()</code></a> must be 4269propagated through the <a href="#readable_destroyerr-callback"><code>readable.destroy(err)</code></a> method. 4270Throwing an <code>Error</code> from within <a href="#readable_readsize"><code>readable._read()</code></a> or manually emitting an 4271<code>'error'</code> event results in undefined behavior.</p> 4272<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>); 4273 4274<span class="hljs-keyword">const</span> myReadable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({ 4275 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 4276 <span class="hljs-keyword">const</span> err = <span class="hljs-title function_">checkSomeErrorCondition</span>(); 4277 <span class="hljs-keyword">if</span> (err) { 4278 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err); 4279 } <span class="hljs-keyword">else</span> { 4280 <span class="hljs-comment">// Do some work.</span> 4281 } 4282 }, 4283});</code> <button class="copy-button">copy</button></pre> 4284<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> 4285 4286<p>The following is a basic example of a <code>Readable</code> stream that emits the numerals 4287from 1 to 1,000,000 in ascending order, and then ends.</p> 4288<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>); 4289 4290<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> { 4291 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">opt</span>) { 4292 <span class="hljs-variable language_">super</span>(opt); 4293 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_max</span> = <span class="hljs-number">1000000</span>; 4294 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_index</span> = <span class="hljs-number">1</span>; 4295 } 4296 4297 <span class="hljs-title function_">_read</span>(<span class="hljs-params"></span>) { 4298 <span class="hljs-keyword">const</span> i = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_index</span>++; 4299 <span class="hljs-keyword">if</span> (i > <span class="hljs-variable language_">this</span>.<span class="hljs-property">_max</span>) 4300 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>); 4301 <span class="hljs-keyword">else</span> { 4302 <span class="hljs-keyword">const</span> str = <span class="hljs-title class_">String</span>(i); 4303 <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>); 4304 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(buf); 4305 } 4306 } 4307}</code> <button class="copy-button">copy</button></pre> 4308<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> 4309<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 4310<a href="#class-streamwritable"><code>Writable</code></a>, such as a TCP socket connection.</p> 4311<p>Because JavaScript does not have support for multiple inheritance, the 4312<code>stream.Duplex</code> class is extended to implement a <a href="#class-streamduplex"><code>Duplex</code></a> stream (as opposed 4313to extending the <code>stream.Readable</code> <em>and</em> <code>stream.Writable</code> classes).</p> 4314<p>The <code>stream.Duplex</code> class prototypically inherits from <code>stream.Readable</code> and 4315parasitically from <code>stream.Writable</code>, but <code>instanceof</code> will work properly for 4316both 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 4317<code>stream.Writable</code>.</p> 4318<p>Custom <code>Duplex</code> streams <em>must</em> call the <code>new stream.Duplex([options])</code> 4319constructor and implement <em>both</em> the <a href="#readable_readsize"><code>readable._read()</code></a> and 4320<code>writable._write()</code> methods.</p> 4321<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> 4322<div class="api_metadata"> 4323<details class="changelog"><summary>History</summary> 4324<table> 4325<tbody><tr><th>Version</th><th>Changes</th></tr> 4326<tr><td>v8.4.0</td> 4327<td><p>The <code>readableHighWaterMark</code> and <code>writableHighWaterMark</code> options are supported now.</p></td></tr> 4328</tbody></table> 4329</details> 4330</div> 4331<ul> 4332<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> 4333constructors. Also has the following fields: 4334<ul> 4335<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 4336automatically end the writable side when the readable side ends. 4337<strong>Default:</strong> <code>true</code>.</li> 4338<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. 4339<strong>Default:</strong> <code>true</code>.</li> 4340<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. 4341<strong>Default:</strong> <code>true</code>.</li> 4342<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 4343stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li> 4344<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 4345stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li> 4346<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 4347of the stream. Has no effect if <code>highWaterMark</code> is provided.</li> 4348<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 4349of the stream. Has no effect if <code>highWaterMark</code> is provided.</li> 4350</ul> 4351</li> 4352</ul> 4353<!-- eslint-disable no-useless-constructor --> 4354<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>); 4355 4356<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> { 4357 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 4358 <span class="hljs-variable language_">super</span>(options); 4359 <span class="hljs-comment">// ...</span> 4360 } 4361}</code> <button class="copy-button">copy</button></pre> 4362<p>Or, when using pre-ES6 style constructors:</p> 4363<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>); 4364<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>); 4365 4366<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyDuplex</span>(<span class="hljs-params">options</span>) { 4367 <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>)) 4368 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyDuplex</span>(options); 4369 <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 4370} 4371util.<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> 4372<p>Or, using the simplified constructor approach:</p> 4373<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>); 4374 4375<span class="hljs-keyword">const</span> myDuplex = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Duplex</span>({ 4376 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 4377 <span class="hljs-comment">// ...</span> 4378 }, 4379 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4380 <span class="hljs-comment">// ...</span> 4381 }, 4382});</code> <button class="copy-button">copy</button></pre> 4383<p>When using pipeline:</p> 4384<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>); 4385<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>); 4386 4387<span class="hljs-title function_">pipeline</span>( 4388 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'object.json'</span>) 4389 .<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>), 4390 <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({ 4391 <span class="hljs-attr">decodeStrings</span>: <span class="hljs-literal">false</span>, <span class="hljs-comment">// Accept string input rather than Buffers</span> 4392 <span class="hljs-title function_">construct</span>(<span class="hljs-params">callback</span>) { 4393 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> = <span class="hljs-string">''</span>; 4394 <span class="hljs-title function_">callback</span>(); 4395 }, 4396 <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4397 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += chunk; 4398 <span class="hljs-title function_">callback</span>(); 4399 }, 4400 <span class="hljs-title function_">flush</span>(<span class="hljs-params">callback</span>) { 4401 <span class="hljs-keyword">try</span> { 4402 <span class="hljs-comment">// Make sure is valid json.</span> 4403 <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>); 4404 <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>); 4405 <span class="hljs-title function_">callback</span>(); 4406 } <span class="hljs-keyword">catch</span> (err) { 4407 <span class="hljs-title function_">callback</span>(err); 4408 } 4409 }, 4410 }), 4411 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'valid-object.json'</span>), 4412 <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 4413 <span class="hljs-keyword">if</span> (err) { 4414 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'failed'</span>, err); 4415 } <span class="hljs-keyword">else</span> { 4416 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'completed'</span>); 4417 } 4418 }, 4419);</code> <button class="copy-button">copy</button></pre> 4420<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> 4421<p>The following illustrates a simple example of a <code>Duplex</code> stream that wraps a 4422hypothetical lower-level source object to which data can be written, and 4423from which data can be read, albeit using an API that is not compatible with 4424Node.js streams. 4425The following illustrates a simple example of a <code>Duplex</code> stream that buffers 4426incoming written data via the <a href="#class-streamwritable"><code>Writable</code></a> interface that is read back out 4427via the <a href="#class-streamreadable"><code>Readable</code></a> interface.</p> 4428<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>); 4429<span class="hljs-keyword">const</span> kSource = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'source'</span>); 4430 4431<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> { 4432 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">source, options</span>) { 4433 <span class="hljs-variable language_">super</span>(options); 4434 <span class="hljs-variable language_">this</span>[kSource] = source; 4435 } 4436 4437 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4438 <span class="hljs-comment">// The underlying source only deals with strings.</span> 4439 <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(chunk)) 4440 chunk = chunk.<span class="hljs-title function_">toString</span>(); 4441 <span class="hljs-variable language_">this</span>[kSource].<span class="hljs-title function_">writeSomeData</span>(chunk); 4442 <span class="hljs-title function_">callback</span>(); 4443 } 4444 4445 <span class="hljs-title function_">_read</span>(<span class="hljs-params">size</span>) { 4446 <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> { 4447 <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)); 4448 }); 4449 } 4450}</code> <button class="copy-button">copy</button></pre> 4451<p>The most important aspect of a <code>Duplex</code> stream is that the <code>Readable</code> and 4452<code>Writable</code> sides operate independently of one another despite co-existing within 4453a single object instance.</p> 4454<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> 4455<p>For <code>Duplex</code> streams, <code>objectMode</code> can be set exclusively for either the 4456<code>Readable</code> or <code>Writable</code> side using the <code>readableObjectMode</code> and 4457<code>writableObjectMode</code> options respectively.</p> 4458<p>In the following example, for instance, a new <code>Transform</code> stream (which is a 4459type of <a href="#class-streamduplex"><code>Duplex</code></a> stream) is created that has an object mode <code>Writable</code> side 4460that accepts JavaScript numbers that are converted to hexadecimal strings on 4461the <code>Readable</code> side.</p> 4462<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>); 4463 4464<span class="hljs-comment">// All Transform streams are also Duplex Streams.</span> 4465<span class="hljs-keyword">const</span> myTransform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({ 4466 <span class="hljs-attr">writableObjectMode</span>: <span class="hljs-literal">true</span>, 4467 4468 <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4469 <span class="hljs-comment">// Coerce the chunk to a number if necessary.</span> 4470 chunk |= <span class="hljs-number">0</span>; 4471 4472 <span class="hljs-comment">// Transform the chunk into something else.</span> 4473 <span class="hljs-keyword">const</span> data = chunk.<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>); 4474 4475 <span class="hljs-comment">// Push the data onto the readable queue.</span> 4476 <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); 4477 }, 4478}); 4479 4480myTransform.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'ascii'</span>); 4481myTransform.<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)); 4482 4483myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">1</span>); 4484<span class="hljs-comment">// Prints: 01</span> 4485myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">10</span>); 4486<span class="hljs-comment">// Prints: 0a</span> 4487myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">100</span>); 4488<span class="hljs-comment">// Prints: 64</span></code> <button class="copy-button">copy</button></pre> 4489<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> 4490<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 4491in some way from the input. Examples include <a href="zlib.html">zlib</a> streams or <a href="crypto.html">crypto</a> 4492streams that compress, encrypt, or decrypt data.</p> 4493<p>There is no requirement that the output be the same size as the input, the same 4494number of chunks, or arrive at the same time. For example, a <code>Hash</code> stream will 4495only ever have a single chunk of output which is provided when the input is 4496ended. A <code>zlib</code> stream will produce output that is either much smaller or much 4497larger than its input.</p> 4498<p>The <code>stream.Transform</code> class is extended to implement a <a href="#class-streamtransform"><code>Transform</code></a> stream.</p> 4499<p>The <code>stream.Transform</code> class prototypically inherits from <code>stream.Duplex</code> and 4500implements its own versions of the <code>writable._write()</code> and 4501<a href="#readable_readsize"><code>readable._read()</code></a> methods. Custom <code>Transform</code> implementations <em>must</em> 4502implement the <a href="#transform_transformchunk-encoding-callback"><code>transform._transform()</code></a> method and <em>may</em> 4503also implement the <a href="#transform_flushcallback"><code>transform._flush()</code></a> method.</p> 4504<p>Care must be taken when using <code>Transform</code> streams in that data written to the 4505stream can cause the <code>Writable</code> side of the stream to become paused if the 4506output on the <code>Readable</code> side is not consumed.</p> 4507<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> 4508<ul> 4509<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> 4510constructors. Also has the following fields: 4511<ul> 4512<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 4513<a href="#transform_transformchunk-encoding-callback"><code>stream._transform()</code></a> method.</li> 4514<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> 4515method.</li> 4516</ul> 4517</li> 4518</ul> 4519<!-- eslint-disable no-useless-constructor --> 4520<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>); 4521 4522<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> { 4523 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 4524 <span class="hljs-variable language_">super</span>(options); 4525 <span class="hljs-comment">// ...</span> 4526 } 4527}</code> <button class="copy-button">copy</button></pre> 4528<p>Or, when using pre-ES6 style constructors:</p> 4529<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>); 4530<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>); 4531 4532<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyTransform</span>(<span class="hljs-params">options</span>) { 4533 <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>)) 4534 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyTransform</span>(options); 4535 <span class="hljs-title class_">Transform</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 4536} 4537util.<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> 4538<p>Or, using the simplified constructor approach:</p> 4539<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>); 4540 4541<span class="hljs-keyword">const</span> myTransform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({ 4542 <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 4543 <span class="hljs-comment">// ...</span> 4544 }, 4545});</code> <button class="copy-button">copy</button></pre> 4546<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> 4547<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 4548emitted after all data has been output, which occurs after the callback in 4549<a href="#transform_flushcallback"><code>transform._flush()</code></a> has been called. In the case of an error, 4550<code>'end'</code> should not be emitted.</p> 4551<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> 4552<p>The <a href="#event-finish"><code>'finish'</code></a> event is from the <code>stream.Writable</code> class. The <code>'finish'</code> 4553event is emitted after <a href="#writableendchunk-encoding-callback"><code>stream.end()</code></a> is called and all chunks 4554have been processed by <a href="#transform_transformchunk-encoding-callback"><code>stream._transform()</code></a>. In the case 4555of an error, <code>'finish'</code> should not be emitted.</p> 4556<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> 4557<ul> 4558<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 4559argument and data) to be called when remaining data has been flushed.</li> 4560</ul> 4561<p>This function MUST NOT be called by application code directly. It should be 4562implemented by child classes, and called by the internal <code>Readable</code> class 4563methods only.</p> 4564<p>In some cases, a transform operation may need to emit an additional bit of 4565data at the end of the stream. For example, a <code>zlib</code> compression stream will 4566store an amount of internal state used to optimally compress the output. When 4567the stream ends, however, that additional data needs to be flushed so that the 4568compressed data will be complete.</p> 4569<p>Custom <a href="#class-streamtransform"><code>Transform</code></a> implementations <em>may</em> implement the <code>transform._flush()</code> 4570method. This will be called when there is no more written data to be consumed, 4571but before the <a href="#event-end"><code>'end'</code></a> event is emitted signaling the end of the 4572<a href="#class-streamreadable"><code>Readable</code></a> stream.</p> 4573<p>Within the <code>transform._flush()</code> implementation, the <code>transform.push()</code> method 4574may be called zero or more times, as appropriate. The <code>callback</code> function must 4575be called when the flush operation is complete.</p> 4576<p>The <code>transform._flush()</code> method is prefixed with an underscore because it is 4577internal to the class that defines it, and should never be called directly by 4578user programs.</p> 4579<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> 4580<ul> 4581<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 4582the <code>string</code> passed to <a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>. If the stream's 4583<code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode, 4584the chunk will not be converted & will be whatever was passed to 4585<a href="#writablewritechunk-encoding-callback"><code>stream.write()</code></a>.</li> 4586<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 4587encoding type. If chunk is a buffer, then this is the special 4588value <code>'buffer'</code>. Ignore it in that case.</li> 4589<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 4590argument and data) to be called after the supplied <code>chunk</code> has been 4591processed.</li> 4592</ul> 4593<p>This function MUST NOT be called by application code directly. It should be 4594implemented by child classes, and called by the internal <code>Readable</code> class 4595methods only.</p> 4596<p>All <code>Transform</code> stream implementations must provide a <code>_transform()</code> 4597method to accept input and produce output. The <code>transform._transform()</code> 4598implementation handles the bytes being written, computes an output, then passes 4599that output off to the readable portion using the <code>transform.push()</code> method.</p> 4600<p>The <code>transform.push()</code> method may be called zero or more times to generate 4601output from a single input chunk, depending on how much is to be output 4602as a result of the chunk.</p> 4603<p>It is possible that no output is generated from any given chunk of input data.</p> 4604<p>The <code>callback</code> function must be called only when the current chunk is completely 4605consumed. The first argument passed to the <code>callback</code> must be an <code>Error</code> object 4606if an error occurred while processing the input or <code>null</code> otherwise. If a second 4607argument is passed to the <code>callback</code>, it will be forwarded on to the 4608<code>transform.push()</code> method, but only if the first argument is falsy. In other 4609words, the following are equivalent:</p> 4610<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>) { 4611 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(data); 4612 <span class="hljs-title function_">callback</span>(); 4613}; 4614 4615transform.<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>) { 4616 <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, data); 4617};</code> <button class="copy-button">copy</button></pre> 4618<p>The <code>transform._transform()</code> method is prefixed with an underscore because it 4619is internal to the class that defines it, and should never be called directly by 4620user programs.</p> 4621<p><code>transform._transform()</code> is never called in parallel; streams implement a 4622queue mechanism, and to receive the next chunk, <code>callback</code> must be 4623called, either synchronously or asynchronously.</p> 4624<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> 4625<p>The <code>stream.PassThrough</code> class is a trivial implementation of a <a href="#class-streamtransform"><code>Transform</code></a> 4626stream that simply passes the input bytes across to the output. Its purpose is 4627primarily for examples and testing, but there are some use cases where 4628<code>stream.PassThrough</code> is useful as a building block for novel sorts of streams.</p> 4629</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> 4630 4631<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> 4632<p>With the support of async generators and iterators in JavaScript, async 4633generators are effectively a first-class language-level stream construct at 4634this point.</p> 4635<p>Some common interop cases of using Node.js streams with async generators 4636and async iterators are provided below.</p> 4637<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> 4638<pre><code class="language-js">(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { 4639 <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) { 4640 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); 4641 } 4642})();</code> <button class="copy-button">copy</button></pre> 4643<p>Async iterators register a permanent error handler on the stream to prevent any 4644unhandled post-destroy errors.</p> 4645<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> 4646<p>A Node.js readable stream can be created from an asynchronous generator using 4647the <code>Readable.from()</code> utility method:</p> 4648<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>); 4649 4650<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 4651<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>; 4652 4653<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) { 4654 <span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>; 4655 <span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningFn</span>({ signal }); 4656 <span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>; 4657 <span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>; 4658} 4659 4660<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>()); 4661readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> { 4662 ac.<span class="hljs-title function_">abort</span>(); 4663}); 4664 4665readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 4666 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); 4667});</code> <button class="copy-button">copy</button></pre> 4668<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> 4669<p>When writing to a writable stream from an async iterator, ensure correct 4670handling of backpressure and errors. <a href="#streampipelinesource-transforms-destination-callback"><code>stream.pipeline()</code></a> abstracts away 4671the handling of backpressure and backpressure-related errors:</p> 4672<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>); 4673<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>); 4674<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>); 4675 4676<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./file'</span>); 4677 4678<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>(); 4679<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>; 4680 4681<span class="hljs-keyword">const</span> iterator = <span class="hljs-title function_">createIterator</span>({ signal }); 4682 4683<span class="hljs-comment">// Callback Pattern</span> 4684<span class="hljs-title function_">pipeline</span>(iterator, writable, <span class="hljs-function">(<span class="hljs-params">err, value</span>) =></span> { 4685 <span class="hljs-keyword">if</span> (err) { 4686 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err); 4687 } <span class="hljs-keyword">else</span> { 4688 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value, <span class="hljs-string">'value returned'</span>); 4689 } 4690}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> { 4691 ac.<span class="hljs-title function_">abort</span>(); 4692}); 4693 4694<span class="hljs-comment">// Promise Pattern</span> 4695<span class="hljs-title function_">pipelinePromise</span>(iterator, writable) 4696 .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">value</span>) =></span> { 4697 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value, <span class="hljs-string">'value returned'</span>); 4698 }) 4699 .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 4700 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err); 4701 ac.<span class="hljs-title function_">abort</span>(); 4702 });</code> <button class="copy-button">copy</button></pre> 4703 4704<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> 4705 4706<p>Prior to Node.js 0.10, the <code>Readable</code> stream interface was simpler, but also 4707less powerful and less useful.</p> 4708<ul> 4709<li>Rather than waiting for calls to the <a href="#readablereadsize"><code>stream.read()</code></a> method, 4710<a href="#event-data"><code>'data'</code></a> events would begin emitting immediately. Applications that 4711would need to perform some amount of work to decide how to handle data 4712were required to store read data into buffers so the data would not be lost.</li> 4713<li>The <a href="#readablepause"><code>stream.pause()</code></a> method was advisory, rather than 4714guaranteed. This meant that it was still necessary to be prepared to receive 4715<a href="#event-data"><code>'data'</code></a> events <em>even when the stream was in a paused state</em>.</li> 4716</ul> 4717<p>In Node.js 0.10, the <a href="#class-streamreadable"><code>Readable</code></a> class was added. For backward 4718compatibility with older Node.js programs, <code>Readable</code> streams switch into 4719"flowing mode" when a <a href="#event-data"><code>'data'</code></a> event handler is added, or when the 4720<a href="#readableresume"><code>stream.resume()</code></a> method is called. The effect is that, even 4721when not using the new <a href="#readablereadsize"><code>stream.read()</code></a> method and 4722<a href="#event-readable"><code>'readable'</code></a> event, it is no longer necessary to worry about losing 4723<a href="#event-data"><code>'data'</code></a> chunks.</p> 4724<p>While most applications will continue to function normally, this introduces an 4725edge case in the following conditions:</p> 4726<ul> 4727<li>No <a href="#event-data"><code>'data'</code></a> event listener is added.</li> 4728<li>The <a href="#readableresume"><code>stream.resume()</code></a> method is never called.</li> 4729<li>The stream is not piped to any writable destination.</li> 4730</ul> 4731<p>For example, consider the following code:</p> 4732<pre><code class="language-js"><span class="hljs-comment">// WARNING! BROKEN!</span> 4733net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> { 4734 4735 <span class="hljs-comment">// We add an 'end' listener, but never consume the data.</span> 4736 socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 4737 <span class="hljs-comment">// It will never get here.</span> 4738 socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'The message was received but was not processed.\n'</span>); 4739 }); 4740 4741}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code> <button class="copy-button">copy</button></pre> 4742<p>Prior to Node.js 0.10, the incoming message data would be simply discarded. 4743However, in Node.js 0.10 and beyond, the socket remains paused forever.</p> 4744<p>The workaround in this situation is to call the 4745<a href="#readableresume"><code>stream.resume()</code></a> method to begin the flow of data:</p> 4746<pre><code class="language-js"><span class="hljs-comment">// Workaround.</span> 4747net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> { 4748 socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 4749 socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'The message was received but was not processed.\n'</span>); 4750 }); 4751 4752 <span class="hljs-comment">// Start the flow of data, discarding it.</span> 4753 socket.<span class="hljs-title function_">resume</span>(); 4754}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code> <button class="copy-button">copy</button></pre> 4755<p>In addition to new <code>Readable</code> streams switching into flowing mode, 4756pre-0.10 style streams can be wrapped in a <code>Readable</code> class using the 4757<a href="#readablewrapstream"><code>readable.wrap()</code></a> method.</p> 4758<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> 4759<p>There are some cases where it is necessary to trigger a refresh of the 4760underlying readable stream mechanisms, without actually consuming any 4761data. In such cases, it is possible to call <code>readable.read(0)</code>, which will 4762always return <code>null</code>.</p> 4763<p>If the internal read buffer is below the <code>highWaterMark</code>, and the 4764stream is not currently reading, then calling <code>stream.read(0)</code> will trigger 4765a low-level <a href="#readable_readsize"><code>stream._read()</code></a> call.</p> 4766<p>While most applications will almost never need to do this, there are 4767situations within Node.js where this is done, particularly in the 4768<code>Readable</code> stream class internals.</p> 4769<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> 4770<p>Use of <code>readable.push('')</code> is not recommended.</p> 4771<p>Pushing a zero-byte string, <code>Buffer</code>, or <code>Uint8Array</code> to a stream that is not in 4772object mode has an interesting side effect. Because it <em>is</em> a call to 4773<a href="#readablepushchunk-encoding"><code>readable.push()</code></a>, the call will end the reading process. 4774However, because the argument is an empty string, no data is added to the 4775readable buffer so there is nothing for a user to consume.</p> 4776<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> 4777<p>The use of <code>readable.setEncoding()</code> will change the behavior of how the 4778<code>highWaterMark</code> operates in non-object mode.</p> 4779<p>Typically, the size of the current buffer is measured against the 4780<code>highWaterMark</code> in <em>bytes</em>. However, after <code>setEncoding()</code> is called, the 4781comparison function will begin to measure the buffer's size in <em>characters</em>.</p> 4782<p>This is not a problem in common cases with <code>latin1</code> or <code>ascii</code>. But it is 4783advised to be mindful about this behavior when working with strings that could 4784contain multi-byte characters.</p></section> 4785 <!-- API END --> 4786 </div> 4787 </div> 4788 </div> 4789</body> 4790</html> 4791