为了演示如何实现串行流程控制,我们准备做个小程序,让它从一个随机选择的RSS预定源中获取一片标题和URL,并显示出来。
RSS预定源列表放在rss_feeds.txt文件中,内容如下:
http://feed.cnblogs.com/blog/u/376823/rsshttp://lambda-the-ultimate.org/rss.xml
运行程序前我们需要安装两个模块:request模块是个经过简化的HTTP客户端,你可以用它获取RSS数据。htmlparser模块能把原始的RSS数据转换成JavaScript数据结构。
使用如下命令:
npm install requestnpm install htmlparser
代码如下:
var fs ?????????= require(‘fs‘);var request ????= require(‘request‘);var htmlparser ?= require(‘htmlparser‘);var configFilename = ‘./rss_feeds.txt‘;function checkForRSSFile () { ???fs.exists(configFilename, function (exists) { ???????if (!exists) ???????????return next(new Error(‘Missing RSS file: ‘ + configFilename)); ???????next(null, configFilename); ???});}function readRSSFile (configFilename) { ???fs.readFile(configFilename, function(err, feedList) { ???????if (err) return next(err); ???????feedList = feedList ???????????????????.toString() ???????????????????.replace(/~\s+|\s+$/g, ‘‘) ???????????????????.split("\n"); ???????????????var random = Math.floor(Math.random() * feedList.length); ???????next(null, feedList[random]); ???});}function downloadRSSFeed (feedUrl) { ???request({uri: feedUrl}, function(err, res, body) { ???????if (err) return next(err); ???????if (res.statusCode != 200) ???????????return next(new Error(‘Abnormal response status code‘)); ???????next(null, body); ???});}function parseRSSFeed (rss) { ???var handler = new htmlparser.RssHandler(); ???var parser = new htmlparser.Parser(handler); ???parser.parseComplete(rss); ???if (!handler.dom.items.length) ???????return next(new Error(‘No RSS items found‘)); ???????var item = handler.dom.items.shift(); ???console.log(item.title); ???console.log(item.link);}var tasks = [ checkForRSSFile, ???????????????readRSSFile, ???????????????downloadRSSFeed, ???????????????parseRSSFeed ];function next(err, result) { ???if (err) throw err; ???var currentTask = tasks.shift(); ???if (currentTask) { ???????currentTask(result); ???}}next();
Node.js 实现串行化流程控制
原文地址:http://www.cnblogs.com/sumuzhe/p/7468009.html