1 // Copyright Joyent, Inc. and other Node contributors.
3 // Permission is hereby granted, free of charge, to any person obtaining a
4 // copy of this software and associated documentation files (the
5 // "Software"), to deal in the Software without restriction, including
6 // without limitation the rights to use, copy, modify, merge, publish,
7 // distribute, sublicense, and/or sell copies of the Software, and to permit
8 // persons to whom the Software is furnished to do so, subject to the
9 // following conditions:
11 // The above copyright notice and this permission notice shall be included
12 // in all copies or substantial portions of the Software.
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
22 module.exports = Readable;
23 Readable.ReadableState = ReadableState;
25 var EE = require('events').EventEmitter;
26 var Stream = require('stream');
27 var util = require('util');
29 var debug = util.debuglog('stream');
31 util.inherits(Readable, Stream);
33 function ReadableState(options, stream) {
34 options = options || {};
36 // the point at which it stops calling _read() to fill the buffer
37 // Note: 0 is a valid value, means "don't call _read preemptively ever"
38 var hwm = options.highWaterMark;
39 var defaultHwm = options.objectMode ? 16 : 16 * 1024;
40 this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
43 this.highWaterMark = ~~this.highWaterMark;
51 this.endEmitted = false;
54 // a flag to be able to tell if the onwrite cb is called immediately,
55 // or on a later tick. We set this to true at first, because any
56 // actions that shouldn't happen until "later" should generally also
57 // not happen before the first write call.
60 // whenever we return null, then we set a flag to say
61 // that we're awaiting a 'readable' event emission.
62 this.needReadable = false;
63 this.emittedReadable = false;
64 this.readableListening = false;
67 // object stream flag. Used to make read(n) ignore n and to
68 // make all the buffer merging and length checks go away
69 this.objectMode = !!options.objectMode;
71 // Crypto is kind of old and crusty. Historically, its default string
72 // encoding is 'binary' so we have to make this configurable.
73 // Everything else in the universe uses 'utf8', though.
74 this.defaultEncoding = options.defaultEncoding || 'utf8';
76 // when piping, we only care about 'readable' events that happen
77 // after read()ing all the bytes and not getting any pushback.
80 // the number of writers that are awaiting a drain event in .pipe()s
83 // if true, a maybeReadMore has been scheduled
84 this.readingMore = false;
88 if (options.encoding) {
90 StringDecoder = require('string_decoder').StringDecoder;
91 this.decoder = new StringDecoder(options.encoding);
92 this.encoding = options.encoding;
96 function Readable(options) {
97 if (!(this instanceof Readable))
98 return new Readable(options);
100 this._readableState = new ReadableState(options, this);
103 this.readable = true;
108 // Manually shove something into the read() buffer.
109 // This returns true if the highWaterMark has not been hit yet,
110 // similar to how Writable.write() returns true if you should
111 // write() some more.
112 Readable.prototype.push = function(chunk, encoding) {
113 var state = this._readableState;
115 if (util.isString(chunk) && !state.objectMode) {
116 encoding = encoding || state.defaultEncoding;
117 if (encoding !== state.encoding) {
118 chunk = new Buffer(chunk, encoding);
123 return readableAddChunk(this, state, chunk, encoding, false);
126 // Unshift should *always* be something directly out of read()
127 Readable.prototype.unshift = function(chunk) {
128 var state = this._readableState;
129 return readableAddChunk(this, state, chunk, '', true);
132 function readableAddChunk(stream, state, chunk, encoding, addToFront) {
133 var er = chunkInvalid(state, chunk);
135 stream.emit('error', er);
136 } else if (util.isNullOrUndefined(chunk)) {
137 state.reading = false;
139 onEofChunk(stream, state);
140 } else if (state.objectMode || chunk && chunk.length > 0) {
141 if (state.ended && !addToFront) {
142 var e = new Error('stream.push() after EOF');
143 stream.emit('error', e);
144 } else if (state.endEmitted && addToFront) {
145 var e = new Error('stream.unshift() after end event');
146 stream.emit('error', e);
148 if (state.decoder && !addToFront && !encoding)
149 chunk = state.decoder.write(chunk);
152 state.reading = false;
154 // if we want the data now, just emit it.
155 if (state.flowing && state.length === 0 && !state.sync) {
156 stream.emit('data', chunk);
159 // update the buffer info.
160 state.length += state.objectMode ? 1 : chunk.length;
162 state.buffer.unshift(chunk);
164 state.buffer.push(chunk);
166 if (state.needReadable)
167 emitReadable(stream);
170 maybeReadMore(stream, state);
172 } else if (!addToFront) {
173 state.reading = false;
176 return needMoreData(state);
181 // if it's past the high water mark, we can push in some more.
182 // Also, if we have no data yet, we can stand some
183 // more bytes. This is to work around cases where hwm=0,
184 // such as the repl. Also, if the push() triggered a
185 // readable event, and the user called read(largeNumber) such that
186 // needReadable was set, then we ought to push more, so that another
187 // 'readable' event will be triggered.
188 function needMoreData(state) {
189 return !state.ended &&
190 (state.needReadable ||
191 state.length < state.highWaterMark ||
195 // backwards compatibility.
196 Readable.prototype.setEncoding = function(enc) {
198 StringDecoder = require('string_decoder').StringDecoder;
199 this._readableState.decoder = new StringDecoder(enc);
200 this._readableState.encoding = enc;
203 // Don't raise the hwm > 128MB
204 var MAX_HWM = 0x800000;
205 function roundUpToNextPowerOf2(n) {
209 // Get the next highest power of 2
211 for (var p = 1; p < 32; p <<= 1) n |= n >> p;
217 function howMuchToRead(n, state) {
218 if (state.length === 0 && state.ended)
221 if (state.objectMode)
222 return n === 0 ? 0 : 1;
224 if (isNaN(n) || util.isNull(n)) {
225 // only flow one buffer at a time
226 if (state.flowing && state.buffer.length)
227 return state.buffer[0].length;
235 // If we're asking for more than the target buffer level,
236 // then raise the water mark. Bump up to the next highest
237 // power of 2, to prevent increasing it excessively in tiny
239 if (n > state.highWaterMark)
240 state.highWaterMark = roundUpToNextPowerOf2(n);
242 // don't have that much. return null, unless we've ended.
243 if (n > state.length) {
245 state.needReadable = true;
254 // you can override either this method, or the async _read(n) below.
255 Readable.prototype.read = function(n) {
257 var state = this._readableState;
260 if (!util.isNumber(n) || n > 0)
261 state.emittedReadable = false;
263 // if we're doing read(0) to trigger a readable event, but we
264 // already have a bunch of data in the buffer, then just trigger
265 // the 'readable' event and move on.
267 state.needReadable &&
268 (state.length >= state.highWaterMark || state.ended)) {
269 debug('read: emitReadable', state.length, state.ended);
270 if (state.length === 0 && state.ended)
277 n = howMuchToRead(n, state);
279 // if we've ended, and we're now clear, then finish it up.
280 if (n === 0 && state.ended) {
281 if (state.length === 0)
286 // All the actual chunk generation logic needs to be
287 // *below* the call to _read. The reason is that in certain
288 // synthetic stream cases, such as passthrough streams, _read
289 // may be a completely synchronous operation which may change
290 // the state of the read buffer, providing enough data when
291 // before there was *not* enough.
293 // So, the steps are:
294 // 1. Figure out what the state of things will be after we do
295 // a read from the buffer.
297 // 2. If that resulting state will trigger a _read, then call _read.
298 // Note that this may be asynchronous, or synchronous. Yes, it is
299 // deeply ugly to write APIs this way, but that still doesn't mean
300 // that the Readable class should behave improperly, as streams are
301 // designed to be sync/async agnostic.
302 // Take note if the _read call is sync or async (ie, if the read call
303 // has returned yet), so that we know whether or not it's safe to emit
306 // 3. Actually pull the requested chunks out of the buffer and return.
308 // if we need a readable event, then we need to do some reading.
309 var doRead = state.needReadable;
310 debug('need readable', doRead);
312 // if we currently have less than the highWaterMark, then also read some
313 if (state.length === 0 || state.length - n < state.highWaterMark) {
315 debug('length less than watermark', doRead);
318 // however, if we've ended, then there's no point, and if we're already
319 // reading, then it's unnecessary.
320 if (state.ended || state.reading) {
322 debug('reading or ended', doRead);
327 state.reading = true;
329 // if the length is currently zero, then we *need* a readable event.
330 if (state.length === 0)
331 state.needReadable = true;
332 // call internal read method
333 this._read(state.highWaterMark);
337 // If _read pushed data synchronously, then `reading` will be false,
338 // and we need to re-evaluate how much data we can return to the user.
339 if (doRead && !state.reading)
340 n = howMuchToRead(nOrig, state);
344 ret = fromList(n, state);
348 if (util.isNull(ret)) {
349 state.needReadable = true;
355 // If we have nothing in the buffer, then we want to know
356 // as soon as we *do* get something into the buffer.
357 if (state.length === 0 && !state.ended)
358 state.needReadable = true;
360 // If we tried to read() past the EOF, then emit end on the next tick.
361 if (nOrig !== n && state.ended && state.length === 0)
364 if (!util.isNull(ret))
365 this.emit('data', ret);
370 function chunkInvalid(state, chunk) {
372 if (!util.isBuffer(chunk) &&
373 !util.isString(chunk) &&
374 !util.isNullOrUndefined(chunk) &&
377 er = new TypeError('Invalid non-string/buffer chunk');
383 function onEofChunk(stream, state) {
384 if (state.decoder && !state.ended) {
385 var chunk = state.decoder.end();
386 if (chunk && chunk.length) {
387 state.buffer.push(chunk);
388 state.length += state.objectMode ? 1 : chunk.length;
393 // emit 'readable' now to make sure it gets picked up.
394 emitReadable(stream);
397 // Don't emit readable right away in sync mode, because this can trigger
398 // another read() call => stack overflow. This way, it might trigger
399 // a nextTick recursion warning, but that's not so bad.
400 function emitReadable(stream) {
401 var state = stream._readableState;
402 state.needReadable = false;
403 if (!state.emittedReadable) {
404 debug('emitReadable', state.flowing);
405 state.emittedReadable = true;
407 process.nextTick(function() {
408 emitReadable_(stream);
411 emitReadable_(stream);
415 function emitReadable_(stream) {
416 debug('emit readable');
417 stream.emit('readable');
422 // at this point, the user has presumably seen the 'readable' event,
423 // and called read() to consume some data. that may have triggered
424 // in turn another _read(n) call, in which case reading = true if
426 // However, if we're not ended, or reading, and the length < hwm,
427 // then go ahead and try to read some more preemptively.
428 function maybeReadMore(stream, state) {
429 if (!state.readingMore) {
430 state.readingMore = true;
431 process.nextTick(function() {
432 maybeReadMore_(stream, state);
437 function maybeReadMore_(stream, state) {
438 var len = state.length;
439 while (!state.reading && !state.flowing && !state.ended &&
440 state.length < state.highWaterMark) {
441 debug('maybeReadMore read 0');
443 if (len === state.length)
444 // didn't get any data, stop spinning.
449 state.readingMore = false;
452 // abstract method. to be overridden in specific implementation classes.
453 // call cb(er, data) where data is <= n in length.
454 // for virtual (non-string, non-buffer) streams, "length" is somewhat
455 // arbitrary, and perhaps not very meaningful.
456 Readable.prototype._read = function(n) {
457 this.emit('error', new Error('not implemented'));
460 Readable.prototype.pipe = function(dest, pipeOpts) {
462 var state = this._readableState;
464 switch (state.pipesCount) {
469 state.pipes = [state.pipes, dest];
472 state.pipes.push(dest);
475 state.pipesCount += 1;
476 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
478 var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
479 dest !== process.stdout &&
480 dest !== process.stderr;
482 var endFn = doEnd ? onend : cleanup;
483 if (state.endEmitted)
484 process.nextTick(endFn);
486 src.once('end', endFn);
488 dest.on('unpipe', onunpipe);
489 function onunpipe(readable) {
491 if (readable === src) {
501 // when the dest drains, it reduces the awaitDrain counter
502 // on the source. This would be more elegant with a .once()
503 // handler in flow(), but adding and removing repeatedly is
505 var ondrain = pipeOnDrain(src);
506 dest.on('drain', ondrain);
510 // cleanup event handlers once the pipe is broken
511 dest.removeListener('close', onclose);
512 dest.removeListener('finish', onfinish);
513 dest.removeListener('drain', ondrain);
514 dest.removeListener('error', onerror);
515 dest.removeListener('unpipe', onunpipe);
516 src.removeListener('end', onend);
517 src.removeListener('end', cleanup);
518 src.removeListener('data', ondata);
520 // if the reader is waiting for a drain event from this
521 // specific writer, then it would cause it to never start
523 // So, if this is awaiting a drain, then we just call it now.
524 // If we don't know, then assume that we are waiting for one.
525 if (state.awaitDrain &&
526 (!dest._writableState || dest._writableState.needDrain))
530 src.on('data', ondata);
531 function ondata(chunk) {
533 var ret = dest.write(chunk);
535 debug('false write response, pause',
536 src._readableState.awaitDrain);
537 src._readableState.awaitDrain++;
542 // if the dest has an error, then stop piping into it.
543 // however, don't suppress the throwing behavior for this.
544 function onerror(er) {
545 debug('onerror', er);
547 dest.removeListener('error', onerror);
548 if (EE.listenerCount(dest, 'error') === 0)
549 dest.emit('error', er);
551 // This is a brutally ugly hack to make sure that our error handler
552 // is attached before any userland ones. NEVER DO THIS.
553 if (!dest._events.error)
554 dest.on('error', onerror);
555 else if (Array.isArray(dest._events.error))
556 dest._events.error.unshift(onerror);
558 dest._events.error = [onerror, dest._events.error];
562 // Both close and finish should trigger unpipe, but only once.
564 dest.removeListener('finish', onfinish);
567 dest.once('close', onclose);
568 function onfinish() {
570 dest.removeListener('close', onclose);
573 dest.once('finish', onfinish);
580 // tell the dest that it's being piped to
581 dest.emit('pipe', src);
583 // start the flow if it hasn't been started already.
584 if (!state.flowing) {
585 debug('pipe resume');
592 function pipeOnDrain(src) {
594 var state = src._readableState;
595 debug('pipeOnDrain', state.awaitDrain);
596 if (state.awaitDrain)
598 if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
599 state.flowing = true;
606 Readable.prototype.unpipe = function(dest) {
607 var state = this._readableState;
609 // if we're not piping anywhere, then do nothing.
610 if (state.pipesCount === 0)
613 // just one destination. most common case.
614 if (state.pipesCount === 1) {
615 // passed in one, but it's not the right one.
616 if (dest && dest !== state.pipes)
624 state.pipesCount = 0;
625 state.flowing = false;
627 dest.emit('unpipe', this);
631 // slow case. multiple pipe destinations.
635 var dests = state.pipes;
636 var len = state.pipesCount;
638 state.pipesCount = 0;
639 state.flowing = false;
641 for (var i = 0; i < len; i++)
642 dests[i].emit('unpipe', this);
646 // try to find the right one.
647 var i = state.pipes.indexOf(dest);
651 state.pipes.splice(i, 1);
652 state.pipesCount -= 1;
653 if (state.pipesCount === 1)
654 state.pipes = state.pipes[0];
656 dest.emit('unpipe', this);
661 // set up data events if they are asked for
662 // Ensure readable listeners eventually get something
663 Readable.prototype.on = function(ev, fn) {
664 var res = Stream.prototype.on.call(this, ev, fn);
666 // If listening to data, and it has not explicitly been paused,
667 // then call resume to start the flow of data on the next tick.
668 if (ev === 'data' && false !== this._readableState.flowing) {
672 if (ev === 'readable' && this.readable) {
673 var state = this._readableState;
674 if (!state.readableListening) {
675 state.readableListening = true;
676 state.emittedReadable = false;
677 state.needReadable = true;
678 if (!state.reading) {
680 process.nextTick(function() {
681 debug('readable nexttick read 0');
684 } else if (state.length) {
685 emitReadable(this, state);
692 Readable.prototype.addListener = Readable.prototype.on;
694 // pause() and resume() are remnants of the legacy readable stream API
695 // If the user uses them, then switch into old mode.
696 Readable.prototype.resume = function() {
697 var state = this._readableState;
698 if (!state.flowing) {
700 state.flowing = true;
701 if (!state.reading) {
702 debug('resume read 0');
709 function resume(stream, state) {
710 if (!state.resumeScheduled) {
711 state.resumeScheduled = true;
712 process.nextTick(function() {
713 resume_(stream, state);
718 function resume_(stream, state) {
719 state.resumeScheduled = false;
720 stream.emit('resume');
722 if (state.flowing && !state.reading)
726 Readable.prototype.pause = function() {
727 debug('call pause flowing=%j', this._readableState.flowing);
728 if (false !== this._readableState.flowing) {
730 this._readableState.flowing = false;
735 function flow(stream) {
736 var state = stream._readableState;
737 debug('flow', state.flowing);
740 var chunk = stream.read();
741 } while (null !== chunk && state.flowing);
745 // wrap an old-style stream as the async data source.
746 // This is *not* part of the readable stream interface.
747 // It is an ugly unfortunate mess of history.
748 Readable.prototype.wrap = function(stream) {
749 var state = this._readableState;
753 stream.on('end', function() {
754 debug('wrapped end');
755 if (state.decoder && !state.ended) {
756 var chunk = state.decoder.end();
757 if (chunk && chunk.length)
764 stream.on('data', function(chunk) {
765 debug('wrapped data');
767 chunk = state.decoder.write(chunk);
768 if (!chunk || !state.objectMode && !chunk.length)
771 var ret = self.push(chunk);
778 // proxy all the other methods.
779 // important when wrapping filters and duplexes.
780 for (var i in stream) {
781 if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
782 this[i] = function(method) { return function() {
783 return stream[method].apply(stream, arguments);
788 // proxy certain important events.
789 var events = ['error', 'close', 'destroy', 'pause', 'resume'];
790 events.forEach(function(ev) {
791 stream.on(ev, self.emit.bind(self, ev));
794 // when we try to consume some more bytes, simply unpause the
795 // underlying stream.
796 self._read = function(n) {
797 debug('wrapped _read', n);
809 // exposed for testing purposes only.
810 Readable._fromList = fromList;
812 // Pluck off n bytes from an array of buffers.
813 // Length is the combined lengths of all the buffers in the list.
814 function fromList(n, state) {
815 var list = state.buffer;
816 var length = state.length;
817 var stringMode = !!state.decoder;
818 var objectMode = !!state.objectMode;
821 // nothing in the list, definitely empty.
822 if (list.length === 0)
829 else if (!n || n >= length) {
830 // read it all, truncate the array.
834 ret = Buffer.concat(list, length);
837 // read just some of it.
838 if (n < list[0].length) {
839 // just take a part of the first list item.
840 // slice is the same for buffers and strings.
842 ret = buf.slice(0, n);
843 list[0] = buf.slice(n);
844 } else if (n === list[0].length) {
845 // first list is a perfect match
849 // we have enough to cover it, but it spans past the first buffer.
856 for (var i = 0, l = list.length; i < l && c < n; i++) {
858 var cpy = Math.min(n - c, buf.length);
861 ret += buf.slice(0, cpy);
863 buf.copy(ret, c, 0, cpy);
865 if (cpy < buf.length)
866 list[0] = buf.slice(cpy);
878 function endReadable(stream) {
879 var state = stream._readableState;
881 // If we get here before consuming all the bytes, then that is a
882 // bug in node. Should never happen.
883 if (state.length > 0)
884 throw new Error('endReadable called on non-empty stream');
886 if (!state.endEmitted) {
888 process.nextTick(function() {
889 // Check that we didn't get one last unshift.
890 if (!state.endEmitted && state.length === 0) {
891 state.endEmitted = true;
892 stream.readable = false;