Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

setEncoding and abstract out endReadable

  • Loading branch information...
commit d99d39cdd65363e4adb9e8caddd291f075680cb3 1 parent 42f1197
@isaacs isaacs authored
Showing with 27 additions and 6 deletions.
  1. +27 −6 lib/_stream_readable.js
View
33 lib/_stream_readable.js
@@ -42,6 +42,7 @@ function ReadableState(options, stream) {
this.pipes = [];
this.flowing = false;
this.ended = false;
+ this.endEmitted = false;
this.stream = stream;
this.reading = false;
@@ -74,7 +75,7 @@ Readable.prototype.read = function(n) {
var state = this._readableState;
if (state.length === 0 && state.ended) {
- process.nextTick(this.emit.bind(this, 'end'));
+ endReadable(this);
return null;
}
@@ -100,6 +101,7 @@ Readable.prototype.read = function(n) {
n = state.length;
}
+
var ret;
if (n > 0)
ret = fromList(n, state.buffer, state.length, !!state.decoder);
@@ -127,6 +129,8 @@ Readable.prototype.read = function(n) {
// 'readable' now to make sure it gets picked up.
if (state.length > 0)
this.emit('readable');
+ else
+ endReadable(this);
return;
}
@@ -135,8 +139,16 @@ Readable.prototype.read = function(n) {
state.length += chunk.length;
state.buffer.push(chunk);
- if (state.length < state.lowWaterMark)
+
+ // if we haven't gotten enough to pass the lowWaterMark,
+ // and we haven't ended, then don't bother telling the user
+ // that it's time to read more data. Otherwise, that'll
+ // probably kick off another stream.read(), which can trigger
+ // another _read(n,cb) before this one returns!
+ if (state.length < state.lowWaterMark) {
this._read(state.bufferSize, onread.bind(this));
+ return;
+ }
// now we have something to call this.read() to get.
if (state.needReadable) {
@@ -331,7 +343,7 @@ Readable.prototype.wrap = function(stream) {
stream.on('end', function() {
state.ended = true;
if (state.length === 0)
- this.emit('end');
+ endReadable(this);
}.bind(this));
stream.on('data', function(chunk) {
@@ -391,7 +403,7 @@ Readable.prototype.wrap = function(stream) {
}
if (state.length === 0 && state.ended)
- process.nextTick(this.emit.bind(this, 'end'));
+ endReadable(this);
return ret;
};
@@ -412,9 +424,9 @@ function fromList(n, list, length, stringMode) {
return null;
}
- if (length === 0) {
+ if (length === 0)
ret = null;
- } else if (!n || n >= length) {
+ else if (!n || n >= length) {
// read it all, truncate the array.
if (stringMode)
ret = list.join('');
@@ -462,3 +474,12 @@ function fromList(n, list, length, stringMode) {
return ret;
}
+
+function endReadable(stream) {
+ var state = stream._readableState;
+ if (state.endEmitted)
+ return;
+ state.ended = true;
+ state.endEmitted = true;
+ process.nextTick(stream.emit.bind(stream, 'end'));
+}
Please sign in to comment.
Something went wrong with that request. Please try again.