-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sink.js
51 lines (44 loc) · 1.27 KB
/
Sink.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
50
51
'use strict';
var stream = require('stream');
/**
* A stream that consumes all data written to it. Supports buffering data for later consumption.
*/
class Sink extends stream.Writable {
/**
* @see {@link Writable}
* @param {Object} [options]
* @property {boolean|Buffer[]} [options.buffer] Enable buffering or pass in an array reference where data will be stored.
*/
constructor(options) {
super(options);
if (options) {
this._buffer = options.buffer instanceof Array ? options.buffer : [];
}
}
_write(chunk, encoding, cb) {
this._buffer && this._buffer.push(chunk instanceof Buffer ? chunk : new Buffer(chunk, encoding));
setImmediate(cb);
}
/**
* Returns a reference to the buffer used by the sink (if one has been set).
* @returns {Buffer[]}
*/
get buffer() {
return this._buffer;
}
/**
* Returns the buffered string as one message.
* @param {string} [encoding='utf8'] The encoding used to generate the string from the buffer.
* @returns {string}
*/
message(encoding = 'utf8') {
return this._buffer ? Buffer.concat(this._buffer).toString(encoding) : '';
}
/**
* Clears the buffer (if there is any).
*/
clear() {
this._buffer && (this._buffer.length = 0);
}
}
module.exports = Sink;