• node lesson4--eventproxy不懂


    var express = require('express');
    var superagent = require('superagent');
    var cheerio = require('cheerio');
    var eventproxy = require('eventproxy');
    var url = require('url');// url 模块是 Node.js 标准库里面的
    var app = express();
    var cnodeurl = 'https://cnodejs.org/';
    app.get('/', function(req, res, next){
        superagent.get('https://cnodejs.org/')
        .end(function(err, sres){
                if(err){
                    return next(err);//It passes control to the next matching route,参数err是???
                }
                var $ = cheerio.load(sres.text);
                var topicUrls = [];
                $("#topic_list .topic_title").each(function(idx, ele){
                    var $ele = $(ele);
                    var href = $ele.attr('href');
                    var jumpHref = url.resolve(cnodeurl, href);
                    topicUrls.push(jumpHref);
                })
                //res.send(topicUrls);//好像res.send()必须有
                // 命令 ep 重复监听 topicUrls.length 次(在这里也就是 40 次) `topic_html` 事件再行动
                var ep = new eventproxy();// 得到一个 eventproxy 的实例
                ep.after('topic_html', topicUrls.length, function(topics){
                    // topics 是个数组,包含了 40 次 ep.emit('topic_html', pair) 中的那 40 个 pair
                    // 在所有文件的异步执行结束后将被执行
                    // 所有文件的内容都存在topics数组中
                    //开始行动
                    topics = topics.map(function(topicPair){//topics里的每一个元素
                        var topicUrl = topicPair[0];
                        var topicHtml = topicPair[1];
                        var $ = cheerio.load(topicHtml);
                        return ({
                            title: $('.topic_full_title').text().trim(),
                            href: topicUrl,
                            comment1: $('.reply_content').eq(0).text().trim()
                        })
                    })
                    console.log('final: ');
                    console.log(topics);
                });
                topicUrls.forEach(function(topicUrl){
                    superagent.get(topicUrl)
                    .end(function(err, res){
                            console.log('fetch ' + topicUrl + ' successfully');
                            ep.emit('topic_html', [topicUrl, res.text])//触发事件,并且执行所有监听器
                            //emit 相当于jQuery里的trigger
                        })
                });
    
            });
    });
    app.listen(8000, function(){
        console.log("app start");
    })

    https://github.com/alsotang/node-lessons/tree/master/lesson4

  • 相关阅读:
    CF91 B. Queue
    CF18 C. Stripe
    CF767 A. Snacktower
    CF349 B. Color the Fence
    CF519 B. A and B and Compilation Errors
    NLog Helpper日志帮助类配置和使用
    一步一步搭建 .net core 应用
    使用webform、websevice来进行ajax请求操作
    各种奇技淫巧-持续更新
    防止表单提交时刷新页面-阻止form表单的默认提交行为
  • 原文地址:https://www.cnblogs.com/darr/p/4864658.html
Copyright © 2020-2023  润新知