Skip to content
Merged
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
22 changes: 18 additions & 4 deletions lib/internal/streams/iter/classic.js
Original file line number Diff line number Diff line change
Expand Up @@ -363,23 +363,37 @@ function toReadableSync(source, options = kNullPrototype) {

const ReadableCtor = lazyReadable();
const iterator = source[SymbolIterator]();
let hasBatch = false;
let batch;
let batchIndex = 0;

return new ReadableCtor({
__proto__: null,
highWaterMark,
read() {
for (;;) {
const { value: batch, done } = iterator.next();
if (hasBatch) {
while (batchIndex < batch.length) {
if (!this.push(batch[batchIndex++])) return;
}
batch = undefined;
hasBatch = false;
batchIndex = 0;
}

const result = iterator.next();
const { done } = result;
if (done) {
this.push(null);
return;
}
for (let i = 0; i < batch.length; i++) {
if (!this.push(batch[i])) return;
}
batch = result.value;
hasBatch = true;
}
},
destroy(err, cb) {
batch = undefined;
hasBatch = false;
if (typeof iterator.return === 'function') iterator.return();
cb(err);
},
Expand Down
16 changes: 16 additions & 0 deletions test/parallel/test-stream-iter-to-readable.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,21 @@ async function testBackpressureSync() {
assert.strictEqual(chunks.length, 10);
}

// =============================================================================
// fromStreamIterSync: backpressure within a batch
// =============================================================================

async function testBackpressureSyncMultiChunkBatch() {
function* gen() {
yield [Buffer.from('a'), Buffer.from('b'), Buffer.from('c')];
}

const readable = toReadableSync(gen(), { highWaterMark: 1 });
const result = await collect(readable);

assert.strictEqual(result.toString(), 'abc');
}

// =============================================================================
// fromStreamIterSync: source error
// =============================================================================
Expand Down Expand Up @@ -613,6 +628,7 @@ Promise.all([
testWithTransformAsync(),
testBasicSync(),
testBackpressureSync(),
testBackpressureSyncMultiChunkBatch(),
testErrorSync(),
testDestroySync(),
testRoundTrip(),
Expand Down
Loading