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