-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom_story.js
64 lines (61 loc) · 1.81 KB
/
random_story.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
var fs = require('fs')
, request = require('request')
, htmlparser = require('htmlparser');
var tasks = [
function () {
var configFilename = './data/rss_feeds.txt';
fs.exists(configFilename, function (exists) {
if (!exists) {
next('Create a list of RSS feeds in the file ./rss_feeds.txt.');
} else {
next(false, configFilename);
}
});
},
function (configFilename) {
fs.readFile(configFilename, function (err, feedList) {
if (err) {
next(err.message);
} else {
feedList = feedList
.toString()
.replace(/^\s+|\s+$/g, '')
.split("\n");
var random = Math.floor(Math.random()
* feedList.length);
next(false, feedList[random]);
}
});
},
function (feedUrl) {
request({uri: feedUrl}, function (err, response, body) {
if (err) {
next(err.message);
} else if (response.statusCode == 200) {
next(false, body);
} else {
next('Abnormal request status code.');
}
});
},
function (rss) {
var handler = new htmlparser.RssHandler();
var parser = new htmlparser.Parser(handler);
parser.parseComplete(rss);
if (handler.dom.items.length) {
var item = handler.dom.items.shift();
console.log(item.title);
console.log(item.link);
} else {
next('No RSS items found.');
}
}
];
function next(err, result) {
if (err) throw new Error(err);
var currentTask = tasks.shift();
if (currentTask) {
currentTask(result);
}
}
next();