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`][].
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.
14 This document is split up into 3 sections:
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
27 ## API for Stream Consumers
31 Streams can be either [Readable][], [Writable][], or both ([Duplex][]).
33 All streams are EventEmitters, but they also have other custom methods
34 and properties depending on whether they are Readable, Writable, or
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
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][].
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:
51 const http = require('http');
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
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');
62 // Readable streams emit 'data' events once a listener is added
63 req.on('data', (chunk) => {
67 // the end event tells you that you have entire body
70 var data = JSON.parse(body);
74 return res.end(`error: ${er.message}`);
77 // write back something interesting to the user:
78 res.write(typeof data);
85 // $ curl localhost:1337 -d '{}'
87 // $ curl localhost:1337 -d '"foo"'
89 // $ curl localhost:1337 -d 'not json'
90 // error: Unexpected token o
93 ### Class: stream.Duplex
95 Duplex streams are streams that implement both the [Readable][] and
96 [Writable][] interfaces.
98 Examples of Duplex streams include:
101 * [zlib streams][zlib]
102 * [crypto streams][crypto]
104 ### Class: stream.Readable
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
112 A Readable stream will not start emitting data until you indicate that
113 you are ready to receive it.
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.
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.
125 You can switch to flowing mode by doing any of the following:
127 * Adding a [`'data'`][] event handler to listen for data.
128 * Calling the [`stream.resume()`][stream-resume] method to explicitly open the
130 * Calling the [`stream.pipe()`][] method to send the data to a [Writable][].
132 You can switch back to paused mode by doing either of the following:
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.
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.
146 Examples of readable streams include:
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]
154 * [child process stdout and stderr][]
155 * [`process.stdin`][]
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.
163 Not all streams will emit the `'close'` event.
167 * `chunk` {Buffer|String} The chunk of data.
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.
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.
177 var readable = getReadableStreamSomehow();
178 readable.on('data', (chunk) => {
179 console.log('got %d bytes of data', chunk.length);
185 This event fires when there will be no more data to read.
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
193 var readable = getReadableStreamSomehow();
194 readable.on('data', (chunk) => {
195 console.log('got %d bytes of data', chunk.length);
197 readable.on('end', () => {
198 console.log('there will be no more data.');
206 Emitted if there was an error receiving data.
208 #### Event: 'readable'
210 When a chunk of data can be read from the stream, it will emit a
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
218 var readable = getReadableStreamSomehow();
219 readable.on('readable', () => {
220 // there is some data to read now
224 Once the internal buffer is drained, a `'readable'` event will fire
225 again when more data is available.
227 The `'readable'` event is not emitted in the "flowing" mode with the
228 sole exception of the last one, on end-of-stream.
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:
237 const fs = require('fs');
238 var rr = fs.createReadStream('foo.txt');
239 rr.on('readable', () => {
240 console.log('readable:', rr.read());
247 The output of running this script is:
255 #### readable.isPaused()
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]).
264 var readable = new stream.Readable
266 readable.isPaused() // === false
268 readable.isPaused() // === true
270 readable.isPaused() // === false
273 #### readable.pause()
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.
282 var readable = getReadableStreamSomehow();
283 readable.on('data', (chunk) => {
284 console.log('got %d bytes of data', chunk.length);
286 console.log('there will be no more data for 1 second');
288 console.log('now data will start flowing again');
294 #### readable.pipe(destination[, options])
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`
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.
304 Multiple destinations can be piped to safely.
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);
313 This function returns the destination stream, so you can set up pipe
317 var r = fs.createReadStream('file.txt');
318 var z = zlib.createGzip();
319 var w = fs.createWriteStream('file.txt.gz');
323 For example, emulating the Unix `cat` command:
326 process.stdin.pipe(process.stdout);
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.
333 This keeps `writer` open so that "Goodbye" can be written at the
337 reader.pipe(writer, { end: false });
338 reader.on('end', () => {
339 writer.end('Goodbye\n');
343 Note that [`process.stderr`][] and [`process.stdout`][] are never closed until
344 the process exits, regardless of the specified options.
346 #### readable.read([size])
348 * `size` {Number} Optional argument to specify how much data to read.
349 * Return {String|Buffer|Null}
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
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
360 If you do not specify a `size` argument, then it will return all the
361 data in the internal buffer.
363 This method should only be called in paused mode. In flowing mode,
364 this method is called automatically until the internal buffer is
368 var readable = getReadableStreamSomehow();
369 readable.on('readable', () => {
371 while (null !== (chunk = readable.read())) {
372 console.log('got %d bytes of data', chunk.length);
377 If this method returns a data chunk, then it will also trigger the
378 emission of a [`'data'`][] event.
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.
383 #### readable.resume()
387 This method will cause the readable stream to resume emitting [`'data'`][]
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
396 var readable = getReadableStreamSomehow();
398 readable.on('end', () => {
399 console.log('got to the end, but did not read anything');
403 #### readable.setEncoding(encoding)
405 * `encoding` {String} The encoding to use.
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.
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.
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.
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);
432 #### readable.unpipe([destination])
434 * `destination` {stream.Writable} Optional specific stream to unpipe
436 This method will remove the hooks set up for a previous [`stream.pipe()`][]
439 If the destination is not specified, then all pipes are removed.
441 If the destination is specified, but no pipe is set up for it, then
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);
451 console.log('stop writing to file.txt');
452 readable.unpipe(writable);
453 console.log('manually close the file stream');
458 #### readable.unshift(chunk)
460 * `chunk` {Buffer|String} Chunk of data to unshift onto the read queue
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.
467 Note that `stream.unshift(chunk)` cannot be called after the [`'end'`][] event
468 has been triggered; a runtime error will be raised.
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][].)
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');
484 function onReadable() {
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');
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);
501 // still reading the header.
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
518 #### readable.wrap(stream)
520 * `stream` {Stream} An "old style" readable stream
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
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.
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.
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);
542 myReader.on('readable', () => {
543 myReader.read(); // etc.
547 ### Class: stream.Transform
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.
553 Examples of Transform streams include:
555 * [zlib streams][zlib]
556 * [crypto streams][crypto]
558 ### Class: stream.Writable
562 The Writable stream interface is an abstraction for a *destination*
563 that you are writing data *to*.
565 Examples of writable streams include:
567 * [HTTP requests, on the client][]
568 * [HTTP responses, on the server][]
569 * [fs write streams][]
570 * [zlib streams][zlib]
571 * [crypto streams][crypto]
573 * [child process stdin][]
574 * [`process.stdout`][], [`process.stderr`][]
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
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) {
594 writer.write(data, encoding, callback);
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);
600 } while (i > 0 && ok);
602 // had to stop early!
603 // write some more once it drains
604 writer.once('drain', write);
614 Emitted if there was an error when writing or piping data.
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.
622 var writer = getWritableStreamSomehow();
623 for (var i = 0; i < 100; i ++) {
624 writer.write('hello, #${i}!\n');
626 writer.end('this is the end\n');
627 writer.on('finish', () => {
628 console.error('all writes are now complete.');
634 * `src` {stream.Readable} source stream that is piping to this writable
636 This is emitted whenever the [`stream.pipe()`][] method is called on a readable
637 stream, adding this writable to its set of destinations.
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);
651 * `src` {[Readable][] Stream} The source stream that
652 [unpiped][`stream.unpipe()`] this writable
654 This is emitted whenever the [`stream.unpipe()`][] method is called on a
655 readable stream, removing this writable from its set of destinations.
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);
665 reader.unpipe(writer);
670 Forces buffering of all writes.
672 Buffered data will be flushed either at [`stream.uncork()`][] or at
673 [`stream.end()`][stream-end] call.
675 #### writable.end([chunk][, encoding][, callback])
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
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.
684 Calling [`stream.write()`][stream-write] after calling
685 [`stream.end()`][stream-end] will raise an error.
688 // write 'hello, ' and then end with 'world!'
689 var file = fs.createWriteStream('example.txt');
690 file.write('hello, ');
692 // writing more now is not allowed!
695 #### writable.setDefaultEncoding(encoding)
697 * `encoding` {String} The new default encoding
699 Sets the default encoding for a writable stream.
701 #### writable.uncork()
703 Flush all data, buffered since [`stream.cork()`][] call.
705 #### writable.write(chunk[, encoding][, callback])
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.
712 This method writes some data to the underlying system, and calls the
713 supplied callback once the data has been fully handled.
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`.
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.
725 ## API for Stream Implementors
729 To implement any sort of stream, the pattern is the same:
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.
737 The class to extend and the method(s) to implement depend on the sort
738 of stream class you are writing:
750 <p>Method(s) to implement</p>
759 <p>[Readable](#stream_class_stream_readable_1)</p>
762 <p><code>[_read][stream-_read]</code></p>
770 <p>[Writable](#stream_class_stream_writable_1)</p>
773 <p><code>[_write][stream-_write]</code>, <code>[_writev][stream-_writev]</code></p>
778 <p>Reading and writing</p>
781 <p>[Duplex](#stream_class_stream_duplex_1)</p>
784 <p><code>[_read][stream-_read]</code>, <code>[_write][stream-_write]</code>, <code>[_writev][stream-_writev]</code></p>
789 <p>Operate on written data, then read the result</p>
792 <p>[Transform](#stream_class_stream_transform_1)</p>
795 <p><code>[_transform][stream-_transform]</code>, <code>[_flush][stream-_flush]</code></p>
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.
804 ### Class: stream.Duplex
808 A "duplex" stream is one that is both Readable and Writable, such as a TCP
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.
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
823 #### new stream.Duplex(options)
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`
833 * `writableObjectMode` {Boolean} Default = `false`. Sets `objectMode`
834 for writable side of the stream. Has no effect if `objectMode`
837 In classes that extend the Duplex class, make sure to call the
838 constructor so that the buffering settings can be properly
841 ### Class: stream.PassThrough
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.
848 ### Class: stream.Readable
852 `stream.Readable` is an abstract class designed to be extended with an
853 underlying implementation of the [`stream._read(size)`][stream-_read] method.
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.
859 #### new stream.Readable([options])
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]
873 In classes that extend the Readable class, make sure to call the
874 Readable constructor so that the buffering settings can be properly
877 #### readable.\_read(size)
879 * `size` {Number} Number of bytes to read asynchronously
881 Note: **Implement this method, but do NOT call it directly.**
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.
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.
896 Note: once the `_read()` method is called, it will not be called again until
897 the [`stream.push()`][stream-push] method is called.
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].
906 #### readable.push(chunk[, encoding])
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
914 Note: **This method should be called by Readable implementors, NOT
915 by consumers of Readable streams.**
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
922 The data added with `push()` can be pulled out by calling the
923 [`stream.read()`][stream-read] method when the [`'readable'`][] event fires.
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:
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.
935 util.inherits(SourceWrapper, Readable);
937 function SourceWrapper(options) {
938 Readable.call(this, options);
940 this._source = getLowlevelSourceObject();
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();
949 // When the source ends, we push the EOF-signaling `null` chunk
950 this._source.onend = () => {
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();
962 #### Example: A Counting Stream
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.
970 const Readable = require('stream').Readable;
971 const util = require('util');
972 util.inherits(Counter, Readable);
974 function Counter(opt) {
975 Readable.call(this, opt);
980 Counter.prototype._read = function() {
981 var i = this._index++;
986 var buf = new Buffer(str, 'ascii');
992 #### Example: SimpleProtocol v1 (Sub-optimal)
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
999 However, this would be better implemented as a [Transform][] stream. See
1000 [SimpleProtocol v2][] for a better implementation.
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.
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.
1011 const Readable = require('stream').Readable;
1012 const util = require('util');
1014 util.inherits(SimpleProtocol, Readable);
1016 function SimpleProtocol(source, options) {
1017 if (!(this instanceof SimpleProtocol))
1018 return new SimpleProtocol(source, options);
1020 Readable.call(this, options);
1021 this._inBody = false;
1022 this._sawFirstCr = false;
1024 // source is a readable stream, such as a socket or file
1025 this._source = source;
1028 source.on('end', () => {
1032 // give it a kick whenever the source is readable
1033 // read(0) will not consume any bytes
1034 source.on('readable', () => {
1038 this._rawHeader = [];
1042 SimpleProtocol.prototype._read = function(n) {
1043 if (!this._inBody) {
1044 var chunk = this._source.read();
1046 // if the source doesn't have data, we don't have data yet.
1048 return this.push('');
1050 // check if the chunk has a \n\n
1052 for (var i = 0; i < chunk.length; i++) {
1053 if (chunk[i] === 10) { // '\n'
1054 if (this._sawFirstCr) {
1058 this._sawFirstCr = true;
1061 this._sawFirstCr = false;
1066 // still waiting for the \n\n
1067 // stash the chunk, and try again.
1068 this._rawHeader.push(chunk);
1071 this._inBody = true;
1072 var h = chunk.slice(0, split);
1073 this._rawHeader.push(h);
1074 var header = Buffer.concat(this._rawHeader).toString();
1076 this.header = JSON.parse(header);
1078 this.emit('error', new Error('invalid simple protocol data'));
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);
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.
1090 // and let them know that we are done parsing the header.
1091 this.emit('header', this.header);
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);
1102 // var parser = new SimpleProtocol(source);
1103 // Now parser is a readable stream that will emit 'header'
1104 // with the parsed header data.
1107 ### Class: stream.Transform
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
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.
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.)
1124 #### new stream.Transform([options])
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]
1133 In classes that extend the Transform class, make sure to call the
1134 constructor so that the buffering settings can be properly
1137 #### Events: 'finish' and 'end'
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]
1146 #### transform.\_flush(callback)
1148 * `callback` {Function} Call this function (optionally with an error
1149 argument) when you are done flushing any remaining data.
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
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.
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.
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.
1173 #### transform.\_transform(chunk, encoding, callback)
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.
1183 Note: **This function MUST NOT be called directly.** It should be
1184 implemented by child classes, and called by the internal Transform
1187 All Transform stream implementations must provide a `_transform()`
1188 method to accept input and produce output.
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.
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.
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
1206 transform.prototype._transform = function (data, encoding, callback) {
1211 transform.prototype._transform = function (data, encoding, callback) {
1212 callback(null, data);
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.
1221 #### Example: `SimpleProtocol` parser v2
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
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
1233 const util = require('util');
1234 const Transform = require('stream').Transform;
1235 util.inherits(SimpleProtocol, Transform);
1237 function SimpleProtocol(options) {
1238 if (!(this instanceof SimpleProtocol))
1239 return new SimpleProtocol(options);
1241 Transform.call(this, options);
1242 this._inBody = false;
1243 this._sawFirstCr = false;
1244 this._rawHeader = [];
1248 SimpleProtocol.prototype._transform = function(chunk, encoding, done) {
1249 if (!this._inBody) {
1250 // check if the chunk has a \n\n
1252 for (var i = 0; i < chunk.length; i++) {
1253 if (chunk[i] === 10) { // '\n'
1254 if (this._sawFirstCr) {
1258 this._sawFirstCr = true;
1261 this._sawFirstCr = false;
1266 // still waiting for the \n\n
1267 // stash the chunk, and try again.
1268 this._rawHeader.push(chunk);
1270 this._inBody = true;
1271 var h = chunk.slice(0, split);
1272 this._rawHeader.push(h);
1273 var header = Buffer.concat(this._rawHeader).toString();
1275 this.header = JSON.parse(header);
1277 this.emit('error', new Error('invalid simple protocol data'));
1280 // and let them know that we are done parsing the header.
1281 this.emit('header', this.header);
1283 // now, because we got some extra data, emit this first.
1284 this.push(chunk.slice(split));
1287 // from there on, just provide the data to our consumer as-is.
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.
1300 ### Class: stream.Writable
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.
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.
1312 #### new stream.Writable([options])
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].
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.
1325 * `write` {Function} Implementation for the
1326 [`stream._write()`][stream-_write] method.
1327 * `writev` {Function} Implementation for the
1328 [`stream._writev()`][stream-_writev] method.
1330 In classes that extend the Writable class, make sure to call the
1331 constructor so that the buffering settings can be properly
1334 #### writable.\_write(chunk, encoding, callback)
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.
1344 All Writable stream implementations must provide a
1345 [`stream._write()`][stream-_write] method to send data to the underlying
1348 Note: **This function MUST NOT be called directly.** It should be
1349 implemented by child classes, and called by the internal Writable
1352 Call the callback using the standard `callback(error)` pattern to
1353 signal that the write completed successfully or with an error.
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.
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.
1368 #### writable.\_writev(chunks, callback)
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.
1375 Note: **This function MUST NOT be called directly.** It may be
1376 implemented by child classes, and called by the internal Writable
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.
1384 ## Simplified Constructor API
1388 In simple cases there is now the added benefit of being able to construct a
1389 stream without inheritance.
1391 This can be done by passing the appropriate methods as constructor options:
1398 var duplex = new stream.Duplex({
1400 // sets this._read under the hood
1402 // push data onto the read queue, passing null
1403 // will signal the end of the stream (EOF)
1406 write: function(chunk, encoding, next) {
1407 // sets this._write under the hood
1409 // An optional error can be passed as the first argument
1416 var duplex = new stream.Duplex({
1418 // sets this._read under the hood
1420 // push data onto the read queue, passing null
1421 // will signal the end of the stream (EOF)
1424 writev: function(chunks, next) {
1425 // sets this._writev under the hood
1427 // An optional error can be passed as the first argument
1436 var readable = new stream.Readable({
1438 // sets this._read under the hood
1440 // push data onto the read queue, passing null
1441 // will signal the end of the stream (EOF)
1450 var transform = new stream.Transform({
1451 transform: function(chunk, encoding, next) {
1452 // sets this._transform under the hood
1454 // generate output as many times as needed
1455 // this.push(chunk);
1457 // call when the current chunk is consumed
1460 flush: function(done) {
1461 // sets this._flush under the hood
1463 // generate output as many times as needed
1464 // this.push(chunk);
1474 var writable = new stream.Writable({
1475 write: function(chunk, encoding, next) {
1476 // sets this._write under the hood
1478 // An optional error can be passed as the first argument
1485 var writable = new stream.Writable({
1486 writev: function(chunks, next) {
1487 // sets this._writev under the hood
1489 // An optional error can be passed as the first argument
1495 ## Streams: Under the Hood
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.
1507 The amount of data that will potentially be buffered depends on the
1508 `highWaterMark` option which is passed into the constructor.
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.
1515 Buffering in Writable streams happens when the user calls
1516 [`stream.write(chunk)`][stream-write] repeatedly, even when it returns `false`.
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.
1522 ### Compatibility with Older Node.js Versions
1526 In versions of Node.js prior to v0.10, the Readable stream interface was
1527 simpler, but also less powerful and less useful.
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.
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.
1545 Most programs will continue to function normally. However, this
1546 introduces an edge case in the following conditions:
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.
1552 For example, consider the following code:
1556 net.createServer((socket) => {
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');
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.
1571 The workaround in this situation is to call the
1572 [`stream.resume()`][stream-resume] method to start the flow of data:
1576 net.createServer((socket) => {
1578 socket.on('end', () => {
1579 socket.end('I got your message (but didnt read it)\n');
1582 // start the flow of data, discarding it.
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.
1597 Normally, Streams operate on Strings and Buffers exclusively.
1599 Streams that are in **object mode** can emit generic JavaScript values
1600 other than Buffers and Strings.
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
1606 A Writable stream in object mode will always ignore the `encoding`
1607 argument to [`stream.write(data, encoding)`][stream-write].
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
1615 No streams in Node.js core are object mode streams. This pattern is only
1616 used by userland streaming libraries.
1618 You should set `objectMode` in your stream child class constructor on
1619 the options object. Setting `objectMode` mid-stream is not safe.
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.
1627 const util = require('util');
1628 const StringDecoder = require('string_decoder').StringDecoder;
1629 const Transform = require('stream').Transform;
1630 util.inherits(JSONParseStream, Transform);
1632 // Gets \n-delimited JSON string data, and emits the parsed objects
1633 function JSONParseStream() {
1634 if (!(this instanceof JSONParseStream))
1635 return new JSONParseStream();
1637 Transform.call(this, { readableObjectMode : true });
1640 this._decoder = new StringDecoder('utf8');
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];
1652 var obj = JSON.parse(line);
1654 this.emit('error', er);
1657 // push the parsed object out to the readable consumer
1663 JSONParseStream.prototype._flush = function(cb) {
1664 // Just handle any leftover
1665 var rem = this._buffer.trim();
1668 var obj = JSON.parse(rem);
1670 this.emit('error', er);
1673 // push the parsed object out to the readable consumer
1680 ### `stream.read(0)`
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
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.
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.
1695 ### `stream.push('')`
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
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('')`.
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
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