From a83008a35235c8559502eb9accc735a183fb7e0c Mon Sep 17 00:00:00 2001 From: Mathias Buus Date: Thu, 1 Feb 2018 23:20:49 +0100 Subject: [PATCH] stream: defer readable and flow when sync --- lib/_stream_readable.js | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 6854b3d9ebca8a..869a060f01c09e 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -486,11 +486,18 @@ function onEofChunk(stream, state) { } state.ended = true; - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); + if (state.sync && state.length) { + // if we are sync and have data in the buffer, wait until next tick + // to emit the data. otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } } }