-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
128 lines (121 loc) · 2.73 KB
/
index.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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/*
index.js
Convert HTML to JSONML
Created: 2014-02-12
Copyright (c)2014 Roman Glebsky <[email protected]>
Distributed under The MIT License: http://github.com/Maqentaer/html2jsonml/raw/master/LICENSE
*/
var htmlparser2 = require('htmlparser2');
/**
* @param {string} html
* @param {object} options (optional)
* @param {function} callback (optional)
* @return {array} JsonML
*/
module.exports = function(html, options, callback)
{
if(typeof options === 'function'){
callback = options;
options = {};
}
options = options || {};
var errors = null;
var jsonMl = null;
if(typeof html === 'string'){
jsonMl = [];
var current = jsonMl;
var currentChildren = null;
var parents = [];
var parentsChildren = [];
var parser = new htmlparser2.Parser({
onopentag: function(name, attribs){
var parent = current;
parents.push(parent);
current = [name];
if(attribs){
var found = false;
for(var attr in attribs){
if(attribs.hasOwnProperty(attr)){
found = true;
break;
}
}
if(found || options.requireAttributes){
current.push(attribs);
}
}else if(options.requireAttributes){
current.push({});
}
if(options.childrenInArray){
if(!currentChildren){
currentChildren = [current];
parent.push(currentChildren);
}else{
currentChildren.push(current);
}
parentsChildren.push(currentChildren);
currentChildren = null;
}else{
parent.push(current);
}
},
ontext: function(text){
if(options.childrenInArray){
if(!currentChildren){
currentChildren = [text];
current.push(currentChildren);
}else{
currentChildren.push(text);
}
}else{
current.push(text);
}
},
onclosetag: function(name){
current = parents.pop();
if(options.childrenInArray){
currentChildren = parentsChildren.pop();
}
},
onprocessinginstruction: function(name, value){
if(!options.noProcessingInstructions)
current.push([value.substr(0,1), value.substr(1)]);
},
onerror: function(err){
if(null !== errors){
errors = [errors, err];
}else{
errors = err;
}
}
}, options);
parser.write(html);
parser.end();
if(options.childrenInArray){
jsonMl = jsonMl[0];
}
if (jsonMl.length === 1){
jsonMl = jsonMl[0];
}
else if (jsonMl.length > 1){
if(options.childrenInArray){
jsonMl = [jsonMl];
}
if(options.requireAttributes){
jsonMl.unshift({});
}
jsonMl.unshift('');
}
if(html.length && !jsonMl.length){
jsonMl = null;
}
}
if(callback){
if(null === jsonMl || null !== errors){
callback(null === errors ? new Error("Invalid HTML") : errors);
}else{
callback(null, jsonMl)
}
}
return jsonMl;
}