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