-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
105 lines (91 loc) · 2.39 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
var native = require('./build/Release/parser');
function parseDate(article) {
if (typeof article.date !== 'undefined') {
article.date = new Date(Date.parse(article.date));
}
}
// Finds "best" link for an Atom feed article.
function atomLink(article) {
var link;
var links = article.links;
var best = false;
if (links.length > 0) {
link = links[0];
}
for (var i = 0; i < links.length; i++) {
var l = links[i];
if (l.rel === 'alternate') {
if (l.type === 'text/html') {
link = l;
best = true;
} else if (!best) {
link = l;
}
}
}
if (link) {
if (link.href) {
article.link = link.href;
} else {
article.link = link.text;
}
}
}
// Postprocess a single Atom feed article.
function postProcAtomArticle(article) {
parseDate(article);
atomLink(article);
}
// Postprocess a single RSS 2 feed article.
function postProcRss2Article(article) {
parseDate(article);
}
// Postprocess the whole Atom feed.
function postProcAtom(feed) {
feed.items.forEach(postProcAtomArticle);
}
// Postprocess the whole RSS 2 feed.
function postProcRss2(feed) {
feed.items.forEach(postProcRss2Article);
}
function parseAndPostProc(xml, options) {
var result = native.parse(xml, options.content, options.extensions);
if (result.type === 'atom') {
postProcAtom(result);
} else {
postProcRss2(result);
}
return result;
}
// parse(xml, [options], [cb]).
exports.parse = function(xml, options, cb) {
// Options not given but callback is.
if (typeof options === 'function') {
cb = options;
options = {};
}
// Options not given, callback neither.
if (typeof options === 'undefined') {
options = {};
}
// Options given, add defaults for
// non-specified options.
if (typeof options.content === 'undefined') {
options.content = true;
}
if (typeof options.extensions === 'undefined') {
options.extensions = false;
}
var result;
if (typeof cb === 'function') {
try {
result = parseAndPostProc(xml, options);
cb(null, result);
} catch (err) {
cb(err);
}
} else {
result = parseAndPostProc(xml, options);
return result;
}
};