3 module.exports = Readable;
6 var processNextTick = require('process-nextick-args');
10 var isArray = require('isarray');
13 Readable.ReadableState = ReadableState;
16 var EE = require('events').EventEmitter;
18 var EElistenerCount = function (emitter, type) {
19 return emitter.listeners(type).length;
27 Stream = require('st' + 'ream');
28 } catch (_) {} finally {
29 if (!Stream) Stream = require('events').EventEmitter;
34 var Buffer = require('buffer').Buffer;
36 var bufferShim = require('buffer-shims');
40 var util = require('core-util-is');
41 util.inherits = require('inherits');
45 var debugUtil = require('util');
47 if (debugUtil && debugUtil.debuglog) {
48 debug = debugUtil.debuglog('stream');
50 debug = function () {};
54 var BufferList = require('./internal/streams/BufferList');
57 util.inherits(Readable, Stream);
59 function prependListener(emitter, event, fn) {
60 if (typeof emitter.prependListener === 'function') {
61 return emitter.prependListener(event, fn);
63 // This is a hack to make sure that our error handler is attached before any
64 // userland ones. NEVER DO THIS. This is here only because this code needs
65 // to continue to work with older versions of Node.js that do not include
66 // the prependListener() method. The goal is to eventually remove this hack.
67 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
72 function ReadableState(options, stream) {
73 Duplex = Duplex || require('./_stream_duplex');
75 options = options || {};
77 // object stream flag. Used to make read(n) ignore n and to
78 // make all the buffer merging and length checks go away
79 this.objectMode = !!options.objectMode;
81 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
83 // the point at which it stops calling _read() to fill the buffer
84 // Note: 0 is a valid value, means "don't call _read preemptively ever"
85 var hwm = options.highWaterMark;
86 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
87 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
90 this.highWaterMark = ~ ~this.highWaterMark;
92 // A linked list is used to store data chunks instead of an array because the
93 // linked list can remove elements from the beginning faster than
95 this.buffer = new BufferList();
101 this.endEmitted = false;
102 this.reading = false;
104 // a flag to be able to tell if the onwrite cb is called immediately,
105 // or on a later tick. We set this to true at first, because any
106 // actions that shouldn't happen until "later" should generally also
107 // not happen before the first write call.
110 // whenever we return null, then we set a flag to say
111 // that we're awaiting a 'readable' event emission.
112 this.needReadable = false;
113 this.emittedReadable = false;
114 this.readableListening = false;
115 this.resumeScheduled = false;
117 // Crypto is kind of old and crusty. Historically, its default string
118 // encoding is 'binary' so we have to make this configurable.
119 // Everything else in the universe uses 'utf8', though.
120 this.defaultEncoding = options.defaultEncoding || 'utf8';
122 // when piping, we only care about 'readable' events that happen
123 // after read()ing all the bytes and not getting any pushback.
126 // the number of writers that are awaiting a drain event in .pipe()s
129 // if true, a maybeReadMore has been scheduled
130 this.readingMore = false;
133 this.encoding = null;
134 if (options.encoding) {
135 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
136 this.decoder = new StringDecoder(options.encoding);
137 this.encoding = options.encoding;
142 function Readable(options) {
143 Duplex = Duplex || require('./_stream_duplex');
145 if (!(this instanceof Readable)) return new Readable(options);
147 this._readableState = new ReadableState(options, this);
150 this.readable = true;
152 if (options && typeof options.read === 'function') this._read = options.read;
157 // Manually shove something into the read() buffer.
158 // This returns true if the highWaterMark has not been hit yet,
159 // similar to how Writable.write() returns true if you should
160 // write() some more.
161 Readable.prototype.push = function (chunk, encoding) {
162 var state = this._readableState;
164 if (!state.objectMode && typeof chunk === 'string') {
165 encoding = encoding || state.defaultEncoding;
166 if (encoding !== state.encoding) {
167 chunk = bufferShim.from(chunk, encoding);
172 return readableAddChunk(this, state, chunk, encoding, false);
175 // Unshift should *always* be something directly out of read()
176 Readable.prototype.unshift = function (chunk) {
177 var state = this._readableState;
178 return readableAddChunk(this, state, chunk, '', true);
181 Readable.prototype.isPaused = function () {
182 return this._readableState.flowing === false;
185 function readableAddChunk(stream, state, chunk, encoding, addToFront) {
186 var er = chunkInvalid(state, chunk);
188 stream.emit('error', er);
189 } else if (chunk === null) {
190 state.reading = false;
191 onEofChunk(stream, state);
192 } else if (state.objectMode || chunk && chunk.length > 0) {
193 if (state.ended && !addToFront) {
194 var e = new Error('stream.push() after EOF');
195 stream.emit('error', e);
196 } else if (state.endEmitted && addToFront) {
197 var _e = new Error('stream.unshift() after end event');
198 stream.emit('error', _e);
201 if (state.decoder && !addToFront && !encoding) {
202 chunk = state.decoder.write(chunk);
203 skipAdd = !state.objectMode && chunk.length === 0;
206 if (!addToFront) state.reading = false;
208 // Don't add to the buffer if we've decoded to an empty string chunk and
209 // we're not in object mode
211 // if we want the data now, just emit it.
212 if (state.flowing && state.length === 0 && !state.sync) {
213 stream.emit('data', chunk);
216 // update the buffer info.
217 state.length += state.objectMode ? 1 : chunk.length;
218 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
220 if (state.needReadable) emitReadable(stream);
224 maybeReadMore(stream, state);
226 } else if (!addToFront) {
227 state.reading = false;
230 return needMoreData(state);
233 // if it's past the high water mark, we can push in some more.
234 // Also, if we have no data yet, we can stand some
235 // more bytes. This is to work around cases where hwm=0,
236 // such as the repl. Also, if the push() triggered a
237 // readable event, and the user called read(largeNumber) such that
238 // needReadable was set, then we ought to push more, so that another
239 // 'readable' event will be triggered.
240 function needMoreData(state) {
241 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
244 // backwards compatibility.
245 Readable.prototype.setEncoding = function (enc) {
246 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
247 this._readableState.decoder = new StringDecoder(enc);
248 this._readableState.encoding = enc;
252 // Don't raise the hwm > 8MB
253 var MAX_HWM = 0x800000;
254 function computeNewHighWaterMark(n) {
258 // Get the next highest power of 2 to prevent increasing hwm excessively in
271 // This function is designed to be inlinable, so please take care when making
272 // changes to the function body.
273 function howMuchToRead(n, state) {
274 if (n <= 0 || state.length === 0 && state.ended) return 0;
275 if (state.objectMode) return 1;
277 // Only flow one buffer at a time
278 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
280 // If we're asking for more than the current hwm, then raise the hwm.
281 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
282 if (n <= state.length) return n;
285 state.needReadable = true;
291 // you can override either this method, or the async _read(n) below.
292 Readable.prototype.read = function (n) {
295 var state = this._readableState;
298 if (n !== 0) state.emittedReadable = false;
300 // if we're doing read(0) to trigger a readable event, but we
301 // already have a bunch of data in the buffer, then just trigger
302 // the 'readable' event and move on.
303 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
304 debug('read: emitReadable', state.length, state.ended);
305 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
309 n = howMuchToRead(n, state);
311 // if we've ended, and we're now clear, then finish it up.
312 if (n === 0 && state.ended) {
313 if (state.length === 0) endReadable(this);
317 // All the actual chunk generation logic needs to be
318 // *below* the call to _read. The reason is that in certain
319 // synthetic stream cases, such as passthrough streams, _read
320 // may be a completely synchronous operation which may change
321 // the state of the read buffer, providing enough data when
322 // before there was *not* enough.
324 // So, the steps are:
325 // 1. Figure out what the state of things will be after we do
326 // a read from the buffer.
328 // 2. If that resulting state will trigger a _read, then call _read.
329 // Note that this may be asynchronous, or synchronous. Yes, it is
330 // deeply ugly to write APIs this way, but that still doesn't mean
331 // that the Readable class should behave improperly, as streams are
332 // designed to be sync/async agnostic.
333 // Take note if the _read call is sync or async (ie, if the read call
334 // has returned yet), so that we know whether or not it's safe to emit
337 // 3. Actually pull the requested chunks out of the buffer and return.
339 // if we need a readable event, then we need to do some reading.
340 var doRead = state.needReadable;
341 debug('need readable', doRead);
343 // if we currently have less than the highWaterMark, then also read some
344 if (state.length === 0 || state.length - n < state.highWaterMark) {
346 debug('length less than watermark', doRead);
349 // however, if we've ended, then there's no point, and if we're already
350 // reading, then it's unnecessary.
351 if (state.ended || state.reading) {
353 debug('reading or ended', doRead);
356 state.reading = true;
358 // if the length is currently zero, then we *need* a readable event.
359 if (state.length === 0) state.needReadable = true;
360 // call internal read method
361 this._read(state.highWaterMark);
363 // If _read pushed data synchronously, then `reading` will be false,
364 // and we need to re-evaluate how much data we can return to the user.
365 if (!state.reading) n = howMuchToRead(nOrig, state);
369 if (n > 0) ret = fromList(n, state);else ret = null;
372 state.needReadable = true;
378 if (state.length === 0) {
379 // If we have nothing in the buffer, then we want to know
380 // as soon as we *do* get something into the buffer.
381 if (!state.ended) state.needReadable = true;
383 // If we tried to read() past the EOF, then emit end on the next tick.
384 if (nOrig !== n && state.ended) endReadable(this);
387 if (ret !== null) this.emit('data', ret);
392 function chunkInvalid(state, chunk) {
394 if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
395 er = new TypeError('Invalid non-string/buffer chunk');
400 function onEofChunk(stream, state) {
401 if (state.ended) return;
403 var chunk = state.decoder.end();
404 if (chunk && chunk.length) {
405 state.buffer.push(chunk);
406 state.length += state.objectMode ? 1 : chunk.length;
411 // emit 'readable' now to make sure it gets picked up.
412 emitReadable(stream);
415 // Don't emit readable right away in sync mode, because this can trigger
416 // another read() call => stack overflow. This way, it might trigger
417 // a nextTick recursion warning, but that's not so bad.
418 function emitReadable(stream) {
419 var state = stream._readableState;
420 state.needReadable = false;
421 if (!state.emittedReadable) {
422 debug('emitReadable', state.flowing);
423 state.emittedReadable = true;
424 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
428 function emitReadable_(stream) {
429 debug('emit readable');
430 stream.emit('readable');
434 // at this point, the user has presumably seen the 'readable' event,
435 // and called read() to consume some data. that may have triggered
436 // in turn another _read(n) call, in which case reading = true if
438 // However, if we're not ended, or reading, and the length < hwm,
439 // then go ahead and try to read some more preemptively.
440 function maybeReadMore(stream, state) {
441 if (!state.readingMore) {
442 state.readingMore = true;
443 processNextTick(maybeReadMore_, stream, state);
447 function maybeReadMore_(stream, state) {
448 var len = state.length;
449 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
450 debug('maybeReadMore read 0');
452 if (len === state.length)
453 // didn't get any data, stop spinning.
454 break;else len = state.length;
456 state.readingMore = false;
459 // abstract method. to be overridden in specific implementation classes.
460 // call cb(er, data) where data is <= n in length.
461 // for virtual (non-string, non-buffer) streams, "length" is somewhat
462 // arbitrary, and perhaps not very meaningful.
463 Readable.prototype._read = function (n) {
464 this.emit('error', new Error('not implemented'));
467 Readable.prototype.pipe = function (dest, pipeOpts) {
469 var state = this._readableState;
471 switch (state.pipesCount) {
476 state.pipes = [state.pipes, dest];
479 state.pipes.push(dest);
482 state.pipesCount += 1;
483 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
485 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
487 var endFn = doEnd ? onend : cleanup;
488 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
490 dest.on('unpipe', onunpipe);
491 function onunpipe(readable) {
493 if (readable === src) {
503 // when the dest drains, it reduces the awaitDrain counter
504 // on the source. This would be more elegant with a .once()
505 // handler in flow(), but adding and removing repeatedly is
507 var ondrain = pipeOnDrain(src);
508 dest.on('drain', ondrain);
510 var cleanedUp = false;
513 // cleanup event handlers once the pipe is broken
514 dest.removeListener('close', onclose);
515 dest.removeListener('finish', onfinish);
516 dest.removeListener('drain', ondrain);
517 dest.removeListener('error', onerror);
518 dest.removeListener('unpipe', onunpipe);
519 src.removeListener('end', onend);
520 src.removeListener('end', cleanup);
521 src.removeListener('data', ondata);
525 // if the reader is waiting for a drain event from this
526 // specific writer, then it would cause it to never start
528 // So, if this is awaiting a drain, then we just call it now.
529 // If we don't know, then assume that we are waiting for one.
530 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
533 // If the user pushes more data while we're writing to dest then we'll end up
534 // in ondata again. However, we only want to increase awaitDrain once because
535 // dest will only emit one 'drain' event for the multiple writes.
536 // => Introduce a guard on increasing awaitDrain.
537 var increasedAwaitDrain = false;
538 src.on('data', ondata);
539 function ondata(chunk) {
541 increasedAwaitDrain = false;
542 var ret = dest.write(chunk);
543 if (false === ret && !increasedAwaitDrain) {
544 // If the user unpiped during `dest.write()`, it is possible
545 // to get stuck in a permanently paused state if that write
546 // also returned false.
547 // => Check whether `dest` is still a piping destination.
548 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
549 debug('false write response, pause', src._readableState.awaitDrain);
550 src._readableState.awaitDrain++;
551 increasedAwaitDrain = true;
557 // if the dest has an error, then stop piping into it.
558 // however, don't suppress the throwing behavior for this.
559 function onerror(er) {
560 debug('onerror', er);
562 dest.removeListener('error', onerror);
563 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
566 // Make sure our error handler is attached before userland ones.
567 prependListener(dest, 'error', onerror);
569 // Both close and finish should trigger unpipe, but only once.
571 dest.removeListener('finish', onfinish);
574 dest.once('close', onclose);
575 function onfinish() {
577 dest.removeListener('close', onclose);
580 dest.once('finish', onfinish);
587 // tell the dest that it's being piped to
588 dest.emit('pipe', src);
590 // start the flow if it hasn't been started already.
591 if (!state.flowing) {
592 debug('pipe resume');
599 function pipeOnDrain(src) {
601 var state = src._readableState;
602 debug('pipeOnDrain', state.awaitDrain);
603 if (state.awaitDrain) state.awaitDrain--;
604 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
605 state.flowing = true;
611 Readable.prototype.unpipe = function (dest) {
612 var state = this._readableState;
614 // if we're not piping anywhere, then do nothing.
615 if (state.pipesCount === 0) return this;
617 // just one destination. most common case.
618 if (state.pipesCount === 1) {
619 // passed in one, but it's not the right one.
620 if (dest && dest !== state.pipes) return this;
622 if (!dest) dest = state.pipes;
626 state.pipesCount = 0;
627 state.flowing = false;
628 if (dest) dest.emit('unpipe', this);
632 // slow case. multiple pipe destinations.
636 var dests = state.pipes;
637 var len = state.pipesCount;
639 state.pipesCount = 0;
640 state.flowing = false;
642 for (var _i = 0; _i < len; _i++) {
643 dests[_i].emit('unpipe', this);
647 // try to find the right one.
648 var i = indexOf(state.pipes, dest);
649 if (i === -1) return this;
651 state.pipes.splice(i, 1);
652 state.pipesCount -= 1;
653 if (state.pipesCount === 1) state.pipes = state.pipes[0];
655 dest.emit('unpipe', this);
660 // set up data events if they are asked for
661 // Ensure readable listeners eventually get something
662 Readable.prototype.on = function (ev, fn) {
663 var res = Stream.prototype.on.call(this, ev, fn);
666 // Start flowing on next tick if stream isn't explicitly paused
667 if (this._readableState.flowing !== false) this.resume();
668 } else if (ev === 'readable') {
669 var state = this._readableState;
670 if (!state.endEmitted && !state.readableListening) {
671 state.readableListening = state.needReadable = true;
672 state.emittedReadable = false;
673 if (!state.reading) {
674 processNextTick(nReadingNextTick, this);
675 } else if (state.length) {
676 emitReadable(this, state);
683 Readable.prototype.addListener = Readable.prototype.on;
685 function nReadingNextTick(self) {
686 debug('readable nexttick read 0');
690 // pause() and resume() are remnants of the legacy readable stream API
691 // If the user uses them, then switch into old mode.
692 Readable.prototype.resume = function () {
693 var state = this._readableState;
694 if (!state.flowing) {
696 state.flowing = true;
702 function resume(stream, state) {
703 if (!state.resumeScheduled) {
704 state.resumeScheduled = true;
705 processNextTick(resume_, stream, state);
709 function resume_(stream, state) {
710 if (!state.reading) {
711 debug('resume read 0');
715 state.resumeScheduled = false;
716 state.awaitDrain = 0;
717 stream.emit('resume');
719 if (state.flowing && !state.reading) stream.read(0);
722 Readable.prototype.pause = function () {
723 debug('call pause flowing=%j', this._readableState.flowing);
724 if (false !== this._readableState.flowing) {
726 this._readableState.flowing = false;
732 function flow(stream) {
733 var state = stream._readableState;
734 debug('flow', state.flowing);
735 while (state.flowing && stream.read() !== null) {}
738 // wrap an old-style stream as the async data source.
739 // This is *not* part of the readable stream interface.
740 // It is an ugly unfortunate mess of history.
741 Readable.prototype.wrap = function (stream) {
742 var state = this._readableState;
746 stream.on('end', function () {
747 debug('wrapped end');
748 if (state.decoder && !state.ended) {
749 var chunk = state.decoder.end();
750 if (chunk && chunk.length) self.push(chunk);
756 stream.on('data', function (chunk) {
757 debug('wrapped data');
758 if (state.decoder) chunk = state.decoder.write(chunk);
760 // don't skip over falsy values in objectMode
761 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
763 var ret = self.push(chunk);
770 // proxy all the other methods.
771 // important when wrapping filters and duplexes.
772 for (var i in stream) {
773 if (this[i] === undefined && typeof stream[i] === 'function') {
774 this[i] = function (method) {
776 return stream[method].apply(stream, arguments);
782 // proxy certain important events.
783 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
784 forEach(events, function (ev) {
785 stream.on(ev, self.emit.bind(self, ev));
788 // when we try to consume some more bytes, simply unpause the
789 // underlying stream.
790 self._read = function (n) {
791 debug('wrapped _read', n);
801 // exposed for testing purposes only.
802 Readable._fromList = fromList;
804 // Pluck off n bytes from an array of buffers.
805 // Length is the combined lengths of all the buffers in the list.
806 // This function is designed to be inlinable, so please take care when making
807 // changes to the function body.
808 function fromList(n, state) {
810 if (state.length === 0) return null;
813 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
814 // read it all, truncate the list
815 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
816 state.buffer.clear();
819 ret = fromListPartial(n, state.buffer, state.decoder);
825 // Extracts only enough buffered data to satisfy the amount requested.
826 // This function is designed to be inlinable, so please take care when making
827 // changes to the function body.
828 function fromListPartial(n, list, hasStrings) {
830 if (n < list.head.data.length) {
831 // slice is the same for buffers and strings
832 ret = list.head.data.slice(0, n);
833 list.head.data = list.head.data.slice(n);
834 } else if (n === list.head.data.length) {
835 // first chunk is a perfect match
838 // result spans more than one buffer
839 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
844 // Copies a specified amount of characters from the list of buffered data
846 // This function is designed to be inlinable, so please take care when making
847 // changes to the function body.
848 function copyFromBufferString(n, list) {
855 var nb = n > str.length ? str.length : n;
856 if (nb === str.length) ret += str;else ret += str.slice(0, n);
859 if (nb === str.length) {
861 if (p.next) list.head = p.next;else list.head = list.tail = null;
864 p.data = str.slice(nb);
874 // Copies a specified amount of bytes from the list of buffered data chunks.
875 // This function is designed to be inlinable, so please take care when making
876 // changes to the function body.
877 function copyFromBuffer(n, list) {
878 var ret = bufferShim.allocUnsafe(n);
885 var nb = n > buf.length ? buf.length : n;
886 buf.copy(ret, ret.length - n, 0, nb);
889 if (nb === buf.length) {
891 if (p.next) list.head = p.next;else list.head = list.tail = null;
894 p.data = buf.slice(nb);
904 function endReadable(stream) {
905 var state = stream._readableState;
907 // If we get here before consuming all the bytes, then that is a
908 // bug in node. Should never happen.
909 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
911 if (!state.endEmitted) {
913 processNextTick(endReadableNT, state, stream);
917 function endReadableNT(state, stream) {
918 // Check that we didn't get one last unshift.
919 if (!state.endEmitted && state.length === 0) {
920 state.endEmitted = true;
921 stream.readable = false;
926 function forEach(xs, f) {
927 for (var i = 0, l = xs.length; i < l; i++) {
932 function indexOf(xs, x) {
933 for (var i = 0, l = xs.length; i < l; i++) {
934 if (xs[i] === x) return i;