Version 1
[yaffs-website] / node_modules / concat-stream / node_modules / readable-stream / doc / stream.markdown
1 # Stream
2
3     Stability: 2 - Stable
4
5 A stream is an abstract interface implemented by various objects in
6 Node.js. For example a [request to an HTTP server][http-incoming-message] is a
7 stream, as is [`process.stdout`][]. Streams are readable, writable, or both. All
8 streams are instances of [`EventEmitter`][].
9
10 You can load the Stream base classes by doing `require('stream')`.
11 There are base classes provided for [Readable][] streams, [Writable][]
12 streams, [Duplex][] streams, and [Transform][] streams.
13
14 This document is split up into 3 sections:
15
16 1. The first section explains the parts of the API that you need to be
17    aware of to use streams in your programs.
18 2. The second section explains the parts of the API that you need to
19    use if you implement your own custom streams yourself. The API is designed to
20    make this easy for you to do.
21 3. The third section goes into more depth about how streams work,
22    including some of the internal mechanisms and functions that you
23    should probably not modify unless you definitely know what you are
24    doing.
25
26
27 ## API for Stream Consumers
28
29 <!--type=misc-->
30
31 Streams can be either [Readable][], [Writable][], or both ([Duplex][]).
32
33 All streams are EventEmitters, but they also have other custom methods
34 and properties depending on whether they are Readable, Writable, or
35 Duplex.
36
37 If a stream is both Readable and Writable, then it implements all of
38 the methods and events. So, a [Duplex][] or [Transform][] stream is
39 fully described by this API, though their implementation may be
40 somewhat different.
41
42 It is not necessary to implement Stream interfaces in order to consume
43 streams in your programs. If you **are** implementing streaming
44 interfaces in your own program, please also refer to
45 [API for Stream Implementors][].
46
47 Almost all Node.js programs, no matter how simple, use Streams in some
48 way. Here is an example of using Streams in an Node.js program:
49
50 ```js
51 const http = require('http');
52
53 var server = http.createServer( (req, res) => {
54   // req is an http.IncomingMessage, which is a Readable Stream
55   // res is an http.ServerResponse, which is a Writable Stream
56
57   var body = '';
58   // we want to get the data as utf8 strings
59   // If you don't set an encoding, then you'll get Buffer objects
60   req.setEncoding('utf8');
61
62   // Readable streams emit 'data' events once a listener is added
63   req.on('data', (chunk) => {
64     body += chunk;
65   });
66
67   // the end event tells you that you have entire body
68   req.on('end', () => {
69     try {
70       var data = JSON.parse(body);
71     } catch (er) {
72       // uh oh!  bad json!
73       res.statusCode = 400;
74       return res.end(`error: ${er.message}`);
75     }
76
77     // write back something interesting to the user:
78     res.write(typeof data);
79     res.end();
80   });
81 });
82
83 server.listen(1337);
84
85 // $ curl localhost:1337 -d '{}'
86 // object
87 // $ curl localhost:1337 -d '"foo"'
88 // string
89 // $ curl localhost:1337 -d 'not json'
90 // error: Unexpected token o
91 ```
92
93 ### Class: stream.Duplex
94
95 Duplex streams are streams that implement both the [Readable][] and
96 [Writable][] interfaces.
97
98 Examples of Duplex streams include:
99
100 * [TCP sockets][]
101 * [zlib streams][zlib]
102 * [crypto streams][crypto]
103
104 ### Class: stream.Readable
105
106 <!--type=class-->
107
108 The Readable stream interface is the abstraction for a *source* of
109 data that you are reading from. In other words, data comes *out* of a
110 Readable stream.
111
112 A Readable stream will not start emitting data until you indicate that
113 you are ready to receive it.
114
115 Readable streams have two "modes": a **flowing mode** and a **paused
116 mode**. When in flowing mode, data is read from the underlying system
117 and provided to your program as fast as possible. In paused mode, you
118 must explicitly call [`stream.read()`][stream-read] to get chunks of data out.
119 Streams start out in paused mode.
120
121 **Note**: If no data event handlers are attached, and there are no
122 [`stream.pipe()`][] destinations, and the stream is switched into flowing
123 mode, then data will be lost.
124
125 You can switch to flowing mode by doing any of the following:
126
127 * Adding a [`'data'`][] event handler to listen for data.
128 * Calling the [`stream.resume()`][stream-resume] method to explicitly open the
129   flow.
130 * Calling the [`stream.pipe()`][] method to send the data to a [Writable][].
131
132 You can switch back to paused mode by doing either of the following:
133
134 * If there are no pipe destinations, by calling the
135   [`stream.pause()`][stream-pause] method.
136 * If there are pipe destinations, by removing any [`'data'`][] event
137   handlers, and removing all pipe destinations by calling the
138   [`stream.unpipe()`][] method.
139
140 Note that, for backwards compatibility reasons, removing [`'data'`][]
141 event handlers will **not** automatically pause the stream. Also, if
142 there are piped destinations, then calling [`stream.pause()`][stream-pause] will
143 not guarantee that the stream will *remain* paused once those
144 destinations drain and ask for more data.
145
146 Examples of readable streams include:
147
148 * [HTTP responses, on the client][http-incoming-message]
149 * [HTTP requests, on the server][http-incoming-message]
150 * [fs read streams][]
151 * [zlib streams][zlib]
152 * [crypto streams][crypto]
153 * [TCP sockets][]
154 * [child process stdout and stderr][]
155 * [`process.stdin`][]
156
157 #### Event: 'close'
158
159 Emitted when the stream and any of its underlying resources (a file
160 descriptor, for example) have been closed. The event indicates that
161 no more events will be emitted, and no further computation will occur.
162
163 Not all streams will emit the `'close'` event.
164
165 #### Event: 'data'
166
167 * `chunk` {Buffer|String} The chunk of data.
168
169 Attaching a `'data'` event listener to a stream that has not been
170 explicitly paused will switch the stream into flowing mode. Data will
171 then be passed as soon as it is available.
172
173 If you just want to get all the data out of the stream as fast as
174 possible, this is the best way to do so.
175
176 ```js
177 var readable = getReadableStreamSomehow();
178 readable.on('data', (chunk) => {
179   console.log('got %d bytes of data', chunk.length);
180 });
181 ```
182
183 #### Event: 'end'
184
185 This event fires when there will be no more data to read.
186
187 Note that the `'end'` event **will not fire** unless the data is
188 completely consumed. This can be done by switching into flowing mode,
189 or by calling [`stream.read()`][stream-read] repeatedly until you get to the
190 end.
191
192 ```js
193 var readable = getReadableStreamSomehow();
194 readable.on('data', (chunk) => {
195   console.log('got %d bytes of data', chunk.length);
196 });
197 readable.on('end', () => {
198   console.log('there will be no more data.');
199 });
200 ```
201
202 #### Event: 'error'
203
204 * {Error Object}
205
206 Emitted if there was an error receiving data.
207
208 #### Event: 'readable'
209
210 When a chunk of data can be read from the stream, it will emit a
211 `'readable'` event.
212
213 In some cases, listening for a `'readable'` event will cause some data
214 to be read into the internal buffer from the underlying system, if it
215 hadn't already.
216
217 ```javascript
218 var readable = getReadableStreamSomehow();
219 readable.on('readable', () => {
220   // there is some data to read now
221 });
222 ```
223
224 Once the internal buffer is drained, a `'readable'` event will fire
225 again when more data is available.
226
227 The `'readable'` event is not emitted in the "flowing" mode with the
228 sole exception of the last one, on end-of-stream.
229
230 The `'readable'` event indicates that the stream has new information:
231 either new data is available or the end of the stream has been reached.
232 In the former case, [`stream.read()`][stream-read] will return that data. In the
233 latter case, [`stream.read()`][stream-read] will return null. For instance, in
234 the following example, `foo.txt` is an empty file:
235
236 ```js
237 const fs = require('fs');
238 var rr = fs.createReadStream('foo.txt');
239 rr.on('readable', () => {
240   console.log('readable:', rr.read());
241 });
242 rr.on('end', () => {
243   console.log('end');
244 });
245 ```
246
247 The output of running this script is:
248
249 ```
250 $ node test.js
251 readable: null
252 end
253 ```
254
255 #### readable.isPaused()
256
257 * Return: {Boolean}
258
259 This method returns whether or not the `readable` has been **explicitly**
260 paused by client code (using [`stream.pause()`][stream-pause] without a
261 corresponding [`stream.resume()`][stream-resume]).
262
263 ```js
264 var readable = new stream.Readable
265
266 readable.isPaused() // === false
267 readable.pause()
268 readable.isPaused() // === true
269 readable.resume()
270 readable.isPaused() // === false
271 ```
272
273 #### readable.pause()
274
275 * Return: `this`
276
277 This method will cause a stream in flowing mode to stop emitting
278 [`'data'`][] events, switching out of flowing mode. Any data that becomes
279 available will remain in the internal buffer.
280
281 ```js
282 var readable = getReadableStreamSomehow();
283 readable.on('data', (chunk) => {
284   console.log('got %d bytes of data', chunk.length);
285   readable.pause();
286   console.log('there will be no more data for 1 second');
287   setTimeout(() => {
288     console.log('now data will start flowing again');
289     readable.resume();
290   }, 1000);
291 });
292 ```
293
294 #### readable.pipe(destination[, options])
295
296 * `destination` {stream.Writable} The destination for writing data
297 * `options` {Object} Pipe options
298   * `end` {Boolean} End the writer when the reader ends. Default = `true`
299
300 This method pulls all the data out of a readable stream, and writes it
301 to the supplied destination, automatically managing the flow so that
302 the destination is not overwhelmed by a fast readable stream.
303
304 Multiple destinations can be piped to safely.
305
306 ```js
307 var readable = getReadableStreamSomehow();
308 var writable = fs.createWriteStream('file.txt');
309 // All the data from readable goes into 'file.txt'
310 readable.pipe(writable);
311 ```
312
313 This function returns the destination stream, so you can set up pipe
314 chains like so:
315
316 ```js
317 var r = fs.createReadStream('file.txt');
318 var z = zlib.createGzip();
319 var w = fs.createWriteStream('file.txt.gz');
320 r.pipe(z).pipe(w);
321 ```
322
323 For example, emulating the Unix `cat` command:
324
325 ```js
326 process.stdin.pipe(process.stdout);
327 ```
328
329 By default [`stream.end()`][stream-end] is called on the destination when the
330 source stream emits [`'end'`][], so that `destination` is no longer writable.
331 Pass `{ end: false }` as `options` to keep the destination stream open.
332
333 This keeps `writer` open so that "Goodbye" can be written at the
334 end.
335
336 ```js
337 reader.pipe(writer, { end: false });
338 reader.on('end', () => {
339   writer.end('Goodbye\n');
340 });
341 ```
342
343 Note that [`process.stderr`][] and [`process.stdout`][] are never closed until
344 the process exits, regardless of the specified options.
345
346 #### readable.read([size])
347
348 * `size` {Number} Optional argument to specify how much data to read.
349 * Return {String|Buffer|Null}
350
351 The `read()` method pulls some data out of the internal buffer and
352 returns it. If there is no data available, then it will return
353 `null`.
354
355 If you pass in a `size` argument, then it will return that many
356 bytes. If `size` bytes are not available, then it will return `null`,
357 unless we've ended, in which case it will return the data remaining
358 in the buffer.
359
360 If you do not specify a `size` argument, then it will return all the
361 data in the internal buffer.
362
363 This method should only be called in paused mode. In flowing mode,
364 this method is called automatically until the internal buffer is
365 drained.
366
367 ```js
368 var readable = getReadableStreamSomehow();
369 readable.on('readable', () => {
370   var chunk;
371   while (null !== (chunk = readable.read())) {
372     console.log('got %d bytes of data', chunk.length);
373   }
374 });
375 ```
376
377 If this method returns a data chunk, then it will also trigger the
378 emission of a [`'data'`][] event.
379
380 Note that calling [`stream.read([size])`][stream-read] after the [`'end'`][]
381 event has been triggered will return `null`. No runtime error will be raised.
382
383 #### readable.resume()
384
385 * Return: `this`
386
387 This method will cause the readable stream to resume emitting [`'data'`][]
388 events.
389
390 This method will switch the stream into flowing mode. If you do *not*
391 want to consume the data from a stream, but you *do* want to get to
392 its [`'end'`][] event, you can call [`stream.resume()`][stream-resume] to open
393 the flow of data.
394
395 ```js
396 var readable = getReadableStreamSomehow();
397 readable.resume();
398 readable.on('end', () => {
399   console.log('got to the end, but did not read anything');
400 });
401 ```
402
403 #### readable.setEncoding(encoding)
404
405 * `encoding` {String} The encoding to use.
406 * Return: `this`
407
408 Call this function to cause the stream to return strings of the specified
409 encoding instead of Buffer objects. For example, if you do
410 `readable.setEncoding('utf8')`, then the output data will be interpreted as
411 UTF-8 data, and returned as strings. If you do `readable.setEncoding('hex')`,
412 then the data will be encoded in hexadecimal string format.
413
414 This properly handles multi-byte characters that would otherwise be
415 potentially mangled if you simply pulled the Buffers directly and
416 called [`buf.toString(encoding)`][] on them. If you want to read the data
417 as strings, always use this method.
418
419 Also you can disable any encoding at all with `readable.setEncoding(null)`.
420 This approach is very useful if you deal with binary data or with large
421 multi-byte strings spread out over multiple chunks.
422
423 ```js
424 var readable = getReadableStreamSomehow();
425 readable.setEncoding('utf8');
426 readable.on('data', (chunk) => {
427   assert.equal(typeof chunk, 'string');
428   console.log('got %d characters of string data', chunk.length);
429 });
430 ```
431
432 #### readable.unpipe([destination])
433
434 * `destination` {stream.Writable} Optional specific stream to unpipe
435
436 This method will remove the hooks set up for a previous [`stream.pipe()`][]
437 call.
438
439 If the destination is not specified, then all pipes are removed.
440
441 If the destination is specified, but no pipe is set up for it, then
442 this is a no-op.
443
444 ```js
445 var readable = getReadableStreamSomehow();
446 var writable = fs.createWriteStream('file.txt');
447 // All the data from readable goes into 'file.txt',
448 // but only for the first second
449 readable.pipe(writable);
450 setTimeout(() => {
451   console.log('stop writing to file.txt');
452   readable.unpipe(writable);
453   console.log('manually close the file stream');
454   writable.end();
455 }, 1000);
456 ```
457
458 #### readable.unshift(chunk)
459
460 * `chunk` {Buffer|String} Chunk of data to unshift onto the read queue
461
462 This is useful in certain cases where a stream is being consumed by a
463 parser, which needs to "un-consume" some data that it has
464 optimistically pulled out of the source, so that the stream can be
465 passed on to some other party.
466
467 Note that `stream.unshift(chunk)` cannot be called after the [`'end'`][] event
468 has been triggered; a runtime error will be raised.
469
470 If you find that you must often call `stream.unshift(chunk)` in your
471 programs, consider implementing a [Transform][] stream instead. (See [API
472 for Stream Implementors][].)
473
474 ```js
475 // Pull off a header delimited by \n\n
476 // use unshift() if we get too much
477 // Call the callback with (error, header, stream)
478 const StringDecoder = require('string_decoder').StringDecoder;
479 function parseHeader(stream, callback) {
480   stream.on('error', callback);
481   stream.on('readable', onReadable);
482   var decoder = new StringDecoder('utf8');
483   var header = '';
484   function onReadable() {
485     var chunk;
486     while (null !== (chunk = stream.read())) {
487       var str = decoder.write(chunk);
488       if (str.match(/\n\n/)) {
489         // found the header boundary
490         var split = str.split(/\n\n/);
491         header += split.shift();
492         var remaining = split.join('\n\n');
493         var buf = new Buffer(remaining, 'utf8');
494         if (buf.length)
495           stream.unshift(buf);
496         stream.removeListener('error', callback);
497         stream.removeListener('readable', onReadable);
498         // now the body of the message can be read from the stream.
499         callback(null, header, stream);
500       } else {
501         // still reading the header.
502         header += str;
503       }
504     }
505   }
506 }
507 ```
508
509 Note that, unlike [`stream.push(chunk)`][stream-push], `stream.unshift(chunk)`
510 will not end the reading process by resetting the internal reading state of the
511 stream. This can cause unexpected results if `unshift()` is called during a
512 read (i.e. from within a [`stream._read()`][stream-_read] implementation on a
513 custom stream). Following the call to `unshift()` with an immediate
514 [`stream.push('')`][stream-push] will reset the reading state appropriately,
515 however it is best to simply avoid calling `unshift()` while in the process of
516 performing a read.
517
518 #### readable.wrap(stream)
519
520 * `stream` {Stream} An "old style" readable stream
521
522 Versions of Node.js prior to v0.10 had streams that did not implement the
523 entire Streams API as it is today. (See [Compatibility][] for
524 more information.)
525
526 If you are using an older Node.js library that emits [`'data'`][] events and
527 has a [`stream.pause()`][stream-pause] method that is advisory only, then you
528 can use the `wrap()` method to create a [Readable][] stream that uses the old
529 stream as its data source.
530
531 You will very rarely ever need to call this function, but it exists
532 as a convenience for interacting with old Node.js programs and libraries.
533
534 For example:
535
536 ```js
537 const OldReader = require('./old-api-module.js').OldReader;
538 const Readable = require('stream').Readable;
539 const oreader = new OldReader;
540 const myReader = new Readable().wrap(oreader);
541
542 myReader.on('readable', () => {
543   myReader.read(); // etc.
544 });
545 ```
546
547 ### Class: stream.Transform
548
549 Transform streams are [Duplex][] streams where the output is in some way
550 computed from the input. They implement both the [Readable][] and
551 [Writable][] interfaces.
552
553 Examples of Transform streams include:
554
555 * [zlib streams][zlib]
556 * [crypto streams][crypto]
557
558 ### Class: stream.Writable
559
560 <!--type=class-->
561
562 The Writable stream interface is an abstraction for a *destination*
563 that you are writing data *to*.
564
565 Examples of writable streams include:
566
567 * [HTTP requests, on the client][]
568 * [HTTP responses, on the server][]
569 * [fs write streams][]
570 * [zlib streams][zlib]
571 * [crypto streams][crypto]
572 * [TCP sockets][]
573 * [child process stdin][]
574 * [`process.stdout`][], [`process.stderr`][]
575
576 #### Event: 'drain'
577
578 If a [`stream.write(chunk)`][stream-write] call returns `false`, then the
579 `'drain'` event will indicate when it is appropriate to begin writing more data
580 to the stream.
581
582 ```js
583 // Write the data to the supplied writable stream one million times.
584 // Be attentive to back-pressure.
585 function writeOneMillionTimes(writer, data, encoding, callback) {
586   var i = 1000000;
587   write();
588   function write() {
589     var ok = true;
590     do {
591       i -= 1;
592       if (i === 0) {
593         // last time!
594         writer.write(data, encoding, callback);
595       } else {
596         // see if we should continue, or wait
597         // don't pass the callback, because we're not done yet.
598         ok = writer.write(data, encoding);
599       }
600     } while (i > 0 && ok);
601     if (i > 0) {
602       // had to stop early!
603       // write some more once it drains
604       writer.once('drain', write);
605     }
606   }
607 }
608 ```
609
610 #### Event: 'error'
611
612 * {Error}
613
614 Emitted if there was an error when writing or piping data.
615
616 #### Event: 'finish'
617
618 When the [`stream.end()`][stream-end] method has been called, and all data has
619 been flushed to the underlying system, this event is emitted.
620
621 ```javascript
622 var writer = getWritableStreamSomehow();
623 for (var i = 0; i < 100; i ++) {
624   writer.write('hello, #${i}!\n');
625 }
626 writer.end('this is the end\n');
627 writer.on('finish', () => {
628   console.error('all writes are now complete.');
629 });
630 ```
631
632 #### Event: 'pipe'
633
634 * `src` {stream.Readable} source stream that is piping to this writable
635
636 This is emitted whenever the [`stream.pipe()`][] method is called on a readable
637 stream, adding this writable to its set of destinations.
638
639 ```js
640 var writer = getWritableStreamSomehow();
641 var reader = getReadableStreamSomehow();
642 writer.on('pipe', (src) => {
643   console.error('something is piping into the writer');
644   assert.equal(src, reader);
645 });
646 reader.pipe(writer);
647 ```
648
649 #### Event: 'unpipe'
650
651 * `src` {[Readable][] Stream} The source stream that
652   [unpiped][`stream.unpipe()`] this writable
653
654 This is emitted whenever the [`stream.unpipe()`][] method is called on a
655 readable stream, removing this writable from its set of destinations.
656
657 ```js
658 var writer = getWritableStreamSomehow();
659 var reader = getReadableStreamSomehow();
660 writer.on('unpipe', (src) => {
661   console.error('something has stopped piping into the writer');
662   assert.equal(src, reader);
663 });
664 reader.pipe(writer);
665 reader.unpipe(writer);
666 ```
667
668 #### writable.cork()
669
670 Forces buffering of all writes.
671
672 Buffered data will be flushed either at [`stream.uncork()`][] or at
673 [`stream.end()`][stream-end] call.
674
675 #### writable.end([chunk][, encoding][, callback])
676
677 * `chunk` {String|Buffer} Optional data to write
678 * `encoding` {String} The encoding, if `chunk` is a String
679 * `callback` {Function} Optional callback for when the stream is finished
680
681 Call this method when no more data will be written to the stream. If supplied,
682 the callback is attached as a listener on the [`'finish'`][] event.
683
684 Calling [`stream.write()`][stream-write] after calling
685 [`stream.end()`][stream-end] will raise an error.
686
687 ```js
688 // write 'hello, ' and then end with 'world!'
689 var file = fs.createWriteStream('example.txt');
690 file.write('hello, ');
691 file.end('world!');
692 // writing more now is not allowed!
693 ```
694
695 #### writable.setDefaultEncoding(encoding)
696
697 * `encoding` {String} The new default encoding
698
699 Sets the default encoding for a writable stream.
700
701 #### writable.uncork()
702
703 Flush all data, buffered since [`stream.cork()`][] call.
704
705 #### writable.write(chunk[, encoding][, callback])
706
707 * `chunk` {String|Buffer} The data to write
708 * `encoding` {String} The encoding, if `chunk` is a String
709 * `callback` {Function} Callback for when this chunk of data is flushed
710 * Returns: {Boolean} `true` if the data was handled completely.
711
712 This method writes some data to the underlying system, and calls the
713 supplied callback once the data has been fully handled.
714
715 The return value indicates if you should continue writing right now.
716 If the data had to be buffered internally, then it will return
717 `false`. Otherwise, it will return `true`.
718
719 This return value is strictly advisory. You MAY continue to write,
720 even if it returns `false`. However, writes will be buffered in
721 memory, so it is best not to do this excessively. Instead, wait for
722 the [`'drain'`][] event before writing more data.
723
724
725 ## API for Stream Implementors
726
727 <!--type=misc-->
728
729 To implement any sort of stream, the pattern is the same:
730
731 1. Extend the appropriate parent class in your own subclass. (The
732    [`util.inherits()`][] method is particularly helpful for this.)
733 2. Call the appropriate parent class constructor in your constructor,
734    to be sure that the internal mechanisms are set up properly.
735 3. Implement one or more specific methods, as detailed below.
736
737 The class to extend and the method(s) to implement depend on the sort
738 of stream class you are writing:
739
740 <table>
741   <thead>
742     <tr>
743       <th>
744         <p>Use-case</p>
745       </th>
746       <th>
747         <p>Class</p>
748       </th>
749       <th>
750         <p>Method(s) to implement</p>
751       </th>
752     </tr>
753   </thead>
754   <tr>
755     <td>
756       <p>Reading only</p>
757     </td>
758     <td>
759       <p>[Readable](#stream_class_stream_readable_1)</p>
760     </td>
761     <td>
762       <p><code>[_read][stream-_read]</code></p>
763     </td>
764   </tr>
765   <tr>
766     <td>
767       <p>Writing only</p>
768     </td>
769     <td>
770       <p>[Writable](#stream_class_stream_writable_1)</p>
771     </td>
772     <td>
773       <p><code>[_write][stream-_write]</code>, <code>[_writev][stream-_writev]</code></p>
774     </td>
775   </tr>
776   <tr>
777     <td>
778       <p>Reading and writing</p>
779     </td>
780     <td>
781       <p>[Duplex](#stream_class_stream_duplex_1)</p>
782     </td>
783     <td>
784       <p><code>[_read][stream-_read]</code>, <code>[_write][stream-_write]</code>, <code>[_writev][stream-_writev]</code></p>
785     </td>
786   </tr>
787   <tr>
788     <td>
789       <p>Operate on written data, then read the result</p>
790     </td>
791     <td>
792       <p>[Transform](#stream_class_stream_transform_1)</p>
793     </td>
794     <td>
795       <p><code>[_transform][stream-_transform]</code>, <code>[_flush][stream-_flush]</code></p>
796     </td>
797   </tr>
798 </table>
799
800 In your implementation code, it is very important to never call the methods
801 described in [API for Stream Consumers][]. Otherwise, you can potentially cause
802 adverse side effects in programs that consume your streaming interfaces.
803
804 ### Class: stream.Duplex
805
806 <!--type=class-->
807
808 A "duplex" stream is one that is both Readable and Writable, such as a TCP
809 socket connection.
810
811 Note that `stream.Duplex` is an abstract class designed to be extended
812 with an underlying implementation of the [`stream._read(size)`][stream-_read]
813 and [`stream._write(chunk, encoding, callback)`][stream-_write] methods as you
814 would with a Readable or Writable stream class.
815
816 Since JavaScript doesn't have multiple prototypal inheritance, this class
817 prototypally inherits from Readable, and then parasitically from Writable. It is
818 thus up to the user to implement both the low-level
819 [`stream._read(n)`][stream-_read] method as well as the low-level
820 [`stream._write(chunk, encoding, callback)`][stream-_write] method on extension
821 duplex classes.
822
823 #### new stream.Duplex(options)
824
825 * `options` {Object} Passed to both Writable and Readable
826   constructors. Also has the following fields:
827   * `allowHalfOpen` {Boolean} Default = `true`. If set to `false`, then
828     the stream will automatically end the readable side when the
829     writable side ends and vice versa.
830   * `readableObjectMode` {Boolean} Default = `false`. Sets `objectMode`
831     for readable side of the stream. Has no effect if `objectMode`
832     is `true`.
833   * `writableObjectMode` {Boolean} Default = `false`. Sets `objectMode`
834     for writable side of the stream. Has no effect if `objectMode`
835     is `true`.
836
837 In classes that extend the Duplex class, make sure to call the
838 constructor so that the buffering settings can be properly
839 initialized.
840
841 ### Class: stream.PassThrough
842
843 This is a trivial implementation of a [Transform][] stream that simply
844 passes the input bytes across to the output. Its purpose is mainly
845 for examples and testing, but there are occasionally use cases where
846 it can come in handy as a building block for novel sorts of streams.
847
848 ### Class: stream.Readable
849
850 <!--type=class-->
851
852 `stream.Readable` is an abstract class designed to be extended with an
853 underlying implementation of the [`stream._read(size)`][stream-_read] method.
854
855 Please see [API for Stream Consumers][] for how to consume
856 streams in your programs. What follows is an explanation of how to
857 implement Readable streams in your programs.
858
859 #### new stream.Readable([options])
860
861 * `options` {Object}
862   * `highWaterMark` {Number} The maximum number of bytes to store in
863     the internal buffer before ceasing to read from the underlying
864     resource. Default = `16384` (16kb), or `16` for `objectMode` streams
865   * `encoding` {String} If specified, then buffers will be decoded to
866     strings using the specified encoding. Default = `null`
867   * `objectMode` {Boolean} Whether this stream should behave
868     as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns
869     a single value instead of a Buffer of size n. Default = `false`
870   * `read` {Function} Implementation for the [`stream._read()`][stream-_read]
871     method.
872
873 In classes that extend the Readable class, make sure to call the
874 Readable constructor so that the buffering settings can be properly
875 initialized.
876
877 #### readable.\_read(size)
878
879 * `size` {Number} Number of bytes to read asynchronously
880
881 Note: **Implement this method, but do NOT call it directly.**
882
883 This method is prefixed with an underscore because it is internal to the
884 class that defines it and should only be called by the internal Readable
885 class methods. All Readable stream implementations must provide a \_read
886 method to fetch data from the underlying resource.
887
888 When `_read()` is called, if data is available from the resource, the `_read()`
889 implementation should start pushing that data into the read queue by calling
890 [`this.push(dataChunk)`][stream-push]. `_read()` should continue reading from
891 the resource and pushing data until push returns `false`, at which point it
892 should stop reading from the resource. Only when `_read()` is called again after
893 it has stopped should it start reading more data from the resource and pushing
894 that data onto the queue.
895
896 Note: once the `_read()` method is called, it will not be called again until
897 the [`stream.push()`][stream-push] method is called.
898
899 The `size` argument is advisory. Implementations where a "read" is a
900 single call that returns data can use this to know how much data to
901 fetch. Implementations where that is not relevant, such as TCP or
902 TLS, may ignore this argument, and simply provide data whenever it
903 becomes available. There is no need, for example to "wait" until
904 `size` bytes are available before calling [`stream.push(chunk)`][stream-push].
905
906 #### readable.push(chunk[, encoding])
907
908
909 * `chunk` {Buffer|Null|String} Chunk of data to push into the read queue
910 * `encoding` {String} Encoding of String chunks.  Must be a valid
911   Buffer encoding, such as `'utf8'` or `'ascii'`
912 * return {Boolean} Whether or not more pushes should be performed
913
914 Note: **This method should be called by Readable implementors, NOT
915 by consumers of Readable streams.**
916
917 If a value other than null is passed, The `push()` method adds a chunk of data
918 into the queue for subsequent stream processors to consume. If `null` is
919 passed, it signals the end of the stream (EOF), after which no more data
920 can be written.
921
922 The data added with `push()` can be pulled out by calling the
923 [`stream.read()`][stream-read] method when the [`'readable'`][] event fires.
924
925 This API is designed to be as flexible as possible. For example,
926 you may be wrapping a lower-level source which has some sort of
927 pause/resume mechanism, and a data callback. In those cases, you
928 could wrap the low-level source object by doing something like this:
929
930 ```js
931 // source is an object with readStop() and readStart() methods,
932 // and an `ondata` member that gets called when it has data, and
933 // an `onend` member that gets called when the data is over.
934
935 util.inherits(SourceWrapper, Readable);
936
937 function SourceWrapper(options) {
938   Readable.call(this, options);
939
940   this._source = getLowlevelSourceObject();
941
942   // Every time there's data, we push it into the internal buffer.
943   this._source.ondata = (chunk) => {
944     // if push() returns false, then we need to stop reading from source
945     if (!this.push(chunk))
946       this._source.readStop();
947   };
948
949   // When the source ends, we push the EOF-signaling `null` chunk
950   this._source.onend = () => {
951     this.push(null);
952   };
953 }
954
955 // _read will be called when the stream wants to pull more data in
956 // the advisory size argument is ignored in this case.
957 SourceWrapper.prototype._read = function(size) {
958   this._source.readStart();
959 };
960 ```
961
962 #### Example: A Counting Stream
963
964 <!--type=example-->
965
966 This is a basic example of a Readable stream. It emits the numerals
967 from 1 to 1,000,000 in ascending order, and then ends.
968
969 ```js
970 const Readable = require('stream').Readable;
971 const util = require('util');
972 util.inherits(Counter, Readable);
973
974 function Counter(opt) {
975   Readable.call(this, opt);
976   this._max = 1000000;
977   this._index = 1;
978 }
979
980 Counter.prototype._read = function() {
981   var i = this._index++;
982   if (i > this._max)
983     this.push(null);
984   else {
985     var str = '' + i;
986     var buf = new Buffer(str, 'ascii');
987     this.push(buf);
988   }
989 };
990 ```
991
992 #### Example: SimpleProtocol v1 (Sub-optimal)
993
994 This is similar to the `parseHeader` function described
995 [here](#stream_readable_unshift_chunk), but implemented as a custom stream.
996 Also, note that this implementation does not convert the incoming data to a
997 string.
998
999 However, this would be better implemented as a [Transform][] stream. See
1000 [SimpleProtocol v2][] for a better implementation.
1001
1002 ```js
1003 // A parser for a simple data protocol.
1004 // The "header" is a JSON object, followed by 2 \n characters, and
1005 // then a message body.
1006 //
1007 // NOTE: This can be done more simply as a Transform stream!
1008 // Using Readable directly for this is sub-optimal. See the
1009 // alternative example below under the Transform section.
1010
1011 const Readable = require('stream').Readable;
1012 const util = require('util');
1013
1014 util.inherits(SimpleProtocol, Readable);
1015
1016 function SimpleProtocol(source, options) {
1017   if (!(this instanceof SimpleProtocol))
1018     return new SimpleProtocol(source, options);
1019
1020   Readable.call(this, options);
1021   this._inBody = false;
1022   this._sawFirstCr = false;
1023
1024   // source is a readable stream, such as a socket or file
1025   this._source = source;
1026
1027   var self = this;
1028   source.on('end', () => {
1029     self.push(null);
1030   });
1031
1032   // give it a kick whenever the source is readable
1033   // read(0) will not consume any bytes
1034   source.on('readable', () => {
1035     self.read(0);
1036   });
1037
1038   this._rawHeader = [];
1039   this.header = null;
1040 }
1041
1042 SimpleProtocol.prototype._read = function(n) {
1043   if (!this._inBody) {
1044     var chunk = this._source.read();
1045
1046     // if the source doesn't have data, we don't have data yet.
1047     if (chunk === null)
1048       return this.push('');
1049
1050     // check if the chunk has a \n\n
1051     var split = -1;
1052     for (var i = 0; i < chunk.length; i++) {
1053       if (chunk[i] === 10) { // '\n'
1054         if (this._sawFirstCr) {
1055           split = i;
1056           break;
1057         } else {
1058           this._sawFirstCr = true;
1059         }
1060       } else {
1061         this._sawFirstCr = false;
1062       }
1063     }
1064
1065     if (split === -1) {
1066       // still waiting for the \n\n
1067       // stash the chunk, and try again.
1068       this._rawHeader.push(chunk);
1069       this.push('');
1070     } else {
1071       this._inBody = true;
1072       var h = chunk.slice(0, split);
1073       this._rawHeader.push(h);
1074       var header = Buffer.concat(this._rawHeader).toString();
1075       try {
1076         this.header = JSON.parse(header);
1077       } catch (er) {
1078         this.emit('error', new Error('invalid simple protocol data'));
1079         return;
1080       }
1081       // now, because we got some extra data, unshift the rest
1082       // back into the read queue so that our consumer will see it.
1083       var b = chunk.slice(split);
1084       this.unshift(b);
1085       // calling unshift by itself does not reset the reading state
1086       // of the stream; since we're inside _read, doing an additional
1087       // push('') will reset the state appropriately.
1088       this.push('');
1089
1090       // and let them know that we are done parsing the header.
1091       this.emit('header', this.header);
1092     }
1093   } else {
1094     // from there on, just provide the data to our consumer.
1095     // careful not to push(null), since that would indicate EOF.
1096     var chunk = this._source.read();
1097     if (chunk) this.push(chunk);
1098   }
1099 };
1100
1101 // Usage:
1102 // var parser = new SimpleProtocol(source);
1103 // Now parser is a readable stream that will emit 'header'
1104 // with the parsed header data.
1105 ```
1106
1107 ### Class: stream.Transform
1108
1109 A "transform" stream is a duplex stream where the output is causally
1110 connected in some way to the input, such as a [zlib][] stream or a
1111 [crypto][] stream.
1112
1113 There is no requirement that the output be the same size as the input,
1114 the same number of chunks, or arrive at the same time. For example, a
1115 Hash stream will only ever have a single chunk of output which is
1116 provided when the input is ended. A zlib stream will produce output
1117 that is either much smaller or much larger than its input.
1118
1119 Rather than implement the [`stream._read()`][stream-_read] and
1120 [`stream._write()`][stream-_write] methods, Transform classes must implement the
1121 [`stream._transform()`][stream-_transform] method, and may optionally
1122 also implement the [`stream._flush()`][stream-_flush] method. (See below.)
1123
1124 #### new stream.Transform([options])
1125
1126 * `options` {Object} Passed to both Writable and Readable
1127   constructors. Also has the following fields:
1128   * `transform` {Function} Implementation for the
1129     [`stream._transform()`][stream-_transform] method.
1130   * `flush` {Function} Implementation for the [`stream._flush()`][stream-_flush]
1131     method.
1132
1133 In classes that extend the Transform class, make sure to call the
1134 constructor so that the buffering settings can be properly
1135 initialized.
1136
1137 #### Events: 'finish' and 'end'
1138
1139 The [`'finish'`][] and [`'end'`][] events are from the parent Writable
1140 and Readable classes respectively. The `'finish'` event is fired after
1141 [`stream.end()`][stream-end] is called and all chunks have been processed by
1142 [`stream._transform()`][stream-_transform], `'end'` is fired after all data has
1143 been output which is after the callback in [`stream._flush()`][stream-_flush]
1144 has been called.
1145
1146 #### transform.\_flush(callback)
1147
1148 * `callback` {Function} Call this function (optionally with an error
1149   argument) when you are done flushing any remaining data.
1150
1151 Note: **This function MUST NOT be called directly.**  It MAY be implemented
1152 by child classes, and if so, will be called by the internal Transform
1153 class methods only.
1154
1155 In some cases, your transform operation may need to emit a bit more
1156 data at the end of the stream. For example, a `Zlib` compression
1157 stream will store up some internal state so that it can optimally
1158 compress the output. At the end, however, it needs to do the best it
1159 can with what is left, so that the data will be complete.
1160
1161 In those cases, you can implement a `_flush()` method, which will be
1162 called at the very end, after all the written data is consumed, but
1163 before emitting [`'end'`][] to signal the end of the readable side. Just
1164 like with [`stream._transform()`][stream-_transform], call
1165 `transform.push(chunk)` zero or more times, as appropriate, and call `callback`
1166 when the flush operation is complete.
1167
1168 This method is prefixed with an underscore because it is internal to
1169 the class that defines it, and should not be called directly by user
1170 programs. However, you **are** expected to override this method in
1171 your own extension classes.
1172
1173 #### transform.\_transform(chunk, encoding, callback)
1174
1175 * `chunk` {Buffer|String} The chunk to be transformed. Will **always**
1176   be a buffer unless the `decodeStrings` option was set to `false`.
1177 * `encoding` {String} If the chunk is a string, then this is the
1178   encoding type. If chunk is a buffer, then this is the special
1179   value - 'buffer', ignore it in this case.
1180 * `callback` {Function} Call this function (optionally with an error
1181   argument and data) when you are done processing the supplied chunk.
1182
1183 Note: **This function MUST NOT be called directly.**  It should be
1184 implemented by child classes, and called by the internal Transform
1185 class methods only.
1186
1187 All Transform stream implementations must provide a `_transform()`
1188 method to accept input and produce output.
1189
1190 `_transform()` should do whatever has to be done in this specific
1191 Transform class, to handle the bytes being written, and pass them off
1192 to the readable portion of the interface. Do asynchronous I/O,
1193 process things, and so on.
1194
1195 Call `transform.push(outputChunk)` 0 or more times to generate output
1196 from this input chunk, depending on how much data you want to output
1197 as a result of this chunk.
1198
1199 Call the callback function only when the current chunk is completely
1200 consumed. Note that there may or may not be output as a result of any
1201 particular input chunk. If you supply a second argument to the callback
1202 it will be passed to the push method. In other words the following are
1203 equivalent:
1204
1205 ```js
1206 transform.prototype._transform = function (data, encoding, callback) {
1207   this.push(data);
1208   callback();
1209 };
1210
1211 transform.prototype._transform = function (data, encoding, callback) {
1212   callback(null, data);
1213 };
1214 ```
1215
1216 This method is prefixed with an underscore because it is internal to
1217 the class that defines it, and should not be called directly by user
1218 programs. However, you **are** expected to override this method in
1219 your own extension classes.
1220
1221 #### Example: `SimpleProtocol` parser v2
1222
1223 The example [here](#stream_example_simpleprotocol_v1_sub_optimal) of a simple
1224 protocol parser can be implemented simply by using the higher level
1225 [Transform][] stream class, similar to the `parseHeader` and `SimpleProtocol
1226 v1` examples.
1227
1228 In this example, rather than providing the input as an argument, it
1229 would be piped into the parser, which is a more idiomatic Node.js stream
1230 approach.
1231
1232 ```javascript
1233 const util = require('util');
1234 const Transform = require('stream').Transform;
1235 util.inherits(SimpleProtocol, Transform);
1236
1237 function SimpleProtocol(options) {
1238   if (!(this instanceof SimpleProtocol))
1239     return new SimpleProtocol(options);
1240
1241   Transform.call(this, options);
1242   this._inBody = false;
1243   this._sawFirstCr = false;
1244   this._rawHeader = [];
1245   this.header = null;
1246 }
1247
1248 SimpleProtocol.prototype._transform = function(chunk, encoding, done) {
1249   if (!this._inBody) {
1250     // check if the chunk has a \n\n
1251     var split = -1;
1252     for (var i = 0; i < chunk.length; i++) {
1253       if (chunk[i] === 10) { // '\n'
1254         if (this._sawFirstCr) {
1255           split = i;
1256           break;
1257         } else {
1258           this._sawFirstCr = true;
1259         }
1260       } else {
1261         this._sawFirstCr = false;
1262       }
1263     }
1264
1265     if (split === -1) {
1266       // still waiting for the \n\n
1267       // stash the chunk, and try again.
1268       this._rawHeader.push(chunk);
1269     } else {
1270       this._inBody = true;
1271       var h = chunk.slice(0, split);
1272       this._rawHeader.push(h);
1273       var header = Buffer.concat(this._rawHeader).toString();
1274       try {
1275         this.header = JSON.parse(header);
1276       } catch (er) {
1277         this.emit('error', new Error('invalid simple protocol data'));
1278         return;
1279       }
1280       // and let them know that we are done parsing the header.
1281       this.emit('header', this.header);
1282
1283       // now, because we got some extra data, emit this first.
1284       this.push(chunk.slice(split));
1285     }
1286   } else {
1287     // from there on, just provide the data to our consumer as-is.
1288     this.push(chunk);
1289   }
1290   done();
1291 };
1292
1293 // Usage:
1294 // var parser = new SimpleProtocol();
1295 // source.pipe(parser)
1296 // Now parser is a readable stream that will emit 'header'
1297 // with the parsed header data.
1298 ```
1299
1300 ### Class: stream.Writable
1301
1302 <!--type=class-->
1303
1304 `stream.Writable` is an abstract class designed to be extended with an
1305 underlying implementation of the
1306 [`stream._write(chunk, encoding, callback)`][stream-_write] method.
1307
1308 Please see [API for Stream Consumers][] for how to consume
1309 writable streams in your programs. What follows is an explanation of
1310 how to implement Writable streams in your programs.
1311
1312 #### new stream.Writable([options])
1313
1314 * `options` {Object}
1315   * `highWaterMark` {Number} Buffer level when
1316     [`stream.write()`][stream-write] starts returning `false`. Default = `16384`
1317     (16kb), or `16` for `objectMode` streams.
1318   * `decodeStrings` {Boolean} Whether or not to decode strings into
1319     Buffers before passing them to [`stream._write()`][stream-_write].
1320     Default = `true`
1321   * `objectMode` {Boolean} Whether or not the
1322     [`stream.write(anyObj)`][stream-write] is a valid operation. If set you can
1323     write arbitrary data instead of only `Buffer` / `String` data.
1324     Default = `false`
1325   * `write` {Function} Implementation for the
1326     [`stream._write()`][stream-_write] method.
1327   * `writev` {Function} Implementation for the
1328     [`stream._writev()`][stream-_writev] method.
1329
1330 In classes that extend the Writable class, make sure to call the
1331 constructor so that the buffering settings can be properly
1332 initialized.
1333
1334 #### writable.\_write(chunk, encoding, callback)
1335
1336 * `chunk` {Buffer|String} The chunk to be written. Will **always**
1337   be a buffer unless the `decodeStrings` option was set to `false`.
1338 * `encoding` {String} If the chunk is a string, then this is the
1339   encoding type. If chunk is a buffer, then this is the special
1340   value - 'buffer', ignore it in this case.
1341 * `callback` {Function} Call this function (optionally with an error
1342   argument) when you are done processing the supplied chunk.
1343
1344 All Writable stream implementations must provide a
1345 [`stream._write()`][stream-_write] method to send data to the underlying
1346 resource.
1347
1348 Note: **This function MUST NOT be called directly.**  It should be
1349 implemented by child classes, and called by the internal Writable
1350 class methods only.
1351
1352 Call the callback using the standard `callback(error)` pattern to
1353 signal that the write completed successfully or with an error.
1354
1355 If the `decodeStrings` flag is set in the constructor options, then
1356 `chunk` may be a string rather than a Buffer, and `encoding` will
1357 indicate the sort of string that it is. This is to support
1358 implementations that have an optimized handling for certain string
1359 data encodings. If you do not explicitly set the `decodeStrings`
1360 option to `false`, then you can safely ignore the `encoding` argument,
1361 and assume that `chunk` will always be a Buffer.
1362
1363 This method is prefixed with an underscore because it is internal to
1364 the class that defines it, and should not be called directly by user
1365 programs. However, you **are** expected to override this method in
1366 your own extension classes.
1367
1368 #### writable.\_writev(chunks, callback)
1369
1370 * `chunks` {Array} The chunks to be written. Each chunk has following
1371   format: `{ chunk: ..., encoding: ... }`.
1372 * `callback` {Function} Call this function (optionally with an error
1373   argument) when you are done processing the supplied chunks.
1374
1375 Note: **This function MUST NOT be called directly.**  It may be
1376 implemented by child classes, and called by the internal Writable
1377 class methods only.
1378
1379 This function is completely optional to implement. In most cases it is
1380 unnecessary. If implemented, it will be called with all the chunks
1381 that are buffered in the write queue.
1382
1383
1384 ## Simplified Constructor API
1385
1386 <!--type=misc-->
1387
1388 In simple cases there is now the added benefit of being able to construct a
1389 stream without inheritance.
1390
1391 This can be done by passing the appropriate methods as constructor options:
1392
1393 Examples:
1394
1395 ### Duplex
1396
1397 ```js
1398 var duplex = new stream.Duplex({
1399   read: function(n) {
1400     // sets this._read under the hood
1401
1402     // push data onto the read queue, passing null
1403     // will signal the end of the stream (EOF)
1404     this.push(chunk);
1405   },
1406   write: function(chunk, encoding, next) {
1407     // sets this._write under the hood
1408
1409     // An optional error can be passed as the first argument
1410     next()
1411   }
1412 });
1413
1414 // or
1415
1416 var duplex = new stream.Duplex({
1417   read: function(n) {
1418     // sets this._read under the hood
1419
1420     // push data onto the read queue, passing null
1421     // will signal the end of the stream (EOF)
1422     this.push(chunk);
1423   },
1424   writev: function(chunks, next) {
1425     // sets this._writev under the hood
1426
1427     // An optional error can be passed as the first argument
1428     next()
1429   }
1430 });
1431 ```
1432
1433 ### Readable
1434
1435 ```js
1436 var readable = new stream.Readable({
1437   read: function(n) {
1438     // sets this._read under the hood
1439
1440     // push data onto the read queue, passing null
1441     // will signal the end of the stream (EOF)
1442     this.push(chunk);
1443   }
1444 });
1445 ```
1446
1447 ### Transform
1448
1449 ```js
1450 var transform = new stream.Transform({
1451   transform: function(chunk, encoding, next) {
1452     // sets this._transform under the hood
1453
1454     // generate output as many times as needed
1455     // this.push(chunk);
1456
1457     // call when the current chunk is consumed
1458     next();
1459   },
1460   flush: function(done) {
1461     // sets this._flush under the hood
1462
1463     // generate output as many times as needed
1464     // this.push(chunk);
1465
1466     done();
1467   }
1468 });
1469 ```
1470
1471 ### Writable
1472
1473 ```js
1474 var writable = new stream.Writable({
1475   write: function(chunk, encoding, next) {
1476     // sets this._write under the hood
1477
1478     // An optional error can be passed as the first argument
1479     next()
1480   }
1481 });
1482
1483 // or
1484
1485 var writable = new stream.Writable({
1486   writev: function(chunks, next) {
1487     // sets this._writev under the hood
1488
1489     // An optional error can be passed as the first argument
1490     next()
1491   }
1492 });
1493 ```
1494
1495 ## Streams: Under the Hood
1496
1497 <!--type=misc-->
1498
1499 ### Buffering
1500
1501 <!--type=misc-->
1502
1503 Both Writable and Readable streams will buffer data on an internal
1504 object which can be retrieved from `_writableState.getBuffer()` or
1505 `_readableState.buffer`, respectively.
1506
1507 The amount of data that will potentially be buffered depends on the
1508 `highWaterMark` option which is passed into the constructor.
1509
1510 Buffering in Readable streams happens when the implementation calls
1511 [`stream.push(chunk)`][stream-push]. If the consumer of the Stream does not
1512 call [`stream.read()`][stream-read], then the data will sit in the internal
1513 queue until it is consumed.
1514
1515 Buffering in Writable streams happens when the user calls
1516 [`stream.write(chunk)`][stream-write] repeatedly, even when it returns `false`.
1517
1518 The purpose of streams, especially with the [`stream.pipe()`][] method, is to
1519 limit the buffering of data to acceptable levels, so that sources and
1520 destinations of varying speed will not overwhelm the available memory.
1521
1522 ### Compatibility with Older Node.js Versions
1523
1524 <!--type=misc-->
1525
1526 In versions of Node.js prior to v0.10, the Readable stream interface was
1527 simpler, but also less powerful and less useful.
1528
1529 * Rather than waiting for you to call the [`stream.read()`][stream-read] method,
1530   [`'data'`][] events would start emitting immediately. If you needed to do
1531   some I/O to decide how to handle data, then you had to store the chunks
1532   in some kind of buffer so that they would not be lost.
1533 * The [`stream.pause()`][stream-pause] method was advisory, rather than
1534   guaranteed. This meant that you still had to be prepared to receive
1535   [`'data'`][] events even when the stream was in a paused state.
1536
1537 In Node.js v0.10, the [Readable][] class was added.
1538 For backwards compatibility with older Node.js programs, Readable streams
1539 switch into "flowing mode" when a [`'data'`][] event handler is added, or
1540 when the [`stream.resume()`][stream-resume] method is called. The effect is
1541 that, even if you are not using the new [`stream.read()`][stream-read] method
1542 and [`'readable'`][] event, you no longer have to worry about losing
1543 [`'data'`][] chunks.
1544
1545 Most programs will continue to function normally. However, this
1546 introduces an edge case in the following conditions:
1547
1548 * No [`'data'`][] event handler is added.
1549 * The [`stream.resume()`][stream-resume] method is never called.
1550 * The stream is not piped to any writable destination.
1551
1552 For example, consider the following code:
1553
1554 ```js
1555 // WARNING!  BROKEN!
1556 net.createServer((socket) => {
1557
1558   // we add an 'end' method, but never consume the data
1559   socket.on('end', () => {
1560     // It will never get here.
1561     socket.end('I got your message (but didnt read it)\n');
1562   });
1563
1564 }).listen(1337);
1565 ```
1566
1567 In versions of Node.js prior to v0.10, the incoming message data would be
1568 simply discarded. However, in Node.js v0.10 and beyond,
1569 the socket will remain paused forever.
1570
1571 The workaround in this situation is to call the
1572 [`stream.resume()`][stream-resume] method to start the flow of data:
1573
1574 ```js
1575 // Workaround
1576 net.createServer((socket) => {
1577
1578   socket.on('end', () => {
1579     socket.end('I got your message (but didnt read it)\n');
1580   });
1581
1582   // start the flow of data, discarding it.
1583   socket.resume();
1584
1585 }).listen(1337);
1586 ```
1587
1588 In addition to new Readable streams switching into flowing mode,
1589 pre-v0.10 style streams can be wrapped in a Readable class using the
1590 [`stream.wrap()`][] method.
1591
1592
1593 ### Object Mode
1594
1595 <!--type=misc-->
1596
1597 Normally, Streams operate on Strings and Buffers exclusively.
1598
1599 Streams that are in **object mode** can emit generic JavaScript values
1600 other than Buffers and Strings.
1601
1602 A Readable stream in object mode will always return a single item from
1603 a call to [`stream.read(size)`][stream-read], regardless of what the size
1604 argument is.
1605
1606 A Writable stream in object mode will always ignore the `encoding`
1607 argument to [`stream.write(data, encoding)`][stream-write].
1608
1609 The special value `null` still retains its special value for object
1610 mode streams. That is, for object mode readable streams, `null` as a
1611 return value from [`stream.read()`][stream-read] indicates that there is no more
1612 data, and [`stream.push(null)`][stream-push] will signal the end of stream data
1613 (`EOF`).
1614
1615 No streams in Node.js core are object mode streams. This pattern is only
1616 used by userland streaming libraries.
1617
1618 You should set `objectMode` in your stream child class constructor on
1619 the options object. Setting `objectMode` mid-stream is not safe.
1620
1621 For Duplex streams `objectMode` can be set exclusively for readable or
1622 writable side with `readableObjectMode` and `writableObjectMode`
1623 respectively. These options can be used to implement parsers and
1624 serializers with Transform streams.
1625
1626 ```js
1627 const util = require('util');
1628 const StringDecoder = require('string_decoder').StringDecoder;
1629 const Transform = require('stream').Transform;
1630 util.inherits(JSONParseStream, Transform);
1631
1632 // Gets \n-delimited JSON string data, and emits the parsed objects
1633 function JSONParseStream() {
1634   if (!(this instanceof JSONParseStream))
1635     return new JSONParseStream();
1636
1637   Transform.call(this, { readableObjectMode : true });
1638
1639   this._buffer = '';
1640   this._decoder = new StringDecoder('utf8');
1641 }
1642
1643 JSONParseStream.prototype._transform = function(chunk, encoding, cb) {
1644   this._buffer += this._decoder.write(chunk);
1645   // split on newlines
1646   var lines = this._buffer.split(/\r?\n/);
1647   // keep the last partial line buffered
1648   this._buffer = lines.pop();
1649   for (var l = 0; l < lines.length; l++) {
1650     var line = lines[l];
1651     try {
1652       var obj = JSON.parse(line);
1653     } catch (er) {
1654       this.emit('error', er);
1655       return;
1656     }
1657     // push the parsed object out to the readable consumer
1658     this.push(obj);
1659   }
1660   cb();
1661 };
1662
1663 JSONParseStream.prototype._flush = function(cb) {
1664   // Just handle any leftover
1665   var rem = this._buffer.trim();
1666   if (rem) {
1667     try {
1668       var obj = JSON.parse(rem);
1669     } catch (er) {
1670       this.emit('error', er);
1671       return;
1672     }
1673     // push the parsed object out to the readable consumer
1674     this.push(obj);
1675   }
1676   cb();
1677 };
1678 ```
1679
1680 ### `stream.read(0)`
1681
1682 There are some cases where you want to trigger a refresh of the
1683 underlying readable stream mechanisms, without actually consuming any
1684 data. In that case, you can call `stream.read(0)`, which will always
1685 return null.
1686
1687 If the internal read buffer is below the `highWaterMark`, and the
1688 stream is not currently reading, then calling `stream.read(0)` will trigger
1689 a low-level [`stream._read()`][stream-_read] call.
1690
1691 There is almost never a need to do this. However, you will see some
1692 cases in Node.js's internals where this is done, particularly in the
1693 Readable stream class internals.
1694
1695 ### `stream.push('')`
1696
1697 Pushing a zero-byte string or Buffer (when not in [Object mode][]) has an
1698 interesting side effect. Because it *is* a call to
1699 [`stream.push()`][stream-push], it will end the `reading` process. However, it
1700 does *not* add any data to the readable buffer, so there's nothing for
1701 a user to consume.
1702
1703 Very rarely, there are cases where you have no data to provide now,
1704 but the consumer of your stream (or, perhaps, another bit of your own
1705 code) will know when to check again, by calling [`stream.read(0)`][stream-read].
1706 In those cases, you *may* call `stream.push('')`.
1707
1708 So far, the only use case for this functionality is in the
1709 [`tls.CryptoStream`][] class, which is deprecated in Node.js/io.js v1.0. If you
1710 find that you have to use `stream.push('')`, please consider another
1711 approach, because it almost certainly indicates that something is
1712 horribly wrong.
1713
1714 [`'data'`]: #stream_event_data
1715 [`'drain'`]: #stream_event_drain
1716 [`'end'`]: #stream_event_end
1717 [`'finish'`]: #stream_event_finish
1718 [`'readable'`]: #stream_event_readable
1719 [`buf.toString(encoding)`]: https://nodejs.org/docs/v5.8.0/api/buffer.html#buffer_buf_tostring_encoding_start_end
1720 [`EventEmitter`]: https://nodejs.org/docs/v5.8.0/api/events.html#events_class_eventemitter
1721 [`process.stderr`]: https://nodejs.org/docs/v5.8.0/api/process.html#process_process_stderr
1722 [`process.stdin`]: https://nodejs.org/docs/v5.8.0/api/process.html#process_process_stdin
1723 [`process.stdout`]: https://nodejs.org/docs/v5.8.0/api/process.html#process_process_stdout
1724 [`stream.cork()`]: #stream_writable_cork
1725 [`stream.pipe()`]: #stream_readable_pipe_destination_options
1726 [`stream.uncork()`]: #stream_writable_uncork
1727 [`stream.unpipe()`]: #stream_readable_unpipe_destination
1728 [`stream.wrap()`]: #stream_readable_wrap_stream
1729 [`tls.CryptoStream`]: https://nodejs.org/docs/v5.8.0/api/tls.html#tls_class_cryptostream
1730 [`util.inherits()`]: https://nodejs.org/docs/v5.8.0/api/util.html#util_util_inherits_constructor_superconstructor
1731 [API for Stream Consumers]: #stream_api_for_stream_consumers
1732 [API for Stream Implementors]: #stream_api_for_stream_implementors
1733 [child process stdin]: https://nodejs.org/docs/v5.8.0/api/child_process.html#child_process_child_stdin
1734 [child process stdout and stderr]: https://nodejs.org/docs/v5.8.0/api/child_process.html#child_process_child_stdout
1735 [Compatibility]: #stream_compatibility_with_older_node_js_versions
1736 [crypto]: crypto.html
1737 [Duplex]: #stream_class_stream_duplex
1738 [fs read streams]: https://nodejs.org/docs/v5.8.0/api/fs.html#fs_class_fs_readstream
1739 [fs write streams]: https://nodejs.org/docs/v5.8.0/api/fs.html#fs_class_fs_writestream
1740 [HTTP requests, on the client]: https://nodejs.org/docs/v5.8.0/api/http.html#http_class_http_clientrequest
1741 [HTTP responses, on the server]: https://nodejs.org/docs/v5.8.0/api/http.html#http_class_http_serverresponse
1742 [http-incoming-message]: https://nodejs.org/docs/v5.8.0/api/http.html#http_class_http_incomingmessage
1743 [Object mode]: #stream_object_mode
1744 [Readable]: #stream_class_stream_readable
1745 [SimpleProtocol v2]: #stream_example_simpleprotocol_parser_v2
1746 [stream-_flush]: #stream_transform_flush_callback
1747 [stream-_read]: #stream_readable_read_size_1
1748 [stream-_transform]: #stream_transform_transform_chunk_encoding_callback
1749 [stream-_write]: #stream_writable_write_chunk_encoding_callback_1
1750 [stream-_writev]: #stream_writable_writev_chunks_callback
1751 [stream-end]: #stream_writable_end_chunk_encoding_callback
1752 [stream-pause]: #stream_readable_pause
1753 [stream-push]: #stream_readable_push_chunk_encoding
1754 [stream-read]: #stream_readable_read_size
1755 [stream-resume]: #stream_readable_resume
1756 [stream-write]: #stream_writable_write_chunk_encoding_callback
1757 [TCP sockets]: https://nodejs.org/docs/v5.8.0/api/net.html#net_class_net_socket
1758 [Transform]: #stream_class_stream_transform
1759 [Writable]: #stream_class_stream_writable
1760 [zlib]: zlib.html