如何在Node.js中用http.request限制响应长度

所以在这个(简化的)代码中,当有人点击我的节点服务器时,我向另一个网站发出GET请求,并将HTML页面标题打印到控制台。 工作正常:

var http = require("http"); var cheerio = require('cheerio'); var port = 8081; s = http.createServer(function (req, res) { var opts = { method: 'GET', port: 80, hostname: "pwoing.com", path: "/" }; http.request(opts, function(response) { console.log("Content-length: ", response.headers['content-length']); var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function() { dom = cheerio.load(str); var title = dom('title'); console.log("PAGE TITLE: ",title.html()); }); }).end(); res.end("Done."); }).listen(port, '127.0.0.1'); 

但是,在实际的应用程序中,用户可以指定要打的URL。 这意味着我的节点服务器可能正在下载20GB电影文件或任何。 不好。 内容长度标题不能用于停止,因为它不会被所有的服务器传送。 那么问题是:

我怎么能告诉它停止GET请求,比如说,收到的第一个10KB?

干杯!

一旦读取了足够的数据,就可以中止请求:

  http.request(opts, function(response) { var request = this; console.log("Content-length: ", response.headers['content-length']); var str = ''; response.on('data', function (chunk) { str += chunk; if (str.length > 10000) { request.abort(); } }); response.on('end', function() { console.log('done', str.length); ... }); }).end(); 

这将在大约 10.000字节中止请求,因为数据以各种大小的块到达。