-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfeedparser.js
More file actions
61 lines (50 loc) · 1.89 KB
/
feedparser.js
File metadata and controls
61 lines (50 loc) · 1.89 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
// Adapted from https://github.com/danmactough/node-feedparser#usage
const request = require("request");
const FeedParser = require("feedparser");
exports.parse = requestedFeed =>
new Promise((resolve, reject) => {
let feedResponse = {};
let feedItems = [];
// Set up the request for the feed.
const feedRequest = request(requestedFeed);
// We're not setting options because the defaults are fine.
const options = [];
const feedparser = new FeedParser([options]);
feedRequest.on("error", function(error) {
// Reject the Promise by returning an error, with the origin
// of the error set to the request.
reject({ error: error, origin: "request" });
});
feedRequest.on("response", function(response) {
if (response.statusCode !== 200) {
// If we didn't get a 200 OK, emit an error.
feedRequest.emit("error", new Error("Bad status code: " + response.statusCode));
} else {
// Otherwise, pipe the request into feedparser.
feedRequest.pipe(feedparser);
}
});
feedparser.on("error", function(error) {
// Reject the Promise by returning an error, with the origin
// of the error set to feedparser.
reject({ error: error, origin: "feedparser" });
});
feedparser.on("meta", function(meta) {
// When the meta event is received, add it as a property on feedResponse.
feedResponse.meta = meta;
});
feedparser.on("readable", function() {
var stream = this,
item;
while ((item = stream.read())) {
// Push each item in the feed into the feedItems array.
feedItems.push(item);
}
});
feedparser.on("end", function() {
// Add the feedItems array as a property on feedResponse.
feedResponse.items = feedItems;
// Resolve the Promise and return the feedResponse object.
resolve(feedResponse);
});
});