admin管理员组文章数量:1426320
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.
http.get('', 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?
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.
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?
Share Improve this question asked Aug 26, 2013 at 17:54 mikemike 931 gold badge1 silver badge3 bronze badges 3- Drop a for(var k in res.headers) { console.log(k, res.headers[k]); } to see all the keys available in the headers. Could be a capitalization thing. – Charlie Key Commented Aug 26, 2013 at 17:56
- Thanks, but I already inspected the object tree and see everything EXCEPT the content-length header. – mike Commented Aug 26, 2013 at 17:59
- @CharlieKey All the header fields' names in the response object are lowercase, no matter what case they actually have. – Константин Ван Commented Feb 15, 2018 at 17:46
2 Answers
Reset to default 10www.google.com does not send a Content-Length
. It uses chunked encoding, which you can tell by the 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. When end
fires, you have the final size.
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.
For example:
http.get('http://www.google.com', function(res) {
console.log(res.headers['content-length']); // undefined
});
But if you request 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).
本文标签:
版权声明:本文标题:javascript - In node.js, how do I get the Content-Length header in response to http.get()? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739295814a2156900.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论