Skip to content

Commit f537c86

Browse files
addaleaxrichardlau
authored andcommitted
stream: allow using .push()/.unshift() during once('data')
Previously, the `.push()` or `.unshift()` call would just have jumped straight to emitting a `'data'` event, even if there were no listeners, effectively just silently dropping the chunk. PR-URL: #34957 Reviewed-By: Benjamin Gruenbaum <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Rich Trott <[email protected]> Reviewed-By: Denys Otrishko <[email protected]> Reviewed-By: Robert Nagy <[email protected]> Reviewed-By: Ricky Zhou <[email protected]>
1 parent 94c6e09 commit f537c86

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

lib/_stream_readable.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,8 @@ function readableAddChunk(stream, chunk, encoding, addToFront) {
292292
}
293293

294294
function addChunk(stream, state, chunk, addToFront) {
295-
if (state.flowing && state.length === 0 && !state.sync) {
295+
if (state.flowing && state.length === 0 && !state.sync &&
296+
stream.listenerCount('data') > 0) {
296297
// Use the guard to avoid creating `Set()` repeatedly
297298
// when we have multiple pipes.
298299
if (state.multiAwaitDrain) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const { Readable } = require('stream');
5+
6+
// Verify that .push() and .unshift() can be called from 'data' listeners.
7+
8+
for (const method of ['push', 'unshift']) {
9+
const r = new Readable({ read() {} });
10+
r.once('data', common.mustCall((chunk) => {
11+
assert.strictEqual(r.readableLength, 0);
12+
r[method](chunk);
13+
assert.strictEqual(r.readableLength, chunk.length);
14+
15+
r.on('data', common.mustCall((chunk) => {
16+
assert.strictEqual(chunk.toString(), 'Hello, world');
17+
}));
18+
}));
19+
20+
r.push('Hello, world');
21+
}

0 commit comments

Comments
 (0)