-
Notifications
You must be signed in to change notification settings - Fork 1
/
unfixated.js
69 lines (47 loc) · 1.31 KB
/
unfixated.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
var LineStream = require('byline').LineStream;
var Transform = require('stream').Transform;
var util = require('util');
util.inherits(UnFixated, Transform);
function UnFixated(format, opt) {
if (!(this instanceof UnFixated)) {
return new UnFixated(format, opt);
}
opt = opt || {};
opt.writableObjectMode = false;
opt.readableObjectMode = true;
this._options = opt;
Transform.call(this, opt);
this._format = format;
var self = this;
function lineToObject(line) {
line = line.toString();
var offset = 0;
var format = self._format;
var obj = {};
Object.keys(format).forEach(function(key) {
var value = line.substr(offset, format[key]);
value = value && value.trim();
if (value) {
obj[key] = value;
}
offset += format[key];
});
self.push(obj);
}
this.lineStream = new LineStream();
this.lineStream.on('data', lineToObject);
this.on('finish', function() {
self.lineStream.end()
})
}
UnFixated.prototype._transform = function (data, encoding, callback) {
var convert = this._options.convert;
var value = convert? convert(data): data;
if (Buffer.isBuffer(value)) {
encoding = 'utf8';
value = value.toString();
}
this.lineStream.write(value, encoding);
return callback();
};
module.exports = UnFixated;