Skip to content

Commit 5167080

Browse files
committed
harden event handling
1 parent ef0b8e0 commit 5167080

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

lib/sink.js

+23-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
var Writable = require('readable-stream/writable');
44

5+
function listenerCount(stream, evt) {
6+
return stream.listeners(evt).length;
7+
}
8+
59
function sink(stream) {
610
var sinkStream = new Writable({
711
objectMode: true,
@@ -10,9 +14,26 @@ function sink(stream) {
1014
},
1115
});
1216

17+
stream.on('removeListener', function() {
18+
if (listenerCount(stream, 'readable') || listenerCount(stream, 'data')) {
19+
stream.unpipe(sinkStream);
20+
}
21+
});
22+
23+
stream.on('unpipe', function() {
24+
if (!(listenerCount(stream, 'readable') || listenerCount(stream, 'data'))) {
25+
stream.pipe(sinkStream);
26+
}
27+
});
28+
29+
stream.on('newListener', function() {
30+
if (listenerCount(stream, 'readable') || listenerCount(stream, 'data')) {
31+
stream.unpipe(sinkStream);
32+
}
33+
});
34+
1335
return function() {
14-
// Respect readable listeners on the underlying stream
15-
if (stream.listeners('readable').length > 0) {
36+
if (listenerCount(stream, 'readable') || listenerCount(stream, 'data')) {
1637
return;
1738
}
1839

0 commit comments

Comments
 (0)