如何使用Node.js中的http.request限制响应长度 [英] How to limit response length with http.request in Node.js
问题描述
所以在这个(简化的)代码中,当有人点击我的节点服务器时,我向另一个网站发出GET请求并将HTML页面标题打印到控制台。工作正常:
So in this (simplified) bit of code, when someone hits my node server I make a GET request to another website and print the HTML page title to the console. Works fine:
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的电影文件或其他什么。不好。内容长度标头不能用于停止它,因为它不是由所有服务器传输的。接下来的问题是:
However, in the actual app, users can specify a URL to hit. That means my node server could be downloading 20GB movie files or whatever. Not good. The content-length header is no use for stopping this either as it isn't transmitted by all servers. The question then:
如果收到前10KB后我怎么能告诉它停止GET请求?
干杯!
推荐答案
您可以在读取足够数据后中止请求:
You could abort the request once you have read enough data:
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字节处中止请求,因为数据到达各种尺寸的块。
This will abort the request at around 10.000 bytes, since the data arrives in chunks of various sizes.
这篇关于如何使用Node.js中的http.request限制响应长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!