From 7ca762d27af1a8f0bb97add600115449c8178901 Mon Sep 17 00:00:00 2001 From: Christian Aurich Zanettini Martins Date: Wed, 25 Nov 2026 01:11:41 -0300 Subject: [PATCH] stream: emit end when paused on the last chunk flowSync() calls _read() before delivering each chunk, like read(), but did not schedule 'end' when that call pushed EOF and nothing was left to deliver. A consumer that paused on the last chunk, such as pipe() after write() returned false, then got no 'end' until it resumed. Schedule endReadable() there, as read() does. Signed-off-by: Christian Aurich Zanettini Martins --- lib/internal/streams/readable.js | 5 ++ .../test-stream-readable-flow-sync-end.js | 48 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 test/parallel/test-stream-readable-flow-sync-end.js diff --git a/lib/internal/streams/readable.js b/lib/internal/streams/readable.js index 8fe29e94057..5e958f7fc20 100644 --- a/lib/internal/streams/readable.js +++ b/lib/internal/streams/readable.js @@ -1482,6 +1482,11 @@ function flowSync(stream, state) { } state[kState] &= ~(kSync | kFastPush); + // Last chunk before EOF. Schedule 'end' now, as read() does, since a + // pause() from its 'data' event leaves nothing else to call endReadable(). + if (state.length === 0 && (state[kState] & kEnded) !== 0) + endReadable(stream); + if ((state[kState] & (kErrorEmitted | kCloseEmitted)) === 0) { state[kState] |= kDataEmitted; deliverFlowChunk(stream, state, current); diff --git a/test/parallel/test-stream-readable-flow-sync-end.js b/test/parallel/test-stream-readable-flow-sync-end.js new file mode 100644 index 00000000000..73487ed2814 --- /dev/null +++ b/test/parallel/test-stream-readable-flow-sync-end.js @@ -0,0 +1,48 @@ +'use strict'; + +// A flowing Readable whose _read() pushes EOF in the call after its last +// chunk emits 'end' even if the consumer pauses on that chunk. pipe() then +// ends a destination whose last write returned false without waiting for +// 'drain'. + +const common = require('../common'); +const assert = require('assert'); +const { Readable, Writable } = require('stream'); + +function source() { + const chunks = [Buffer.alloc(64), Buffer.alloc(64), Buffer.alloc(64)]; + return new Readable({ + highWaterMark: 64, + read() { + this.push(chunks.shift() ?? null); + }, + }); +} + +// pause() from the 'data' listener of the last chunk. +{ + const src = source(); + let received = 0; + src.on('data', common.mustCall(() => { + if (++received === 3) + src.pause(); + }, 3)); + src.on('end', common.mustCall()); +} + +// pipe() to a destination that never completes its last write. +{ + const src = source(); + let written = 0; + const dest = new Writable({ + highWaterMark: 1, + write: common.mustCall((chunk, encoding, cb) => { + if (++written < 3) + setImmediate(cb); + }, 3), + }); + src.pipe(dest); + src.on('end', common.mustCall(() => { + assert.strictEqual(dest.writableEnded, true); + })); +}