【发布时间】: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