blob: cfab46980aad291cca9949d3849c4820274eca18 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
'use strict';
var Writable = require('readable-stream/writable');
function listenerCount(stream, evt) {
return stream.listeners(evt).length;
}
function hasListeners(stream) {
return !!(listenerCount(stream, 'readable') || listenerCount(stream, 'data'));
}
function sink(stream) {
var sinkAdded = false;
var sinkStream = new Writable({
objectMode: true,
write: function(file, enc, cb) {
cb();
},
});
function addSink() {
if (sinkAdded) {
return;
}
if (hasListeners(stream)) {
return;
}
sinkAdded = true;
stream.pipe(sinkStream);
}
function removeSink(evt) {
if (evt !== 'readable' && evt !== 'data') {
return;
}
if (hasListeners(stream)) {
sinkAdded = false;
stream.unpipe(sinkStream);
}
}
stream.on('newListener', removeSink);
stream.on('removeListener', removeSink);
stream.on('removeListener', addSink);
return addSink;
}
module.exports = sink;
|