Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stream: correctly pause and resume after once('readable') #24366

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions lib/_stream_readable.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ function ReadableState(options, stream, isDuplex) {
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
this.paused = true;

// Should close be emitted on destroy. Defaults to true.
this.emitClose = options.emitClose !== false;
Expand Down Expand Up @@ -862,10 +863,16 @@ Readable.prototype.removeAllListeners = function(ev) {
};

function updateReadableListening(self) {
self._readableState.readableListening = self.listenerCount('readable') > 0;
const state = self._readableState;
state.readableListening = self.listenerCount('readable') > 0;

// crude way to check if we should resume
if (self.listenerCount('data') > 0) {
if (state.resumeScheduled && !state.paused) {
// flowing needs to be set to true now, otherwise
// the upcoming resume will not flow.
state.flowing = true;

// crude way to check if we should resume
} else if (self.listenerCount('data') > 0) {
self.resume();
}
}
Expand All @@ -887,6 +894,7 @@ Readable.prototype.resume = function() {
state.flowing = !state.readableListening;
resume(this, state);
}
state.paused = false;
return this;
};

Expand Down Expand Up @@ -917,6 +925,7 @@ Readable.prototype.pause = function() {
this._readableState.flowing = false;
this.emit('pause');
}
this._readableState.paused = true;
return this;
};

Expand Down
29 changes: 29 additions & 0 deletions test/parallel/test-stream-readable-readable-then-resume.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict';

const common = require('../common');
const { Readable } = require('stream');

// This test verifies that a stream could be resumed after
// removing the readable event in the same tick

check(new Readable({
objectMode: true,
highWaterMark: 1,
read() {
if (!this.first) {
this.push('hello');
this.first = true;
return;
}

this.push(null);
}
}));

function check(s) {
const readableListener = common.mustNotCall();
s.on('readable', readableListener);
s.on('end', common.mustCall());
s.removeListener('readable', readableListener);
s.resume();
}