过滤请求pipe道Node.js

我是Node.js的新手,我正在使用Filestreams和Requests。 我写了一个程序,获取一个交易论坛的HTML,并过滤它获得所有职位的标题。 我的代码如下所示:

var request = require('request'); var http = require('http'); var fs = require('fs'); var server = http.createServer(); server.on('request', function(req, response){ var matches = []; var desination = fs.createWriteStream("posts.txt"); request('https://www.reddit.com/r/TagPro/top/?sort=top&t=all', function (error, response, body) { if (!error && response.statusCode == 200) { var re = /tabindex="1" >(.+?)</g; var match; while (match = re.exec(body)) { matches[matches.length] = match[1]; } } }).pipe(response); }); server.listen(8080) 

基本上数组matches保存过滤的信息,我试图pipe道内容到服务器请求的响应。

现在,我的代码pipe道整个HTML的响应,但我想知道如果我可以pipe我的数组的内容,所以只有有用的信息被写入。

你实际上是在处理这个响应两次:使用一个callback函数(在这个函数中提取匹配项) 通过pipe道传递给HTTP响应(未经修改)。

相反,你应该select一个或另一个。 最简单的方法就是不要传输数据,只要你累积了所有的匹配,就发回一个(JSON)响应:

 server.on('request', function(req, res) { var matches = []; request('https://www.reddit.com/r/TagPro/top/?sort=top&t=all', function (error, response, body) { // Handle errors properly. if (error || response.statusCode !== 200) { return res.writeHead(error ? 500 : response.statusCode); } // Accumulate the matches. var re = /tabindex="1" >(.+?)</g; var match; while (match = re.exec(body)) { matches[matches.length] = match[1]; } // Send back the array as JSON. res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(matches)); }); }); 

(请注意,我将响应对象重命名为res以防止它被requestcallback的response参数破坏)

你可以调用每个匹配的response.write()和完成时的response.write()每个匹配与前一个匹配,以便总响应具有所有正确的分隔符),而不是响应我不确定每场比赛有什么),或者你可以在一个response.end()调用中发送整组比赛。 你做什么取决于你期望有多less匹配。