-
Notifications
You must be signed in to change notification settings - Fork 0
/
MultiplexStream.js
49 lines (43 loc) · 1.04 KB
/
MultiplexStream.js
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
'use strict';
var stream = require('stream');
/**
* A stream that will multiplex data from a single stream to multiple streams.
*/
class MultiplexStream extends stream.Writable {
/**
* @see {@link Writable}
* @param {Object} [options]
*/
constructor(options) {
super(options);
this._streams = [];
}
/**
* @param {Buffer|*} chunk
* @param {string} [encoding]
* @param {function} cb
* @private
*/
_write(chunk, encoding, cb) {
for (let stream of this._streams) {
if (chunk instanceof Buffer) {
let copy = Buffer.alloc(chunk.length);
chunk.copy(copy);
stream.write(copy, encoding);
} else {
stream.write(chunk.slice(0), encoding);
}
}
setImmediate(cb);
}
/**
* @param {Writable[]} streams One or more writable streams (each argument should be a new stream).
*/
pipe(streams, options) {
for (let stream of arguments) {
this._streams = this._streams.concat((stream));
}
return this;
}
}
module.exports = MultiplexStream;