-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathparser.js
More file actions
96 lines (86 loc) · 2.05 KB
/
parser.js
File metadata and controls
96 lines (86 loc) · 2.05 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
91
92
93
var expat = require('node-expat');
var fs = require('fs');
var parser;
var inputFile = process.argv[2];
var outputFile = process.argv[3];
function writeTree(tree) {
fs.appendFileSync(outputFile, "{");
fs.appendFileSync(outputFile,"\"name\":\"" + tree.text + "\"");
if(tree.children.length > 0) {
fs.appendFileSync(outputFile, ",");
fs.appendFileSync(outputFile, "\"children\":[");
for(var i=0; i<tree.children.length; i++) {
writeTree(tree.children[i]);
if(i != tree.children.length - 1) {
fs.appendFileSync(outputFile, ",");
}
}
fs.appendFileSync(outputFile, "]");
}
fs.appendFileSync(outputFile, "}");
}
if (!inputFile || !outputFile) {
console.log("Usage:node parser.js inputfile.opml outputfile.json\nYou might need to use sudo node if you do not have enough permissions.");
}
else
{
//Check if input file exists
try {
// Query the entry
var stats = fs.lstatSync(inputFile);
// Is it a directory?
if (stats.isDirectory()) {
console.log("The specified path:" + inputFile + " is a directory not file.");
}
else
{
var tree;
var currentNode;
parser = expat.createParser();
parser.on('startElement', function (name, attrs) {
if(name=="outline") {
if(tree === undefined) {
tree = {
parent:null,
text: attrs.text,
children: []
};
currentNode = tree;
}
else {
var node = {
parent:currentNode,
text: attrs.text,
children: []
};
currentNode.children.push(node);
currentNode = node;
}
}
});
parser.on('endElement', function (name) {
if(name=="outline") {
currentNode = currentNode.parent;
}
});
parser.on('error', function (err) {
console.error(err);
});
parser.on('close', function() {
try
{
writeTree(tree);
}
catch(err) {
console.log("Error writing to:" + outputFile);
console.log(err);
}
});
var inpStream = fs.createReadStream(inputFile);
inpStream.pipe(parser);
}
}
catch (e) {
console.log("Error loading file:" + inputFile);
}
}