-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
80 lines (69 loc) · 1.97 KB
/
index.js
File metadata and controls
80 lines (69 loc) · 1.97 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
/*
Author: Sameer Deshmukh
Description: Utility to convert large xml to json line
*/
'use strict';
const fs = require('fs');
const XmlStream = require('xml-stream');
const flags = require('flags');
flags.defineString('input', 'test.xml', 'name of input xml file');
flags.defineString('output', 'test.json', 'name of output json file');
flags.defineString('tagtoextract', '', 'name of xml tag/subtag to extract as json');
flags.defineNumber('limit', 10, 'max buffer size limit');
flags.parse();
const xml_file_path = flags.get('input');
const output_file = flags.get('output');
const xml_tag_to_extract = flags.get('tagtoextract');
let completed = 0;
let buffer = [];
function main() {
if (!fs.existsSync(xml_file_path)) {
console.warn('Input file not found');
process.exit(1);
}
if (!xml_tag_to_extract) {
console.warn('Specify xml tag to extract as json. If nothing, specify root xml tag');
process.exit(1);
}
if (fs.existsSync(output_file)) {
fs.unlinkSync(output_file);
}
parse();
}
function parse() {
const xml = fs.createReadStream(xml_file_path);
var xmlStream = new XmlStream(xml);
xmlStream.on(`endElement ${xml_tag_to_extract}`, function (element) {
buffer.push(JSON.stringify(parseOneXml(element)));
if (buffer.length >= flags.get('limit')) {
flush();
}
completed = completed + 1;
});
xmlStream.on('end', function () {
flush();
console.info('Done !!!')
process.exit(0);
});
}
function flush() {
fs.appendFileSync(output_file, buffer.join('\n') + "\n", 'utf-8');
buffer = [];
console.info(`Completed ${completed} records`);
return;
}
function parseOneXml(element) {
const newelement = {};
//If root xml tag has attributes, add it to json root
if (element['$']) {
for (const attr in element['$']) {
newelement[attr] = element['$'][attr]
}
}
//delete attribute keys
delete element['$'];
//add rest of tags as child
newelement['child'] = element;
return newelement;
}
main();