-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathparser.js
More file actions
90 lines (77 loc) · 2.86 KB
/
parser.js
File metadata and controls
90 lines (77 loc) · 2.86 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Generated by CoffeeScript 1.7.1
(function() {
var EventEmitter, Header, Parser, fs, iconv,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
EventEmitter = require('events').EventEmitter;
Header = require('./header');
fs = require('fs');
iconv = require('iconv-lite');
Parser = (function(_super) {
__extends(Parser, _super);
function Parser(filename, encoding) {
this.filename = filename;
this.encoding = encoding;
this.parseField = __bind(this.parseField, this);
this.parseRecord = __bind(this.parseRecord, this);
this.parse = __bind(this.parse, this);
}
Parser.prototype.parse = function() {
this.emit('start', this);
this.header = new Header(this.filename);
this.header.parse((function(_this) {
return function(err) {
var sequenceNumber;
_this.emit('header', _this.header);
sequenceNumber = 0;
return fs.readFile(_this.filename, function(err, buffer) {
var loc;
if (err) {
throw err;
}
loc = _this.header.start;
while (loc < (_this.header.start + _this.header.numberOfRecords * _this.header.recordLength) && loc < buffer.length) {
_this.emit('record', _this.parseRecord(++sequenceNumber, buffer.slice(loc, loc += _this.header.recordLength)));
}
return _this.emit('end', _this);
});
};
})(this));
return this;
};
Parser.prototype.parseRecord = function(sequenceNumber, buffer) {
var field, loc, record, _fn, _i, _len, _ref;
record = {
'@sequenceNumber': sequenceNumber,
'@deleted': (buffer.slice(0, 1))[0] !== 32
};
loc = 1;
_ref = this.header.fields;
_fn = (function(_this) {
return function(field) {
return record[field.name] = _this.parseField(field, buffer.slice(loc, loc += field.length));
};
})(this);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
field = _ref[_i];
_fn(field);
}
return record;
};
Parser.prototype.parseField = function(field, buffer) {
var encoding, value;
encoding = 'utf-8';
if (this.encoding) {
encoding = this.encoding;
}
value = iconv.decode(buffer, encoding).replace(/^\x20+|\x20+$/g, '');
if (field.type === 'N') {
value = parseInt(value, 10);
}
return value;
};
return Parser;
})(EventEmitter);
module.exports = Parser;
}).call(this);