【问题标题】:How to send array in real time on node js?如何在节点js上实时发送数组?
【发布时间】:2020-09-02 16:24:54
【问题描述】:

我正在研究爬虫 npm。根据域,可以有 n 个 URL。现在,我想实时发送 URL。一旦数组中的一个 url 被更新,它应该触发一个事件和数据发送到前端。

  • Res.send 返回数据一次,然后显示标头设置错误。执行 res.send 后,其他值无法进一步发送,但我设法在处理完每个路由后发送数据,但我想实时发送。

有没有办法在 node.js 中实时发送数组?这里 val 是来自另一个爬虫的 URL 数组。

代码如下:

promise.then( (val) => {
var count = 0;
  let urlsarray = [];
  var element = {
    title: '',
    url: '',
    description: '',
    robots: '',
    pagesize: '',
    h1: '',
    h2: '',
    protocol: '',
    keywords: ''
  };
var c = new Crawler({
    maxConnections : 20,
    // This will be called for each crawled page
    callback : function (error, response, done) {
        if(error){
            console.log(error);
        }else{
            var $ = response.$;
             element.title = $("title").text();
             element.url = response.options.uri;
             element.description = $("meta[name=description]").attr("content");
             element.robots = $("meta[name=robots]").attr("content");
             element.pagesize = response.body.length;
             element.h1 = $("h1").text();
             element.h2 = $("h2").text();
             element.protocol = response.options.protocol;
             element.keywords = $("meta[name=keywords]").attr("content");
             var x = urlsarray.length;
             urlsarray.push(element);
             if(val.length === urlsarray.length){
            console.log(urlsarray.length);
            return res.send(urlsarray);
          }
            }
          done();
        }
      });

      c.queue(val);
    });

【问题讨论】:

    标签: node.js web-crawler


    【解决方案1】:

    我也遇到了同样的问题,我使用了带有 nuxt.js 的 socket.io。

    1. 我安装了 nuxt-socket.io 插件(如果你使用的是 vue/react/angular 则需要根据需要安装)
    2. 我将socket.io配置为socket.io.js文件中的插件
    3. 完成!现在,使用 socket.on 监听所有传入的消息/URL,使用 socket.emit 将值从前端发送到后端。这同样适用于后端。

    【讨论】:

    • 谢谢,我将它与 nuxt.js 一起使用,它工作得很好。最初,我使用 axios 发送请求和接收响应,我不得不使用超时功能并等待爬虫完成对所有 URL 的爬取。现在,socket 让获取实时 url 变得非常容易。它的完美解决方案!!!
    【解决方案2】:

    如果您使用的是实时数据,那么我建议您研究一下 websocket 协议。

    socket.io 是一个很好的框架,用于向客户端或从客户端向服务器发送实时数据。

    如果您想要视觉教程:create a messaging app

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 2017-02-04
      • 2021-08-22
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多