To demonstrate how to implement serial process control, we are going to make a small program that gets a title and URL from a randomly selected RSS feed and displays it.
The RSS feed list is placed in the Rss_feeds.txt file with the following content:
Http://feed.cnblogs.com/blog/u/376823/rsshttp://lambda-the-ultimate.org/rss.xml
We need to install two modules before running the program: The request module is a simplified HTTP client that you can use to get RSS data. The Htmlparser module converts the original RSS data into a JavaScript structure.
Use the following command:
NPM Install REQUESTNPM Install Htmlparser
The code is as follows:
varFS = require (' FS ');varRequest = require (' request '));varHtmlparser = require (' Htmlparser '));varConfigfilename = './rss_feeds.txt ';functionCheckforrssfile () {fs.exists (Configfilename,function(exists) {if(!exists)returnNextNewError (' Missing RSS file: ' +configfilename)); Next (NULL, Configfilename); });}functionReadrssfile (configfilename) {fs.readfile (Configfilename,function(Err, feedlist) {if(ERR)returnNext (ERR); Feedlist=feedlist. toString (). Replace (/~\s+|\s+$/g, "). Split ("\ n"); varRandom = Math.floor (Math.random () *feedlist.length); Next (NULL, Feedlist[random]); });}functionDownloadrssfeed (Feedurl) {request ({Uri:feedurl},function(err, res, body) {if(ERR)returnNext (ERR); if(Res.statuscode! = 200) returnNextNewError (' Abnormal response status code ')); Next (NULL, body); });}functionParserssfeed (RSS) {varHandler =NewHtmlparser. RssHandler (); varParser =NewHtmlparser. Parser (handler); Parser.parsecomplete (RSS); if(!handler.dom.items.length)returnNextNewError (' No RSS items found ')); varitem =Handler.dom.items.shift (); Console.log (Item.title); Console.log (Item.link);}vartasks =[Checkforrssfile, Readrssfile, Downloadrssfeed, parserssfeed];functionNext (err, result) {if(ERR)Throwerr; varCurrenttask =Tasks.shift (); if(currenttask) {currenttask (result); }}next ();
Node. JS enables serialization of process control