javascript 在 node.js 中,如何获取响应 http.get() 的 Content-Length 标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18450054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In node.js, how do I get the Content-Length header in response to http.get()?
提问by mike
I have the following script and it seems as though node is not including the Content-Length header in the response object. I need to know the length before consuming the data and since the data could be quite large, I'd rather not buffer it.
我有以下脚本,似乎 node 没有在响应对象中包含 Content-Length 标头。我需要在使用数据之前知道长度,并且由于数据可能非常大,我宁愿不缓冲它。
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?
有任何想法吗?
采纳答案by josh3736
www.google.com does not send a Content-Length. It uses chunked encoding, which you can tell by the Transfer-Encoding: chunkedheader.
www.google.com 不会发送Content-Length. 它使用分块编码,您可以通过Transfer-Encoding: chunked标头来判断。
If you want the size of the response body, listen to res's dataevents, and add the size of the received buffer to a counter variable. When endfires, you have the final size.
如果您想要响应正文的大小,请侦听res的data事件,并将接收到的缓冲区的大小添加到计数器变量中。当end火灾,你有最后的大小。
If you're worried about large responses, abort the request once your counter goes above how ever many bytes.
如果您担心大的响应,一旦您的计数器超过多少字节就中止请求。
回答by Chad
Not every server will send content-lengthheaders.
并非每个服务器都会发送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).
您正确地从响应中提取该标头,谷歌只是没有在他们的主页上发送它(他们使用分块编码)。

