javascript - In node.js, how do I get the Content-Length header in response to http.get()? - Stack Overflow

I have the following script and it seems as though node is not including the Content-Length header in t

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
Add a comment  | 

2 Answers 2

Reset to default 10

www.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).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1739295814a4121065.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信