简体   繁体   English

在node.js中,如何获取Content-Length头以响应http.get()?

[英]In node.js, how do I get the Content-Length header in response to http.get()?

I have the following script and it seems as though node is not including the Content-Length header in the response object. 我有以下脚本,似乎节点不包括响应对象中的Content-Length标头。 I need to know the length before consuming the data and since the data could be quite large, I'd rather not buffer it. 我需要知道消耗数据之前的长度,因为数据可能非常大,我宁愿不缓冲它。

http.get('http://www.google.com', function(res){    

    console.log(res.headers['content-length']); // DOESN'T EXIST
});

I've navigated all over the object tree and don't see anything. 我已经遍布对象树,没有看到任何东西。 All other headers are in the 'headers' field. 所有其他标题都在“标题”字段中。

Any ideas? 有任何想法吗?

www.google.com does not send a Content-Length . www.google.com不发送Content-Length It uses chunked encoding , which you can tell by the Transfer-Encoding: chunked header. 它使用分块编码 ,您可以通过Transfer-Encoding: chunked header告诉它。

If you want the size of the response body, listen to res 's data events, and add the size of the received buffer to a counter variable. 如果需要响应主体的大小,请侦听resdata事件,并将接收到的缓冲区的大小添加到计数器变量中。 When end fires, you have the final size. end射击时,你有最终的大小。

If you're worried about large responses, abort the request once your counter goes above how ever many bytes. 如果你担心大的响应,一旦你的计数器高于多少字节,就会中止请求。

Not every server will send content-length headers. 并非每个服务器都会发送content-length标头。

For example: 例如:

http.get('http://www.google.com', function(res) {
    console.log(res.headers['content-length']); // undefined
});

But if you request SO: 但是如果你要求SO:

http.get('http://stackoverflow.com/', function(res) {
    console.log(res.headers['content-length']); // 1192916
});

You are correctly pulling that header from the response, google just doesn't send it on their homepage (they use chunked encoding instead). 你正确地从响应中提取了这个标题,谷歌只是不在他们的主页上发送它(他们使用分块编码代替)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM