Skip to content

Instantly share code, notes, and snippets.

@hanishi
Created January 23, 2013 23:47
Show Gist options
  • Save hanishi/4615888 to your computer and use it in GitHub Desktop.
Save hanishi/4615888 to your computer and use it in GitHub Desktop.
node_in_action_3_4_2
var fs = require('fs')
, request = require('request')
, htmlparser = require('htmlparser');
var tasks = [
function () {
var configFileName = './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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment