forked from chilts/node-ofx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathofx.js
More file actions
72 lines (58 loc) · 1.85 KB
/
ofx.js
File metadata and controls
72 lines (58 loc) · 1.85 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
var xml2json = require('xml2json');
function parse(data) {
// firstly, split into the header attributes and the footer sgml
var ofx = data.split('<OFX>', 2);
// firstly, parse the headers
var headerString = ofx[0].split(/\r?\n/);
var header = {};
headerString.forEach(function(attrs) {
var headAttr = attrs.split(/:/,2);
header[headAttr[0]] = headAttr[1];
});
// make the SGML and the XML
var sgml = '<OFX>' + ofx[1];
var xml = sgml
.replace(/>\s+</g, '><')
.replace(/\s+</g, '<')
.replace(/>\s+/g, '>')
.replace(/<([A-Z0-9_]*)+\.+([A-Z0-9_]*)>([^<]+)/g, '<\$1\$2>\$3' )
.replace(/<(\w+?)>([^<]+)/g, '<\$1>\$2</\$1>');
// parse the XML
var data = JSON.parse(xml2json.toJson(xml, { coerce: false }));
// put the headers into the returned data
data.header = header;
return data;
}
function serialize(header, body) {
var out = '';
// header order could matter
var headers = ['OFXHEADER', 'DATA', 'VERSION', 'SECURITY', 'ENCODING', 'CHARSET',
'COMPRESSION', 'OLDFILEUID', 'NEWFILEUID'];
headers.forEach(function(name) {
out += name + ':' + header[name] + '\n';
});
out += '\n';
out += objToOfx({ OFX: body });
return out;
}
var objToOfx = function(obj) {
var out = '';
Object.keys(obj).forEach(function(name) {
var item = obj[name];
var start = '<' + name + '>';
var end = '</' + name + '>';
if (item instanceof Object) {
if (item instanceof Array) {
item.forEach(function(it) {
out += start + '\n' + objToOfx(it) + end + '\n';
});
return;
}
return out += start + '\n' + objToOfx(item) + end + '\n';
}
out += start + item + '\n';
});
return out;
}
module.exports.parse = parse;
module.exports.serialize = serialize;