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="v14.21.2"> 7 <title>Stream | Node.js v14.21.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</head> 13<body class="alt apidoc" id="api-section-stream"> 14 <div id="content" class="clearfix"> 15 <div id="column2" class="interior"> 16 <div id="intro" class="interior"> 17 <a href="/" title="Go back to the home page"> 18 Node.js 19 </a> 20 </div> 21 <ul> 22<li><a href="documentation.html" class="nav-documentation">About this documentation</a></li> 23<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li> 24</ul> 25<hr class="line"> 26<ul> 27<li><a href="assert.html" class="nav-assert">Assertion testing</a></li> 28<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li> 29<li><a href="buffer.html" class="nav-buffer">Buffer</a></li> 30<li><a href="addons.html" class="nav-addons">C++ addons</a></li> 31<li><a href="n-api.html" class="nav-n-api">C/C++ addons with Node-API</a></li> 32<li><a href="embedding.html" class="nav-embedding">C++ embedder API</a></li> 33<li><a href="child_process.html" class="nav-child_process">Child processes</a></li> 34<li><a href="cluster.html" class="nav-cluster">Cluster</a></li> 35<li><a href="cli.html" class="nav-cli">Command-line options</a></li> 36<li><a href="console.html" class="nav-console">Console</a></li> 37<li><a href="corepack.html" class="nav-corepack">Corepack</a></li> 38<li><a href="crypto.html" class="nav-crypto">Crypto</a></li> 39<li><a href="debugger.html" class="nav-debugger">Debugger</a></li> 40<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> 41<li><a href="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</a></li> 42<li><a href="dns.html" class="nav-dns">DNS</a></li> 43<li><a href="domain.html" class="nav-domain">Domain</a></li> 44<li><a href="errors.html" class="nav-errors">Errors</a></li> 45<li><a href="events.html" class="nav-events">Events</a></li> 46<li><a href="fs.html" class="nav-fs">File system</a></li> 47<li><a href="globals.html" class="nav-globals">Globals</a></li> 48<li><a href="http.html" class="nav-http">HTTP</a></li> 49<li><a href="http2.html" class="nav-http2">HTTP/2</a></li> 50<li><a href="https.html" class="nav-https">HTTPS</a></li> 51<li><a href="inspector.html" class="nav-inspector">Inspector</a></li> 52<li><a href="intl.html" class="nav-intl">Internationalization</a></li> 53<li><a href="modules.html" class="nav-modules">Modules: CommonJS modules</a></li> 54<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li> 55<li><a href="module.html" class="nav-module">Modules: <code>module</code> API</a></li> 56<li><a href="packages.html" class="nav-packages">Modules: Packages</a></li> 57<li><a href="net.html" class="nav-net">Net</a></li> 58<li><a href="os.html" class="nav-os">OS</a></li> 59<li><a href="path.html" class="nav-path">Path</a></li> 60<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li> 61<li><a href="policy.html" class="nav-policy">Policies</a></li> 62<li><a href="process.html" class="nav-process">Process</a></li> 63<li><a href="punycode.html" class="nav-punycode">Punycode</a></li> 64<li><a href="querystring.html" class="nav-querystring">Query strings</a></li> 65<li><a href="readline.html" class="nav-readline">Readline</a></li> 66<li><a href="repl.html" class="nav-repl">REPL</a></li> 67<li><a href="report.html" class="nav-report">Report</a></li> 68<li><a href="stream.html" class="nav-stream active">Stream</a></li> 69<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li> 70<li><a href="timers.html" class="nav-timers">Timers</a></li> 71<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> 72<li><a href="tracing.html" class="nav-tracing">Trace events</a></li> 73<li><a href="tty.html" class="nav-tty">TTY</a></li> 74<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li> 75<li><a href="url.html" class="nav-url">URL</a></li> 76<li><a href="util.html" class="nav-util">Utilities</a></li> 77<li><a href="v8.html" class="nav-v8">V8</a></li> 78<li><a href="vm.html" class="nav-vm">VM</a></li> 79<li><a href="wasi.html" class="nav-wasi">WASI</a></li> 80<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li> 81<li><a href="zlib.html" class="nav-zlib">Zlib</a></li> 82</ul> 83<hr class="line"> 84<ul> 85<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li> 86</ul> 87 </div> 88 89 <div id="column1" data-id="stream" class="interior"> 90 <header> 91 <div class="header-container"> 92 <h1>Node.js v14.21.2 documentation</h1> 93 <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden> 94 <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24"> 95 <path fill="none" d="M0 0h24v24H0z" /> 96 <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"/> 97 <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"/> 98 </svg> 99 <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24"> 100 <path d="M0 0h24v24H0z" fill="none" /> 101 <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"/> 102 </svg> 103 </button> 104 </div> 105 <div id="gtoc"> 106 <ul> 107 <li> 108 <a href="index.html">Index</a> 109 </li> 110 <li> 111 <a href="all.html">View on single page</a> 112 </li> 113 <li> 114 <a href="stream.json">View as JSON</a> 115 </li> 116 117 <li class="version-picker"> 118 <a href="#">View another version <span>▼</span></a> 119 <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v19.x/api/stream.html">19.x</a></li> 120<li><a href="https://nodejs.org/docs/latest-v18.x/api/stream.html">18.x <b>LTS</b></a></li> 121<li><a href="https://nodejs.org/docs/latest-v17.x/api/stream.html">17.x</a></li> 122<li><a href="https://nodejs.org/docs/latest-v16.x/api/stream.html">16.x <b>LTS</b></a></li> 123<li><a href="https://nodejs.org/docs/latest-v15.x/api/stream.html">15.x</a></li> 124<li><a href="https://nodejs.org/docs/latest-v14.x/api/stream.html">14.x <b>LTS</b></a></li> 125<li><a href="https://nodejs.org/docs/latest-v13.x/api/stream.html">13.x</a></li> 126<li><a href="https://nodejs.org/docs/latest-v12.x/api/stream.html">12.x</a></li> 127<li><a href="https://nodejs.org/docs/latest-v11.x/api/stream.html">11.x</a></li> 128<li><a href="https://nodejs.org/docs/latest-v10.x/api/stream.html">10.x</a></li> 129<li><a href="https://nodejs.org/docs/latest-v9.x/api/stream.html">9.x</a></li> 130<li><a href="https://nodejs.org/docs/latest-v8.x/api/stream.html">8.x</a></li> 131<li><a href="https://nodejs.org/docs/latest-v7.x/api/stream.html">7.x</a></li> 132<li><a href="https://nodejs.org/docs/latest-v6.x/api/stream.html">6.x</a></li> 133<li><a href="https://nodejs.org/docs/latest-v5.x/api/stream.html">5.x</a></li> 134<li><a href="https://nodejs.org/docs/latest-v4.x/api/stream.html">4.x</a></li> 135<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/stream.html">0.12.x</a></li> 136<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/stream.html">0.10.x</a></li></ol> 137 </li> 138 139 <li class="edit_on_github"><a href="https://github.com/nodejs/node/edit/master/doc/api/stream.md">Edit on GitHub</a></li> 140 </ul> 141 </div> 142 <hr> 143 </header> 144 145 <details id="toc" open><summary>Table of contents</summary><ul> 146<li><span class="stability_2"><a href="#stream_stream">Stream</a></span> 147<ul> 148<li><a href="#stream_organization_of_this_document">Organization of this document</a></li> 149<li><a href="#stream_types_of_streams">Types of streams</a> 150<ul> 151<li><a href="#stream_object_mode">Object mode</a></li> 152<li><a href="#stream_buffering">Buffering</a></li> 153</ul> 154</li> 155<li><a href="#stream_api_for_stream_consumers">API for stream consumers</a> 156<ul> 157<li><a href="#stream_writable_streams">Writable streams</a> 158<ul> 159<li><a href="#stream_class_stream_writable">Class: <code>stream.Writable</code></a> 160<ul> 161<li><a href="#stream_event_close">Event: <code>'close'</code></a></li> 162<li><a href="#stream_event_drain">Event: <code>'drain'</code></a></li> 163<li><a href="#stream_event_error">Event: <code>'error'</code></a></li> 164<li><a href="#stream_event_finish">Event: <code>'finish'</code></a></li> 165<li><a href="#stream_event_pipe">Event: <code>'pipe'</code></a></li> 166<li><a href="#stream_event_unpipe">Event: <code>'unpipe'</code></a></li> 167<li><a href="#stream_writable_cork"><code>writable.cork()</code></a></li> 168<li><a href="#stream_writable_destroy_error"><code>writable.destroy([error])</code></a></li> 169<li><a href="#stream_writable_destroyed"><code>writable.destroyed</code></a></li> 170<li><a href="#stream_writable_end_chunk_encoding_callback"><code>writable.end([chunk[, encoding]][, callback])</code></a></li> 171<li><a href="#stream_writable_setdefaultencoding_encoding"><code>writable.setDefaultEncoding(encoding)</code></a></li> 172<li><a href="#stream_writable_uncork"><code>writable.uncork()</code></a></li> 173<li><a href="#stream_writable_writable"><code>writable.writable</code></a></li> 174<li><a href="#stream_writable_writableended"><code>writable.writableEnded</code></a></li> 175<li><a href="#stream_writable_writablecorked"><code>writable.writableCorked</code></a></li> 176<li><a href="#stream_writable_writablefinished"><code>writable.writableFinished</code></a></li> 177<li><a href="#stream_writable_writablehighwatermark"><code>writable.writableHighWaterMark</code></a></li> 178<li><a href="#stream_writable_writablelength"><code>writable.writableLength</code></a></li> 179<li><a href="#stream_writable_writableneeddrain"><code>writable.writableNeedDrain</code></a></li> 180<li><a href="#stream_writable_writableobjectmode"><code>writable.writableObjectMode</code></a></li> 181<li><a href="#stream_writable_write_chunk_encoding_callback"><code>writable.write(chunk[, encoding][, callback])</code></a></li> 182</ul> 183</li> 184</ul> 185</li> 186<li><a href="#stream_readable_streams">Readable streams</a> 187<ul> 188<li><a href="#stream_two_reading_modes">Two reading modes</a></li> 189<li><a href="#stream_three_states">Three states</a></li> 190<li><a href="#stream_choose_one_api_style">Choose one API style</a></li> 191<li><a href="#stream_class_stream_readable">Class: <code>stream.Readable</code></a> 192<ul> 193<li><a href="#stream_event_close_1">Event: <code>'close'</code></a></li> 194<li><a href="#stream_event_data">Event: <code>'data'</code></a></li> 195<li><a href="#stream_event_end">Event: <code>'end'</code></a></li> 196<li><a href="#stream_event_error_1">Event: <code>'error'</code></a></li> 197<li><a href="#stream_event_pause">Event: <code>'pause'</code></a></li> 198<li><a href="#stream_event_readable">Event: <code>'readable'</code></a></li> 199<li><a href="#stream_event_resume">Event: <code>'resume'</code></a></li> 200<li><a href="#stream_readable_destroy_error"><code>readable.destroy([error])</code></a></li> 201<li><a href="#stream_readable_destroyed"><code>readable.destroyed</code></a></li> 202<li><a href="#stream_readable_ispaused"><code>readable.isPaused()</code></a></li> 203<li><a href="#stream_readable_pause"><code>readable.pause()</code></a></li> 204<li><a href="#stream_readable_pipe_destination_options"><code>readable.pipe(destination[, options])</code></a></li> 205<li><a href="#stream_readable_read_size"><code>readable.read([size])</code></a></li> 206<li><a href="#stream_readable_readable"><code>readable.readable</code></a></li> 207<li><a href="#stream_readable_readabledidread"><code>readable.readableDidRead</code></a></li> 208<li><a href="#stream_readable_readableencoding"><code>readable.readableEncoding</code></a></li> 209<li><a href="#stream_readable_readableended"><code>readable.readableEnded</code></a></li> 210<li><a href="#stream_readable_readableflowing"><code>readable.readableFlowing</code></a></li> 211<li><a href="#stream_readable_readablehighwatermark"><code>readable.readableHighWaterMark</code></a></li> 212<li><a href="#stream_readable_readablelength"><code>readable.readableLength</code></a></li> 213<li><a href="#stream_readable_readableobjectmode"><code>readable.readableObjectMode</code></a></li> 214<li><a href="#stream_readable_resume"><code>readable.resume()</code></a></li> 215<li><a href="#stream_readable_setencoding_encoding"><code>readable.setEncoding(encoding)</code></a></li> 216<li><a href="#stream_readable_unpipe_destination"><code>readable.unpipe([destination])</code></a></li> 217<li><a href="#stream_readable_unshift_chunk_encoding"><code>readable.unshift(chunk[, encoding])</code></a></li> 218<li><a href="#stream_readable_wrap_stream"><code>readable.wrap(stream)</code></a></li> 219<li><a href="#stream_readable_symbol_asynciterator"><code>readable[Symbol.asyncIterator]()</code></a></li> 220</ul> 221</li> 222</ul> 223</li> 224<li><a href="#stream_duplex_and_transform_streams">Duplex and transform streams</a> 225<ul> 226<li><a href="#stream_class_stream_duplex">Class: <code>stream.Duplex</code></a></li> 227<li><a href="#stream_class_stream_transform">Class: <code>stream.Transform</code></a> 228<ul> 229<li><a href="#stream_transform_destroy_error"><code>transform.destroy([error])</code></a></li> 230</ul> 231</li> 232</ul> 233</li> 234<li><a href="#stream_stream_finished_stream_options_callback"><code>stream.finished(stream[, options], callback)</code></a></li> 235<li><a href="#stream_stream_pipeline_source_transforms_destination_callback"><code>stream.pipeline(source[, ...transforms], destination, callback)</code></a></li> 236<li><a href="#stream_stream_pipeline_streams_callback"><code>stream.pipeline(streams, callback)</code></a></li> 237<li><a href="#stream_stream_readable_from_iterable_options"><code>stream.Readable.from(iterable, [options])</code></a></li> 238</ul> 239</li> 240<li><a href="#stream_api_for_stream_implementers">API for stream implementers</a> 241<ul> 242<li><a href="#stream_simplified_construction">Simplified construction</a></li> 243<li><a href="#stream_implementing_a_writable_stream">Implementing a writable stream</a> 244<ul> 245<li><a href="#stream_new_stream_writable_options"><code>new stream.Writable([options])</code></a></li> 246<li><a href="#stream_writable_write_chunk_encoding_callback_1"><code>writable._write(chunk, encoding, callback)</code></a></li> 247<li><a href="#stream_writable_writev_chunks_callback"><code>writable._writev(chunks, callback)</code></a></li> 248<li><a href="#stream_writable_destroy_err_callback"><code>writable._destroy(err, callback)</code></a></li> 249<li><a href="#stream_writable_final_callback"><code>writable._final(callback)</code></a></li> 250<li><a href="#stream_errors_while_writing">Errors while writing</a></li> 251<li><a href="#stream_an_example_writable_stream">An example writable stream</a></li> 252<li><a href="#stream_decoding_buffers_in_a_writable_stream">Decoding buffers in a writable stream</a></li> 253</ul> 254</li> 255<li><a href="#stream_implementing_a_readable_stream">Implementing a readable stream</a> 256<ul> 257<li><a href="#stream_new_stream_readable_options"><code>new stream.Readable([options])</code></a></li> 258<li><a href="#stream_readable_read_size_1"><code>readable._read(size)</code></a></li> 259<li><a href="#stream_readable_destroy_err_callback"><code>readable._destroy(err, callback)</code></a></li> 260<li><a href="#stream_readable_push_chunk_encoding"><code>readable.push(chunk[, encoding])</code></a></li> 261<li><a href="#stream_errors_while_reading">Errors while reading</a></li> 262<li><a href="#stream_an_example_counting_stream">An example counting stream</a></li> 263</ul> 264</li> 265<li><a href="#stream_implementing_a_duplex_stream">Implementing a duplex stream</a> 266<ul> 267<li><a href="#stream_new_stream_duplex_options"><code>new stream.Duplex(options)</code></a></li> 268<li><a href="#stream_an_example_duplex_stream">An example duplex stream</a></li> 269<li><a href="#stream_object_mode_duplex_streams">Object mode duplex streams</a></li> 270</ul> 271</li> 272<li><a href="#stream_implementing_a_transform_stream">Implementing a transform stream</a> 273<ul> 274<li><a href="#stream_new_stream_transform_options"><code>new stream.Transform([options])</code></a></li> 275<li><a href="#stream_event_end_1">Event: <code>'end'</code></a></li> 276<li><a href="#stream_event_finish_1">Event: <code>'finish'</code></a></li> 277<li><a href="#stream_transform_flush_callback"><code>transform._flush(callback)</code></a></li> 278<li><a href="#stream_transform_transform_chunk_encoding_callback"><code>transform._transform(chunk, encoding, callback)</code></a></li> 279<li><a href="#stream_class_stream_passthrough">Class: <code>stream.PassThrough</code></a></li> 280</ul> 281</li> 282</ul> 283</li> 284<li><a href="#stream_additional_notes">Additional notes</a> 285<ul> 286<li><a href="#stream_streams_compatibility_with_async_generators_and_async_iterators">Streams compatibility with async generators and async iterators</a> 287<ul> 288<li><a href="#stream_consuming_readable_streams_with_async_iterators">Consuming readable streams with async iterators</a></li> 289<li><a href="#stream_creating_readable_streams_with_async_generators">Creating readable streams with async generators</a></li> 290<li><a href="#stream_piping_to_writable_streams_from_async_iterators">Piping to writable streams from async iterators</a></li> 291</ul> 292</li> 293<li><a href="#stream_compatibility_with_older_node_js_versions">Compatibility with older Node.js versions</a></li> 294<li><a href="#stream_readable_read_0"><code>readable.read(0)</code></a></li> 295<li><a href="#stream_readable_push"><code>readable.push('')</code></a></li> 296<li><a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li> 297</ul> 298</li> 299</ul> 300</li> 301</ul></details> 302 303 <div id="apicontent"> 304 <h2>Stream<a class="srclink" href="https://github.com/nodejs/node/blob/92caea621d0fea47ef5af0b3dda427ac2fe2df3f/lib/stream.js#L28">[src]</a><span><a class="mark" href="#stream_stream" id="stream_stream">#</a></span></h2> 305 306<p></p><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> 307<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v14.21.2/lib/stream.js">lib/stream.js</a></p> 308<p>A stream is an abstract interface for working with streaming data in Node.js. 309The <code>stream</code> module provides an API for implementing the stream interface.</p> 310<p>There are many stream objects provided by Node.js. For instance, a 311<a href="http.html#http_class_http_incomingmessage">request to an HTTP server</a> and <a href="process.html#process_process_stdout"><code>process.stdout</code></a> 312are both stream instances.</p> 313<p>Streams can be readable, writable, or both. All streams are instances of 314<a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a>.</p> 315<p>To access the <code>stream</code> module:</p> 316<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-built_in">require</span>(<span class="hljs-string">'stream'</span>);</code></pre> 317<p>The <code>stream</code> module is useful for creating new types of stream instances. It is 318usually not necessary to use the <code>stream</code> module to consume streams.</p> 319<section><h3>Organization of this document<span><a class="mark" href="#stream_organization_of_this_document" id="stream_organization_of_this_document">#</a></span></h3> 320<p>This document contains two primary sections and a third section for notes. The 321first section explains how to use existing streams within an application. The 322second section explains how to create new types of streams.</p> 323</section><section><h3>Types of streams<span><a class="mark" href="#stream_types_of_streams" id="stream_types_of_streams">#</a></span></h3> 324<p>There are four fundamental stream types within Node.js:</p> 325<ul> 326<li><a href="#stream_class_stream_writable"><code>Writable</code></a>: streams to which data can be written (for example, 327<a href="fs.html#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a>).</li> 328<li><a href="#stream_class_stream_readable"><code>Readable</code></a>: streams from which data can be read (for example, 329<a href="fs.html#fs_fs_createreadstream_path_options"><code>fs.createReadStream()</code></a>).</li> 330<li><a href="#stream_class_stream_duplex"><code>Duplex</code></a>: streams that are both <code>Readable</code> and <code>Writable</code> (for example, 331<a href="net.html#net_class_net_socket"><code>net.Socket</code></a>).</li> 332<li><a href="#stream_class_stream_transform"><code>Transform</code></a>: <code>Duplex</code> streams that can modify or transform the data as it 333is written and read (for example, <a href="zlib.html#zlib_zlib_createdeflate_options"><code>zlib.createDeflate()</code></a>).</li> 334</ul> 335<p>Additionally, this module includes the utility functions 336<a href="#stream_stream_pipeline_source_transforms_destination_callback"><code>stream.pipeline()</code></a>, <a href="#stream_stream_finished_stream_options_callback"><code>stream.finished()</code></a> and 337<a href="#stream_stream_readable_from_iterable_options"><code>stream.Readable.from()</code></a>.</p> 338<h4>Object mode<span><a class="mark" href="#stream_object_mode" id="stream_object_mode">#</a></span></h4> 339<p>All streams created by Node.js APIs operate exclusively on strings and <code>Buffer</code> 340(or <code>Uint8Array</code>) objects. It is possible, however, for stream implementations 341to work with other types of JavaScript values (with the exception of <code>null</code>, 342which serves a special purpose within streams). Such streams are considered to 343operate in "object mode".</p> 344<p>Stream instances are switched into object mode using the <code>objectMode</code> option 345when the stream is created. Attempting to switch an existing stream into 346object mode is not safe.</p> 347<h4>Buffering<span><a class="mark" href="#stream_buffering" id="stream_buffering">#</a></span></h4> 348 349<p>Both <a href="#stream_class_stream_writable"><code>Writable</code></a> and <a href="#stream_class_stream_readable"><code>Readable</code></a> streams will store data in an internal 350buffer.</p> 351<p>The amount of data potentially buffered depends on the <code>highWaterMark</code> option 352passed into the stream's constructor. For normal streams, the <code>highWaterMark</code> 353option specifies a <a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding">total number of bytes</a>. For streams operating 354in object mode, the <code>highWaterMark</code> specifies a total number of objects.</p> 355<p>Data is buffered in <code>Readable</code> streams when the implementation calls 356<a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not 357call <a href="#stream_readable_read_size"><code>stream.read()</code></a>, the data will sit in the internal 358queue until it is consumed.</p> 359<p>Once the total size of the internal read buffer reaches the threshold specified 360by <code>highWaterMark</code>, the stream will temporarily stop reading data from the 361underlying resource until the data currently buffered can be consumed (that is, 362the stream will stop calling the internal <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> method that is 363used to fill the read buffer).</p> 364<p>Data is buffered in <code>Writable</code> streams when the 365<a href="#stream_writable_write_chunk_encoding_callback"><code>writable.write(chunk)</code></a> method is called repeatedly. While the 366total size of the internal write buffer is below the threshold set by 367<code>highWaterMark</code>, calls to <code>writable.write()</code> will return <code>true</code>. Once 368the size of the internal buffer reaches or exceeds the <code>highWaterMark</code>, <code>false</code> 369will be returned.</p> 370<p>A key goal of the <code>stream</code> API, particularly the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method, 371is to limit the buffering of data to acceptable levels such that sources and 372destinations of differing speeds will not overwhelm the available memory.</p> 373<p>The <code>highWaterMark</code> option is a threshold, not a limit: it dictates the amount 374of data that a stream buffers before it stops asking for more data. It does not 375enforce a strict memory limitation in general. Specific stream implementations 376may choose to enforce stricter limits but doing so is optional.</p> 377<p>Because <a href="#stream_class_stream_duplex"><code>Duplex</code></a> and <a href="#stream_class_stream_transform"><code>Transform</code></a> streams are both <code>Readable</code> and 378<code>Writable</code>, each maintains <em>two</em> separate internal buffers used for reading and 379writing, allowing each side to operate independently of the other while 380maintaining an appropriate and efficient flow of data. For example, 381<a href="net.html#net_class_net_socket"><code>net.Socket</code></a> instances are <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams whose <code>Readable</code> side allows 382consumption of data received <em>from</em> the socket and whose <code>Writable</code> side allows 383writing data <em>to</em> the socket. Because data may be written to the socket at a 384faster or slower rate than data is received, each side should 385operate (and buffer) independently of the other.</p> 386<p>The mechanics of the internal buffering are an internal implementation detail 387and may be changed at any time. However, for certain advanced implementations, 388the internal buffers can be retrieved using <code>writable.writableBuffer</code> or 389<code>readable.readableBuffer</code>. Use of these undocumented properties is discouraged.</p> 390</section><section><h3>API for stream consumers<span><a class="mark" href="#stream_api_for_stream_consumers" id="stream_api_for_stream_consumers">#</a></span></h3> 391 392<p>Almost all Node.js applications, no matter how simple, use streams in some 393manner. The following is an example of using streams in a Node.js application 394that implements an HTTP server:</p> 395<pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>); 396 397<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> { 398 <span class="hljs-comment">// `req` is an http.IncomingMessage, which is a readable stream.</span> 399 <span class="hljs-comment">// `res` is an http.ServerResponse, which is a writable stream.</span> 400 401 <span class="hljs-keyword">let</span> body = <span class="hljs-string">''</span>; 402 <span class="hljs-comment">// Get the data as utf8 strings.</span> 403 <span class="hljs-comment">// If an encoding is not set, Buffer objects will be received.</span> 404 req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); 405 406 <span class="hljs-comment">// Readable streams emit 'data' events once a listener is added.</span> 407 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> { 408 body += chunk; 409 }); 410 411 <span class="hljs-comment">// The 'end' event indicates that the entire body has been received.</span> 412 req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 413 <span class="hljs-keyword">try</span> { 414 <span class="hljs-keyword">const</span> data = <span class="hljs-variable constant_">JSON</span>.<span class="hljs-title function_">parse</span>(body); 415 <span class="hljs-comment">// Write back something interesting to the user:</span> 416 res.<span class="hljs-title function_">write</span>(<span class="hljs-keyword">typeof</span> data); 417 res.<span class="hljs-title function_">end</span>(); 418 } <span class="hljs-keyword">catch</span> (er) { 419 <span class="hljs-comment">// uh oh! bad json!</span> 420 res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">400</span>; 421 <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>); 422 } 423 }); 424}); 425 426server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>); 427 428<span class="hljs-comment">// $ curl localhost:1337 -d "{}"</span> 429<span class="hljs-comment">// object</span> 430<span class="hljs-comment">// $ curl localhost:1337 -d "\"foo\""</span> 431<span class="hljs-comment">// string</span> 432<span class="hljs-comment">// $ curl localhost:1337 -d "not json"</span> 433<span class="hljs-comment">// error: Unexpected token o in JSON at position 1</span></code></pre> 434<p><a href="#stream_class_stream_writable"><code>Writable</code></a> streams (such as <code>res</code> in the example) expose methods such as 435<code>write()</code> and <code>end()</code> that are used to write data onto the stream.</p> 436<p><a href="#stream_class_stream_readable"><code>Readable</code></a> streams use the <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> API for notifying application 437code when data is available to be read off the stream. That available data can 438be read from the stream in multiple ways.</p> 439<p>Both <a href="#stream_class_stream_writable"><code>Writable</code></a> and <a href="#stream_class_stream_readable"><code>Readable</code></a> streams use the <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> API in 440various ways to communicate the current state of the stream.</p> 441<p><a href="#stream_class_stream_duplex"><code>Duplex</code></a> and <a href="#stream_class_stream_transform"><code>Transform</code></a> streams are both <a href="#stream_class_stream_writable"><code>Writable</code></a> and 442<a href="#stream_class_stream_readable"><code>Readable</code></a>.</p> 443<p>Applications that are either writing data to or consuming data from a stream 444are not required to implement the stream interfaces directly and will generally 445have no reason to call <code>require('stream')</code>.</p> 446<p>Developers wishing to implement new types of streams should refer to the 447section <a href="#stream_api_for_stream_implementers">API for stream implementers</a>.</p> 448<h4>Writable streams<span><a class="mark" href="#stream_writable_streams" id="stream_writable_streams">#</a></span></h4> 449<p>Writable streams are an abstraction for a <em>destination</em> to which data is 450written.</p> 451<p>Examples of <a href="#stream_class_stream_writable"><code>Writable</code></a> streams include:</p> 452<ul> 453<li><a href="http.html#http_class_http_clientrequest">HTTP requests, on the client</a></li> 454<li><a href="http.html#http_class_http_serverresponse">HTTP responses, on the server</a></li> 455<li><a href="fs.html#fs_class_fs_writestream">fs write streams</a></li> 456<li><a href="zlib.html">zlib streams</a></li> 457<li><a href="crypto.html">crypto streams</a></li> 458<li><a href="net.html#net_class_net_socket">TCP sockets</a></li> 459<li><a href="child_process.html#child_process_subprocess_stdin">child process stdin</a></li> 460<li><a href="process.html#process_process_stdout"><code>process.stdout</code></a>, <a href="process.html#process_process_stderr"><code>process.stderr</code></a></li> 461</ul> 462<p>Some of these examples are actually <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams that implement the 463<a href="#stream_class_stream_writable"><code>Writable</code></a> interface.</p> 464<p>All <a href="#stream_class_stream_writable"><code>Writable</code></a> streams implement the interface defined by the 465<code>stream.Writable</code> class.</p> 466<p>While specific instances of <a href="#stream_class_stream_writable"><code>Writable</code></a> streams may differ in various ways, 467all <code>Writable</code> streams follow the same fundamental usage pattern as illustrated 468in the example below:</p> 469<pre><code class="language-js"><span class="hljs-keyword">const</span> myStream = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 470myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data'</span>); 471myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some more data'</span>); 472myStream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'done writing data'</span>);</code></pre> 473<h5>Class: <code>stream.Writable</code><span><a class="mark" href="#stream_class_stream_writable" id="stream_class_stream_writable">#</a></span></h5> 474<div class="api_metadata"> 475<span>Added in: v0.9.4</span> 476</div> 477 478<h6>Event: <code>'close'</code><span><a class="mark" href="#stream_event_close" id="stream_event_close">#</a></span></h6> 479<div class="api_metadata"> 480<details class="changelog"><summary>History</summary> 481<table> 482<tbody><tr><th>Version</th><th>Changes</th></tr> 483<tr><td>v10.0.0</td> 484<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> 485<tr><td>v0.9.4</td> 486<td><p><span>Added in: v0.9.4</span></p></td></tr> 487</tbody></table> 488</details> 489</div> 490<p>The <code>'close'</code> event is emitted when the stream and any of its underlying 491resources (a file descriptor, for example) have been closed. The event indicates 492that no more events will be emitted, and no further computation will occur.</p> 493<p>A <a href="#stream_class_stream_writable"><code>Writable</code></a> stream will always emit the <code>'close'</code> event if it is 494created with the <code>emitClose</code> option.</p> 495<h6>Event: <code>'drain'</code><span><a class="mark" href="#stream_event_drain" id="stream_event_drain">#</a></span></h6> 496<div class="api_metadata"> 497<span>Added in: v0.9.4</span> 498</div> 499<p>If a call to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(chunk)</code></a> returns <code>false</code>, the 500<code>'drain'</code> event will be emitted when it is appropriate to resume writing data 501to the stream.</p> 502<pre><code class="language-js"><span class="hljs-comment">// Write the data to the supplied writable stream one million times.</span> 503<span class="hljs-comment">// Be attentive to back-pressure.</span> 504<span class="hljs-keyword">function</span> <span class="hljs-title function_">writeOneMillionTimes</span>(<span class="hljs-params">writer, data, encoding, callback</span>) { 505 <span class="hljs-keyword">let</span> i = <span class="hljs-number">1000000</span>; 506 <span class="hljs-title function_">write</span>(); 507 <span class="hljs-keyword">function</span> <span class="hljs-title function_">write</span>(<span class="hljs-params"></span>) { 508 <span class="hljs-keyword">let</span> ok = <span class="hljs-literal">true</span>; 509 <span class="hljs-keyword">do</span> { 510 i--; 511 <span class="hljs-keyword">if</span> (i === <span class="hljs-number">0</span>) { 512 <span class="hljs-comment">// Last time!</span> 513 writer.<span class="hljs-title function_">write</span>(data, encoding, callback); 514 } <span class="hljs-keyword">else</span> { 515 <span class="hljs-comment">// See if we should continue, or wait.</span> 516 <span class="hljs-comment">// Don't pass the callback, because we're not done yet.</span> 517 ok = writer.<span class="hljs-title function_">write</span>(data, encoding); 518 } 519 } <span class="hljs-keyword">while</span> (i > <span class="hljs-number">0</span> && ok); 520 <span class="hljs-keyword">if</span> (i > <span class="hljs-number">0</span>) { 521 <span class="hljs-comment">// Had to stop early!</span> 522 <span class="hljs-comment">// Write some more once it drains.</span> 523 writer.<span class="hljs-title function_">once</span>(<span class="hljs-string">'drain'</span>, write); 524 } 525 } 526}</code></pre> 527<h6>Event: <code>'error'</code><span><a class="mark" href="#stream_event_error" id="stream_event_error">#</a></span></h6> 528<div class="api_metadata"> 529<span>Added in: v0.9.4</span> 530</div> 531<ul> 532<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 533</ul> 534<p>The <code>'error'</code> event is emitted if an error occurred while writing or piping 535data. The listener callback is passed a single <code>Error</code> argument when called.</p> 536<p>The stream is closed when the <code>'error'</code> event is emitted unless the 537<a href="#stream_new_stream_writable_options"><code>autoDestroy</code></a> option was set to <code>false</code> when creating the 538stream.</p> 539<p>After <code>'error'</code>, no further events other than <code>'close'</code> <em>should</em> be emitted 540(including <code>'error'</code> events).</p> 541<h6>Event: <code>'finish'</code><span><a class="mark" href="#stream_event_finish" id="stream_event_finish">#</a></span></h6> 542<div class="api_metadata"> 543<span>Added in: v0.9.4</span> 544</div> 545<p>The <code>'finish'</code> event is emitted after the <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> method 546has been called, and all data has been flushed to the underlying system.</p> 547<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 548<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++) { 549 writer.<span class="hljs-title function_">write</span>(<span class="hljs-string">`hello, #<span class="hljs-subst">${i}</span>!\n`</span>); 550} 551writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'finish'</span>, <span class="hljs-function">() =></span> { 552 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'All writes are now complete.'</span>); 553}); 554writer.<span class="hljs-title function_">end</span>(<span class="hljs-string">'This is the end\n'</span>);</code></pre> 555<h6>Event: <code>'pipe'</code><span><a class="mark" href="#stream_event_pipe" id="stream_event_pipe">#</a></span></h6> 556<div class="api_metadata"> 557<span>Added in: v0.9.4</span> 558</div> 559<ul> 560<li><code>src</code> <a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a> source stream that is piping to this writable</li> 561</ul> 562<p>The <code>'pipe'</code> event is emitted when the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method is called on 563a readable stream, adding this writable to its set of destinations.</p> 564<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 565<span class="hljs-keyword">const</span> reader = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 566writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'pipe'</span>, <span class="hljs-function">(<span class="hljs-params">src</span>) =></span> { 567 <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>); 568 assert.<span class="hljs-title function_">equal</span>(src, reader); 569}); 570reader.<span class="hljs-title function_">pipe</span>(writer);</code></pre> 571<h6>Event: <code>'unpipe'</code><span><a class="mark" href="#stream_event_unpipe" id="stream_event_unpipe">#</a></span></h6> 572<div class="api_metadata"> 573<span>Added in: v0.9.4</span> 574</div> 575<ul> 576<li><code>src</code> <a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a> The source stream that 577<a href="#stream_readable_unpipe_destination">unpiped</a> this writable</li> 578</ul> 579<p>The <code>'unpipe'</code> event is emitted when the <a href="#stream_readable_unpipe_destination"><code>stream.unpipe()</code></a> method is called 580on a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream, removing this <a href="#stream_class_stream_writable"><code>Writable</code></a> from its set of 581destinations.</p> 582<p>This is also emitted in case this <a href="#stream_class_stream_writable"><code>Writable</code></a> stream emits an error when a 583<a href="#stream_class_stream_readable"><code>Readable</code></a> stream pipes into it.</p> 584<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>(); 585<span class="hljs-keyword">const</span> reader = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 586writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unpipe'</span>, <span class="hljs-function">(<span class="hljs-params">src</span>) =></span> { 587 <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>); 588 assert.<span class="hljs-title function_">equal</span>(src, reader); 589}); 590reader.<span class="hljs-title function_">pipe</span>(writer); 591reader.<span class="hljs-title function_">unpipe</span>(writer);</code></pre> 592<h6><code>writable.cork()</code><span><a class="mark" href="#stream_writable_cork" id="stream_writable_cork">#</a></span></h6> 593<div class="api_metadata"> 594<span>Added in: v0.11.2</span> 595</div> 596<p>The <code>writable.cork()</code> method forces all written data to be buffered in memory. 597The buffered data will be flushed when either the <a href="#stream_writable_uncork"><code>stream.uncork()</code></a> or 598<a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> methods are called.</p> 599<p>The primary intent of <code>writable.cork()</code> is to accommodate a situation in which 600several small chunks are written to the stream in rapid succession. Instead of 601immediately forwarding them to the underlying destination, <code>writable.cork()</code> 602buffers all the chunks until <code>writable.uncork()</code> is called, which will pass them 603all to <code>writable._writev()</code>, if present. This prevents a head-of-line blocking 604situation where data is being buffered while waiting for the first small chunk 605to be processed. However, use of <code>writable.cork()</code> without implementing 606<code>writable._writev()</code> may have an adverse effect on throughput.</p> 607<p>See also: <a href="#stream_writable_uncork"><code>writable.uncork()</code></a>, <a href="#stream_writable_writev_chunks_callback"><code>writable._writev()</code></a>.</p> 608<h6><code>writable.destroy([error])</code><span><a class="mark" href="#stream_writable_destroy_error" id="stream_writable_destroy_error">#</a></span></h6> 609<div class="api_metadata"> 610<details class="changelog"><summary>History</summary> 611<table> 612<tbody><tr><th>Version</th><th>Changes</th></tr> 613<tr><td>v14.0.0</td> 614<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr> 615<tr><td>v8.0.0</td> 616<td><p><span>Added in: v8.0.0</span></p></td></tr> 617</tbody></table> 618</details> 619</div> 620<ul> 621<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> 622<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 623</ul> 624<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code> 625event (unless <code>emitClose</code> is set to <code>false</code>). After this call, the writable 626stream has ended and subsequent calls to <code>write()</code> or <code>end()</code> will result in 627an <code>ERR_STREAM_DESTROYED</code> error. 628This is a destructive and immediate way to destroy a stream. Previous calls to 629<code>write()</code> may not have drained, and may trigger an <code>ERR_STREAM_DESTROYED</code> error. 630Use <code>end()</code> instead of destroy if data should flush before close, or wait for 631the <code>'drain'</code> event before destroying the stream.</p> 632 633<pre><input class="js-flavor-selector" type="checkbox" checked aria-label="Show modern ES modules syntax"><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">'stream'</span>); 634 635<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 636 637<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>); 638myStream.<span class="hljs-title function_">destroy</span>(fooErr); 639myStream.<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></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">'stream'</span>); 640 641<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 642 643myStream.<span class="hljs-title function_">destroy</span>(); 644myStream.<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></pre> 645<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">'stream'</span>); 646 647<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 648myStream.<span class="hljs-title function_">destroy</span>(); 649 650myStream.<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>)); 651<span class="hljs-comment">// ERR_STREAM_DESTROYED</span></code></pre> 652<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no 653further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p> 654<p>Implementors should not override this method, 655but instead implement <a href="#stream_writable_destroy_err_callback"><code>writable._destroy()</code></a>.</p> 656<h6><code>writable.destroyed</code><span><a class="mark" href="#stream_writable_destroyed" id="stream_writable_destroyed">#</a></span></h6> 657<div class="api_metadata"> 658<span>Added in: v8.0.0</span> 659</div> 660<ul> 661<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 662</ul> 663<p>Is <code>true</code> after <a href="#stream_writable_destroy_error"><code>writable.destroy()</code></a> has been called.</p> 664<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">'stream'</span>); 665 666<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 667 668<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> 669myStream.<span class="hljs-title function_">destroy</span>(); 670<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></pre> 671<h6><code>writable.end([chunk[, encoding]][, callback])</code><span><a class="mark" href="#stream_writable_end_chunk_encoding_callback" id="stream_writable_end_chunk_encoding_callback">#</a></span></h6> 672<div class="api_metadata"> 673<details class="changelog"><summary>History</summary> 674<table> 675<tbody><tr><th>Version</th><th>Changes</th></tr> 676<tr><td>v14.0.0</td> 677<td><p>The <code>callback</code> is invoked if 'finish' or 'error' is emitted.</p></td></tr> 678<tr><td>v10.0.0</td> 679<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr> 680<tr><td>v8.0.0</td> 681<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 682<tr><td>v0.9.4</td> 683<td><p><span>Added in: v0.9.4</span></p></td></tr> 684</tbody></table> 685</details> 686</div> 687<ul> 688<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#buffer_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 689not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or 690<code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value 691other than <code>null</code>.</li> 692<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> 693<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional callback for when the stream finishes 694or errors</li> 695<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 696</ul> 697<p>Calling the <code>writable.end()</code> method signals that no more data will be written 698to the <a href="#stream_class_stream_writable"><code>Writable</code></a>. The optional <code>chunk</code> and <code>encoding</code> arguments allow one 699final additional chunk of data to be written immediately before closing the 700stream. If provided, the optional <code>callback</code> function is attached as a listener 701for the <a href="#stream_event_finish"><code>'finish'</code></a> and the <code>'error'</code> event.</p> 702<p>Calling the <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> method after calling 703<a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> will raise an error.</p> 704<pre><code class="language-js"><span class="hljs-comment">// Write 'hello, ' and then end with 'world!'.</span> 705<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); 706<span class="hljs-keyword">const</span> file = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'example.txt'</span>); 707file.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello, '</span>); 708file.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world!'</span>); 709<span class="hljs-comment">// Writing more now is not allowed!</span></code></pre> 710<h6><code>writable.setDefaultEncoding(encoding)</code><span><a class="mark" href="#stream_writable_setdefaultencoding_encoding" id="stream_writable_setdefaultencoding_encoding">#</a></span></h6> 711<div class="api_metadata"> 712<details class="changelog"><summary>History</summary> 713<table> 714<tbody><tr><th>Version</th><th>Changes</th></tr> 715<tr><td>v6.1.0</td> 716<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr> 717<tr><td>v0.11.15</td> 718<td><p><span>Added in: v0.11.15</span></p></td></tr> 719</tbody></table> 720</details> 721</div> 722<ul> 723<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> 724<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 725</ul> 726<p>The <code>writable.setDefaultEncoding()</code> method sets the default <code>encoding</code> for a 727<a href="#stream_class_stream_writable"><code>Writable</code></a> stream.</p> 728<h6><code>writable.uncork()</code><span><a class="mark" href="#stream_writable_uncork" id="stream_writable_uncork">#</a></span></h6> 729<div class="api_metadata"> 730<span>Added in: v0.11.2</span> 731</div> 732<p>The <code>writable.uncork()</code> method flushes all data buffered since 733<a href="#stream_writable_cork"><code>stream.cork()</code></a> was called.</p> 734<p>When using <a href="#stream_writable_cork"><code>writable.cork()</code></a> and <code>writable.uncork()</code> to manage the buffering 735of writes to a stream, it is recommended that calls to <code>writable.uncork()</code> be 736deferred using <code>process.nextTick()</code>. Doing so allows batching of all 737<code>writable.write()</code> calls that occur within a given Node.js event loop phase.</p> 738<pre><code class="language-js">stream.<span class="hljs-title function_">cork</span>(); 739stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some '</span>); 740stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'data '</span>); 741process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> stream.<span class="hljs-title function_">uncork</span>());</code></pre> 742<p>If the <a href="#stream_writable_cork"><code>writable.cork()</code></a> method is called multiple times on a stream, the 743same number of calls to <code>writable.uncork()</code> must be called to flush the buffered 744data.</p> 745<pre><code class="language-js">stream.<span class="hljs-title function_">cork</span>(); 746stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some '</span>); 747stream.<span class="hljs-title function_">cork</span>(); 748stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'data '</span>); 749process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> { 750 stream.<span class="hljs-title function_">uncork</span>(); 751 <span class="hljs-comment">// The data will not be flushed until uncork() is called a second time.</span> 752 stream.<span class="hljs-title function_">uncork</span>(); 753});</code></pre> 754<p>See also: <a href="#stream_writable_cork"><code>writable.cork()</code></a>.</p> 755<h6><code>writable.writable</code><span><a class="mark" href="#stream_writable_writable" id="stream_writable_writable">#</a></span></h6> 756<div class="api_metadata"> 757<span>Added in: v11.4.0</span> 758</div> 759<ul> 760<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 761</ul> 762<p>Is <code>true</code> if it is safe to call <a href="#stream_writable_write_chunk_encoding_callback"><code>writable.write()</code></a>, which means 763the stream has not been destroyed, errored or ended.</p> 764<h6><code>writable.writableEnded</code><span><a class="mark" href="#stream_writable_writableended" id="stream_writable_writableended">#</a></span></h6> 765<div class="api_metadata"> 766<span>Added in: v12.9.0</span> 767</div> 768<ul> 769<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 770</ul> 771<p>Is <code>true</code> after <a href="#stream_writable_end_chunk_encoding_callback"><code>writable.end()</code></a> has been called. This property 772does not indicate whether the data has been flushed, for this use 773<a href="#stream_writable_writablefinished"><code>writable.writableFinished</code></a> instead.</p> 774<h6><code>writable.writableCorked</code><span><a class="mark" href="#stream_writable_writablecorked" id="stream_writable_writablecorked">#</a></span></h6> 775<div class="api_metadata"> 776<span>Added in: v13.2.0, v12.16.0</span> 777</div> 778<ul> 779<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> 780</ul> 781<p>Number of times <a href="#stream_writable_uncork"><code>writable.uncork()</code></a> needs to be 782called in order to fully uncork the stream.</p> 783<h6><code>writable.writableFinished</code><span><a class="mark" href="#stream_writable_writablefinished" id="stream_writable_writablefinished">#</a></span></h6> 784<div class="api_metadata"> 785<span>Added in: v12.6.0</span> 786</div> 787<ul> 788<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 789</ul> 790<p>Is set to <code>true</code> immediately before the <a href="#stream_event_finish"><code>'finish'</code></a> event is emitted.</p> 791<h6><code>writable.writableHighWaterMark</code><span><a class="mark" href="#stream_writable_writablehighwatermark" id="stream_writable_writablehighwatermark">#</a></span></h6> 792<div class="api_metadata"> 793<span>Added in: v9.3.0</span> 794</div> 795<ul> 796<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 797</ul> 798<p>Return the value of <code>highWaterMark</code> passed when constructing this 799<code>Writable</code>.</p> 800<h6><code>writable.writableLength</code><span><a class="mark" href="#stream_writable_writablelength" id="stream_writable_writablelength">#</a></span></h6> 801<div class="api_metadata"> 802<span>Added in: v9.4.0</span> 803</div> 804<ul> 805<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 806</ul> 807<p>This property contains the number of bytes (or objects) in the queue 808ready to be written. The value provides introspection data regarding 809the status of the <code>highWaterMark</code>.</p> 810<h6><code>writable.writableNeedDrain</code><span><a class="mark" href="#stream_writable_writableneeddrain" id="stream_writable_writableneeddrain">#</a></span></h6> 811<div class="api_metadata"> 812<span>Added in: v14.17.0</span> 813</div> 814<ul> 815<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 816</ul> 817<p>Is <code>true</code> if the stream's buffer has been full and stream will emit <code>'drain'</code>.</p> 818<h6><code>writable.writableObjectMode</code><span><a class="mark" href="#stream_writable_writableobjectmode" id="stream_writable_writableobjectmode">#</a></span></h6> 819<div class="api_metadata"> 820<span>Added in: v12.3.0</span> 821</div> 822<ul> 823<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 824</ul> 825<p>Getter for the property <code>objectMode</code> of a given <code>Writable</code> stream.</p> 826<h6><code>writable.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#stream_writable_write_chunk_encoding_callback" id="stream_writable_write_chunk_encoding_callback">#</a></span></h6> 827<div class="api_metadata"> 828<details class="changelog"><summary>History</summary> 829<table> 830<tbody><tr><th>Version</th><th>Changes</th></tr> 831<tr><td>v8.0.0</td> 832<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 833<tr><td>v6.0.0</td> 834<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> 835<tr><td>v0.9.4</td> 836<td><p><span>Added in: v0.9.4</span></p></td></tr> 837</tbody></table> 838</details> 839</div> 840<ul> 841<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#buffer_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 842not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or 843<code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value 844other than <code>null</code>.</li> 845<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> 846<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> 847<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 848wait for the <code>'drain'</code> event to be emitted before continuing to write 849additional data; otherwise <code>true</code>.</li> 850</ul> 851<p>The <code>writable.write()</code> method writes some data to the stream, and calls the 852supplied <code>callback</code> once the data has been fully handled. If an error 853occurs, the <code>callback</code> <em>may or may not</em> be called with the error as its 854first argument. To reliably detect write errors, add a listener for the 855<code>'error'</code> event. The <code>callback</code> is called asynchronously and before <code>'error'</code> is 856emitted.</p> 857<p>The return value is <code>true</code> if the internal buffer is less than the 858<code>highWaterMark</code> configured when the stream was created after admitting <code>chunk</code>. 859If <code>false</code> is returned, further attempts to write data to the stream should 860stop until the <a href="#stream_event_drain"><code>'drain'</code></a> event is emitted.</p> 861<p>While a stream is not draining, calls to <code>write()</code> will buffer <code>chunk</code>, and 862return false. Once all currently buffered chunks are drained (accepted for 863delivery by the operating system), the <code>'drain'</code> event will be emitted. 864It is recommended that once <code>write()</code> returns false, no more chunks be written 865until the <code>'drain'</code> event is emitted. While calling <code>write()</code> on a stream that 866is not draining is allowed, Node.js will buffer all written chunks until 867maximum memory usage occurs, at which point it will abort unconditionally. 868Even before it aborts, high memory usage will cause poor garbage collector 869performance and high RSS (which is not typically released back to the system, 870even after the memory is no longer required). Since TCP sockets may never 871drain if the remote peer does not read the data, writing a socket that is 872not draining may lead to a remotely exploitable vulnerability.</p> 873<p>Writing data while the stream is not draining is particularly 874problematic for a <a href="#stream_class_stream_transform"><code>Transform</code></a>, because the <code>Transform</code> streams are paused 875by default until they are piped or a <code>'data'</code> or <code>'readable'</code> event handler 876is added.</p> 877<p>If the data to be written can be generated or fetched on demand, it is 878recommended to encapsulate the logic into a <a href="#stream_class_stream_readable"><code>Readable</code></a> and use 879<a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a>. However, if calling <code>write()</code> is preferred, it is 880possible to respect backpressure and avoid memory issues using the 881<a href="#stream_event_drain"><code>'drain'</code></a> event:</p> 882<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>) { 883 <span class="hljs-keyword">if</span> (!stream.<span class="hljs-title function_">write</span>(data)) { 884 stream.<span class="hljs-title function_">once</span>(<span class="hljs-string">'drain'</span>, cb); 885 } <span class="hljs-keyword">else</span> { 886 process.<span class="hljs-title function_">nextTick</span>(cb); 887 } 888} 889 890<span class="hljs-comment">// Wait for cb to be called before doing any other write.</span> 891<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-function">() =></span> { 892 <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>); 893});</code></pre> 894<p>A <code>Writable</code> stream in object mode will always ignore the <code>encoding</code> argument.</p> 895<h4>Readable streams<span><a class="mark" href="#stream_readable_streams" id="stream_readable_streams">#</a></span></h4> 896<p>Readable streams are an abstraction for a <em>source</em> from which data is 897consumed.</p> 898<p>Examples of <code>Readable</code> streams include:</p> 899<ul> 900<li><a href="http.html#http_class_http_incomingmessage">HTTP responses, on the client</a></li> 901<li><a href="http.html#http_class_http_incomingmessage">HTTP requests, on the server</a></li> 902<li><a href="fs.html#fs_class_fs_readstream">fs read streams</a></li> 903<li><a href="zlib.html">zlib streams</a></li> 904<li><a href="crypto.html">crypto streams</a></li> 905<li><a href="net.html#net_class_net_socket">TCP sockets</a></li> 906<li><a href="child_process.html#child_process_subprocess_stdout">child process stdout and stderr</a></li> 907<li><a href="process.html#process_process_stdin"><code>process.stdin</code></a></li> 908</ul> 909<p>All <a href="#stream_class_stream_readable"><code>Readable</code></a> streams implement the interface defined by the 910<code>stream.Readable</code> class.</p> 911<h5>Two reading modes<span><a class="mark" href="#stream_two_reading_modes" id="stream_two_reading_modes">#</a></span></h5> 912<p><code>Readable</code> streams effectively operate in one of two modes: flowing and 913paused. These modes are separate from <a href="#stream_object_mode">object mode</a>. 914A <a href="#stream_class_stream_readable"><code>Readable</code></a> stream can be in object mode or not, regardless of whether 915it is in flowing mode or paused mode.</p> 916<ul> 917<li> 918<p>In flowing mode, data is read from the underlying system automatically 919and provided to an application as quickly as possible using events via the 920<a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> interface.</p> 921</li> 922<li> 923<p>In paused mode, the <a href="#stream_readable_read_size"><code>stream.read()</code></a> method must be called 924explicitly to read chunks of data from the stream.</p> 925</li> 926</ul> 927<p>All <a href="#stream_class_stream_readable"><code>Readable</code></a> streams begin in paused mode but can be switched to flowing 928mode in one of the following ways:</p> 929<ul> 930<li>Adding a <a href="#stream_event_data"><code>'data'</code></a> event handler.</li> 931<li>Calling the <a href="#stream_readable_resume"><code>stream.resume()</code></a> method.</li> 932<li>Calling the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method to send the data to a <a href="#stream_class_stream_writable"><code>Writable</code></a>.</li> 933</ul> 934<p>The <code>Readable</code> can switch back to paused mode using one of the following:</p> 935<ul> 936<li>If there are no pipe destinations, by calling the 937<a href="#stream_readable_pause"><code>stream.pause()</code></a> method.</li> 938<li>If there are pipe destinations, by removing all pipe destinations. 939Multiple pipe destinations may be removed by calling the 940<a href="#stream_readable_unpipe_destination"><code>stream.unpipe()</code></a> method.</li> 941</ul> 942<p>The important concept to remember is that a <code>Readable</code> will not generate data 943until a mechanism for either consuming or ignoring that data is provided. If 944the consuming mechanism is disabled or taken away, the <code>Readable</code> will <em>attempt</em> 945to stop generating the data.</p> 946<p>For backward compatibility reasons, removing <a href="#stream_event_data"><code>'data'</code></a> event handlers will 947<strong>not</strong> automatically pause the stream. Also, if there are piped destinations, 948then calling <a href="#stream_readable_pause"><code>stream.pause()</code></a> will not guarantee that the 949stream will <em>remain</em> paused once those destinations drain and ask for more data.</p> 950<p>If a <a href="#stream_class_stream_readable"><code>Readable</code></a> is switched into flowing mode and there are no consumers 951available to handle the data, that data will be lost. This can occur, for 952instance, when the <code>readable.resume()</code> method is called without a listener 953attached to the <code>'data'</code> event, or when a <code>'data'</code> event handler is removed 954from the stream.</p> 955<p>Adding a <a href="#stream_event_readable"><code>'readable'</code></a> event handler automatically makes the stream 956stop flowing, and the data has to be consumed via 957<a href="#stream_readable_read_size"><code>readable.read()</code></a>. If the <a href="#stream_event_readable"><code>'readable'</code></a> event handler is 958removed, then the stream will start flowing again if there is a 959<a href="#stream_event_data"><code>'data'</code></a> event handler.</p> 960<h5>Three states<span><a class="mark" href="#stream_three_states" id="stream_three_states">#</a></span></h5> 961<p>The "two modes" of operation for a <code>Readable</code> stream are a simplified 962abstraction for the more complicated internal state management that is happening 963within the <code>Readable</code> stream implementation.</p> 964<p>Specifically, at any given point in time, every <code>Readable</code> is in one of three 965possible states:</p> 966<ul> 967<li><code>readable.readableFlowing === null</code></li> 968<li><code>readable.readableFlowing === false</code></li> 969<li><code>readable.readableFlowing === true</code></li> 970</ul> 971<p>When <code>readable.readableFlowing</code> is <code>null</code>, no mechanism for consuming the 972stream's data is provided. Therefore, the stream will not generate data. 973While in this state, attaching a listener for the <code>'data'</code> event, calling the 974<code>readable.pipe()</code> method, or calling the <code>readable.resume()</code> method will switch 975<code>readable.readableFlowing</code> to <code>true</code>, causing the <code>Readable</code> to begin actively 976emitting events as data is generated.</p> 977<p>Calling <code>readable.pause()</code>, <code>readable.unpipe()</code>, or receiving backpressure 978will cause the <code>readable.readableFlowing</code> to be set as <code>false</code>, 979temporarily halting the flowing of events but <em>not</em> halting the generation of 980data. While in this state, attaching a listener for the <code>'data'</code> event 981will not switch <code>readable.readableFlowing</code> to <code>true</code>.</p> 982<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">'stream'</span>); 983<span class="hljs-keyword">const</span> pass = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PassThrough</span>(); 984<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>(); 985 986pass.<span class="hljs-title function_">pipe</span>(writable); 987pass.<span class="hljs-title function_">unpipe</span>(writable); 988<span class="hljs-comment">// readableFlowing is now false.</span> 989 990pass.<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>()); }); 991pass.<span class="hljs-title function_">write</span>(<span class="hljs-string">'ok'</span>); <span class="hljs-comment">// Will not emit 'data'.</span> 992pass.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Must be called to make stream emit 'data'.</span></code></pre> 993<p>While <code>readable.readableFlowing</code> is <code>false</code>, data may be accumulating 994within the stream's internal buffer.</p> 995<h5>Choose one API style<span><a class="mark" href="#stream_choose_one_api_style" id="stream_choose_one_api_style">#</a></span></h5> 996<p>The <code>Readable</code> stream API evolved across multiple Node.js versions and provides 997multiple methods of consuming stream data. In general, developers should choose 998<em>one</em> of the methods of consuming data and <em>should never</em> use multiple methods 999to consume data from a single stream. Specifically, using a combination 1000of <code>on('data')</code>, <code>on('readable')</code>, <code>pipe()</code>, or async iterators could 1001lead to unintuitive behavior.</p> 1002<p>Use of the <code>readable.pipe()</code> method is recommended for most users as it has been 1003implemented to provide the easiest way of consuming stream data. Developers that 1004require more fine-grained control over the transfer and generation of data can 1005use the <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> and <code>readable.on('readable')</code>/<code>readable.read()</code> 1006or the <code>readable.pause()</code>/<code>readable.resume()</code> APIs.</p> 1007<h5>Class: <code>stream.Readable</code><span><a class="mark" href="#stream_class_stream_readable" id="stream_class_stream_readable">#</a></span></h5> 1008<div class="api_metadata"> 1009<span>Added in: v0.9.4</span> 1010</div> 1011 1012<h6>Event: <code>'close'</code><span><a class="mark" href="#stream_event_close_1" id="stream_event_close_1">#</a></span></h6> 1013<div class="api_metadata"> 1014<details class="changelog"><summary>History</summary> 1015<table> 1016<tbody><tr><th>Version</th><th>Changes</th></tr> 1017<tr><td>v10.0.0</td> 1018<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> 1019<tr><td>v0.9.4</td> 1020<td><p><span>Added in: v0.9.4</span></p></td></tr> 1021</tbody></table> 1022</details> 1023</div> 1024<p>The <code>'close'</code> event is emitted when the stream and any of its underlying 1025resources (a file descriptor, for example) have been closed. The event indicates 1026that no more events will be emitted, and no further computation will occur.</p> 1027<p>A <a href="#stream_class_stream_readable"><code>Readable</code></a> stream will always emit the <code>'close'</code> event if it is 1028created with the <code>emitClose</code> option.</p> 1029<h6>Event: <code>'data'</code><span><a class="mark" href="#stream_event_data" id="stream_event_data">#</a></span></h6> 1030<div class="api_metadata"> 1031<span>Added in: v0.9.4</span> 1032</div> 1033<ul> 1034<li><code>chunk</code> <a href="buffer.html#buffer_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 1035operating in object mode, the chunk will be either a string or <code>Buffer</code>. 1036For streams that are in object mode, the chunk can be any JavaScript value 1037other than <code>null</code>.</li> 1038</ul> 1039<p>The <code>'data'</code> event is emitted whenever the stream is relinquishing ownership of 1040a chunk of data to a consumer. This may occur whenever the stream is switched 1041in flowing mode by calling <code>readable.pipe()</code>, <code>readable.resume()</code>, or by 1042attaching a listener callback to the <code>'data'</code> event. The <code>'data'</code> event will 1043also be emitted whenever the <code>readable.read()</code> method is called and a chunk of 1044data is available to be returned.</p> 1045<p>Attaching a <code>'data'</code> event listener to a stream that has not been explicitly 1046paused will switch the stream into flowing mode. Data will then be passed as 1047soon as it is available.</p> 1048<p>The listener callback will be passed the chunk of data as a string if a default 1049encoding has been specified for the stream using the 1050<code>readable.setEncoding()</code> method; otherwise the data will be passed as a 1051<code>Buffer</code>.</p> 1052<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1053readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1054 <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>); 1055});</code></pre> 1056<h6>Event: <code>'end'</code><span><a class="mark" href="#stream_event_end" id="stream_event_end">#</a></span></h6> 1057<div class="api_metadata"> 1058<span>Added in: v0.9.4</span> 1059</div> 1060<p>The <code>'end'</code> event is emitted when there is no more data to be consumed from 1061the stream.</p> 1062<p>The <code>'end'</code> event <strong>will not be emitted</strong> unless the data is completely 1063consumed. This can be accomplished by switching the stream into flowing mode, 1064or by calling <a href="#stream_readable_read_size"><code>stream.read()</code></a> repeatedly until all data has been 1065consumed.</p> 1066<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1067readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1068 <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>); 1069}); 1070readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1071 <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>); 1072});</code></pre> 1073<h6>Event: <code>'error'</code><span><a class="mark" href="#stream_event_error_1" id="stream_event_error_1">#</a></span></h6> 1074<div class="api_metadata"> 1075<span>Added in: v0.9.4</span> 1076</div> 1077<ul> 1078<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1079</ul> 1080<p>The <code>'error'</code> event may be emitted by a <code>Readable</code> implementation at any time. 1081Typically, this may occur if the underlying stream is unable to generate data 1082due to an underlying internal failure, or when a stream implementation attempts 1083to push an invalid chunk of data.</p> 1084<p>The listener callback will be passed a single <code>Error</code> object.</p> 1085<h6>Event: <code>'pause'</code><span><a class="mark" href="#stream_event_pause" id="stream_event_pause">#</a></span></h6> 1086<div class="api_metadata"> 1087<span>Added in: v0.9.4</span> 1088</div> 1089<p>The <code>'pause'</code> event is emitted when <a href="#stream_readable_pause"><code>stream.pause()</code></a> is called 1090and <code>readableFlowing</code> is not <code>false</code>.</p> 1091<h6>Event: <code>'readable'</code><span><a class="mark" href="#stream_event_readable" id="stream_event_readable">#</a></span></h6> 1092<div class="api_metadata"> 1093<details class="changelog"><summary>History</summary> 1094<table> 1095<tbody><tr><th>Version</th><th>Changes</th></tr> 1096<tr><td>v10.0.0</td> 1097<td><p>The <code>'readable'</code> is always emitted in the next tick after <code>.push()</code> is called.</p></td></tr> 1098<tr><td>v10.0.0</td> 1099<td><p>Using <code>'readable'</code> requires calling <code>.read()</code>.</p></td></tr> 1100<tr><td>v0.9.4</td> 1101<td><p><span>Added in: v0.9.4</span></p></td></tr> 1102</tbody></table> 1103</details> 1104</div> 1105<p>The <code>'readable'</code> event is emitted when there is data available to be read from 1106the stream. In some cases, attaching a listener for the <code>'readable'</code> event will 1107cause some amount of data to be read into an internal buffer.</p> 1108<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1109readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { 1110 <span class="hljs-comment">// There is some data to read now.</span> 1111 <span class="hljs-keyword">let</span> data; 1112 1113 <span class="hljs-keyword">while</span> (data = <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">read</span>()) { 1114 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data); 1115 } 1116});</code></pre> 1117<p>The <code>'readable'</code> event will also be emitted once the end of the stream data 1118has been reached but before the <code>'end'</code> event is emitted.</p> 1119<p>Effectively, the <code>'readable'</code> event indicates that the stream has new 1120information: either new data is available or the end of the stream has been 1121reached. In the former case, <a href="#stream_readable_read_size"><code>stream.read()</code></a> will return the 1122available data. In the latter case, <a href="#stream_readable_read_size"><code>stream.read()</code></a> will return 1123<code>null</code>. For instance, in the following example, <code>foo.txt</code> is an empty file:</p> 1124<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); 1125<span class="hljs-keyword">const</span> rr = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'foo.txt'</span>); 1126rr.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 1127 <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>); 1128}); 1129rr.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1130 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'end'</span>); 1131});</code></pre> 1132<p>The output of running this script is:</p> 1133<pre><code class="language-console"><span class="hljs-meta">$ </span><span class="language-bash">node test.js</span> 1134readable: null 1135end</code></pre> 1136<p>In general, the <code>readable.pipe()</code> and <code>'data'</code> event mechanisms are easier to 1137understand than the <code>'readable'</code> event. However, handling <code>'readable'</code> might 1138result in increased throughput.</p> 1139<p>If both <code>'readable'</code> and <a href="#stream_event_data"><code>'data'</code></a> are used at the same time, <code>'readable'</code> 1140takes precedence in controlling the flow, i.e. <code>'data'</code> will be emitted 1141only when <a href="#stream_readable_read_size"><code>stream.read()</code></a> is called. The 1142<code>readableFlowing</code> property would become <code>false</code>. 1143If there are <code>'data'</code> listeners when <code>'readable'</code> is removed, the stream 1144will start flowing, i.e. <code>'data'</code> events will be emitted without calling 1145<code>.resume()</code>.</p> 1146<h6>Event: <code>'resume'</code><span><a class="mark" href="#stream_event_resume" id="stream_event_resume">#</a></span></h6> 1147<div class="api_metadata"> 1148<span>Added in: v0.9.4</span> 1149</div> 1150<p>The <code>'resume'</code> event is emitted when <a href="#stream_readable_resume"><code>stream.resume()</code></a> is 1151called and <code>readableFlowing</code> is not <code>true</code>.</p> 1152<h6><code>readable.destroy([error])</code><span><a class="mark" href="#stream_readable_destroy_error" id="stream_readable_destroy_error">#</a></span></h6> 1153<div class="api_metadata"> 1154<details class="changelog"><summary>History</summary> 1155<table> 1156<tbody><tr><th>Version</th><th>Changes</th></tr> 1157<tr><td>v14.0.0</td> 1158<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr> 1159<tr><td>v8.0.0</td> 1160<td><p><span>Added in: v8.0.0</span></p></td></tr> 1161</tbody></table> 1162</details> 1163</div> 1164<ul> 1165<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> 1166<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1167</ul> 1168<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code> 1169event (unless <code>emitClose</code> is set to <code>false</code>). After this call, the readable 1170stream will release any internal resources and subsequent calls to <code>push()</code> 1171will be ignored.</p> 1172<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no 1173further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p> 1174<p>Implementors should not override this method, but instead implement 1175<a href="#stream_readable_destroy_err_callback"><code>readable._destroy()</code></a>.</p> 1176<h6><code>readable.destroyed</code><span><a class="mark" href="#stream_readable_destroyed" id="stream_readable_destroyed">#</a></span></h6> 1177<div class="api_metadata"> 1178<span>Added in: v8.0.0</span> 1179</div> 1180<ul> 1181<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1182</ul> 1183<p>Is <code>true</code> after <a href="#stream_readable_destroy_error"><code>readable.destroy()</code></a> has been called.</p> 1184<h6><code>readable.isPaused()</code><span><a class="mark" href="#stream_readable_ispaused" id="stream_readable_ispaused">#</a></span></h6> 1185<div class="api_metadata"> 1186<span>Added in: v0.11.14</span> 1187</div> 1188<ul> 1189<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1190</ul> 1191<p>The <code>readable.isPaused()</code> method returns the current operating state of the 1192<code>Readable</code>. This is used primarily by the mechanism that underlies the 1193<code>readable.pipe()</code> method. In most typical cases, there will be no reason to 1194use this method directly.</p> 1195<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>(); 1196 1197readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === false</span> 1198readable.<span class="hljs-title function_">pause</span>(); 1199readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === true</span> 1200readable.<span class="hljs-title function_">resume</span>(); 1201readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === false</span></code></pre> 1202<h6><code>readable.pause()</code><span><a class="mark" href="#stream_readable_pause" id="stream_readable_pause">#</a></span></h6> 1203<div class="api_metadata"> 1204<span>Added in: v0.9.4</span> 1205</div> 1206<ul> 1207<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1208</ul> 1209<p>The <code>readable.pause()</code> method will cause a stream in flowing mode to stop 1210emitting <a href="#stream_event_data"><code>'data'</code></a> events, switching out of flowing mode. Any data that 1211becomes available will remain in the internal buffer.</p> 1212<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1213readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1214 <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>); 1215 readable.<span class="hljs-title function_">pause</span>(); 1216 <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>); 1217 <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { 1218 <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>); 1219 readable.<span class="hljs-title function_">resume</span>(); 1220 }, <span class="hljs-number">1000</span>); 1221});</code></pre> 1222<p>The <code>readable.pause()</code> method has no effect if there is a <code>'readable'</code> 1223event listener.</p> 1224<h6><code>readable.pipe(destination[, options])</code><span><a class="mark" href="#stream_readable_pipe_destination_options" id="stream_readable_pipe_destination_options">#</a></span></h6> 1225<div class="api_metadata"> 1226<span>Added in: v0.9.4</span> 1227</div> 1228<ul> 1229<li><code>destination</code> <a href="stream.html#stream_class_stream_writable" class="type"><stream.Writable></a> The destination for writing data</li> 1230<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 1231<ul> 1232<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> 1233</ul> 1234</li> 1235<li>Returns: <a href="stream.html#stream_class_stream_writable" class="type"><stream.Writable></a> The <em>destination</em>, allowing for a chain of pipes if 1236it is a <a href="#stream_class_stream_duplex"><code>Duplex</code></a> or a <a href="#stream_class_stream_transform"><code>Transform</code></a> stream</li> 1237</ul> 1238<p>The <code>readable.pipe()</code> method attaches a <a href="#stream_class_stream_writable"><code>Writable</code></a> stream to the <code>readable</code>, 1239causing it to switch automatically into flowing mode and push all of its data 1240to the attached <a href="#stream_class_stream_writable"><code>Writable</code></a>. The flow of data will be automatically managed 1241so that the destination <code>Writable</code> stream is not overwhelmed by a faster 1242<code>Readable</code> stream.</p> 1243<p>The following example pipes all of the data from the <code>readable</code> into a file 1244named <code>file.txt</code>:</p> 1245<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); 1246<span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1247<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt'</span>); 1248<span class="hljs-comment">// All the data from readable goes into 'file.txt'.</span> 1249readable.<span class="hljs-title function_">pipe</span>(writable);</code></pre> 1250<p>It is possible to attach multiple <code>Writable</code> streams to a single <code>Readable</code> 1251stream.</p> 1252<p>The <code>readable.pipe()</code> method returns a reference to the <em>destination</em> stream 1253making it possible to set up chains of piped streams:</p> 1254<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); 1255<span class="hljs-keyword">const</span> r = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'file.txt'</span>); 1256<span class="hljs-keyword">const</span> z = zlib.<span class="hljs-title function_">createGzip</span>(); 1257<span class="hljs-keyword">const</span> w = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt.gz'</span>); 1258r.<span class="hljs-title function_">pipe</span>(z).<span class="hljs-title function_">pipe</span>(w);</code></pre> 1259<p>By default, <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> is called on the destination <code>Writable</code> 1260stream when the source <code>Readable</code> stream emits <a href="#stream_event_end"><code>'end'</code></a>, so that the 1261destination is no longer writable. To disable this default behavior, the <code>end</code> 1262option can be passed as <code>false</code>, causing the destination stream to remain open:</p> 1263<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> }); 1264reader.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1265 writer.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Goodbye\n'</span>); 1266});</code></pre> 1267<p>One important caveat is that if the <code>Readable</code> stream emits an error during 1268processing, the <code>Writable</code> destination <em>is not closed</em> automatically. If an 1269error occurs, it will be necessary to <em>manually</em> close each stream in order 1270to prevent memory leaks.</p> 1271<p>The <a href="process.html#process_process_stderr"><code>process.stderr</code></a> and <a href="process.html#process_process_stdout"><code>process.stdout</code></a> <code>Writable</code> streams are never 1272closed until the Node.js process exits, regardless of the specified options.</p> 1273<h6><code>readable.read([size])</code><span><a class="mark" href="#stream_readable_read_size" id="stream_readable_read_size">#</a></span></h6> 1274<div class="api_metadata"> 1275<span>Added in: v0.9.4</span> 1276</div> 1277<ul> 1278<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> 1279<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#buffer_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> 1280</ul> 1281<p>The <code>readable.read()</code> method pulls some data out of the internal buffer and 1282returns it. If no data available to be read, <code>null</code> is returned. By default, 1283the data will be returned as a <code>Buffer</code> object unless an encoding has been 1284specified using the <code>readable.setEncoding()</code> method or the stream is operating 1285in object mode.</p> 1286<p>The optional <code>size</code> argument specifies a specific number of bytes to read. If 1287<code>size</code> bytes are not available to be read, <code>null</code> will be returned <em>unless</em> 1288the stream has ended, in which case all of the data remaining in the internal 1289buffer will be returned.</p> 1290<p>If the <code>size</code> argument is not specified, all of the data contained in the 1291internal buffer will be returned.</p> 1292<p>The <code>size</code> argument must be less than or equal to 1 GiB.</p> 1293<p>The <code>readable.read()</code> method should only be called on <code>Readable</code> streams 1294operating in paused mode. In flowing mode, <code>readable.read()</code> is called 1295automatically until the internal buffer is fully drained.</p> 1296<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1297 1298<span class="hljs-comment">// 'readable' may be triggered multiple times as data is buffered in</span> 1299readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 1300 <span class="hljs-keyword">let</span> chunk; 1301 <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>); 1302 <span class="hljs-comment">// Use a loop to make sure we read all currently available data</span> 1303 <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = readable.<span class="hljs-title function_">read</span>())) { 1304 <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>); 1305 } 1306}); 1307 1308<span class="hljs-comment">// 'end' will be triggered once when there is no more data available</span> 1309readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1310 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Reached end of stream.'</span>); 1311});</code></pre> 1312<p>Each call to <code>readable.read()</code> returns a chunk of data, or <code>null</code>. The chunks 1313are not concatenated. A <code>while</code> loop is necessary to consume all data 1314currently in the buffer. When reading a large file <code>.read()</code> may return <code>null</code>, 1315having consumed all buffered content so far, but there is still more data to 1316come not yet buffered. In this case a new <code>'readable'</code> event will be emitted 1317when there is more data in the buffer. Finally the <code>'end'</code> event will be 1318emitted when there is no more data to come.</p> 1319<p>Therefore to read a file's whole contents from a <code>readable</code>, it is necessary 1320to collect chunks across multiple <code>'readable'</code> events:</p> 1321<pre><code class="language-js"><span class="hljs-keyword">const</span> chunks = []; 1322 1323readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 1324 <span class="hljs-keyword">let</span> chunk; 1325 <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = readable.<span class="hljs-title function_">read</span>())) { 1326 chunks.<span class="hljs-title function_">push</span>(chunk); 1327 } 1328}); 1329 1330readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1331 <span class="hljs-keyword">const</span> content = chunks.<span class="hljs-title function_">join</span>(<span class="hljs-string">''</span>); 1332});</code></pre> 1333<p>A <code>Readable</code> stream in object mode will always return a single item from 1334a call to <a href="#stream_readable_read_size"><code>readable.read(size)</code></a>, regardless of the value of the 1335<code>size</code> argument.</p> 1336<p>If the <code>readable.read()</code> method returns a chunk of data, a <code>'data'</code> event will 1337also be emitted.</p> 1338<p>Calling <a href="#stream_readable_read_size"><code>stream.read([size])</code></a> after the <a href="#stream_event_end"><code>'end'</code></a> event has 1339been emitted will return <code>null</code>. No runtime error will be raised.</p> 1340<h6><code>readable.readable</code><span><a class="mark" href="#stream_readable_readable" id="stream_readable_readable">#</a></span></h6> 1341<div class="api_metadata"> 1342<span>Added in: v11.4.0</span> 1343</div> 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>Is <code>true</code> if it is safe to call <a href="#stream_readable_read_size"><code>readable.read()</code></a>, which means 1348the stream has not been destroyed or emitted <code>'error'</code> or <code>'end'</code>.</p> 1349<h6><code>readable.readableDidRead</code><span><a class="mark" href="#stream_readable_readabledidread" id="stream_readable_readabledidread">#</a></span></h6> 1350<div class="api_metadata"> 1351<span>Added in: v14.18.0</span> 1352</div> 1353<ul> 1354<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1355</ul> 1356<p>Allows determining if the stream has been or is about to be read. 1357Returns true if <code>'data'</code>, <code>'end'</code>, <code>'error'</code> or <code>'close'</code> has been 1358emitted.</p> 1359<h6><code>readable.readableEncoding</code><span><a class="mark" href="#stream_readable_readableencoding" id="stream_readable_readableencoding">#</a></span></h6> 1360<div class="api_metadata"> 1361<span>Added in: v12.7.0</span> 1362</div> 1363<ul> 1364<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> 1365</ul> 1366<p>Getter for the property <code>encoding</code> of a given <code>Readable</code> stream. The <code>encoding</code> 1367property can be set using the <a href="#stream_readable_setencoding_encoding"><code>readable.setEncoding()</code></a> method.</p> 1368<h6><code>readable.readableEnded</code><span><a class="mark" href="#stream_readable_readableended" id="stream_readable_readableended">#</a></span></h6> 1369<div class="api_metadata"> 1370<span>Added in: v12.9.0</span> 1371</div> 1372<ul> 1373<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1374</ul> 1375<p>Becomes <code>true</code> when <a href="#stream_event_end"><code>'end'</code></a> event is emitted.</p> 1376<h6><code>readable.readableFlowing</code><span><a class="mark" href="#stream_readable_readableflowing" id="stream_readable_readableflowing">#</a></span></h6> 1377<div class="api_metadata"> 1378<span>Added in: v9.4.0</span> 1379</div> 1380<ul> 1381<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1382</ul> 1383<p>This property reflects the current state of a <code>Readable</code> stream as described 1384in the <a href="#stream_three_states">Three states</a> section.</p> 1385<h6><code>readable.readableHighWaterMark</code><span><a class="mark" href="#stream_readable_readablehighwatermark" id="stream_readable_readablehighwatermark">#</a></span></h6> 1386<div class="api_metadata"> 1387<span>Added in: v9.3.0</span> 1388</div> 1389<ul> 1390<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1391</ul> 1392<p>Returns the value of <code>highWaterMark</code> passed when constructing this 1393<code>Readable</code>.</p> 1394<h6><code>readable.readableLength</code><span><a class="mark" href="#stream_readable_readablelength" id="stream_readable_readablelength">#</a></span></h6> 1395<div class="api_metadata"> 1396<span>Added in: v9.4.0</span> 1397</div> 1398<ul> 1399<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> 1400</ul> 1401<p>This property contains the number of bytes (or objects) in the queue 1402ready to be read. The value provides introspection data regarding 1403the status of the <code>highWaterMark</code>.</p> 1404<h6><code>readable.readableObjectMode</code><span><a class="mark" href="#stream_readable_readableobjectmode" id="stream_readable_readableobjectmode">#</a></span></h6> 1405<div class="api_metadata"> 1406<span>Added in: v12.3.0</span> 1407</div> 1408<ul> 1409<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> 1410</ul> 1411<p>Getter for the property <code>objectMode</code> of a given <code>Readable</code> stream.</p> 1412<h6><code>readable.resume()</code><span><a class="mark" href="#stream_readable_resume" id="stream_readable_resume">#</a></span></h6> 1413<div class="api_metadata"> 1414<details class="changelog"><summary>History</summary> 1415<table> 1416<tbody><tr><th>Version</th><th>Changes</th></tr> 1417<tr><td>v10.0.0</td> 1418<td><p>The <code>resume()</code> has no effect if there is a <code>'readable'</code> event listening.</p></td></tr> 1419<tr><td>v0.9.4</td> 1420<td><p><span>Added in: v0.9.4</span></p></td></tr> 1421</tbody></table> 1422</details> 1423</div> 1424<ul> 1425<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1426</ul> 1427<p>The <code>readable.resume()</code> method causes an explicitly paused <code>Readable</code> stream to 1428resume emitting <a href="#stream_event_data"><code>'data'</code></a> events, switching the stream into flowing mode.</p> 1429<p>The <code>readable.resume()</code> method can be used to fully consume the data from a 1430stream without actually processing any of that data:</p> 1431<pre><code class="language-js"><span class="hljs-title function_">getReadableStreamSomehow</span>() 1432 .<span class="hljs-title function_">resume</span>() 1433 .<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 1434 <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>); 1435 });</code></pre> 1436<p>The <code>readable.resume()</code> method has no effect if there is a <code>'readable'</code> 1437event listener.</p> 1438<h6><code>readable.setEncoding(encoding)</code><span><a class="mark" href="#stream_readable_setencoding_encoding" id="stream_readable_setencoding_encoding">#</a></span></h6> 1439<div class="api_metadata"> 1440<span>Added in: v0.9.4</span> 1441</div> 1442<ul> 1443<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> 1444<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1445</ul> 1446<p>The <code>readable.setEncoding()</code> method sets the character encoding for 1447data read from the <code>Readable</code> stream.</p> 1448<p>By default, no encoding is assigned and stream data will be returned as 1449<code>Buffer</code> objects. Setting an encoding causes the stream data 1450to be returned as strings of the specified encoding rather than as <code>Buffer</code> 1451objects. For instance, calling <code>readable.setEncoding('utf8')</code> will cause the 1452output data to be interpreted as UTF-8 data, and passed as strings. Calling 1453<code>readable.setEncoding('hex')</code> will cause the data to be encoded in hexadecimal 1454string format.</p> 1455<p>The <code>Readable</code> stream will properly handle multi-byte characters delivered 1456through the stream that would otherwise become improperly decoded if simply 1457pulled from the stream as <code>Buffer</code> objects.</p> 1458<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1459readable.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); 1460readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1461 assert.<span class="hljs-title function_">equal</span>(<span class="hljs-keyword">typeof</span> chunk, <span class="hljs-string">'string'</span>); 1462 <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>); 1463});</code></pre> 1464<h6><code>readable.unpipe([destination])</code><span><a class="mark" href="#stream_readable_unpipe_destination" id="stream_readable_unpipe_destination">#</a></span></h6> 1465<div class="api_metadata"> 1466<span>Added in: v0.9.4</span> 1467</div> 1468<ul> 1469<li><code>destination</code> <a href="stream.html#stream_class_stream_writable" class="type"><stream.Writable></a> Optional specific stream to unpipe</li> 1470<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1471</ul> 1472<p>The <code>readable.unpipe()</code> method detaches a <code>Writable</code> stream previously attached 1473using the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method.</p> 1474<p>If the <code>destination</code> is not specified, then <em>all</em> pipes are detached.</p> 1475<p>If the <code>destination</code> is specified, but no pipe is set up for it, then 1476the method does nothing.</p> 1477<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); 1478<span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>(); 1479<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt'</span>); 1480<span class="hljs-comment">// All the data from readable goes into 'file.txt',</span> 1481<span class="hljs-comment">// but only for the first second.</span> 1482readable.<span class="hljs-title function_">pipe</span>(writable); 1483<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { 1484 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stop writing to file.txt.'</span>); 1485 readable.<span class="hljs-title function_">unpipe</span>(writable); 1486 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Manually close the file stream.'</span>); 1487 writable.<span class="hljs-title function_">end</span>(); 1488}, <span class="hljs-number">1000</span>);</code></pre> 1489<h6><code>readable.unshift(chunk[, encoding])</code><span><a class="mark" href="#stream_readable_unshift_chunk_encoding" id="stream_readable_unshift_chunk_encoding">#</a></span></h6> 1490<div class="api_metadata"> 1491<details class="changelog"><summary>History</summary> 1492<table> 1493<tbody><tr><th>Version</th><th>Changes</th></tr> 1494<tr><td>v8.0.0</td> 1495<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 1496<tr><td>v0.9.11</td> 1497<td><p><span>Added in: v0.9.11</span></p></td></tr> 1498</tbody></table> 1499</details> 1500</div> 1501<ul> 1502<li><code>chunk</code> <a href="buffer.html#buffer_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 1503read queue. For streams not operating in object mode, <code>chunk</code> must be a 1504string, <code>Buffer</code>, <code>Uint8Array</code> or <code>null</code>. For object mode streams, <code>chunk</code> 1505may be any JavaScript value.</li> 1506<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 1507<code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li> 1508</ul> 1509<p>Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF) and behaves the 1510same as <code>readable.push(null)</code>, after which no more data can be written. The EOF 1511signal is put at the end of the buffer and any buffered data will still be 1512flushed.</p> 1513<p>The <code>readable.unshift()</code> method pushes a chunk of data back into the internal 1514buffer. This is useful in certain situations where a stream is being consumed by 1515code that needs to "un-consume" some amount of data that it has optimistically 1516pulled out of the source, so that the data can be passed on to some other party.</p> 1517<p>The <code>stream.unshift(chunk)</code> method cannot be called after the <a href="#stream_event_end"><code>'end'</code></a> event 1518has been emitted or a runtime error will be thrown.</p> 1519<p>Developers using <code>stream.unshift()</code> often should consider switching to 1520use of a <a href="#stream_class_stream_transform"><code>Transform</code></a> stream instead. See the <a href="#stream_api_for_stream_implementers">API for stream implementers</a> 1521section for more information.</p> 1522<pre><code class="language-js"><span class="hljs-comment">// Pull off a header delimited by \n\n.</span> 1523<span class="hljs-comment">// Use unshift() if we get too much.</span> 1524<span class="hljs-comment">// Call the callback with (error, header, stream).</span> 1525<span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'string_decoder'</span>); 1526<span class="hljs-keyword">function</span> <span class="hljs-title function_">parseHeader</span>(<span class="hljs-params">stream, callback</span>) { 1527 stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, callback); 1528 stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, onReadable); 1529 <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>); 1530 <span class="hljs-keyword">let</span> header = <span class="hljs-string">''</span>; 1531 <span class="hljs-keyword">function</span> <span class="hljs-title function_">onReadable</span>(<span class="hljs-params"></span>) { 1532 <span class="hljs-keyword">let</span> chunk; 1533 <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = stream.<span class="hljs-title function_">read</span>())) { 1534 <span class="hljs-keyword">const</span> str = decoder.<span class="hljs-title function_">write</span>(chunk); 1535 <span class="hljs-keyword">if</span> (str.<span class="hljs-title function_">match</span>(<span class="hljs-regexp">/\n\n/</span>)) { 1536 <span class="hljs-comment">// Found the header boundary.</span> 1537 <span class="hljs-keyword">const</span> split = str.<span class="hljs-title function_">split</span>(<span class="hljs-regexp">/\n\n/</span>); 1538 header += split.<span class="hljs-title function_">shift</span>(); 1539 <span class="hljs-keyword">const</span> remaining = split.<span class="hljs-title function_">join</span>(<span class="hljs-string">'\n\n'</span>); 1540 <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>); 1541 stream.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'error'</span>, callback); 1542 <span class="hljs-comment">// Remove the 'readable' listener before unshifting.</span> 1543 stream.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'readable'</span>, onReadable); 1544 <span class="hljs-keyword">if</span> (buf.<span class="hljs-property">length</span>) 1545 stream.<span class="hljs-title function_">unshift</span>(buf); 1546 <span class="hljs-comment">// Now the body of the message can be read from the stream.</span> 1547 <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, header, stream); 1548 } <span class="hljs-keyword">else</span> { 1549 <span class="hljs-comment">// Still reading the header.</span> 1550 header += str; 1551 } 1552 } 1553 } 1554}</code></pre> 1555<p>Unlike <a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>, <code>stream.unshift(chunk)</code> will not 1556end the reading process by resetting the internal reading state of the stream. 1557This can cause unexpected results if <code>readable.unshift()</code> is called during a 1558read (i.e. from within a <a href="#stream_readable_read_size_1"><code>stream._read()</code></a> implementation on a 1559custom stream). Following the call to <code>readable.unshift()</code> with an immediate 1560<a href="#stream_readable_push_chunk_encoding"><code>stream.push('')</code></a> will reset the reading state appropriately, 1561however it is best to simply avoid calling <code>readable.unshift()</code> while in the 1562process of performing a read.</p> 1563<h6><code>readable.wrap(stream)</code><span><a class="mark" href="#stream_readable_wrap_stream" id="stream_readable_wrap_stream">#</a></span></h6> 1564<div class="api_metadata"> 1565<span>Added in: v0.9.4</span> 1566</div> 1567<ul> 1568<li><code>stream</code> <a href="stream.html#stream_stream" class="type"><Stream></a> An "old style" readable stream</li> 1569<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1570</ul> 1571<p>Prior to Node.js 0.10, streams did not implement the entire <code>stream</code> module API 1572as it is currently defined. (See <a href="#stream_compatibility_with_older_node_js_versions">Compatibility</a> for more information.)</p> 1573<p>When using an older Node.js library that emits <a href="#stream_event_data"><code>'data'</code></a> events and has a 1574<a href="#stream_readable_pause"><code>stream.pause()</code></a> method that is advisory only, the 1575<code>readable.wrap()</code> method can be used to create a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream that uses 1576the old stream as its data source.</p> 1577<p>It will rarely be necessary to use <code>readable.wrap()</code> but the method has been 1578provided as a convenience for interacting with older Node.js applications and 1579libraries.</p> 1580<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>); 1581<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'stream'</span>); 1582<span class="hljs-keyword">const</span> oreader = <span class="hljs-keyword">new</span> <span class="hljs-title class_">OldReader</span>(); 1583<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); 1584 1585myReader.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> { 1586 myReader.<span class="hljs-title function_">read</span>(); <span class="hljs-comment">// etc.</span> 1587});</code></pre> 1588<h6><code>readable[Symbol.asyncIterator]()</code><span><a class="mark" href="#stream_readable_symbol_asynciterator" id="stream_readable_symbol_asynciterator">#</a></span></h6> 1589<div class="api_metadata"> 1590<details class="changelog"><summary>History</summary> 1591<table> 1592<tbody><tr><th>Version</th><th>Changes</th></tr> 1593<tr><td>v11.14.0</td> 1594<td><p>Symbol.asyncIterator support is no longer experimental.</p></td></tr> 1595<tr><td>v10.0.0</td> 1596<td><p><span>Added in: v10.0.0</span></p></td></tr> 1597</tbody></table> 1598</details> 1599</div> 1600<ul> 1601<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> to fully consume the stream.</li> 1602</ul> 1603<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); 1604 1605<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>) { 1606 readable.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>); 1607 <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>; 1608 <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) { 1609 data += chunk; 1610 } 1611 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data); 1612} 1613 1614<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></pre> 1615<p>If the loop terminates with a <code>break</code> or a <code>throw</code>, the stream will be 1616destroyed. In other terms, iterating over a stream will consume the stream 1617fully. The stream will be read in chunks of size equal to the <code>highWaterMark</code> 1618option. In the code example above, data will be in a single chunk if the file 1619has less then 64KB of data because no <code>highWaterMark</code> option is provided to 1620<a href="fs.html#fs_fs_createreadstream_path_options"><code>fs.createReadStream()</code></a>.</p> 1621<h4>Duplex and transform streams<span><a class="mark" href="#stream_duplex_and_transform_streams" id="stream_duplex_and_transform_streams">#</a></span></h4> 1622<h5>Class: <code>stream.Duplex</code><span><a class="mark" href="#stream_class_stream_duplex" id="stream_class_stream_duplex">#</a></span></h5> 1623<div class="api_metadata"> 1624<details class="changelog"><summary>History</summary> 1625<table> 1626<tbody><tr><th>Version</th><th>Changes</th></tr> 1627<tr><td>v6.8.0</td> 1628<td><p>Instances of <code>Duplex</code> now return <code>true</code> when checking <code>instanceof stream.Writable</code>.</p></td></tr> 1629<tr><td>v0.9.4</td> 1630<td><p><span>Added in: v0.9.4</span></p></td></tr> 1631</tbody></table> 1632</details> 1633</div> 1634 1635<p>Duplex streams are streams that implement both the <a href="#stream_class_stream_readable"><code>Readable</code></a> and 1636<a href="#stream_class_stream_writable"><code>Writable</code></a> interfaces.</p> 1637<p>Examples of <code>Duplex</code> streams include:</p> 1638<ul> 1639<li><a href="net.html#net_class_net_socket">TCP sockets</a></li> 1640<li><a href="zlib.html">zlib streams</a></li> 1641<li><a href="crypto.html">crypto streams</a></li> 1642</ul> 1643<h5>Class: <code>stream.Transform</code><span><a class="mark" href="#stream_class_stream_transform" id="stream_class_stream_transform">#</a></span></h5> 1644<div class="api_metadata"> 1645<span>Added in: v0.9.4</span> 1646</div> 1647 1648<p>Transform streams are <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams where the output is in some way 1649related to the input. Like all <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams, <code>Transform</code> streams 1650implement both the <a href="#stream_class_stream_readable"><code>Readable</code></a> and <a href="#stream_class_stream_writable"><code>Writable</code></a> interfaces.</p> 1651<p>Examples of <code>Transform</code> streams include:</p> 1652<ul> 1653<li><a href="zlib.html">zlib streams</a></li> 1654<li><a href="crypto.html">crypto streams</a></li> 1655</ul> 1656<h6><code>transform.destroy([error])</code><span><a class="mark" href="#stream_transform_destroy_error" id="stream_transform_destroy_error">#</a></span></h6> 1657<div class="api_metadata"> 1658<details class="changelog"><summary>History</summary> 1659<table> 1660<tbody><tr><th>Version</th><th>Changes</th></tr> 1661<tr><td>v14.0.0</td> 1662<td><p>Work as a no-op on a stream that has already been destroyed.</p></td></tr> 1663<tr><td>v8.0.0</td> 1664<td><p><span>Added in: v8.0.0</span></p></td></tr> 1665</tbody></table> 1666</details> 1667</div> 1668<ul> 1669<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1670<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> 1671</ul> 1672<p>Destroy the stream, and optionally emit an <code>'error'</code> event. After this call, the 1673transform stream would release any internal resources. 1674Implementors should not override this method, but instead implement 1675<a href="#stream_readable_destroy_err_callback"><code>readable._destroy()</code></a>. 1676The default implementation of <code>_destroy()</code> for <code>Transform</code> also emit <code>'close'</code> 1677unless <code>emitClose</code> is set in false.</p> 1678<p>Once <code>destroy()</code> has been called, any further calls will be a no-op and no 1679further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p> 1680<h4><code>stream.finished(stream[, options], callback)</code><span><a class="mark" href="#stream_stream_finished_stream_options_callback" id="stream_stream_finished_stream_options_callback">#</a></span></h4> 1681<div class="api_metadata"> 1682<details class="changelog"><summary>History</summary> 1683<table> 1684<tbody><tr><th>Version</th><th>Changes</th></tr> 1685<tr><td>v14.0.0</td> 1686<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> 1687<tr><td>v14.0.0</td> 1688<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> 1689<tr><td>v14.0.0</td> 1690<td><p>Callback will be invoked on streams which have already finished before the call to <code>finished(stream, cb)</code>.</p></td></tr> 1691<tr><td>v10.0.0</td> 1692<td><p><span>Added in: v10.0.0</span></p></td></tr> 1693</tbody></table> 1694</details> 1695</div> 1696<ul> 1697<li><code>stream</code> <a href="stream.html#stream_stream" class="type"><Stream></a> A readable and/or writable stream.</li> 1698<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 1699<ul> 1700<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 1701not treated as finished. <strong>Default</strong>: <code>true</code>.</li> 1702<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 1703the stream ends even though the stream might still be readable. 1704<strong>Default</strong>: <code>true</code>.</li> 1705<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 1706the stream ends even though the stream might still be writable. 1707<strong>Default</strong>: <code>true</code>.</li> 1708</ul> 1709</li> 1710<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 1711argument.</li> 1712<li>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 1713listeners.</li> 1714</ul> 1715<p>A function to get notified when a stream is no longer readable, writable 1716or has experienced an error or a premature close event.</p> 1717<pre><code class="language-js"><span class="hljs-keyword">const</span> { finished } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'stream'</span>); 1718 1719<span class="hljs-keyword">const</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>); 1720 1721<span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 1722 <span class="hljs-keyword">if</span> (err) { 1723 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Stream failed.'</span>, err); 1724 } <span class="hljs-keyword">else</span> { 1725 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>); 1726 } 1727}); 1728 1729rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code></pre> 1730<p>Especially useful in error handling scenarios where a stream is destroyed 1731prematurely (like an aborted HTTP request), and will not emit <code>'end'</code> 1732or <code>'finish'</code>.</p> 1733<p>The <code>finished</code> API is promisify-able as well;</p> 1734<pre><code class="language-js"><span class="hljs-keyword">const</span> finished = util.<span class="hljs-title function_">promisify</span>(stream.<span class="hljs-property">finished</span>); 1735 1736<span class="hljs-keyword">const</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>); 1737 1738<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 1739 <span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(rs); 1740 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>); 1741} 1742 1743<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>); 1744rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code></pre> 1745<p><code>stream.finished()</code> leaves dangling event listeners (in particular 1746<code>'error'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code>) after <code>callback</code> has been 1747invoked. The reason for this is so that unexpected <code>'error'</code> events (due to 1748incorrect stream implementations) do not cause unexpected crashes. 1749If this is unwanted behavior then the returned cleanup function needs to be 1750invoked in the callback:</p> 1751<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> { 1752 <span class="hljs-title function_">cleanup</span>(); 1753 <span class="hljs-comment">// ...</span> 1754});</code></pre> 1755<h4><code>stream.pipeline(source[, ...transforms], destination, callback)</code><span><a class="mark" href="#stream_stream_pipeline_source_transforms_destination_callback" id="stream_stream_pipeline_source_transforms_destination_callback">#</a></span></h4> 1756<h4><code>stream.pipeline(streams, callback)</code><span><a class="mark" href="#stream_stream_pipeline_streams_callback" id="stream_stream_pipeline_streams_callback">#</a></span></h4> 1757<div class="api_metadata"> 1758<details class="changelog"><summary>History</summary> 1759<table> 1760<tbody><tr><th>Version</th><th>Changes</th></tr> 1761<tr><td>v14.0.0</td> 1762<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> 1763<tr><td>v13.10.0</td> 1764<td><p>Add support for async generators.</p></td></tr> 1765<tr><td>v10.0.0</td> 1766<td><p><span>Added in: v10.0.0</span></p></td></tr> 1767</tbody></table> 1768</details> 1769</div> 1770<ul> 1771<li><code>streams</code> <a href="stream.html#stream_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> 1772<li><code>source</code> <a href="stream.html#stream_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> 1773<ul> 1774<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> 1775</ul> 1776</li> 1777<li><code>...transforms</code> <a href="stream.html#stream_stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> 1778<ul> 1779<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 1780<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 1781</ul> 1782</li> 1783<li><code>destination</code> <a href="stream.html#stream_stream" class="type"><Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> 1784<ul> 1785<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type"><AsyncIterable></a></li> 1786<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> 1787</ul> 1788</li> 1789<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. 1790<ul> 1791<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> 1792<li><code>val</code> Resolved value of <code>Promise</code> returned by <code>destination</code>.</li> 1793</ul> 1794</li> 1795<li>Returns: <a href="stream.html#stream_stream" class="type"><Stream></a></li> 1796</ul> 1797<p>A module method to pipe between streams and generators forwarding errors and 1798properly cleaning up and provide a callback when the pipeline is complete.</p> 1799<pre><code class="language-js"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'stream'</span>); 1800<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); 1801<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'zlib'</span>); 1802 1803<span class="hljs-comment">// Use the pipeline API to easily pipe a series of streams</span> 1804<span class="hljs-comment">// together and get notified when the pipeline is fully done.</span> 1805 1806<span class="hljs-comment">// A pipeline to gzip a potentially huge tar file efficiently:</span> 1807 1808<span class="hljs-title function_">pipeline</span>( 1809 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 1810 zlib.<span class="hljs-title function_">createGzip</span>(), 1811 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>), 1812 <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> { 1813 <span class="hljs-keyword">if</span> (err) { 1814 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Pipeline failed.'</span>, err); 1815 } <span class="hljs-keyword">else</span> { 1816 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 1817 } 1818 } 1819);</code></pre> 1820<p>The <code>pipeline</code> API is promisify-able as well:</p> 1821<pre><code class="language-js"><span class="hljs-keyword">const</span> pipeline = util.<span class="hljs-title function_">promisify</span>(stream.<span class="hljs-property">pipeline</span>); 1822 1823<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 1824 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 1825 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>), 1826 zlib.<span class="hljs-title function_">createGzip</span>(), 1827 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>) 1828 ); 1829 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 1830} 1831 1832<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></pre> 1833<p>The <code>pipeline</code> API also supports async generators:</p> 1834<pre><code class="language-js"><span class="hljs-keyword">const</span> pipeline = util.<span class="hljs-title function_">promisify</span>(stream.<span class="hljs-property">pipeline</span>); 1835<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); 1836 1837<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) { 1838 <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>( 1839 fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'lowercase.txt'</span>), 1840 <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* (source) { 1841 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> 1842 <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) { 1843 <span class="hljs-keyword">yield</span> chunk.<span class="hljs-title function_">toUpperCase</span>(); 1844 } 1845 }, 1846 fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>) 1847 ); 1848 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>); 1849} 1850 1851<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></pre> 1852<p><code>stream.pipeline()</code> will call <code>stream.destroy(err)</code> on all streams except:</p> 1853<ul> 1854<li><code>Readable</code> streams which have emitted <code>'end'</code> or <code>'close'</code>.</li> 1855<li><code>Writable</code> streams which have emitted <code>'finish'</code> or <code>'close'</code>.</li> 1856</ul> 1857<p><code>stream.pipeline()</code> leaves dangling event listeners on the streams 1858after the <code>callback</code> has been invoked. In the case of reuse of streams after 1859failure, this can cause event listener leaks and swallowed errors.</p> 1860<h4><code>stream.Readable.from(iterable, [options])</code><span><a class="mark" href="#stream_stream_readable_from_iterable_options" id="stream_stream_readable_from_iterable_options">#</a></span></h4> 1861<div class="api_metadata"> 1862<span>Added in: v12.3.0, v10.17.0</span> 1863</div> 1864<ul> 1865<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 1866<code>Symbol.iterator</code> iterable protocol. Emits an 'error' event if a null 1867value is passed.</li> 1868<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>. 1869By default, <code>Readable.from()</code> will set <code>options.objectMode</code> to <code>true</code>, unless 1870this is explicitly opted out by setting <code>options.objectMode</code> to <code>false</code>.</li> 1871<li>Returns: <a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a></li> 1872</ul> 1873<p>A utility method for creating readable streams out of iterators.</p> 1874<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">'stream'</span>); 1875 1876<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) { 1877 <span class="hljs-keyword">yield</span> <span class="hljs-string">'hello'</span>; 1878 <span class="hljs-keyword">yield</span> <span class="hljs-string">'streams'</span>; 1879} 1880 1881<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>()); 1882 1883readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 1884 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); 1885});</code></pre> 1886<p>Calling <code>Readable.from(string)</code> or <code>Readable.from(buffer)</code> will not have 1887the strings or buffers be iterated to match the other streams semantics 1888for performance reasons.</p> 1889</section><section><h3>API for stream implementers<span><a class="mark" href="#stream_api_for_stream_implementers" id="stream_api_for_stream_implementers">#</a></span></h3> 1890 1891<p>The <code>stream</code> module API has been designed to make it possible to easily 1892implement streams using JavaScript's prototypal inheritance model.</p> 1893<p>First, a stream developer would declare a new JavaScript class that extends one 1894of the four basic stream classes (<code>stream.Writable</code>, <code>stream.Readable</code>, 1895<code>stream.Duplex</code>, or <code>stream.Transform</code>), making sure they call the appropriate 1896parent class constructor:</p> 1897<!-- eslint-disable no-useless-constructor --> 1898<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">'stream'</span>); 1899 1900<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> { 1901 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">{ highWaterMark, ...options }</span>) { 1902 <span class="hljs-variable language_">super</span>({ highWaterMark }); 1903 <span class="hljs-comment">// ...</span> 1904 } 1905}</code></pre> 1906<p>When extending streams, keep in mind what options the user 1907can and should provide before forwarding these to the base constructor. For 1908example, if the implementation makes assumptions in regard to the 1909<code>autoDestroy</code> and <code>emitClose</code> options, do not allow the 1910user to override these. Be explicit about what 1911options are forwarded instead of implicitly forwarding all options.</p> 1912<p>The new stream class must then implement one or more specific methods, depending 1913on the type of stream being created, as detailed in the chart below:</p> 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944<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="#stream_class_stream_readable"><code>Readable</code></a></td><td><a href="#stream_readable_read_size_1"><code>_read()</code></a></td></tr><tr><td>Writing only</td><td><a href="#stream_class_stream_writable"><code>Writable</code></a></td><td><a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write()</code></a>, <a href="#stream_writable_writev_chunks_callback"><code>_writev()</code></a>, <a href="#stream_writable_final_callback"><code>_final()</code></a></td></tr><tr><td>Reading and writing</td><td><a href="#stream_class_stream_duplex"><code>Duplex</code></a></td><td><a href="#stream_readable_read_size_1"><code>_read()</code></a>, <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write()</code></a>, <a href="#stream_writable_writev_chunks_callback"><code>_writev()</code></a>, <a href="#stream_writable_final_callback"><code>_final()</code></a></td></tr><tr><td>Operate on written data, then read the result</td><td><a href="#stream_class_stream_transform"><code>Transform</code></a></td><td><a href="#stream_transform_transform_chunk_encoding_callback"><code>_transform()</code></a>, <a href="#stream_transform_flush_callback"><code>_flush()</code></a>, <a href="#stream_writable_final_callback"><code>_final()</code></a></td></tr></tbody></table> 1945<p>The implementation code for a stream should <em>never</em> call the "public" methods 1946of a stream that are intended for use by consumers (as described in the 1947<a href="#stream_api_for_stream_consumers">API for stream consumers</a> section). Doing so may lead to adverse side effects 1948in application code consuming the stream.</p> 1949<p>Avoid overriding public methods such as <code>write()</code>, <code>end()</code>, <code>cork()</code>, 1950<code>uncork()</code>, <code>read()</code> and <code>destroy()</code>, or emitting internal events such 1951as <code>'error'</code>, <code>'data'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code> through <code>.emit()</code>. 1952Doing so can break current and future stream invariants leading to behavior 1953and/or compatibility issues with other streams, stream utilities, and user 1954expectations.</p> 1955<h4>Simplified construction<span><a class="mark" href="#stream_simplified_construction" id="stream_simplified_construction">#</a></span></h4> 1956<div class="api_metadata"> 1957<span>Added in: v1.2.0</span> 1958</div> 1959<p>For many simple cases, it is possible to construct a stream without relying on 1960inheritance. This can be accomplished by directly creating instances of the 1961<code>stream.Writable</code>, <code>stream.Readable</code>, <code>stream.Duplex</code> or <code>stream.Transform</code> 1962objects and passing appropriate methods as constructor options.</p> 1963<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">'stream'</span>); 1964 1965<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 1966 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 1967 <span class="hljs-comment">// ...</span> 1968 } 1969});</code></pre> 1970<h4>Implementing a writable stream<span><a class="mark" href="#stream_implementing_a_writable_stream" id="stream_implementing_a_writable_stream">#</a></span></h4> 1971<p>The <code>stream.Writable</code> class is extended to implement a <a href="#stream_class_stream_writable"><code>Writable</code></a> stream.</p> 1972<p>Custom <code>Writable</code> streams <em>must</em> call the <code>new stream.Writable([options])</code> 1973constructor and implement the <code>writable._write()</code> and/or <code>writable._writev()</code> 1974method.</p> 1975<h5><code>new stream.Writable([options])</code><span><a class="mark" href="#stream_new_stream_writable_options" id="stream_new_stream_writable_options">#</a></span></h5> 1976<div class="api_metadata"> 1977<details class="changelog"><summary>History</summary> 1978<table> 1979<tbody><tr><th>Version</th><th>Changes</th></tr> 1980<tr><td>v14.0.0</td> 1981<td><p>Change <code>autoDestroy</code> option default to <code>true</code>.</p></td></tr> 1982<tr><td>v11.2.0, v10.16.0</td> 1983<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> 1984<tr><td>v10.0.0</td> 1985<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> 1986</tbody></table> 1987</details> 1988</div> 1989<ul> 1990<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 1991<ul> 1992<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 1993<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> starts returning <code>false</code>. <strong>Default:</strong> 1994<code>16384</code> (16KB), or <code>16</code> for <code>objectMode</code> streams.</li> 1995<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 1996<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> to <code>Buffer</code>s (with the encoding 1997specified in the <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> call) before passing 1998them to <a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write()</code></a>. Other types of data are not 1999converted (i.e. <code>Buffer</code>s are not decoded into <code>string</code>s). Setting to 2000false will prevent <code>string</code>s from being converted. <strong>Default:</strong> <code>true</code>.</li> 2001<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 2002encoding is specified as an argument to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>. 2003<strong>Default:</strong> <code>'utf8'</code>.</li> 2004<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 2005<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(anyObj)</code></a> is a valid operation. When set, 2006it becomes possible to write JavaScript values other than string, 2007<code>Buffer</code> or <code>Uint8Array</code> if supported by the stream implementation. 2008<strong>Default:</strong> <code>false</code>.</li> 2009<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> 2010after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li> 2011<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 2012<a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write()</code></a> method.</li> 2013<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 2014<a href="#stream_writable_writev_chunks_callback"><code>stream._writev()</code></a> method.</li> 2015<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 2016<a href="#stream_writable_destroy_err_callback"><code>stream._destroy()</code></a> method.</li> 2017<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 2018<a href="#stream_writable_final_callback"><code>stream._final()</code></a> method.</li> 2019<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 2020<code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>true</code>.</li> 2021</ul> 2022</li> 2023</ul> 2024<!-- eslint-disable no-useless-constructor --> 2025<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">'stream'</span>); 2026 2027<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> { 2028 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 2029 <span class="hljs-comment">// Calls the stream.Writable() constructor.</span> 2030 <span class="hljs-variable language_">super</span>(options); 2031 <span class="hljs-comment">// ...</span> 2032 } 2033}</code></pre> 2034<p>Or, when using pre-ES6 style constructors:</p> 2035<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">'stream'</span>); 2036<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'util'</span>); 2037 2038<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyWritable</span>(<span class="hljs-params">options</span>) { 2039 <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>)) 2040 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyWritable</span>(options); 2041 <span class="hljs-title class_">Writable</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 2042} 2043util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyWritable</span>, <span class="hljs-title class_">Writable</span>);</code></pre> 2044<p>Or, using the simplified constructor approach:</p> 2045<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">'stream'</span>); 2046 2047<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 2048 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 2049 <span class="hljs-comment">// ...</span> 2050 }, 2051 <span class="hljs-title function_">writev</span>(<span class="hljs-params">chunks, callback</span>) { 2052 <span class="hljs-comment">// ...</span> 2053 } 2054});</code></pre> 2055<h5><code>writable._write(chunk, encoding, callback)</code><span><a class="mark" href="#stream_writable_write_chunk_encoding_callback_1" id="stream_writable_write_chunk_encoding_callback_1">#</a></span></h5> 2056<div class="api_metadata"> 2057<details class="changelog"><summary>History</summary> 2058<table> 2059<tbody><tr><th>Version</th><th>Changes</th></tr> 2060<tr><td>v12.11.0</td> 2061<td><p>_write() is optional when providing _writev().</p></td></tr> 2062</tbody></table> 2063</details> 2064</div> 2065<ul> 2066<li><code>chunk</code> <a href="buffer.html#buffer_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 2067<code>string</code> passed to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>. If the stream's 2068<code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode, 2069the chunk will not be converted & will be whatever was passed to 2070<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>.</li> 2071<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 2072character encoding of that string. If chunk is a <code>Buffer</code>, or if the 2073stream is operating in object mode, <code>encoding</code> may be ignored.</li> 2074<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 2075argument) when processing is complete for the supplied chunk.</li> 2076</ul> 2077<p>All <code>Writable</code> stream implementations must provide a 2078<a href="#stream_writable_write_chunk_encoding_callback_1"><code>writable._write()</code></a> and/or 2079<a href="#stream_writable_writev_chunks_callback"><code>writable._writev()</code></a> method to send data to the underlying 2080resource.</p> 2081<p><a href="#stream_class_stream_transform"><code>Transform</code></a> streams provide their own implementation of the 2082<a href="#stream_writable_write_chunk_encoding_callback_1"><code>writable._write()</code></a>.</p> 2083<p>This function MUST NOT be called by application code directly. It should be 2084implemented by child classes, and called by the internal <code>Writable</code> class 2085methods only.</p> 2086<p>The <code>callback</code> function must be called synchronously inside of 2087<code>writable._write()</code> or asynchronously (i.e. different tick) to signal either 2088that the write completed successfully or failed with an error. 2089The first argument passed to the <code>callback</code> must be the <code>Error</code> object if the 2090call failed or <code>null</code> if the write succeeded.</p> 2091<p>All calls to <code>writable.write()</code> that occur between the time <code>writable._write()</code> 2092is called and the <code>callback</code> is called will cause the written data to be 2093buffered. When the <code>callback</code> is invoked, the stream might emit a <a href="#stream_event_drain"><code>'drain'</code></a> 2094event. If a stream implementation is capable of processing multiple chunks of 2095data at once, the <code>writable._writev()</code> method should be implemented.</p> 2096<p>If the <code>decodeStrings</code> property is explicitly set to <code>false</code> in the constructor 2097options, then <code>chunk</code> will remain the same object that is passed to <code>.write()</code>, 2098and may be a string rather than a <code>Buffer</code>. This is to support implementations 2099that have an optimized handling for certain string data encodings. In that case, 2100the <code>encoding</code> argument will indicate the character encoding of the string. 2101Otherwise, the <code>encoding</code> argument can be safely ignored.</p> 2102<p>The <code>writable._write()</code> method is prefixed with an underscore because it is 2103internal to the class that defines it, and should never be called directly by 2104user programs.</p> 2105<h5><code>writable._writev(chunks, callback)</code><span><a class="mark" href="#stream_writable_writev_chunks_callback" id="stream_writable_writev_chunks_callback">#</a></span></h5> 2106<ul> 2107<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> 2108that each represent a discrete chunk of data to write. The properties of 2109these objects are: 2110<ul> 2111<li><code>chunk</code> <a href="buffer.html#buffer_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 2112be written. The <code>chunk</code> will be a string if the <code>Writable</code> was created with 2113the <code>decodeStrings</code> option set to <code>false</code> and a string was passed to <code>write()</code>.</li> 2114<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 2115a <code>Buffer</code>, the <code>encoding</code> will be <code>'buffer'</code>.</li> 2116</ul> 2117</li> 2118<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 2119argument) to be invoked when processing is complete for the supplied chunks.</li> 2120</ul> 2121<p>This function MUST NOT be called by application code directly. It should be 2122implemented by child classes, and called by the internal <code>Writable</code> class 2123methods only.</p> 2124<p>The <code>writable._writev()</code> method may be implemented in addition or alternatively 2125to <code>writable._write()</code> in stream implementations that are capable of processing 2126multiple chunks of data at once. If implemented and if there is buffered data 2127from previous writes, <code>_writev()</code> will be called instead of <code>_write()</code>.</p> 2128<p>The <code>writable._writev()</code> method is prefixed with an underscore because it is 2129internal to the class that defines it, and should never be called directly by 2130user programs.</p> 2131<h5><code>writable._destroy(err, callback)</code><span><a class="mark" href="#stream_writable_destroy_err_callback" id="stream_writable_destroy_err_callback">#</a></span></h5> 2132<div class="api_metadata"> 2133<span>Added in: v8.0.0</span> 2134</div> 2135<ul> 2136<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> 2137<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 2138argument.</li> 2139</ul> 2140<p>The <code>_destroy()</code> method is called by <a href="#stream_writable_destroy_error"><code>writable.destroy()</code></a>. 2141It can be overridden by child classes but it <strong>must not</strong> be called directly.</p> 2142<h5><code>writable._final(callback)</code><span><a class="mark" href="#stream_writable_final_callback" id="stream_writable_final_callback">#</a></span></h5> 2143<div class="api_metadata"> 2144<span>Added in: v8.0.0</span> 2145</div> 2146<ul> 2147<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 2148argument) when finished writing any remaining data.</li> 2149</ul> 2150<p>The <code>_final()</code> method <strong>must not</strong> be called directly. It may be implemented 2151by child classes, and if so, will be called by the internal <code>Writable</code> 2152class methods only.</p> 2153<p>This optional function will be called before the stream closes, delaying the 2154<code>'finish'</code> event until <code>callback</code> is called. This is useful to close resources 2155or write buffered data before a stream ends.</p> 2156<h5>Errors while writing<span><a class="mark" href="#stream_errors_while_writing" id="stream_errors_while_writing">#</a></span></h5> 2157<p>Errors occurring during the processing of the <a href="#stream_writable_write_chunk_encoding_callback_1"><code>writable._write()</code></a>, 2158<a href="#stream_writable_writev_chunks_callback"><code>writable._writev()</code></a> and <a href="#stream_writable_final_callback"><code>writable._final()</code></a> methods must be propagated 2159by invoking the callback and passing the error as the first argument. 2160Throwing an <code>Error</code> from within these methods or manually emitting an <code>'error'</code> 2161event results in undefined behavior.</p> 2162<p>If a <code>Readable</code> stream pipes into a <code>Writable</code> stream when <code>Writable</code> emits an 2163error, the <code>Readable</code> stream will be unpiped.</p> 2164<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">'stream'</span>); 2165 2166<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({ 2167 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 2168 <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>) { 2169 <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>)); 2170 } <span class="hljs-keyword">else</span> { 2171 <span class="hljs-title function_">callback</span>(); 2172 } 2173 } 2174});</code></pre> 2175<h5>An example writable stream<span><a class="mark" href="#stream_an_example_writable_stream" id="stream_an_example_writable_stream">#</a></span></h5> 2176<p>The following illustrates a rather simplistic (and somewhat pointless) custom 2177<code>Writable</code> stream implementation. While this specific <code>Writable</code> stream instance 2178is not of any real particular usefulness, the example illustrates each of the 2179required elements of a custom <a href="#stream_class_stream_writable"><code>Writable</code></a> stream instance:</p> 2180<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">'stream'</span>); 2181 2182<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> { 2183 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 2184 <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>) { 2185 <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>)); 2186 } <span class="hljs-keyword">else</span> { 2187 <span class="hljs-title function_">callback</span>(); 2188 } 2189 } 2190}</code></pre> 2191<h5>Decoding buffers in a writable stream<span><a class="mark" href="#stream_decoding_buffers_in_a_writable_stream" id="stream_decoding_buffers_in_a_writable_stream">#</a></span></h5> 2192<p>Decoding buffers is a common task, for instance, when using transformers whose 2193input is a string. This is not a trivial process when using multi-byte 2194characters encoding, such as UTF-8. The following example shows how to decode 2195multi-byte strings using <code>StringDecoder</code> and <a href="#stream_class_stream_writable"><code>Writable</code></a>.</p> 2196<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">'stream'</span>); 2197<span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'string_decoder'</span>); 2198 2199<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> { 2200 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 2201 <span class="hljs-variable language_">super</span>(options); 2202 <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>); 2203 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> = <span class="hljs-string">''</span>; 2204 } 2205 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 2206 <span class="hljs-keyword">if</span> (encoding === <span class="hljs-string">'buffer'</span>) { 2207 chunk = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span>.<span class="hljs-title function_">write</span>(chunk); 2208 } 2209 <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += chunk; 2210 <span class="hljs-title function_">callback</span>(); 2211 } 2212 <span class="hljs-title function_">_final</span>(<span class="hljs-params">callback</span>) { 2213 <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>(); 2214 <span class="hljs-title function_">callback</span>(); 2215 } 2216} 2217 2218<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>); 2219<span class="hljs-keyword">const</span> w = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringWritable</span>(); 2220 2221w.<span class="hljs-title function_">write</span>(<span class="hljs-string">'currency: '</span>); 2222w.<span class="hljs-title function_">write</span>(euro[<span class="hljs-number">0</span>]); 2223w.<span class="hljs-title function_">end</span>(euro[<span class="hljs-number">1</span>]); 2224 2225<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></pre> 2226<h4>Implementing a readable stream<span><a class="mark" href="#stream_implementing_a_readable_stream" id="stream_implementing_a_readable_stream">#</a></span></h4> 2227<p>The <code>stream.Readable</code> class is extended to implement a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream.</p> 2228<p>Custom <code>Readable</code> streams <em>must</em> call the <code>new stream.Readable([options])</code> 2229constructor and implement the <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> method.</p> 2230<h5><code>new stream.Readable([options])</code><span><a class="mark" href="#stream_new_stream_readable_options" id="stream_new_stream_readable_options">#</a></span></h5> 2231<div class="api_metadata"> 2232<details class="changelog"><summary>History</summary> 2233<table> 2234<tbody><tr><th>Version</th><th>Changes</th></tr> 2235<tr><td>v14.0.0</td> 2236<td><p>Change <code>autoDestroy</code> option default to <code>true</code>.</p></td></tr> 2237<tr><td>v11.2.0, v10.16.0</td> 2238<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> 2239</tbody></table> 2240</details> 2241</div> 2242<ul> 2243<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> 2244<ul> 2245<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="#stream_highwatermark_discrepancy_after_calling_readable_setencoding">number of bytes</a> to store 2246in the internal buffer before ceasing to read from the underlying resource. 2247<strong>Default:</strong> <code>16384</code> (16KB), or <code>16</code> for <code>objectMode</code> streams.</li> 2248<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 2249strings using the specified encoding. <strong>Default:</strong> <code>null</code>.</li> 2250<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 2251as a stream of objects. Meaning that <a href="#stream_readable_read_size"><code>stream.read(n)</code></a> returns 2252a single value instead of a <code>Buffer</code> of size <code>n</code>. <strong>Default:</strong> <code>false</code>.</li> 2253<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> 2254after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li> 2255<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="#stream_readable_read_size_1"><code>stream._read()</code></a> 2256method.</li> 2257<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 2258<a href="#stream_readable_destroy_err_callback"><code>stream._destroy()</code></a> method.</li> 2259<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 2260<code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>true</code>.</li> 2261</ul> 2262</li> 2263</ul> 2264<!-- eslint-disable no-useless-constructor --> 2265<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">'stream'</span>); 2266 2267<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> { 2268 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 2269 <span class="hljs-comment">// Calls the stream.Readable(options) constructor.</span> 2270 <span class="hljs-variable language_">super</span>(options); 2271 <span class="hljs-comment">// ...</span> 2272 } 2273}</code></pre> 2274<p>Or, when using pre-ES6 style constructors:</p> 2275<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">'stream'</span>); 2276<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'util'</span>); 2277 2278<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyReadable</span>(<span class="hljs-params">options</span>) { 2279 <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>)) 2280 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyReadable</span>(options); 2281 <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 2282} 2283util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyReadable</span>, <span class="hljs-title class_">Readable</span>);</code></pre> 2284<p>Or, using the simplified constructor approach:</p> 2285<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">'stream'</span>); 2286 2287<span class="hljs-keyword">const</span> myReadable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({ 2288 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 2289 <span class="hljs-comment">// ...</span> 2290 } 2291});</code></pre> 2292<h5><code>readable._read(size)</code><span><a class="mark" href="#stream_readable_read_size_1" id="stream_readable_read_size_1">#</a></span></h5> 2293<div class="api_metadata"> 2294<span>Added in: v0.9.4</span> 2295</div> 2296<ul> 2297<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> 2298</ul> 2299<p>This function MUST NOT be called by application code directly. It should be 2300implemented by child classes, and called by the internal <code>Readable</code> class 2301methods only.</p> 2302<p>All <code>Readable</code> stream implementations must provide an implementation of the 2303<a href="#stream_readable_read_size_1"><code>readable._read()</code></a> method to fetch data from the underlying resource.</p> 2304<p>When <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> is called, if data is available from the resource, 2305the implementation should begin pushing that data into the read queue using the 2306<a href="#stream_readable_push_chunk_encoding"><code>this.push(dataChunk)</code></a> method. <code>_read()</code> will be called again 2307after each call to <a href="#stream_readable_push_chunk_encoding"><code>this.push(dataChunk)</code></a> once the stream is 2308ready to accept more data. <code>_read()</code> may continue reading from the resource and 2309pushing data until <code>readable.push()</code> returns <code>false</code>. Only when <code>_read()</code> is 2310called again after it has stopped should it resume pushing additional data into 2311the queue.</p> 2312<p>Once the <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> method has been called, it will not be called 2313again until more data is pushed through the <a href="#stream_readable_push_chunk_encoding"><code>readable.push()</code></a> 2314method. Empty data such as empty buffers and strings will not cause 2315<a href="#stream_readable_read_size_1"><code>readable._read()</code></a> to be called.</p> 2316<p>The <code>size</code> argument is advisory. For implementations where a "read" is a 2317single operation that returns data can use the <code>size</code> argument to determine how 2318much data to fetch. Other implementations may ignore this argument and simply 2319provide data whenever it becomes available. There is no need to "wait" until 2320<code>size</code> bytes are available before calling <a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>.</p> 2321<p>The <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> method is prefixed with an underscore because it is 2322internal to the class that defines it, and should never be called directly by 2323user programs.</p> 2324<h5><code>readable._destroy(err, callback)</code><span><a class="mark" href="#stream_readable_destroy_err_callback" id="stream_readable_destroy_err_callback">#</a></span></h5> 2325<div class="api_metadata"> 2326<span>Added in: v8.0.0</span> 2327</div> 2328<ul> 2329<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> 2330<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 2331argument.</li> 2332</ul> 2333<p>The <code>_destroy()</code> method is called by <a href="#stream_readable_destroy_error"><code>readable.destroy()</code></a>. 2334It can be overridden by child classes but it <strong>must not</strong> be called directly.</p> 2335<h5><code>readable.push(chunk[, encoding])</code><span><a class="mark" href="#stream_readable_push_chunk_encoding" id="stream_readable_push_chunk_encoding">#</a></span></h5> 2336<div class="api_metadata"> 2337<details class="changelog"><summary>History</summary> 2338<table> 2339<tbody><tr><th>Version</th><th>Changes</th></tr> 2340<tr><td>v8.0.0</td> 2341<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> 2342</tbody></table> 2343</details> 2344</div> 2345<ul> 2346<li><code>chunk</code> <a href="buffer.html#buffer_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 2347read queue. For streams not operating in object mode, <code>chunk</code> must be a 2348string, <code>Buffer</code> or <code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be 2349any JavaScript value.</li> 2350<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 2351<code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li> 2352<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 2353pushed; <code>false</code> otherwise.</li> 2354</ul> 2355<p>When <code>chunk</code> is a <code>Buffer</code>, <code>Uint8Array</code> or <code>string</code>, the <code>chunk</code> of data will 2356be added to the internal queue for users of the stream to consume. 2357Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF), after which no 2358more data can be written.</p> 2359<p>When the <code>Readable</code> is operating in paused mode, the data added with 2360<code>readable.push()</code> can be read out by calling the 2361<a href="#stream_readable_read_size"><code>readable.read()</code></a> method when the <a href="#stream_event_readable"><code>'readable'</code></a> event is 2362emitted.</p> 2363<p>When the <code>Readable</code> is operating in flowing mode, the data added with 2364<code>readable.push()</code> will be delivered by emitting a <code>'data'</code> event.</p> 2365<p>The <code>readable.push()</code> method is designed to be as flexible as possible. For 2366example, when wrapping a lower-level source that provides some form of 2367pause/resume mechanism, and a data callback, the low-level source can be wrapped 2368by the custom <code>Readable</code> instance:</p> 2369<pre><code class="language-js"><span class="hljs-comment">// `_source` is an object with readStop() and readStart() methods,</span> 2370<span class="hljs-comment">// and an `ondata` member that gets called when it has data, and</span> 2371<span class="hljs-comment">// an `onend` member that gets called when the data is over.</span> 2372 2373<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> { 2374 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 2375 <span class="hljs-variable language_">super</span>(options); 2376 2377 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span> = <span class="hljs-title function_">getLowLevelSourceObject</span>(); 2378 2379 <span class="hljs-comment">// Every time there's data, push it into the internal buffer.</span> 2380 <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> { 2381 <span class="hljs-comment">// If push() returns false, then stop reading from source.</span> 2382 <span class="hljs-keyword">if</span> (!<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(chunk)) 2383 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-title function_">readStop</span>(); 2384 }; 2385 2386 <span class="hljs-comment">// When the source ends, push the EOF-signaling `null` chunk.</span> 2387 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-property">onend</span> = <span class="hljs-function">() =></span> { 2388 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>); 2389 }; 2390 } 2391 <span class="hljs-comment">// _read() will be called when the stream wants to pull more data in.</span> 2392 <span class="hljs-comment">// The advisory size argument is ignored in this case.</span> 2393 <span class="hljs-title function_">_read</span>(<span class="hljs-params">size</span>) { 2394 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-title function_">readStart</span>(); 2395 } 2396}</code></pre> 2397<p>The <code>readable.push()</code> method is used to push the content 2398into the internal buffer. It can be driven by the <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> method.</p> 2399<p>For streams not operating in object mode, if the <code>chunk</code> parameter of 2400<code>readable.push()</code> is <code>undefined</code>, it will be treated as empty string or 2401buffer. See <a href="#stream_readable_push"><code>readable.push('')</code></a> for more information.</p> 2402<h5>Errors while reading<span><a class="mark" href="#stream_errors_while_reading" id="stream_errors_while_reading">#</a></span></h5> 2403<p>Errors occurring during processing of the <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> must be 2404propagated through the <a href="#stream_readable_destroy_err_callback"><code>readable.destroy(err)</code></a> method. 2405Throwing an <code>Error</code> from within <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> or manually emitting an 2406<code>'error'</code> event results in undefined behavior.</p> 2407<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">'stream'</span>); 2408 2409<span class="hljs-keyword">const</span> myReadable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({ 2410 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 2411 <span class="hljs-keyword">const</span> err = <span class="hljs-title function_">checkSomeErrorCondition</span>(); 2412 <span class="hljs-keyword">if</span> (err) { 2413 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err); 2414 } <span class="hljs-keyword">else</span> { 2415 <span class="hljs-comment">// Do some work.</span> 2416 } 2417 } 2418});</code></pre> 2419<h5>An example counting stream<span><a class="mark" href="#stream_an_example_counting_stream" id="stream_an_example_counting_stream">#</a></span></h5> 2420 2421<p>The following is a basic example of a <code>Readable</code> stream that emits the numerals 2422from 1 to 1,000,000 in ascending order, and then ends.</p> 2423<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">'stream'</span>); 2424 2425<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> { 2426 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">opt</span>) { 2427 <span class="hljs-variable language_">super</span>(opt); 2428 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_max</span> = <span class="hljs-number">1000000</span>; 2429 <span class="hljs-variable language_">this</span>.<span class="hljs-property">_index</span> = <span class="hljs-number">1</span>; 2430 } 2431 2432 <span class="hljs-title function_">_read</span>(<span class="hljs-params"></span>) { 2433 <span class="hljs-keyword">const</span> i = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_index</span>++; 2434 <span class="hljs-keyword">if</span> (i > <span class="hljs-variable language_">this</span>.<span class="hljs-property">_max</span>) 2435 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>); 2436 <span class="hljs-keyword">else</span> { 2437 <span class="hljs-keyword">const</span> str = <span class="hljs-title class_">String</span>(i); 2438 <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>); 2439 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(buf); 2440 } 2441 } 2442}</code></pre> 2443<h4>Implementing a duplex stream<span><a class="mark" href="#stream_implementing_a_duplex_stream" id="stream_implementing_a_duplex_stream">#</a></span></h4> 2444<p>A <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream is one that implements both <a href="#stream_class_stream_readable"><code>Readable</code></a> and 2445<a href="#stream_class_stream_writable"><code>Writable</code></a>, such as a TCP socket connection.</p> 2446<p>Because JavaScript does not have support for multiple inheritance, the 2447<code>stream.Duplex</code> class is extended to implement a <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream (as opposed 2448to extending the <code>stream.Readable</code> <em>and</em> <code>stream.Writable</code> classes).</p> 2449<p>The <code>stream.Duplex</code> class prototypically inherits from <code>stream.Readable</code> and 2450parasitically from <code>stream.Writable</code>, but <code>instanceof</code> will work properly for 2451both 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 2452<code>stream.Writable</code>.</p> 2453<p>Custom <code>Duplex</code> streams <em>must</em> call the <code>new stream.Duplex([options])</code> 2454constructor and implement <em>both</em> the <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> and 2455<code>writable._write()</code> methods.</p> 2456<h5><code>new stream.Duplex(options)</code><span><a class="mark" href="#stream_new_stream_duplex_options" id="stream_new_stream_duplex_options">#</a></span></h5> 2457<div class="api_metadata"> 2458<details class="changelog"><summary>History</summary> 2459<table> 2460<tbody><tr><th>Version</th><th>Changes</th></tr> 2461<tr><td>v8.4.0</td> 2462<td><p>The <code>readableHighWaterMark</code> and <code>writableHighWaterMark</code> options are supported now.</p></td></tr> 2463</tbody></table> 2464</details> 2465</div> 2466<ul> 2467<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> 2468constructors. Also has the following fields: 2469<ul> 2470<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 2471automatically end the writable side when the readable side ends. 2472<strong>Default:</strong> <code>true</code>.</li> 2473<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. 2474<strong>Default:</strong> <code>true</code>.</li> 2475<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. 2476<strong>Default:</strong> <code>true</code>.</li> 2477<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 2478stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li> 2479<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 2480stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li> 2481<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 2482of the stream. Has no effect if <code>highWaterMark</code> is provided.</li> 2483<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 2484of the stream. Has no effect if <code>highWaterMark</code> is provided.</li> 2485</ul> 2486</li> 2487</ul> 2488<!-- eslint-disable no-useless-constructor --> 2489<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">'stream'</span>); 2490 2491<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> { 2492 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 2493 <span class="hljs-variable language_">super</span>(options); 2494 <span class="hljs-comment">// ...</span> 2495 } 2496}</code></pre> 2497<p>Or, when using pre-ES6 style constructors:</p> 2498<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">'stream'</span>); 2499<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'util'</span>); 2500 2501<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyDuplex</span>(<span class="hljs-params">options</span>) { 2502 <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>)) 2503 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyDuplex</span>(options); 2504 <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 2505} 2506util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyDuplex</span>, <span class="hljs-title class_">Duplex</span>);</code></pre> 2507<p>Or, using the simplified constructor approach:</p> 2508<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">'stream'</span>); 2509 2510<span class="hljs-keyword">const</span> myDuplex = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Duplex</span>({ 2511 <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) { 2512 <span class="hljs-comment">// ...</span> 2513 }, 2514 <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 2515 <span class="hljs-comment">// ...</span> 2516 } 2517});</code></pre> 2518<h5>An example duplex stream<span><a class="mark" href="#stream_an_example_duplex_stream" id="stream_an_example_duplex_stream">#</a></span></h5> 2519<p>The following illustrates a simple example of a <code>Duplex</code> stream that wraps a 2520hypothetical lower-level source object to which data can be written, and 2521from which data can be read, albeit using an API that is not compatible with 2522Node.js streams. 2523The following illustrates a simple example of a <code>Duplex</code> stream that buffers 2524incoming written data via the <a href="#stream_class_stream_writable"><code>Writable</code></a> interface that is read back out 2525via the <a href="#stream_class_stream_readable"><code>Readable</code></a> interface.</p> 2526<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">'stream'</span>); 2527<span class="hljs-keyword">const</span> kSource = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'source'</span>); 2528 2529<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> { 2530 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">source, options</span>) { 2531 <span class="hljs-variable language_">super</span>(options); 2532 <span class="hljs-variable language_">this</span>[kSource] = source; 2533 } 2534 2535 <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 2536 <span class="hljs-comment">// The underlying source only deals with strings.</span> 2537 <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(chunk)) 2538 chunk = chunk.<span class="hljs-title function_">toString</span>(); 2539 <span class="hljs-variable language_">this</span>[kSource].<span class="hljs-title function_">writeSomeData</span>(chunk); 2540 <span class="hljs-title function_">callback</span>(); 2541 } 2542 2543 <span class="hljs-title function_">_read</span>(<span class="hljs-params">size</span>) { 2544 <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> { 2545 <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)); 2546 }); 2547 } 2548}</code></pre> 2549<p>The most important aspect of a <code>Duplex</code> stream is that the <code>Readable</code> and 2550<code>Writable</code> sides operate independently of one another despite co-existing within 2551a single object instance.</p> 2552<h5>Object mode duplex streams<span><a class="mark" href="#stream_object_mode_duplex_streams" id="stream_object_mode_duplex_streams">#</a></span></h5> 2553<p>For <code>Duplex</code> streams, <code>objectMode</code> can be set exclusively for either the 2554<code>Readable</code> or <code>Writable</code> side using the <code>readableObjectMode</code> and 2555<code>writableObjectMode</code> options respectively.</p> 2556<p>In the following example, for instance, a new <code>Transform</code> stream (which is a 2557type of <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream) is created that has an object mode <code>Writable</code> side 2558that accepts JavaScript numbers that are converted to hexadecimal strings on 2559the <code>Readable</code> side.</p> 2560<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">'stream'</span>); 2561 2562<span class="hljs-comment">// All Transform streams are also Duplex Streams.</span> 2563<span class="hljs-keyword">const</span> myTransform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({ 2564 <span class="hljs-attr">writableObjectMode</span>: <span class="hljs-literal">true</span>, 2565 2566 <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 2567 <span class="hljs-comment">// Coerce the chunk to a number if necessary.</span> 2568 chunk |= <span class="hljs-number">0</span>; 2569 2570 <span class="hljs-comment">// Transform the chunk into something else.</span> 2571 <span class="hljs-keyword">const</span> data = chunk.<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>); 2572 2573 <span class="hljs-comment">// Push the data onto the readable queue.</span> 2574 <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); 2575 } 2576}); 2577 2578myTransform.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'ascii'</span>); 2579myTransform.<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)); 2580 2581myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">1</span>); 2582<span class="hljs-comment">// Prints: 01</span> 2583myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">10</span>); 2584<span class="hljs-comment">// Prints: 0a</span> 2585myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">100</span>); 2586<span class="hljs-comment">// Prints: 64</span></code></pre> 2587<h4>Implementing a transform stream<span><a class="mark" href="#stream_implementing_a_transform_stream" id="stream_implementing_a_transform_stream">#</a></span></h4> 2588<p>A <a href="#stream_class_stream_transform"><code>Transform</code></a> stream is a <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream where the output is computed 2589in some way from the input. Examples include <a href="zlib.html">zlib</a> streams or <a href="crypto.html">crypto</a> 2590streams that compress, encrypt, or decrypt data.</p> 2591<p>There is no requirement that the output be the same size as the input, the same 2592number of chunks, or arrive at the same time. For example, a <code>Hash</code> stream will 2593only ever have a single chunk of output which is provided when the input is 2594ended. A <code>zlib</code> stream will produce output that is either much smaller or much 2595larger than its input.</p> 2596<p>The <code>stream.Transform</code> class is extended to implement a <a href="#stream_class_stream_transform"><code>Transform</code></a> stream.</p> 2597<p>The <code>stream.Transform</code> class prototypically inherits from <code>stream.Duplex</code> and 2598implements its own versions of the <code>writable._write()</code> and 2599<a href="#stream_readable_read_size_1"><code>readable._read()</code></a> methods. Custom <code>Transform</code> implementations <em>must</em> 2600implement the <a href="#stream_transform_transform_chunk_encoding_callback"><code>transform._transform()</code></a> method and <em>may</em> 2601also implement the <a href="#stream_transform_flush_callback"><code>transform._flush()</code></a> method.</p> 2602<p>Care must be taken when using <code>Transform</code> streams in that data written to the 2603stream can cause the <code>Writable</code> side of the stream to become paused if the 2604output on the <code>Readable</code> side is not consumed.</p> 2605<h5><code>new stream.Transform([options])</code><span><a class="mark" href="#stream_new_stream_transform_options" id="stream_new_stream_transform_options">#</a></span></h5> 2606<ul> 2607<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> 2608constructors. Also has the following fields: 2609<ul> 2610<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 2611<a href="#stream_transform_transform_chunk_encoding_callback"><code>stream._transform()</code></a> method.</li> 2612<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="#stream_transform_flush_callback"><code>stream._flush()</code></a> 2613method.</li> 2614</ul> 2615</li> 2616</ul> 2617<!-- eslint-disable no-useless-constructor --> 2618<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">'stream'</span>); 2619 2620<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> { 2621 <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) { 2622 <span class="hljs-variable language_">super</span>(options); 2623 <span class="hljs-comment">// ...</span> 2624 } 2625}</code></pre> 2626<p>Or, when using pre-ES6 style constructors:</p> 2627<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">'stream'</span>); 2628<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'util'</span>); 2629 2630<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyTransform</span>(<span class="hljs-params">options</span>) { 2631 <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>)) 2632 <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyTransform</span>(options); 2633 <span class="hljs-title class_">Transform</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options); 2634} 2635util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyTransform</span>, <span class="hljs-title class_">Transform</span>);</code></pre> 2636<p>Or, using the simplified constructor approach:</p> 2637<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">'stream'</span>); 2638 2639<span class="hljs-keyword">const</span> myTransform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({ 2640 <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) { 2641 <span class="hljs-comment">// ...</span> 2642 } 2643});</code></pre> 2644<h5>Event: <code>'end'</code><span><a class="mark" href="#stream_event_end_1" id="stream_event_end_1">#</a></span></h5> 2645<p>The <a href="#stream_event_end"><code>'end'</code></a> event is from the <code>stream.Readable</code> class. The <code>'end'</code> event is 2646emitted after all data has been output, which occurs after the callback in 2647<a href="#stream_transform_flush_callback"><code>transform._flush()</code></a> has been called. In the case of an error, 2648<code>'end'</code> should not be emitted.</p> 2649<h5>Event: <code>'finish'</code><span><a class="mark" href="#stream_event_finish_1" id="stream_event_finish_1">#</a></span></h5> 2650<p>The <a href="#stream_event_finish"><code>'finish'</code></a> event is from the <code>stream.Writable</code> class. The <code>'finish'</code> 2651event is emitted after <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> is called and all chunks 2652have been processed by <a href="#stream_transform_transform_chunk_encoding_callback"><code>stream._transform()</code></a>. In the case 2653of an error, <code>'finish'</code> should not be emitted.</p> 2654<h5><code>transform._flush(callback)</code><span><a class="mark" href="#stream_transform_flush_callback" id="stream_transform_flush_callback">#</a></span></h5> 2655<ul> 2656<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 2657argument and data) to be called when remaining data has been flushed.</li> 2658</ul> 2659<p>This function MUST NOT be called by application code directly. It should be 2660implemented by child classes, and called by the internal <code>Readable</code> class 2661methods only.</p> 2662<p>In some cases, a transform operation may need to emit an additional bit of 2663data at the end of the stream. For example, a <code>zlib</code> compression stream will 2664store an amount of internal state used to optimally compress the output. When 2665the stream ends, however, that additional data needs to be flushed so that the 2666compressed data will be complete.</p> 2667<p>Custom <a href="#stream_class_stream_transform"><code>Transform</code></a> implementations <em>may</em> implement the <code>transform._flush()</code> 2668method. This will be called when there is no more written data to be consumed, 2669but before the <a href="#stream_event_end"><code>'end'</code></a> event is emitted signaling the end of the 2670<a href="#stream_class_stream_readable"><code>Readable</code></a> stream.</p> 2671<p>Within the <code>transform._flush()</code> implementation, the <code>transform.push()</code> method 2672may be called zero or more times, as appropriate. The <code>callback</code> function must 2673be called when the flush operation is complete.</p> 2674<p>The <code>transform._flush()</code> method is prefixed with an underscore because it is 2675internal to the class that defines it, and should never be called directly by 2676user programs.</p> 2677<h5><code>transform._transform(chunk, encoding, callback)</code><span><a class="mark" href="#stream_transform_transform_chunk_encoding_callback" id="stream_transform_transform_chunk_encoding_callback">#</a></span></h5> 2678<ul> 2679<li><code>chunk</code> <a href="buffer.html#buffer_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 2680the <code>string</code> passed to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>. If the stream's 2681<code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode, 2682the chunk will not be converted & will be whatever was passed to 2683<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>.</li> 2684<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 2685encoding type. If chunk is a buffer, then this is the special 2686value <code>'buffer'</code>. Ignore it in that case.</li> 2687<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 2688argument and data) to be called after the supplied <code>chunk</code> has been 2689processed.</li> 2690</ul> 2691<p>This function MUST NOT be called by application code directly. It should be 2692implemented by child classes, and called by the internal <code>Readable</code> class 2693methods only.</p> 2694<p>All <code>Transform</code> stream implementations must provide a <code>_transform()</code> 2695method to accept input and produce output. The <code>transform._transform()</code> 2696implementation handles the bytes being written, computes an output, then passes 2697that output off to the readable portion using the <code>transform.push()</code> method.</p> 2698<p>The <code>transform.push()</code> method may be called zero or more times to generate 2699output from a single input chunk, depending on how much is to be output 2700as a result of the chunk.</p> 2701<p>It is possible that no output is generated from any given chunk of input data.</p> 2702<p>The <code>callback</code> function must be called only when the current chunk is completely 2703consumed. The first argument passed to the <code>callback</code> must be an <code>Error</code> object 2704if an error occurred while processing the input or <code>null</code> otherwise. If a second 2705argument is passed to the <code>callback</code>, it will be forwarded on to the 2706<code>transform.push()</code> method. In other words, the following are equivalent:</p> 2707<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>) { 2708 <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(data); 2709 <span class="hljs-title function_">callback</span>(); 2710}; 2711 2712transform.<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>) { 2713 <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, data); 2714};</code></pre> 2715<p>The <code>transform._transform()</code> method is prefixed with an underscore because it 2716is internal to the class that defines it, and should never be called directly by 2717user programs.</p> 2718<p><code>transform._transform()</code> is never called in parallel; streams implement a 2719queue mechanism, and to receive the next chunk, <code>callback</code> must be 2720called, either synchronously or asynchronously.</p> 2721<h5>Class: <code>stream.PassThrough</code><span><a class="mark" href="#stream_class_stream_passthrough" id="stream_class_stream_passthrough">#</a></span></h5> 2722<p>The <code>stream.PassThrough</code> class is a trivial implementation of a <a href="#stream_class_stream_transform"><code>Transform</code></a> 2723stream that simply passes the input bytes across to the output. Its purpose is 2724primarily for examples and testing, but there are some use cases where 2725<code>stream.PassThrough</code> is useful as a building block for novel sorts of streams.</p> 2726</section><section><h3>Additional notes<span><a class="mark" href="#stream_additional_notes" id="stream_additional_notes">#</a></span></h3> 2727 2728<h4>Streams compatibility with async generators and async iterators<span><a class="mark" href="#stream_streams_compatibility_with_async_generators_and_async_iterators" id="stream_streams_compatibility_with_async_generators_and_async_iterators">#</a></span></h4> 2729<p>With the support of async generators and iterators in JavaScript, async 2730generators are effectively a first-class language-level stream construct at 2731this point.</p> 2732<p>Some common interop cases of using Node.js streams with async generators 2733and async iterators are provided below.</p> 2734<h5>Consuming readable streams with async iterators<span><a class="mark" href="#stream_consuming_readable_streams_with_async_iterators" id="stream_consuming_readable_streams_with_async_iterators">#</a></span></h5> 2735<pre><code class="language-js">(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { 2736 <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) { 2737 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); 2738 } 2739})();</code></pre> 2740<p>Async iterators register a permanent error handler on the stream to prevent any 2741unhandled post-destroy errors.</p> 2742<h5>Creating readable streams with async generators<span><a class="mark" href="#stream_creating_readable_streams_with_async_generators" id="stream_creating_readable_streams_with_async_generators">#</a></span></h5> 2743<p>We can construct a Node.js readable stream from an asynchronous generator 2744using the <code>Readable.from()</code> utility method:</p> 2745<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">'stream'</span>); 2746 2747<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) { 2748 <span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>; 2749 <span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>; 2750 <span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>; 2751} 2752 2753<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>()); 2754 2755readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { 2756 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); 2757});</code></pre> 2758<h5>Piping to writable streams from async iterators<span><a class="mark" href="#stream_piping_to_writable_streams_from_async_iterators" id="stream_piping_to_writable_streams_from_async_iterators">#</a></span></h5> 2759<p>When writing to a writable stream from an async iterator, ensure correct 2760handling of backpressure and errors. <a href="#stream_stream_pipeline_source_transforms_destination_callback"><code>stream.pipeline()</code></a> abstracts away 2761the handling of backpressure and backpressure-related errors:</p> 2762<pre><code class="language-js"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'stream'</span>); 2763<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'util'</span>); 2764<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>); 2765 2766<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./file'</span>); 2767 2768<span class="hljs-comment">// Callback Pattern</span> 2769<span class="hljs-title function_">pipeline</span>(iterator, writable, <span class="hljs-function">(<span class="hljs-params">err, value</span>) =></span> { 2770 <span class="hljs-keyword">if</span> (err) { 2771 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err); 2772 } <span class="hljs-keyword">else</span> { 2773 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value, <span class="hljs-string">'value returned'</span>); 2774 } 2775}); 2776 2777<span class="hljs-comment">// Promise Pattern</span> 2778<span class="hljs-keyword">const</span> pipelinePromise = util.<span class="hljs-title function_">promisify</span>(pipeline); 2779<span class="hljs-title function_">pipelinePromise</span>(iterator, writable) 2780 .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">value</span>) =></span> { 2781 <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value, <span class="hljs-string">'value returned'</span>); 2782 }) 2783 .<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code></pre> 2784 2785<h4>Compatibility with older Node.js versions<span><a class="mark" href="#stream_compatibility_with_older_node_js_versions" id="stream_compatibility_with_older_node_js_versions">#</a></span></h4> 2786 2787<p>Prior to Node.js 0.10, the <code>Readable</code> stream interface was simpler, but also 2788less powerful and less useful.</p> 2789<ul> 2790<li>Rather than waiting for calls to the <a href="#stream_readable_read_size"><code>stream.read()</code></a> method, 2791<a href="#stream_event_data"><code>'data'</code></a> events would begin emitting immediately. Applications that 2792would need to perform some amount of work to decide how to handle data 2793were required to store read data into buffers so the data would not be lost.</li> 2794<li>The <a href="#stream_readable_pause"><code>stream.pause()</code></a> method was advisory, rather than 2795guaranteed. This meant that it was still necessary to be prepared to receive 2796<a href="#stream_event_data"><code>'data'</code></a> events <em>even when the stream was in a paused state</em>.</li> 2797</ul> 2798<p>In Node.js 0.10, the <a href="#stream_class_stream_readable"><code>Readable</code></a> class was added. For backward 2799compatibility with older Node.js programs, <code>Readable</code> streams switch into 2800"flowing mode" when a <a href="#stream_event_data"><code>'data'</code></a> event handler is added, or when the 2801<a href="#stream_readable_resume"><code>stream.resume()</code></a> method is called. The effect is that, even 2802when not using the new <a href="#stream_readable_read_size"><code>stream.read()</code></a> method and 2803<a href="#stream_event_readable"><code>'readable'</code></a> event, it is no longer necessary to worry about losing 2804<a href="#stream_event_data"><code>'data'</code></a> chunks.</p> 2805<p>While most applications will continue to function normally, this introduces an 2806edge case in the following conditions:</p> 2807<ul> 2808<li>No <a href="#stream_event_data"><code>'data'</code></a> event listener is added.</li> 2809<li>The <a href="#stream_readable_resume"><code>stream.resume()</code></a> method is never called.</li> 2810<li>The stream is not piped to any writable destination.</li> 2811</ul> 2812<p>For example, consider the following code:</p> 2813<pre><code class="language-js"><span class="hljs-comment">// WARNING! BROKEN!</span> 2814net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> { 2815 2816 <span class="hljs-comment">// We add an 'end' listener, but never consume the data.</span> 2817 socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 2818 <span class="hljs-comment">// It will never get here.</span> 2819 socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'The message was received but was not processed.\n'</span>); 2820 }); 2821 2822}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code></pre> 2823<p>Prior to Node.js 0.10, the incoming message data would be simply discarded. 2824However, in Node.js 0.10 and beyond, the socket remains paused forever.</p> 2825<p>The workaround in this situation is to call the 2826<a href="#stream_readable_resume"><code>stream.resume()</code></a> method to begin the flow of data:</p> 2827<pre><code class="language-js"><span class="hljs-comment">// Workaround.</span> 2828net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> { 2829 socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { 2830 socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'The message was received but was not processed.\n'</span>); 2831 }); 2832 2833 <span class="hljs-comment">// Start the flow of data, discarding it.</span> 2834 socket.<span class="hljs-title function_">resume</span>(); 2835}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code></pre> 2836<p>In addition to new <code>Readable</code> streams switching into flowing mode, 2837pre-0.10 style streams can be wrapped in a <code>Readable</code> class using the 2838<a href="#stream_readable_wrap_stream"><code>readable.wrap()</code></a> method.</p> 2839<h4><code>readable.read(0)</code><span><a class="mark" href="#stream_readable_read_0" id="stream_readable_read_0">#</a></span></h4> 2840<p>There are some cases where it is necessary to trigger a refresh of the 2841underlying readable stream mechanisms, without actually consuming any 2842data. In such cases, it is possible to call <code>readable.read(0)</code>, which will 2843always return <code>null</code>.</p> 2844<p>If the internal read buffer is below the <code>highWaterMark</code>, and the 2845stream is not currently reading, then calling <code>stream.read(0)</code> will trigger 2846a low-level <a href="#stream_readable_read_size_1"><code>stream._read()</code></a> call.</p> 2847<p>While most applications will almost never need to do this, there are 2848situations within Node.js where this is done, particularly in the 2849<code>Readable</code> stream class internals.</p> 2850<h4><code>readable.push('')</code><span><a class="mark" href="#stream_readable_push" id="stream_readable_push">#</a></span></h4> 2851<p>Use of <code>readable.push('')</code> is not recommended.</p> 2852<p>Pushing a zero-byte string, <code>Buffer</code> or <code>Uint8Array</code> to a stream that is not in 2853object mode has an interesting side effect. Because it <em>is</em> a call to 2854<a href="#stream_readable_push_chunk_encoding"><code>readable.push()</code></a>, the call will end the reading process. 2855However, because the argument is an empty string, no data is added to the 2856readable buffer so there is nothing for a user to consume.</p> 2857<h4><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code><span><a class="mark" href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding" id="stream_highwatermark_discrepancy_after_calling_readable_setencoding">#</a></span></h4> 2858<p>The use of <code>readable.setEncoding()</code> will change the behavior of how the 2859<code>highWaterMark</code> operates in non-object mode.</p> 2860<p>Typically, the size of the current buffer is measured against the 2861<code>highWaterMark</code> in <em>bytes</em>. However, after <code>setEncoding()</code> is called, the 2862comparison function will begin to measure the buffer's size in <em>characters</em>.</p> 2863<p>This is not a problem in common cases with <code>latin1</code> or <code>ascii</code>. But it is 2864advised to be mindful about this behavior when working with strings that could 2865contain multi-byte characters.</p></section> 2866 <!-- API END --> 2867 </div> 2868 </div> 2869 </div> 2870 <script> 2871 'use strict'; 2872 { 2873 const kCustomPreference = 'customDarkTheme'; 2874 const userSettings = sessionStorage.getItem(kCustomPreference); 2875 const themeToggleButton = document.getElementById('theme-toggle-btn'); 2876 if (userSettings === null && window.matchMedia) { 2877 const mq = window.matchMedia('(prefers-color-scheme: dark)'); 2878 if ('onchange' in mq) { 2879 function mqChangeListener(e) { 2880 document.body.classList.toggle('dark-mode', e.matches); 2881 } 2882 mq.addEventListener('change', mqChangeListener); 2883 if (themeToggleButton) { 2884 themeToggleButton.addEventListener('click', function() { 2885 mq.removeEventListener('change', mqChangeListener); 2886 }, { once: true }); 2887 } 2888 } 2889 if (mq.matches) { 2890 document.body.classList.add('dark-mode'); 2891 } 2892 } else if (userSettings === 'true') { 2893 document.body.classList.add('dark-mode'); 2894 } 2895 if (themeToggleButton) { 2896 themeToggleButton.hidden = false; 2897 themeToggleButton.addEventListener('click', function() { 2898 sessionStorage.setItem( 2899 kCustomPreference, 2900 document.body.classList.toggle('dark-mode') 2901 ); 2902 }); 2903 } 2904 } 2905 </script> 2906</body> 2907</html> 2908