UNPKG

1.11 kBJavaScriptView Raw
1const Streamz = require('streamz');
2const util = require('util');
3
4function Cut(maxLen,options) {
5 if (!(this instanceof Cut))
6 return new Cut(maxLen,options);
7
8 if(!maxLen && isNaN(maxLen))
9 throw 'MaxLen not defined';
10
11 Streamz.call(this,options);
12
13 this.maxLen = +maxLen;
14 this.options = options || {};
15}
16
17util.inherits(Cut,Streamz);
18
19Cut.prototype.buffer = '';
20
21Cut.prototype._proto = {};
22
23Cut.prototype.line = 0;
24
25Cut.prototype._push = function(end) {
26 if (this.buffer.length < this.maxLen && !end)
27 return;
28
29 const obj = Object.create(this._proto);
30 obj.text = this.buffer.slice(0,this.maxLen);
31 obj.__line = this.line++;
32 this.push(obj);
33 this.buffer = this.buffer.slice(this.maxLen);
34 return this._push();
35};
36
37Cut.prototype._fn = function(d) {
38 if (d instanceof Buffer || typeof d !== 'object')
39 d = d.toString('utf8');
40
41 if (typeof d === 'object') this._proto = d;
42 this.buffer += (typeof d == 'string') ? d : d.text;
43
44 this._push();
45};
46
47Cut.prototype._flush = function(cb) {
48 this._push();
49 setImmediate( () => Streamz.prototype._flush(cb));
50};
51
52module.exports = Cut;
\No newline at end of file