最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论