]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.maps.server/node/node-v4.8.0-win-x64/node_modules/npm/node_modules/readable-stream/doc/stream.md
Adding integrated tile server
[simantics/district.git] / org.simantics.maps.server / node / node-v4.8.0-win-x64 / node_modules / npm / node_modules / readable-stream / doc / stream.md
1 # Stream
2
3     Stability: 2 - Stable
4
5 A stream is an abstract interface for working with streaming data in Node.js.
6 The `stream` module provides a base API that makes it easy to build objects
7 that implement the stream interface.
8
9 There are many stream objects provided by Node.js. For instance, a
10 [request to an HTTP server][http-incoming-message] and [`process.stdout`][]
11 are both stream instances.
12
13 Streams can be readable, writable, or both. All streams are instances of
14 [`EventEmitter`][].
15
16 The `stream` module can be accessed using:
17
18 ```js
19 const stream = require('stream');
20 ```
21
22 While it is important for all Node.js users to understand how streams works,
23 the `stream` module itself is most useful for developer's that are creating new
24 types of stream instances. Developer's who are primarily *consuming* stream
25 objects will rarely (if ever) have need to use the `stream` module directly.
26
27 ## Organization of this document
28
29 This document is divided into two primary sections and third section for
30 additional notes. The first section explains the elements of the stream API that
31 are required to *use* streams within an application. The second section explains
32 the elements of the API that are required to *implement* new types of streams.
33
34 ## Types of Streams
35
36 There are four fundamental stream types within Node.js:
37
38 * [Readable][] - streams from which data can be read (for example
39   [`fs.createReadStream()`][]).
40 * [Writable][] - streams to which data can be written (for example
41   [`fs.createWriteStream()`][]).
42 * [Duplex][] - streams that are both Readable and Writable (for example
43   [`net.Socket`][]).
44 * [Transform][] - Duplex streams that can modify or transform the data as it
45   is written and read (for example [`zlib.createDeflate()`][]).
46
47 ### Object Mode
48
49 All streams created by Node.js APIs operate exclusively on strings and `Buffer`
50 objects. It is possible, however, for stream implementations to work with other
51 types of JavaScript values (with the exception of `null` which serves a special
52 purpose within streams). Such streams are considered to operate in "object
53 mode".
54
55 Stream instances are switched into object mode using the `objectMode` option
56 when the stream is created. Attempting to switch an existing stream into
57 object mode is not safe.
58
59 ### Buffering
60
61 <!--type=misc-->
62
63 Both [Writable][] and [Readable][] streams will store data in an internal
64 buffer that can be retrieved using `writable._writableState.getBuffer()` or
65 `readable._readableState.buffer`, respectively.
66
67 The amount of data potentially buffered depends on the `highWaterMark` option
68 passed into the streams constructor. For normal streams, the `highWaterMark`
69 option specifies a total number of bytes. For streams operating in object mode,
70 the `highWaterMark` specifies a total number of objects.
71
72 Data is buffered in Readable streams when the implementation calls
73 [`stream.push(chunk)`][stream-push]. If the consumer of the Stream does not
74 call [`stream.read()`][stream-read], the data will sit in the internal
75 queue until it is consumed.
76
77 Once the total size of the internal read buffer reaches the threshold specified
78 by `highWaterMark`, the stream will temporarily stop reading data from the
79 underlying resource until the data currently buffered can be consumed (that is,
80 the stream will stop calling the internal `readable._read()` method that is
81 used to fill the read buffer).
82
83 Data is buffered in Writable streams when the
84 [`writable.write(chunk)`][stream-write] method is called repeatedly. While the
85 total size of the internal write buffer is below the threshold set by
86 `highWaterMark`, calls to `writable.write()` will return `true`. Once the
87 the size of the internal buffer reaches or exceeds the `highWaterMark`, `false`
88 will be returned.
89
90 A key goal of the `stream` API, and in particular the [`stream.pipe()`] method,
91 is to limit the buffering of data to acceptable levels such that sources and
92 destinations of differing speeds will not overwhelm the available memory.
93
94 Because [Duplex][] and [Transform][] streams are both Readable and Writable,
95 each maintain *two* separate internal buffers used for reading and writing,
96 allowing each side to operate independently of the other while maintaining an
97 appropriate and efficient flow of data. For example, [`net.Socket`][] instances
98 are [Duplex][] streams whose Readable side allows consumption of data received
99 *from* the socket and whose Writable side allows writing data *to* the socket.
100 Because data may be written to the socket at a faster or slower rate than data
101 is received, it is important each side operate (and buffer) independently of
102 the other.
103
104 ## API for Stream Consumers
105
106 <!--type=misc-->
107
108 Almost all Node.js applications, no matter how simple, use streams in some
109 manner. The following is an example of using streams in a Node.js application
110 that implements an HTTP server:
111
112 ```js
113 const http = require('http');
114
115 const server = http.createServer( (req, res) => {
116   // req is an http.IncomingMessage, which is a Readable Stream
117   // res is an http.ServerResponse, which is a Writable Stream
118
119   let body = '';
120   // Get the data as utf8 strings.
121   // If an encoding is not set, Buffer objects will be received.
122   req.setEncoding('utf8');
123
124   // Readable streams emit 'data' events once a listener is added
125   req.on('data', (chunk) => {
126     body += chunk;
127   });
128
129   // the end event indicates that the entire body has been received
130   req.on('end', () => {
131     try {
132       const data = JSON.parse(body);
133     } catch (er) {
134       // uh oh!  bad json!
135       res.statusCode = 400;
136       return res.end(`error: ${er.message}`);
137     }
138
139     // write back something interesting to the user:
140     res.write(typeof data);
141     res.end();
142   });
143 });
144
145 server.listen(1337);
146
147 // $ curl localhost:1337 -d '{}'
148 // object
149 // $ curl localhost:1337 -d '"foo"'
150 // string
151 // $ curl localhost:1337 -d 'not json'
152 // error: Unexpected token o
153 ```
154
155 [Writable][] streams (such as `res` in the example) expose methods such as
156 `write()` and `end()` that are used to write data onto the stream.
157
158 [Readable][] streams use the [`EventEmitter`][] API for notifying application
159 code when data is available to be read off the stream. That available data can
160 be read from the stream in multiple ways.
161
162 Both [Writable][] and [Readable][] streams use the [`EventEmitter`][] API in
163 various ways to communicate the current state of the stream.
164
165 [Duplex][] and [Transform][] streams are both [Writable][] and [Readable][].
166
167 Applications that are either writing data to or consuming data from a stream
168 are not required to implement the stream interfaces directly and will generally
169 have no reason to call `require('stream')`.
170
171 Developers wishing to implement new types of streams should refer to the
172 section [API for Stream Implementers][].
173
174 ### Writable Streams
175
176 Writable streams are an abstraction for a *destination* to which data is
177 written.
178
179 Examples of [Writable][] streams include:
180
181 * [HTTP requests, on the client][]
182 * [HTTP responses, on the server][]
183 * [fs write streams][]
184 * [zlib streams][zlib]
185 * [crypto streams][crypto]
186 * [TCP sockets][]
187 * [child process stdin][]
188 * [`process.stdout`][], [`process.stderr`][]
189
190 *Note*: Some of these examples are actually [Duplex][] streams that implement
191 the [Writable][] interface.
192
193 All [Writable][] streams implement the interface defined by the
194 `stream.Writable` class.
195
196 While specific instances of [Writable][] streams may differ in various ways,
197 all Writable streams follow the same fundamental usage pattern as illustrated
198 in the example below:
199
200 ```js
201 const myStream = getWritableStreamSomehow();
202 myStream.write('some data');
203 myStream.write('some more data');
204 myStream.end('done writing data');
205 ```
206
207 #### Class: stream.Writable
208 <!-- YAML
209 added: v0.9.4
210 -->
211
212 <!--type=class-->
213
214 ##### Event: 'close'
215 <!-- YAML
216 added: v0.9.4
217 -->
218
219 The `'close'` event is emitted when the stream and any of its underlying
220 resources (a file descriptor, for example) have been closed. The event indicates
221 that no more events will be emitted, and no further computation will occur.
222
223 Not all Writable streams will emit the `'close'` event.
224
225 ##### Event: 'drain'
226 <!-- YAML
227 added: v0.9.4
228 -->
229
230 If a call to [`stream.write(chunk)`][stream-write] returns `false`, the
231 `'drain'` event will be emitted when it is appropriate to resume writing data
232 to the stream.
233
234 ```js
235 // Write the data to the supplied writable stream one million times.
236 // Be attentive to back-pressure.
237 function writeOneMillionTimes(writer, data, encoding, callback) {
238   let i = 1000000;
239   write();
240   function write() {
241     var ok = true;
242     do {
243       i--;
244       if (i === 0) {
245         // last time!
246         writer.write(data, encoding, callback);
247       } else {
248         // see if we should continue, or wait
249         // don't pass the callback, because we're not done yet.
250         ok = writer.write(data, encoding);
251       }
252     } while (i > 0 && ok);
253     if (i > 0) {
254       // had to stop early!
255       // write some more once it drains
256       writer.once('drain', write);
257     }
258   }
259 }
260 ```
261
262 ##### Event: 'error'
263 <!-- YAML
264 added: v0.9.4
265 -->
266
267 * {Error}
268
269 The `'error'` event is emitted if an error occurred while writing or piping
270 data. The listener callback is passed a single `Error` argument when called.
271
272 *Note*: The stream is not closed when the `'error'` event is emitted.
273
274 ##### Event: 'finish'
275 <!-- YAML
276 added: v0.9.4
277 -->
278
279 The `'finish'` event is emitted after the [`stream.end()`][stream-end] method
280 has been called, and all data has been flushed to the underlying system.
281
282 ```js
283 const writer = getWritableStreamSomehow();
284 for (var i = 0; i < 100; i ++) {
285   writer.write('hello, #${i}!\n');
286 }
287 writer.end('This is the end\n');
288 writer.on('finish', () => {
289   console.error('All writes are now complete.');
290 });
291 ```
292
293 ##### Event: 'pipe'
294 <!-- YAML
295 added: v0.9.4
296 -->
297
298 * `src` {stream.Readable} source stream that is piping to this writable
299
300 The `'pipe'` event is emitted when the [`stream.pipe()`][] method is called on
301 a readable stream, adding this writable to its set of destinations.
302
303 ```js
304 const writer = getWritableStreamSomehow();
305 const reader = getReadableStreamSomehow();
306 writer.on('pipe', (src) => {
307   console.error('something is piping into the writer');
308   assert.equal(src, reader);
309 });
310 reader.pipe(writer);
311 ```
312
313 ##### Event: 'unpipe'
314 <!-- YAML
315 added: v0.9.4
316 -->
317
318 * `src` {[Readable][] Stream} The source stream that
319   [unpiped][`stream.unpipe()`] this writable
320
321 The `'unpipe'` event is emitted when the [`stream.unpipe()`][] method is called
322 on a [Readable][] stream, removing this [Writable][] from its set of
323 destinations.
324
325 ```js
326 const writer = getWritableStreamSomehow();
327 const reader = getReadableStreamSomehow();
328 writer.on('unpipe', (src) => {
329   console.error('Something has stopped piping into the writer.');
330   assert.equal(src, reader);
331 });
332 reader.pipe(writer);
333 reader.unpipe(writer);
334 ```
335
336 ##### writable.cork()
337 <!-- YAML
338 added: v0.11.2
339 -->
340
341 The `writable.cork()` method forces all written data to be buffered in memory.
342 The buffered data will be flushed when either the [`stream.uncork()`][] or
343 [`stream.end()`][stream-end] methods are called.
344
345 The primary intent of `writable.cork()` is to avoid a situation where writing
346 many small chunks of data to a stream do not cause an backup in the internal
347 buffer that would have an adverse impact on performance. In such situations,
348 implementations that implement the `writable._writev()` method can perform
349 buffered writes in a more optimized manner.
350
351 ##### writable.end([chunk][, encoding][, callback])
352 <!-- YAML
353 added: v0.9.4
354 -->
355
356 * `chunk` {String|Buffer|any} Optional data to write. For streams not operating
357   in object mode, `chunk` must be a string or a `Buffer`. For object mode
358   streams, `chunk` may be any JavaScript value other than `null`.
359 * `encoding` {String} The encoding, if `chunk` is a String
360 * `callback` {Function} Optional callback for when the stream is finished
361
362 Calling the `writable.end()` method signals that no more data will be written
363 to the [Writable][]. The optional `chunk` and `encoding` arguments allow one
364 final additional chunk of data to be written immediately before closing the
365 stream. If provided, the optional `callback` function is attached as a listener
366 for the [`'finish'`][] event.
367
368 Calling the [`stream.write()`][stream-write] method after calling
369 [`stream.end()`][stream-end] will raise an error.
370
371 ```js
372 // write 'hello, ' and then end with 'world!'
373 const file = fs.createWriteStream('example.txt');
374 file.write('hello, ');
375 file.end('world!');
376 // writing more now is not allowed!
377 ```
378
379 ##### writable.setDefaultEncoding(encoding)
380 <!-- YAML
381 added: v0.11.15
382 -->
383
384 * `encoding` {String} The new default encoding
385 * Return: `this`
386
387 The `writable.setDefaultEncoding()` method sets the default `encoding` for a
388 [Writable][] stream.
389
390 ##### writable.uncork()
391 <!-- YAML
392 added: v0.11.2
393 -->
394
395 The `writable.uncork()` method flushes all data buffered since
396 [`stream.cork()`][] was called.
397
398 When using `writable.cork()` and `writable.uncork()` to manage the buffering
399 of writes to a stream, it is recommended that calls to `writable.uncork()` be
400 deferred using `process.nextTick()`. Doing so allows batching of all
401 `writable.write()` calls that occur within a given Node.js event loop phase.
402
403 ```js
404 stream.cork();
405 stream.write('some ');
406 stream.write('data ');
407 process.nextTick(() => stream.uncork());
408 ```
409
410 If the `writable.cork()` method is called multiple times on a stream, the same
411 number of calls to `writable.uncork()` must be called to flush the buffered
412 data.
413
414 ```
415 stream.cork();
416 stream.write('some ');
417 stream.cork();
418 stream.write('data ');
419 process.nextTick(() => {
420   stream.uncork();
421   // The data will not be flushed until uncork() is called a second time.
422   stream.uncork();
423 });
424 ```
425
426 ##### writable.write(chunk[, encoding][, callback])
427 <!-- YAML
428 added: v0.9.4
429 -->
430
431 * `chunk` {String|Buffer} The data to write
432 * `encoding` {String} The encoding, if `chunk` is a String
433 * `callback` {Function} Callback for when this chunk of data is flushed
434 * Returns: {Boolean} `false` if the stream wishes for the calling code to
435   wait for the `'drain'` event to be emitted before continuing to write
436   additional data; otherwise `true`.
437
438 The `writable.write()` method writes some data to the stream, and calls the
439 supplied `callback` once the data has been fully handled. If an error
440 occurs, the `callback` *may or may not* be called with the error as its
441 first argument. To reliably detect write errors, add a listener for the
442 `'error'` event.
443
444 The return value indicates whether the written `chunk` was buffered internally
445 and the buffer has exceeded the `highWaterMark` configured when the stream was
446 created. If `false` is returned, further attempts to write data to the stream
447 should be paused until the `'drain'` event is emitted.
448
449 A Writable stream in object mode will always ignore the `encoding` argument.
450
451 ### Readable Streams
452
453 Readable streams are an abstraction for a *source* from which data is
454 consumed.
455
456 Examples of Readable streams include:
457
458 * [HTTP responses, on the client][http-incoming-message]
459 * [HTTP requests, on the server][http-incoming-message]
460 * [fs read streams][]
461 * [zlib streams][zlib]
462 * [crypto streams][crypto]
463 * [TCP sockets][]
464 * [child process stdout and stderr][]
465 * [`process.stdin`][]
466
467 All [Readable][] streams implement the interface defined by the
468 `stream.Readable` class.
469
470 #### Two Modes
471
472 Readable streams effectively operate in one of two modes: flowing and paused.
473
474 When in flowing mode, data is read from the underlying system automatically
475 and provided to an application as quickly as possible using events via the
476 [`EventEmitter`][] interface.
477
478 In paused mode, the [`stream.read()`][stream-read] method must be called
479 explicitly to read chunks of data from the stream.
480
481 All [Readable][] streams begin in paused mode but can be switched to flowing
482 mode in one of the following ways:
483
484 * Adding a [`'data'`][] event handler.
485 * Calling the [`stream.resume()`][stream-resume] method.
486 * Calling the [`stream.pipe()`][] method to send the data to a [Writable][].
487
488 The Readable can switch back to paused mode using one of the following:
489
490 * If there are no pipe destinations, by calling the
491   [`stream.pause()`][stream-pause] method.
492 * If there are pipe destinations, by removing any [`'data'`][] event
493   handlers, and removing all pipe destinations by calling the
494   [`stream.unpipe()`][] method.
495
496 The important concept to remember is that a Readable will not generate data
497 until a mechanism for either consuming or ignoring that data is provided. If
498 the consuming mechanism is disabled or taken away, the Readable will *attempt*
499 to stop generating the data.
500
501 *Note*: For backwards compatibility reasons, removing [`'data'`][] event
502 handlers will **not** automatically pause the stream. Also, if there are piped
503 destinations, then calling [`stream.pause()`][stream-pause] will not guarantee
504 that the stream will *remain* paused once those destinations drain and ask for
505 more data.
506
507 *Note*: If a [Readable][] is switched into flowing mode and there are no
508 consumers available handle the data, that data will be lost. This can occur,
509 for instance, when the `readable.resume()` method is called without a listener
510 attached to the `'data'` event, or when a `'data'` event handler is removed
511 from the stream.
512
513 #### Three States
514
515 The "two modes" of operation for a Readable stream are a simplified abstraction
516 for the more complicated internal state management that is happening within the
517 Readable stream implementation.
518
519 Specifically, at any given point in time, every Readable is in one of three
520 possible states:
521
522 * `readable._readableState.flowing = null`
523 * `readable._readableState.flowing = false`
524 * `readable._readableState.flowing = true`
525
526 When `readable._readableState.flowing` is `null`, no mechanism for consuming the
527 streams data is provided so the stream will not generate its data.
528
529 Attaching a listener for the `'data'` event, calling the `readable.pipe()`
530 method, or calling the `readable.resume()` method will switch
531 `readable._readableState.flowing` to `true`, causing the Readable to begin
532 actively emitting events as data is generated.
533
534 Calling `readable.pause()`, `readable.unpipe()`, or receiving "back pressure"
535 will cause the `readable._readableState.flowing` to be set as `false`,
536 temporarily halting the flowing of events but *not* halting the generation of
537 data.
538
539 While `readable._readableState.flowing` is `false`, data may be accumulating
540 within the streams internal buffer.
541
542 #### Choose One
543
544 The Readable stream API evolved across multiple Node.js versions and provides
545 multiple methods of consuming stream data. In general, developers should choose
546 *one* of the methods of consuming data and *should never* use multiple methods
547 to consume data from a single stream.
548
549 Use of the `readable.pipe()` method is recommended for most users as it has been
550 implemented to provide the easiest way of consuming stream data. Developers that
551 require more fine-grained control over the transfer and generation of data can
552 use the [`EventEmitter`][] and `readable.pause()`/`readable.resume()` APIs.
553
554 #### Class: stream.Readable
555 <!-- YAML
556 added: v0.9.4
557 -->
558
559 <!--type=class-->
560
561 ##### Event: 'close'
562 <!-- YAML
563 added: v0.9.4
564 -->
565
566 The `'close'` event is emitted when the stream and any of its underlying
567 resources (a file descriptor, for example) have been closed. The event indicates
568 that no more events will be emitted, and no further computation will occur.
569
570 Not all [Readable][] streams will emit the `'close'` event.
571
572 ##### Event: 'data'
573 <!-- YAML
574 added: v0.9.4
575 -->
576
577 * `chunk` {Buffer|String|any} The chunk of data. For streams that are not
578   operating in object mode, the chunk will be either a string or `Buffer`.
579   For streams that are in object mode, the chunk can be any JavaScript value
580   other than `null`.
581
582 The `'data'` event is emitted whenever the stream is relinquishing ownership of
583 a chunk of data to a consumer. This may occur whenever the stream is switched
584 in flowing mode by calling `readable.pipe()`, `readable.resume()`, or by
585 attaching a listener callback to the `'data'` event. The `'data'` event will
586 also be emitted whenever the `readable.read()` method is called and a chunk of
587 data is available to be returned.
588
589 Attaching a `'data'` event listener to a stream that has not been explicitly
590 paused will switch the stream into flowing mode. Data will then be passed as
591 soon as it is available.
592
593 The listener callback will be passed the chunk of data as a string if a default
594 encoding has been specified for the stream using the
595 `readable.setEncoding()` method; otherwise the data will be passed as a
596 `Buffer`.
597
598 ```js
599 const readable = getReadableStreamSomehow();
600 readable.on('data', (chunk) => {
601   console.log(`Received ${chunk.length} bytes of data.`);
602 });
603 ```
604
605 ##### Event: 'end'
606 <!-- YAML
607 added: v0.9.4
608 -->
609
610 The `'end'` event is emitted when there is no more data to be consumed from
611 the stream.
612
613 *Note*: The `'end'` event **will not be emitted** unless the data is
614 completely consumed. This can be accomplished by switching the stream into
615 flowing mode, or by calling [`stream.read()`][stream-read] repeatedly until
616 all data has been consumed.
617
618 ```js
619 const readable = getReadableStreamSomehow();
620 readable.on('data', (chunk) => {
621   console.log(`Received ${chunk.length} bytes of data.`);
622 });
623 readable.on('end', () => {
624   console.log('There will be no more data.');
625 });
626 ```
627
628 ##### Event: 'error'
629 <!-- YAML
630 added: v0.9.4
631 -->
632
633 * {Error}
634
635 The `'error'` event may be emitted by a Readable implementation at any time.
636 Typically, this may occur if the underlying stream in unable to generate data
637 due to an underlying internal failure, or when a stream implementation attempts
638 to push an invalid chunk of data.
639
640 The listener callback will be passed a single `Error` object.
641
642 ##### Event: 'readable'
643 <!-- YAML
644 added: v0.9.4
645 -->
646
647 The `'readable'` event is emitted when there is data available to be read from
648 the stream. In some cases, attaching a listener for the `'readable'` event will
649 cause some amount of data to be read into an internal buffer.
650
651 ```javascript
652 const readable = getReadableStreamSomehow();
653 readable.on('readable', () => {
654   // there is some data to read now
655 });
656 ```
657 The `'readable'` event will also be emitted once the end of the stream data
658 has been reached but before the `'end'` event is emitted.
659
660 Effectively, the `'readable'` event indicates that the stream has new
661 information: either new data is available or the end of the stream has been
662 reached. In the former case, [`stream.read()`][stream-read] will return the
663 available data. In the latter case, [`stream.read()`][stream-read] will return
664 `null`. For instance, in the following example, `foo.txt` is an empty file:
665
666 ```js
667 const fs = require('fs');
668 const rr = fs.createReadStream('foo.txt');
669 rr.on('readable', () => {
670   console.log('readable:', rr.read());
671 });
672 rr.on('end', () => {
673   console.log('end');
674 });
675 ```
676
677 The output of running this script is:
678
679 ```
680 $ node test.js
681 readable: null
682 end
683 ```
684
685 *Note*: In general, the `readable.pipe()` and `'data'` event mechanisms are
686 preferred over the use of the `'readable'` event.
687
688 ##### readable.isPaused()
689 <!--
690 added: v0.11.14
691 -->
692
693 * Return: {Boolean}
694
695 The `readable.isPaused()` method returns the current operating state of the
696 Readable. This is used primarily by the mechanism that underlies the
697 `readable.pipe()` method. In most typical cases, there will be no reason to
698 use this method directly.
699
700 ```js
701 const readable = new stream.Readable
702
703 readable.isPaused() // === false
704 readable.pause()
705 readable.isPaused() // === true
706 readable.resume()
707 readable.isPaused() // === false
708 ```
709
710 ##### readable.pause()
711 <!-- YAML
712 added: v0.9.4
713 -->
714
715 * Return: `this`
716
717 The `readable.pause()` method will cause a stream in flowing mode to stop
718 emitting [`'data'`][] events, switching out of flowing mode. Any data that
719 becomes available will remain in the internal buffer.
720
721 ```js
722 const readable = getReadableStreamSomehow();
723 readable.on('data', (chunk) => {
724   console.log(`Received ${chunk.length} bytes of data.`);
725   readable.pause();
726   console.log('There will be no additional data for 1 second.');
727   setTimeout(() => {
728     console.log('Now data will start flowing again.');
729     readable.resume();
730   }, 1000);
731 });
732 ```
733
734 ##### readable.pipe(destination[, options])
735 <!-- YAML
736 added: v0.9.4
737 -->
738
739 * `destination` {stream.Writable} The destination for writing data
740 * `options` {Object} Pipe options
741   * `end` {Boolean} End the writer when the reader ends. Defaults to `true`.
742
743 The `readable.pipe()` method attaches a [Writable][] stream to the `readable`,
744 causing it to switch automatically into flowing mode and push all of its data
745 to the attached [Writable][]. The flow of data will be automatically managed so
746 that the destination Writable stream is not overwhelmed by a faster Readable
747 stream.
748
749 The following example pipes all of the data from the `readable` into a file
750 named `file.txt`:
751
752 ```js
753 const readable = getReadableStreamSomehow();
754 const writable = fs.createWriteStream('file.txt');
755 // All the data from readable goes into 'file.txt'
756 readable.pipe(writable);
757 ```
758 It is possible to attach multiple Writable streams to a single Readable stream.
759
760 The `readable.pipe()` method returns a reference to the *destination* stream
761 making it possible to set up chains of piped streams:
762
763 ```js
764 const r = fs.createReadStream('file.txt');
765 const z = zlib.createGzip();
766 const w = fs.createWriteStream('file.txt.gz');
767 r.pipe(z).pipe(w);
768 ```
769
770 By default, [`stream.end()`][stream-end] is called on the destination Writable
771 stream when the source Readable stream emits [`'end'`][], so that the
772 destination is no longer writable. To disable this default behavior, the `end`
773 option can be passed as `false`, causing the destination stream to remain open,
774 as illustrated in the following example:
775
776 ```js
777 reader.pipe(writer, { end: false });
778 reader.on('end', () => {
779   writer.end('Goodbye\n');
780 });
781 ```
782
783 One important caveat is that if the Readable stream emits an error during
784 processing, the Writable destination *is not closed* automatically. If an
785 error occurs, it will be necessary to *manually* close each stream in order
786 to prevent memory leaks.
787
788 *Note*: The [`process.stderr`][] and [`process.stdout`][] Writable streams are
789 never closed until the Node.js process exits, regardless of the specified
790 options.
791
792 ##### readable.read([size])
793 <!-- YAML
794 added: v0.9.4
795 -->
796
797 * `size` {Number} Optional argument to specify how much data to read.
798 * Return {String|Buffer|Null}
799
800 The `readable.read()` method pulls some data out of the internal buffer and
801 returns it. If no data available to be read, `null` is returned. By default,
802 the data will be returned as a `Buffer` object unless an encoding has been
803 specified using the `readable.setEncoding()` method or the stream is operating
804 in object mode.
805
806 The optional `size` argument specifies a specific number of bytes to read. If
807 `size` bytes are not available to be read, `null` will be returned *unless*
808 the stream has ended, in which case all of the data remaining in the internal
809 buffer will be returned (*even if it exceeds `size` bytes*).
810
811 If the `size` argument is not specified, all of the data contained in the
812 internal buffer will be returned.
813
814 The `readable.read()` method should only be called on Readable streams operating
815 in paused mode. In flowing mode, `readable.read()` is called automatically until
816 the internal buffer is fully drained.
817
818 ```js
819 const readable = getReadableStreamSomehow();
820 readable.on('readable', () => {
821   var chunk;
822   while (null !== (chunk = readable.read())) {
823     console.log(`Received ${chunk.length} bytes of data.`);
824   }
825 });
826 ```
827
828 In general, it is recommended that developers avoid the use of the `'readable'`
829 event and the `readable.read()` method in favor of using either
830 `readable.pipe()` or the `'data'` event.
831
832 A Readable stream in object mode will always return a single item from
833 a call to [`readable.read(size)`][stream-read], regardless of the value of the
834 `size` argument.
835
836 *Note:* If the `readable.read()` method returns a chunk of data, a `'data'`
837 event will also be emitted.
838
839 *Note*: Calling [`stream.read([size])`][stream-read] after the [`'end'`][]
840 event has been emitted will return `null`. No runtime error will be raised.
841
842 ##### readable.resume()
843 <!-- YAML
844 added: v0.9.4
845 -->
846
847 * Return: `this`
848
849 The `readable.resume()` method causes an explicitly paused Readable stream to
850 resume emitting [`'data'`][] events, switching the stream into flowing mode.
851
852 The `readable.resume()` method can be used to fully consume the data from a
853 stream without actually processing any of that data as illustrated in the
854 following example:
855
856 ```js
857 getReadableStreamSomehow()
858   .resume()
859   .on('end', () => {
860     console.log('Reached the end, but did not read anything.');
861   });
862 ```
863
864 ##### readable.setEncoding(encoding)
865 <!-- YAML
866 added: v0.9.4
867 -->
868
869 * `encoding` {String} The encoding to use.
870 * Return: `this`
871
872 The `readable.setEncoding()` method sets the default character encoding for
873 data read from the Readable stream.
874
875 Setting an encoding causes the stream data
876 to be returned as string of the specified encoding rather than as `Buffer`
877 objects. For instance, calling `readable.setEncoding('utf8')` will cause the
878 output data will be interpreted as UTF-8 data, and passed as strings. Calling
879 `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal
880 string format.
881
882 The Readable stream will properly handle multi-byte characters delivered through
883 the stream that would otherwise become improperly decoded if simply pulled from
884 the stream as `Buffer` objects.
885
886 Encoding can be disabled by calling `readable.setEncoding(null)`. This approach
887 is useful when working with binary data or with large multi-byte strings spread
888 out over multiple chunks.
889
890 ```js
891 const readable = getReadableStreamSomehow();
892 readable.setEncoding('utf8');
893 readable.on('data', (chunk) => {
894   assert.equal(typeof chunk, 'string');
895   console.log('got %d characters of string data', chunk.length);
896 });
897 ```
898
899 ##### readable.unpipe([destination])
900 <!-- YAML
901 added: v0.9.4
902 -->
903
904 * `destination` {stream.Writable} Optional specific stream to unpipe
905
906 The `readable.unpipe()` method detaches a Writable stream previously attached
907 using the [`stream.pipe()`][] method.
908
909 If the `destination` is not specified, then *all* pipes are detached.
910
911 If the `destination` is specified, but no pipe is set up for it, then
912 the method does nothing.
913
914 ```js
915 const readable = getReadableStreamSomehow();
916 const writable = fs.createWriteStream('file.txt');
917 // All the data from readable goes into 'file.txt',
918 // but only for the first second
919 readable.pipe(writable);
920 setTimeout(() => {
921   console.log('Stop writing to file.txt');
922   readable.unpipe(writable);
923   console.log('Manually close the file stream');
924   writable.end();
925 }, 1000);
926 ```
927
928 ##### readable.unshift(chunk)
929 <!-- YAML
930 added: v0.9.11
931 -->
932
933 * `chunk` {Buffer|String} Chunk of data to unshift onto the read queue
934
935 The `readable.unshift()` method pushes a chunk of data back into the internal
936 buffer. This is useful in certain situations where a stream is being consumed by
937 code that needs to "un-consume" some amount of data that it has optimistically
938 pulled out of the source, so that the data can be passed on to some other party.
939
940 *Note*: The `stream.unshift(chunk)` method cannot be called after the
941 [`'end'`][] event has been emitted or a runtime error will be thrown.
942
943 Developers using `stream.unshift()` often should consider switching to
944 use of a [Transform][] stream instead. See the [API for Stream Implementers][]
945 section for more information.
946
947 ```js
948 // Pull off a header delimited by \n\n
949 // use unshift() if we get too much
950 // Call the callback with (error, header, stream)
951 const StringDecoder = require('string_decoder').StringDecoder;
952 function parseHeader(stream, callback) {
953   stream.on('error', callback);
954   stream.on('readable', onReadable);
955   const decoder = new StringDecoder('utf8');
956   var header = '';
957   function onReadable() {
958     var chunk;
959     while (null !== (chunk = stream.read())) {
960       var str = decoder.write(chunk);
961       if (str.match(/\n\n/)) {
962         // found the header boundary
963         var split = str.split(/\n\n/);
964         header += split.shift();
965         const remaining = split.join('\n\n');
966         const buf = Buffer.from(remaining, 'utf8');
967         if (buf.length)
968           stream.unshift(buf);
969         stream.removeListener('error', callback);
970         stream.removeListener('readable', onReadable);
971         // now the body of the message can be read from the stream.
972         callback(null, header, stream);
973       } else {
974         // still reading the header.
975         header += str;
976       }
977     }
978   }
979 }
980 ```
981
982 *Note*: Unlike [`stream.push(chunk)`][stream-push], `stream.unshift(chunk)`
983 will not end the reading process by resetting the internal reading state of the
984 stream. This can cause unexpected results if `readable.unshift()` is called
985 during a read (i.e. from within a [`stream._read()`][stream-_read]
986 implementation on a custom stream). Following the call to `readable.unshift()`
987 with an immediate [`stream.push('')`][stream-push] will reset the reading state
988 appropriately, however it is best to simply avoid calling `readable.unshift()`
989 while in the process of performing a read.
990
991 ##### readable.wrap(stream)
992 <!-- YAML
993 added: v0.9.4
994 -->
995
996 * `stream` {Stream} An "old style" readable stream
997
998 Versions of Node.js prior to v0.10 had streams that did not implement the
999 entire `stream` module API as it is currently defined. (See [Compatibility][]
1000 for more information.)
1001
1002 When using an older Node.js library that emits [`'data'`][] events and has a
1003 [`stream.pause()`][stream-pause] method that is advisory only, the
1004 `readable.wrap()` method can be used to create a [Readable][] stream that uses
1005 the old stream as its data source.
1006
1007 It will rarely be necessary to use `readable.wrap()` but the method has been
1008 provided as a convenience for interacting with older Node.js applications and
1009 libraries.
1010
1011 For example:
1012
1013 ```js
1014 const OldReader = require('./old-api-module.js').OldReader;
1015 const Readable = require('stream').Readable;
1016 const oreader = new OldReader;
1017 const myReader = new Readable().wrap(oreader);
1018
1019 myReader.on('readable', () => {
1020   myReader.read(); // etc.
1021 });
1022 ```
1023
1024 ### Duplex and Transform Streams
1025
1026 #### Class: stream.Duplex
1027 <!-- YAML
1028 added: v0.9.4
1029 -->
1030
1031 <!--type=class-->
1032
1033 Duplex streams are streams that implement both the [Readable][] and
1034 [Writable][] interfaces.
1035
1036 Examples of Duplex streams include:
1037
1038 * [TCP sockets][]
1039 * [zlib streams][zlib]
1040 * [crypto streams][crypto]
1041
1042 #### Class: stream.Transform
1043 <!-- YAML
1044 added: v0.9.4
1045 -->
1046
1047 <!--type=class-->
1048
1049 Transform streams are [Duplex][] streams where the output is in some way
1050 related to the input. Like all [Duplex][] streams, Transform streams
1051 implement both the [Readable][] and [Writable][] interfaces.
1052
1053 Examples of Transform streams include:
1054
1055 * [zlib streams][zlib]
1056 * [crypto streams][crypto]
1057
1058
1059 ## API for Stream Implementers
1060
1061 <!--type=misc-->
1062
1063 The `stream` module API has been designed to make it possible to easily
1064 implement streams using JavaScript's prototypical inheritance model.
1065
1066 First, a stream developer would declare a new JavaScript class that extends one
1067 of the four basic stream classes (`stream.Writable`, `stream.Readable`,
1068 `stream.Duplex`, or `stream.Transform`), making sure the call the appropriate
1069 parent class constructor:
1070
1071 ```js
1072 const Writable = require('stream').Writable;
1073
1074 class MyWritable extends Writable {
1075   constructor(options) {
1076     super(options);
1077   }
1078 }
1079 ```
1080
1081 The new stream class must then implement one or more specific methods, depending
1082 on the type of stream being created, as detailed in the chart below:
1083
1084 <table>
1085   <thead>
1086     <tr>
1087       <th>
1088         <p>Use-case</p>
1089       </th>
1090       <th>
1091         <p>Class</p>
1092       </th>
1093       <th>
1094         <p>Method(s) to implement</p>
1095       </th>
1096     </tr>
1097   </thead>
1098   <tr>
1099     <td>
1100       <p>Reading only</p>
1101     </td>
1102     <td>
1103       <p>[Readable](#stream_class_stream_readable)</p>
1104     </td>
1105     <td>
1106       <p><code>[_read][stream-_read]</code></p>
1107     </td>
1108   </tr>
1109   <tr>
1110     <td>
1111       <p>Writing only</p>
1112     </td>
1113     <td>
1114       <p>[Writable](#stream_class_stream_writable)</p>
1115     </td>
1116     <td>
1117       <p><code>[_write][stream-_write]</code>, <code>[_writev][stream-_writev]</code></p>
1118     </td>
1119   </tr>
1120   <tr>
1121     <td>
1122       <p>Reading and writing</p>
1123     </td>
1124     <td>
1125       <p>[Duplex](#stream_class_stream_duplex)</p>
1126     </td>
1127     <td>
1128       <p><code>[_read][stream-_read]</code>, <code>[_write][stream-_write]</code>, <code>[_writev][stream-_writev]</code></p>
1129     </td>
1130   </tr>
1131   <tr>
1132     <td>
1133       <p>Operate on written data, then read the result</p>
1134     </td>
1135     <td>
1136       <p>[Transform](#stream_class_stream_transform)</p>
1137     </td>
1138     <td>
1139       <p><code>[_transform][stream-_transform]</code>, <code>[_flush][stream-_flush]</code></p>
1140     </td>
1141   </tr>
1142 </table>
1143
1144 *Note*: The implementation code for a stream should *never* call the "public"
1145 methods of a stream that are intended for use by consumers (as described in
1146 the [API for Stream Consumers][] section). Doing so may lead to adverse
1147 side effects in application code consuming the stream.
1148
1149 ### Simplified Construction
1150
1151 For many simple cases, it is possible to construct a stream without relying on
1152 inheritance. This can be accomplished by directly creating instances of the
1153 `stream.Writable`, `stream.Readable`, `stream.Duplex` or `stream.Transform`
1154 objects and passing appropriate methods as constructor options.
1155
1156 For example:
1157
1158 ```js
1159 const Writable = require('stream').Writable;
1160
1161 const myWritable = new Writable({
1162   write(chunk, encoding, callback) {
1163     // ...
1164   }
1165 });
1166 ```
1167
1168 ### Implementing a Writable Stream
1169
1170 The `stream.Writable` class is extended to implement a [Writable][] stream.
1171
1172 Custom Writable streams *must* call the `new stream.Writable([options])`
1173 constructor and implement the `writable._write()` method. The
1174 `writable._writev()` method *may* also be implemented.
1175
1176 #### Constructor: new stream.Writable([options])
1177
1178 * `options` {Object}
1179   * `highWaterMark` {Number} Buffer level when
1180     [`stream.write()`][stream-write] starts returning `false`. Defaults to
1181     `16384` (16kb), or `16` for `objectMode` streams.
1182   * `decodeStrings` {Boolean} Whether or not to decode strings into
1183     Buffers before passing them to [`stream._write()`][stream-_write].
1184     Defaults to `true`
1185   * `objectMode` {Boolean} Whether or not the
1186     [`stream.write(anyObj)`][stream-write] is a valid operation. When set,
1187     it becomes possible to write JavaScript values other than string or
1188     `Buffer` if supported by the stream implementation. Defaults to `false`
1189   * `write` {Function} Implementation for the
1190     [`stream._write()`][stream-_write] method.
1191   * `writev` {Function} Implementation for the
1192     [`stream._writev()`][stream-_writev] method.
1193
1194 For example:
1195
1196 ```js
1197 const Writable = require('stream').Writable;
1198
1199 class MyWritable extends Writable {
1200   constructor(options) {
1201     // Calls the stream.Writable() constructor
1202     super(options);
1203   }
1204 }
1205 ```
1206
1207 Or, when using pre-ES6 style constructors:
1208
1209 ```js
1210 const Writable = require('stream').Writable;
1211 const util = require('util');
1212
1213 function MyWritable(options) {
1214   if (!(this instanceof MyWritable))
1215     return new MyWritable(options);
1216   Writable.call(this, options);
1217 }
1218 util.inherits(MyWritable, Writable);
1219 ```
1220
1221 Or, using the Simplified Constructor approach:
1222
1223 ```js
1224 const Writable = require('stream').Writable;
1225
1226 const myWritable = new Writable({
1227   write(chunk, encoding, callback) {
1228     // ...
1229   },
1230   writev(chunks, callback) {
1231     // ...
1232   }
1233 });
1234 ```
1235
1236 #### writable.\_write(chunk, encoding, callback)
1237
1238 * `chunk` {Buffer|String} The chunk to be written. Will **always**
1239   be a buffer unless the `decodeStrings` option was set to `false`.
1240 * `encoding` {String} If the chunk is a string, then `encoding` is the
1241   character encoding of that string. If chunk is a `Buffer`, or if the
1242   stream is operating in object mode, `encoding` may be ignored.
1243 * `callback` {Function} Call this function (optionally with an error
1244   argument) when processing is complete for the supplied chunk.
1245
1246 All Writable stream implementations must provide a
1247 [`writable._write()`][stream-_write] method to send data to the underlying
1248 resource.
1249
1250 *Note*: [Transform][] streams provide their own implementation of the
1251 [`writable._write()`][stream-_write].
1252
1253 *Note*: **This function MUST NOT be called by application code directly.** It
1254 should be implemented by child classes, and called only by the internal Writable
1255 class methods only.
1256
1257 The `callback` method must be called to signal either that the write completed
1258 successfully or failed with an error. The first argument passed to the
1259 `callback` must be the `Error` object if the call failed or `null` if the
1260 write succeeded.
1261
1262 It is important to note that all calls to `writable.write()` that occur between
1263 the time `writable._write()` is called and the `callback` is called will cause
1264 the written data to be buffered. Once the `callback` is invoked, the stream will
1265 emit a `'drain'` event. If a stream implementation is capable of processing
1266 multiple chunks of data at once, the `writable._writev()` method should be
1267 implemented.
1268
1269 If the `decodeStrings` property is set in the constructor options, then
1270 `chunk` may be a string rather than a Buffer, and `encoding` will
1271 indicate the character encoding of the string. This is to support
1272 implementations that have an optimized handling for certain string
1273 data encodings. If the `decodeStrings` property is explicitly set to `false`,
1274 the `encoding` argument can be safely ignored, and `chunk` will always be a
1275 `Buffer`.
1276
1277 The `writable._write()` method is prefixed with an underscore because it is
1278 internal to the class that defines it, and should never be called directly by
1279 user programs.
1280
1281 #### writable.\_writev(chunks, callback)
1282
1283 * `chunks` {Array} The chunks to be written. Each chunk has following
1284   format: `{ chunk: ..., encoding: ... }`.
1285 * `callback` {Function} A callback function (optionally with an error
1286   argument) to be invoked when processing is complete for the supplied chunks.
1287
1288 *Note*: **This function MUST NOT be called by application code directly.** It
1289 should be implemented by child classes, and called only by the internal Writable
1290 class methods only.
1291
1292 The `writable._writev()` method may be implemented in addition to
1293 `writable._write()` in stream implementations that are capable of processing
1294 multiple chunks of data at once. If implemented, the method will be called with
1295 all chunks of data currently buffered in the write queue.
1296
1297 The `writable._writev()` method is prefixed with an underscore because it is
1298 internal to the class that defines it, and should never be called directly by
1299 user programs.
1300
1301 #### Errors While Writing
1302
1303 It is recommended that errors occurring during the processing of the
1304 `writable._write()` and `writable._writev()` methods are reported by invoking
1305 the callback and passing the error as the first argument. This will cause an
1306 `'error'` event to be emitted by the Writable. Throwing an Error from within
1307 `writable._write()` can result in expected and inconsistent behavior depending
1308 on how the stream is being used.  Using the callback ensures consistent and
1309 predictable handling of errors.
1310
1311 ```js
1312 const Writable = require('stream').Writable;
1313
1314 const myWritable = new Writable({
1315   write(chunk, encoding, callback) {
1316     if (chunk.toString().indexOf('a') >= 0) {
1317       callback(new Error('chunk is invalid'));
1318     } else {
1319       callback();
1320     }
1321   }
1322 });
1323 ```
1324
1325 #### An Example Writable Stream
1326
1327 The following illustrates a rather simplistic (and somewhat pointless) custom
1328 Writable stream implementation. While this specific Writable stream instance
1329 is not of any real particular usefulness, the example illustrates each of the
1330 required elements of a custom [Writable][] stream instance:
1331
1332 ```js
1333 const Writable = require('stream').Writable;
1334
1335 class MyWritable extends Writable {
1336   constructor(options) {
1337     super(options);
1338   }
1339
1340   _write(chunk, encoding, callback) {
1341     if (chunk.toString().indexOf('a') >= 0) {
1342       callback(new Error('chunk is invalid'));
1343     } else {
1344       callback();
1345     }
1346   }
1347 }
1348 ```
1349
1350 ### Implementing a Readable Stream
1351
1352 The `stream.Readable` class is extended to implement a [Readable][] stream.
1353
1354 Custom Readable streams *must* call the `new stream.Readable([options])`
1355 constructor and implement the `readable._read()` method.
1356
1357 #### new stream.Readable([options])
1358
1359 * `options` {Object}
1360   * `highWaterMark` {Number} The maximum number of bytes to store in
1361     the internal buffer before ceasing to read from the underlying
1362     resource. Defaults to `16384` (16kb), or `16` for `objectMode` streams
1363   * `encoding` {String} If specified, then buffers will be decoded to
1364     strings using the specified encoding. Defaults to `null`
1365   * `objectMode` {Boolean} Whether this stream should behave
1366     as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns
1367     a single value instead of a Buffer of size n. Defaults to `false`
1368   * `read` {Function} Implementation for the [`stream._read()`][stream-_read]
1369     method.
1370
1371 For example:
1372
1373 ```js
1374 const Readable = require('stream').Readable;
1375
1376 class MyReadable extends Readable {
1377   constructor(options) {
1378     // Calls the stream.Readable(options) constructor
1379     super(options);
1380   }
1381 }
1382 ```
1383
1384 Or, when using pre-ES6 style constructors:
1385
1386 ```js
1387 const Readable = require('stream').Readable;
1388 const util = require('util');
1389
1390 function MyReadable(options) {
1391   if (!(this instanceof MyReadable))
1392     return new MyReadable(options);
1393   Readable.call(this, options);
1394 }
1395 util.inherits(MyReadable, Readable);
1396 ```
1397
1398 Or, using the Simplified Constructor approach:
1399
1400 ```js
1401 const Readable = require('stream').Readable;
1402
1403 const myReadable = new Readable({
1404   read(size) {
1405     // ...
1406   }
1407 });
1408 ```
1409
1410 #### readable.\_read(size)
1411
1412 * `size` {Number} Number of bytes to read asynchronously
1413
1414 *Note*: **This function MUST NOT be called by application code directly.** It
1415 should be implemented by child classes, and called only by the internal Readable
1416 class methods only.
1417
1418 All Readable stream implementations must provide an implementation of the
1419 `readable._read()` method to fetch data from the underlying resource.
1420
1421 When `readable._read()` is called, if data is available from the resource, the
1422 implementation should begin pushing that data into the read queue using the
1423 [`this.push(dataChunk)`][stream-push] method. `_read()` should continue reading
1424 from the resource and pushing data until `readable.push()` returns `false`. Only
1425 when `_read()` is called again after it has stopped should it resume pushing
1426 additional data onto the queue.
1427
1428 *Note*: Once the `readable._read()` method has been called, it will not be
1429 called again until the [`readable.push()`][stream-push] method is called.
1430
1431 The `size` argument is advisory. For implementations where a "read" is a
1432 single operation that returns data can use the `size` argument to determine how
1433 much data to fetch. Other implementations may ignore this argument and simply
1434 provide data whenever it becomes available. There is no need to "wait" until
1435 `size` bytes are available before calling [`stream.push(chunk)`][stream-push].
1436
1437 The `readable._read()` method is prefixed with an underscore because it is
1438 internal to the class that defines it, and should never be called directly by
1439 user programs.
1440
1441 #### readable.push(chunk[, encoding])
1442
1443 * `chunk` {Buffer|Null|String} Chunk of data to push into the read queue
1444 * `encoding` {String} Encoding of String chunks.  Must be a valid
1445   Buffer encoding, such as `'utf8'` or `'ascii'`
1446 * Returns {Boolean} `true` if additional chunks of data may continued to be
1447   pushed; `false` otherwise.
1448
1449 When `chunk` is a `Buffer` or `string`, the `chunk` of data will be added to the
1450 internal queue for users of the stream to consume. Passing `chunk` as `null`
1451 signals the end of the stream (EOF), after which no more data can be written.
1452
1453 When the Readable is operating in paused mode, the data added with
1454 `readable.push()` can be read out by calling the
1455 [`readable.read()`][stream-read] method when the [`'readable'`][] event is
1456 emitted.
1457
1458 When the Readable is operating in flowing mode, the data added with
1459 `readable.push()` will be delivered by emitting a `'data'` event.
1460
1461 The `readable.push()` method is designed to be as flexible as possible. For
1462 example, when wrapping a lower-level source that provides some form of
1463 pause/resume mechanism, and a data callback, the low-level source can be wrapped
1464 by the custom Readable instance as illustrated in the following example:
1465
1466 ```js
1467 // source is an object with readStop() and readStart() methods,
1468 // and an `ondata` member that gets called when it has data, and
1469 // an `onend` member that gets called when the data is over.
1470
1471 class SourceWrapper extends Readable {
1472   constructor(options) {
1473     super(options);
1474
1475     this._source = getLowlevelSourceObject();
1476
1477     // Every time there's data, push it into the internal buffer.
1478     this._source.ondata = (chunk) => {
1479       // if push() returns false, then stop reading from source
1480       if (!this.push(chunk))
1481         this._source.readStop();
1482     };
1483
1484     // When the source ends, push the EOF-signaling `null` chunk
1485     this._source.onend = () => {
1486       this.push(null);
1487     };
1488   }
1489   // _read will be called when the stream wants to pull more data in
1490   // the advisory size argument is ignored in this case.
1491   _read(size) {
1492     this._source.readStart();
1493   }
1494 }
1495 ```
1496 *Note*: The `readable.push()` method is intended be called only by Readable
1497 Implementers, and only from within the `readable._read()` method.
1498
1499 #### Errors While Reading
1500
1501 It is recommended that errors occurring during the processing of the
1502 `readable._read()` method are emitted using the `'error'` event rather than
1503 being thrown. Throwing an Error from within `readable._read()` can result in
1504 expected and inconsistent behavior depending on whether the stream is operating
1505 in flowing or paused mode. Using the `'error'` event ensures consistent and
1506 predictable handling of errors.
1507
1508 ```js
1509 const Readable = require('stream').Readable;
1510
1511 const myReadable = new Readable({
1512   read(size) {
1513     if (checkSomeErrorCondition()) {
1514       process.nextTick(() => this.emit('error', err));
1515       return;
1516     }
1517     // do some work
1518   }
1519 });
1520 ```
1521
1522 #### An Example Counting Stream
1523
1524 <!--type=example-->
1525
1526 The following is a basic example of a Readable stream that emits the numerals
1527 from 1 to 1,000,000 in ascending order, and then ends.
1528
1529 ```js
1530 const Readable = require('stream').Readable;
1531
1532 class Counter extends Readable {
1533   constructor(opt) {
1534     super(opt);
1535     this._max = 1000000;
1536     this._index = 1;
1537   }
1538
1539   _read() {
1540     var i = this._index++;
1541     if (i > this._max)
1542       this.push(null);
1543     else {
1544       var str = '' + i;
1545       var buf = Buffer.from(str, 'ascii');
1546       this.push(buf);
1547     }
1548   }
1549 }
1550 ```
1551
1552 ### Implementing a Duplex Stream
1553
1554 A [Duplex][] stream is one that implements both [Readable][] and [Writable][],
1555 such as a TCP socket connection.
1556
1557 Because Javascript does not have support for multiple inheritance, the
1558 `stream.Duplex` class is extended to implement a [Duplex][] stream (as opposed
1559 to extending the `stream.Readable` *and* `stream.Writable` classes).
1560
1561 *Note*: The `stream.Duplex` class prototypically inherits from `stream.Readable`
1562 and parasitically from `stream.Writable`.
1563
1564 Custom Duplex streams *must* call the `new stream.Duplex([options])`
1565 constructor and implement *both* the `readable._read()` and
1566 `writable._write()` methods.
1567
1568 #### new stream.Duplex(options)
1569
1570 * `options` {Object} Passed to both Writable and Readable
1571   constructors. Also has the following fields:
1572   * `allowHalfOpen` {Boolean} Defaults to `true`. If set to `false`, then
1573     the stream will automatically end the readable side when the
1574     writable side ends and vice versa.
1575   * `readableObjectMode` {Boolean} Defaults to `false`. Sets `objectMode`
1576     for readable side of the stream. Has no effect if `objectMode`
1577     is `true`.
1578   * `writableObjectMode` {Boolean} Defaults to `false`. Sets `objectMode`
1579     for writable side of the stream. Has no effect if `objectMode`
1580     is `true`.
1581
1582 For example:
1583
1584 ```js
1585 const Duplex = require('stream').Duplex;
1586
1587 class MyDuplex extends Duplex {
1588   constructor(options) {
1589     super(options);
1590   }
1591 }
1592 ```
1593
1594 Or, when using pre-ES6 style constructors:
1595
1596 ```js
1597 const Duplex = require('stream').Duplex;
1598 const util = require('util');
1599
1600 function MyDuplex(options) {
1601   if (!(this instanceof MyDuplex))
1602     return new MyDuplex(options);
1603   Duplex.call(this, options);
1604 }
1605 util.inherits(MyDuplex, Duplex);
1606 ```
1607
1608 Or, using the Simplified Constructor approach:
1609
1610 ```js
1611 const Duplex = require('stream').Duplex;
1612
1613 const myDuplex = new Duplex({
1614   read(size) {
1615     // ...
1616   },
1617   write(chunk, encoding, callback) {
1618     // ...
1619   }
1620 });
1621 ```
1622
1623 #### An Example Duplex Stream
1624
1625 The following illustrates a simple example of a Duplex stream that wraps a
1626 hypothetical lower-level source object to which data can be written, and
1627 from which data can be read, albeit using an API that is not compatible with
1628 Node.js streams.
1629 The following illustrates a simple example of a Duplex stream that buffers
1630 incoming written data via the [Writable][] interface that is read back out
1631 via the [Readable][] interface.
1632
1633 ```js
1634 const Duplex = require('stream').Duplex;
1635 const kSource = Symbol('source');
1636
1637 class MyDuplex extends Duplex {
1638   constructor(source, options) {
1639     super(options);
1640     this[kSource] = source;
1641   }
1642
1643   _write(chunk, encoding, callback) {
1644     // The underlying source only deals with strings
1645     if (Buffer.isBuffer(chunk))
1646       chunk = chunk.toString(encoding);
1647     this[kSource].writeSomeData(chunk, encoding);
1648     callback();
1649   }
1650
1651   _read(size) {
1652     this[kSource].fetchSomeData(size, (data, encoding) => {
1653       this.push(Buffer.from(data, encoding));
1654     });
1655   }
1656 }
1657 ```
1658
1659 The most important aspect of a Duplex stream is that the Readable and Writable
1660 sides operate independently of one another despite co-existing within a single
1661 object instance.
1662
1663 #### Object Mode Duplex Streams
1664
1665 For Duplex streams, `objectMode` can be set exclusively for either the Readable
1666 or Writable side using the `readableObjectMode` and `writableObjectMode` options
1667 respectively.
1668
1669 In the following example, for instance, a new Transform stream (which is a
1670 type of [Duplex][] stream) is created that has an object mode Writable side
1671 that accepts JavaScript numbers that are converted to hexidecimal strings on
1672 the Readable side.
1673
1674 ```js
1675 const Transform = require('stream').Transform;
1676
1677 // All Transform streams are also Duplex Streams
1678 const myTransform = new Transform({
1679   writableObjectMode: true,
1680
1681   transform(chunk, encoding, callback) {
1682     // Coerce the chunk to a number if necessary
1683     chunk |= 0;
1684
1685     // Transform the chunk into something else.
1686     const data = chunk.toString(16);
1687
1688     // Push the data onto the readable queue.
1689     callback(null, '0'.repeat(data.length % 2) + data);
1690   }
1691 });
1692
1693 myTransform.setEncoding('ascii');
1694 myTransform.on('data', (chunk) => console.log(chunk));
1695
1696 myTransform.write(1);
1697   // Prints: 01
1698 myTransform.write(10);
1699   // Prints: 0a
1700 myTransform.write(100);
1701   // Prints: 64
1702 ```
1703
1704 ### Implementing a Transform Stream
1705
1706 A [Transform][] stream is a [Duplex][] stream where the output is computed
1707 in some way from the input. Examples include [zlib][] streams or [crypto][]
1708 streams that compress, encrypt, or decrypt data.
1709
1710 *Note*: There is no requirement that the output be the same size as the input,
1711 the same number of chunks, or arrive at the same time. For example, a
1712 Hash stream will only ever have a single chunk of output which is
1713 provided when the input is ended. A `zlib` stream will produce output
1714 that is either much smaller or much larger than its input.
1715
1716 The `stream.Transform` class is extended to implement a [Transform][] stream.
1717
1718 The `stream.Transform` class prototypically inherits from `stream.Duplex` and
1719 implements its own versions of the `writable._write()` and `readable._read()`
1720 methods. Custom Transform implementations *must* implement the
1721 [`transform._transform()`][stream-_transform] method and *may* also implement
1722 the [`transform._flush()`][stream-_flush] method.
1723
1724 *Note*: Care must be taken when using Transform streams in that data written
1725 to the stream can cause the Writable side of the stream to become paused if
1726 the output on the Readable side is not consumed.
1727
1728 #### new stream.Transform([options])
1729
1730 * `options` {Object} Passed to both Writable and Readable
1731   constructors. Also has the following fields:
1732   * `transform` {Function} Implementation for the
1733     [`stream._transform()`][stream-_transform] method.
1734   * `flush` {Function} Implementation for the [`stream._flush()`][stream-_flush]
1735     method.
1736
1737 For example:
1738
1739 ```js
1740 const Transform = require('stream').Transform;
1741
1742 class MyTransform extends Transform {
1743   constructor(options) {
1744     super(options);
1745   }
1746 }
1747 ```
1748
1749 Or, when using pre-ES6 style constructors:
1750
1751 ```js
1752 const Transform = require('stream').Transform;
1753 const util = require('util');
1754
1755 function MyTransform(options) {
1756   if (!(this instanceof MyTransform))
1757     return new MyTransform(options);
1758   Transform.call(this, options);
1759 }
1760 util.inherits(MyTransform, Transform);
1761 ```
1762
1763 Or, using the Simplified Constructor approach:
1764
1765 ```js
1766 const Transform = require('stream').Transform;
1767
1768 const myTransform = new Transform({
1769   transform(chunk, encoding, callback) {
1770     // ...
1771   }
1772 });
1773 ```
1774
1775 #### Events: 'finish' and 'end'
1776
1777 The [`'finish'`][] and [`'end'`][] events are from the `stream.Writable`
1778 and `stream.Readable` classes, respectively. The `'finish'` event is emitted
1779 after [`stream.end()`][stream-end] is called and all chunks have been processed
1780 by [`stream._transform()`][stream-_transform]. The `'end'` event is emitted
1781 after all data has been output, which occurs after the callback in
1782 [`transform._flush()`][stream-_flush] has been called.
1783
1784 #### transform.\_flush(callback)
1785
1786 * `callback` {Function} A callback function (optionally with an error
1787   argument) to be called when remaining data has been flushed.
1788
1789 *Note*: **This function MUST NOT be called by application code directly.** It
1790 should be implemented by child classes, and called only by the internal Readable
1791 class methods only.
1792
1793 In some cases, a transform operation may need to emit an additional bit of
1794 data at the end of the stream. For example, a `zlib` compression stream will
1795 store an amount of internal state used to optimally compress the output. When
1796 the stream ends, however, that additional data needs to be flushed so that the
1797 compressed data will be complete.
1798
1799 Custom [Transform][] implementations *may* implement the `transform._flush()`
1800 method. This will be called when there is no more written data to be consumed,
1801 but before the [`'end'`][] event is emitted signaling the end of the
1802 [Readable][] stream.
1803
1804 Within the `transform._flush()` implementation, the `readable.push()` method
1805 may be called zero or more times, as appropriate. The `callback` function must
1806 be called when the flush operation is complete.
1807
1808 The `transform._flush()` method is prefixed with an underscore because it is
1809 internal to the class that defines it, and should never be called directly by
1810 user programs.
1811
1812 #### transform.\_transform(chunk, encoding, callback)
1813
1814 * `chunk` {Buffer|String} The chunk to be transformed. Will **always**
1815   be a buffer unless the `decodeStrings` option was set to `false`.
1816 * `encoding` {String} If the chunk is a string, then this is the
1817   encoding type. If chunk is a buffer, then this is the special
1818   value - 'buffer', ignore it in this case.
1819 * `callback` {Function} A callback function (optionally with an error
1820   argument and data) to be called after the supplied `chunk` has been
1821   processed.
1822
1823 *Note*: **This function MUST NOT be called by application code directly.** It
1824 should be implemented by child classes, and called only by the internal Readable
1825 class methods only.
1826
1827 All Transform stream implementations must provide a `_transform()`
1828 method to accept input and produce output. The `transform._transform()`
1829 implementation handles the bytes being written, computes an output, then passes
1830 that output off to the readable portion using the `readable.push()` method.
1831
1832 The `transform.push()` method may be called zero or more times to generate
1833 output from a single input chunk, depending on how much is to be output
1834 as a result of the chunk.
1835
1836 It is possible that no output is generated from any given chunk of input data.
1837
1838 The `callback` function must be called only when the current chunk is completely
1839 consumed. The first argument passed to the `callback` must be an `Error` object
1840 if an error occurred while processing the input or `null` otherwise. If a second
1841 argument is passed to the `callback`, it will be forwarded on to the
1842 `readable.push()` method. In other words the following are equivalent:
1843
1844 ```js
1845 transform.prototype._transform = function (data, encoding, callback) {
1846   this.push(data);
1847   callback();
1848 };
1849
1850 transform.prototype._transform = function (data, encoding, callback) {
1851   callback(null, data);
1852 };
1853 ```
1854
1855 The `transform._transform()` method is prefixed with an underscore because it
1856 is internal to the class that defines it, and should never be called directly by
1857 user programs.
1858
1859 #### Class: stream.PassThrough
1860
1861 The `stream.PassThrough` class is a trivial implementation of a [Transform][]
1862 stream that simply passes the input bytes across to the output. Its purpose is
1863 primarily for examples and testing, but there are some use cases where
1864 `stream.PassThrough` is useful as a building block for novel sorts of streams.
1865
1866 ## Additional Notes
1867
1868 <!--type=misc-->
1869
1870 ### Compatibility with Older Node.js Versions
1871
1872 <!--type=misc-->
1873
1874 In versions of Node.js prior to v0.10, the Readable stream interface was
1875 simpler, but also less powerful and less useful.
1876
1877 * Rather than waiting for calls the [`stream.read()`][stream-read] method,
1878   [`'data'`][] events would begin emitting immediately. Applications that
1879   would need to perform some amount of work to decide how to handle data
1880   were required to store read data into buffers so the data would not be lost.
1881 * The [`stream.pause()`][stream-pause] method was advisory, rather than
1882   guaranteed. This meant that it was still necessary to be prepared to receive
1883   [`'data'`][] events *even when the stream was in a paused state*.
1884
1885 In Node.js v0.10, the [Readable][] class was added. For backwards compatibility
1886 with older Node.js programs, Readable streams switch into "flowing mode" when a
1887 [`'data'`][] event handler is added, or when the
1888 [`stream.resume()`][stream-resume] method is called. The effect is that, even
1889 when not using the new [`stream.read()`][stream-read] method and
1890 [`'readable'`][] event, it is no longer necessary to worry about losing
1891 [`'data'`][] chunks.
1892
1893 While most applications will continue to function normally, this introduces an
1894 edge case in the following conditions:
1895
1896 * No [`'data'`][] event listener is added.
1897 * The [`stream.resume()`][stream-resume] method is never called.
1898 * The stream is not piped to any writable destination.
1899
1900 For example, consider the following code:
1901
1902 ```js
1903 // WARNING!  BROKEN!
1904 net.createServer((socket) => {
1905
1906   // we add an 'end' method, but never consume the data
1907   socket.on('end', () => {
1908     // It will never get here.
1909     socket.end('The message was received but was not processed.\n');
1910   });
1911
1912 }).listen(1337);
1913 ```
1914
1915 In versions of Node.js prior to v0.10, the incoming message data would be
1916 simply discarded. However, in Node.js v0.10 and beyond, the socket remains
1917 paused forever.
1918
1919 The workaround in this situation is to call the
1920 [`stream.resume()`][stream-resume] method to begin the flow of data:
1921
1922 ```js
1923 // Workaround
1924 net.createServer((socket) => {
1925
1926   socket.on('end', () => {
1927     socket.end('The message was received but was not processed.\n');
1928   });
1929
1930   // start the flow of data, discarding it.
1931   socket.resume();
1932
1933 }).listen(1337);
1934 ```
1935
1936 In addition to new Readable streams switching into flowing mode,
1937 pre-v0.10 style streams can be wrapped in a Readable class using the
1938 [`readable.wrap()`][`stream.wrap()`] method.
1939
1940
1941 ### `readable.read(0)`
1942
1943 There are some cases where it is necessary to trigger a refresh of the
1944 underlying readable stream mechanisms, without actually consuming any
1945 data. In such cases, it is possible to call `readable.read(0)`, which will
1946 always return `null`.
1947
1948 If the internal read buffer is below the `highWaterMark`, and the
1949 stream is not currently reading, then calling `stream.read(0)` will trigger
1950 a low-level [`stream._read()`][stream-_read] call.
1951
1952 While most applications will almost never need to do this, there are
1953 situations within Node.js where this is done, particularly in the
1954 Readable stream class internals.
1955
1956 ### `readable.push('')`
1957
1958 Use of `readable.push('')` is not recommended.
1959
1960 Pushing a zero-byte string or `Buffer` to a stream that is not in object mode
1961 has an interesting side effect. Because it *is* a call to
1962 [`readable.push()`][stream-push], the call will end the reading process.
1963 However, because the argument is an empty string, no data is added to the
1964 readable buffer so there is nothing for a user to consume.
1965
1966 [`'data'`]: #stream_event_data
1967 [`'drain'`]: #stream_event_drain
1968 [`'end'`]: #stream_event_end
1969 [`'finish'`]: #stream_event_finish
1970 [`'readable'`]: #stream_event_readable
1971 [`buf.toString(encoding)`]: https://nodejs.org/docs/v6.3.1/api/buffer.html#buffer_buf_tostring_encoding_start_end
1972 [`EventEmitter`]: https://nodejs.org/docs/v6.3.1/api/events.html#events_class_eventemitter
1973 [`process.stderr`]: https://nodejs.org/docs/v6.3.1/api/process.html#process_process_stderr
1974 [`process.stdin`]: https://nodejs.org/docs/v6.3.1/api/process.html#process_process_stdin
1975 [`process.stdout`]: https://nodejs.org/docs/v6.3.1/api/process.html#process_process_stdout
1976 [`stream.cork()`]: #stream_writable_cork
1977 [`stream.pipe()`]: #stream_readable_pipe_destination_options
1978 [`stream.uncork()`]: #stream_writable_uncork
1979 [`stream.unpipe()`]: #stream_readable_unpipe_destination
1980 [`stream.wrap()`]: #stream_readable_wrap_stream
1981 [`tls.CryptoStream`]: https://nodejs.org/docs/v6.3.1/api/tls.html#tls_class_cryptostream
1982 [API for Stream Consumers]: #stream_api_for_stream_consumers
1983 [API for Stream Implementers]: #stream_api_for_stream_implementers
1984 [child process stdin]: https://nodejs.org/docs/v6.3.1/api/child_process.html#child_process_child_stdin
1985 [child process stdout and stderr]: https://nodejs.org/docs/v6.3.1/api/child_process.html#child_process_child_stdout
1986 [Compatibility]: #stream_compatibility_with_older_node_js_versions
1987 [crypto]: crypto.html
1988 [Duplex]: #stream_class_stream_duplex
1989 [fs read streams]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_class_fs_readstream
1990 [fs write streams]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_class_fs_writestream
1991 [`fs.createReadStream()`]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_fs_createreadstream_path_options
1992 [`fs.createWriteStream()`]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_fs_createwritestream_path_options
1993 [`net.Socket`]: https://nodejs.org/docs/v6.3.1/api/net.html#net_class_net_socket
1994 [`zlib.createDeflate()`]: https://nodejs.org/docs/v6.3.1/api/zlib.html#zlib_zlib_createdeflate_options
1995 [HTTP requests, on the client]: https://nodejs.org/docs/v6.3.1/api/http.html#http_class_http_clientrequest
1996 [HTTP responses, on the server]: https://nodejs.org/docs/v6.3.1/api/http.html#http_class_http_serverresponse
1997 [http-incoming-message]: https://nodejs.org/docs/v6.3.1/api/http.html#http_class_http_incomingmessage
1998 [Object mode]: #stream_object_mode
1999 [Readable]: #stream_class_stream_readable
2000 [SimpleProtocol v2]: #stream_example_simpleprotocol_parser_v2
2001 [stream-_flush]: #stream_transform_flush_callback
2002 [stream-_read]: #stream_readable_read_size_1
2003 [stream-_transform]: #stream_transform_transform_chunk_encoding_callback
2004 [stream-_write]: #stream_writable_write_chunk_encoding_callback_1
2005 [stream-_writev]: #stream_writable_writev_chunks_callback
2006 [stream-end]: #stream_writable_end_chunk_encoding_callback
2007 [stream-pause]: #stream_readable_pause
2008 [stream-push]: #stream_readable_push_chunk_encoding
2009 [stream-read]: #stream_readable_read_size
2010 [stream-resume]: #stream_readable_resume
2011 [stream-write]: #stream_writable_write_chunk_encoding_callback
2012 [TCP sockets]: https://nodejs.org/docs/v6.3.1/api/net.html#net_class_net_socket
2013 [Transform]: #stream_class_stream_transform
2014 [Writable]: #stream_class_stream_writable
2015 [zlib]: zlib.html