zoukankan      html  css  js  c++  java
  • Node.js 实现串行化流程控制

    为了演示如何实现串行流程控制,我们准备做个小程序,让它从一个随机选择的RSS预定源中获取一片标题和URL,并显示出来。

    RSS预定源列表放在rss_feeds.txt文件中,内容如下:

    http://feed.cnblogs.com/blog/u/376823/rss
    http://lambda-the-ultimate.org/rss.xml

    运行程序前我们需要安装两个模块:request模块是个经过简化的HTTP客户端,你可以用它获取RSS数据。htmlparser模块能把原始的RSS数据转换成JavaScript数据结构。

    使用如下命令:

    npm install request
    npm 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("
    ");
            
            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();
  • 相关阅读:
    VScode出现无法打开“X”: 找不到文件(file:///XXXX) 的解决办法
    Re:0通过服务器自建内网穿透远程桌面(10分钟可完成)
    (补题 POJ 3013) Big Christmas Tree
    (补题 cf 1140)Detective Book
    (2019.9.5~2019.9.11)补题汇总(字符串相关)
    最小生成树(克鲁斯卡尔算法)
    最短路问题
    字符串匹配(部分整理)
    Linux内核分析——第八周学习笔记
    《Linux内核设计与实现》第四章读书笔记
  • 原文地址:https://www.cnblogs.com/sumuzhe/p/7468009.html
Copyright © 2011-2022 走看看