Skip to content

Commit d44b05b

Browse files
committed
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 327d009 commit d44b05b

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

lib/_stream_readable.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,8 @@ function readableAddChunk(stream, chunk, encoding, addToFront) {
284284
}
285285

286286
function addChunk(stream, state, chunk, addToFront) {
287-
if (state.flowing && state.length === 0 && !state.sync) {
287+
if (state.flowing && state.length === 0 && !state.sync &&
288+
stream.listenerCount('data') > 0) {
288289
// Use the guard to avoid creating `Set()` repeatedly
289290
// when we have multiple pipes.
290291
if (state.multiAwaitDrain) {
Lines changed: 21 additions & 0 deletions
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)