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

时间:2021-11-24 21:14:22

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.

我有以下脚本,似乎节点不包括响应对象中的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?

2 个解决方案

#1


7  

www.google.com does not send a Content-Length. It uses chunked encoding, which you can tell by the Transfer-Encoding: chunked header.

www.google.com不发送内容长度。它使用分块编码,您可以通过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.

如果需要响应主体的大小,请侦听res的数据事件,并将接收到的缓冲区的大小添加到计数器变量中。结束射击时,你有最终的大小。

If you're worried about large responses, abort the request once your counter goes above how ever many bytes.

如果你担心大的响应,一旦你的计数器高于多少字节,就中止请求。

#2


3  

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:

但是如果你要求SO:

http.get('http://*.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).

你正确地从响应中提取了这个标题,谷歌只是不在他们的主页上发送它(他们使用分块编码代替)。

#1


7  

www.google.com does not send a Content-Length. It uses chunked encoding, which you can tell by the Transfer-Encoding: chunked header.

www.google.com不发送内容长度。它使用分块编码,您可以通过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.

如果需要响应主体的大小,请侦听res的数据事件,并将接收到的缓冲区的大小添加到计数器变量中。结束射击时,你有最终的大小。

If you're worried about large responses, abort the request once your counter goes above how ever many bytes.

如果你担心大的响应,一旦你的计数器高于多少字节,就中止请求。

#2


3  

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:

但是如果你要求SO:

http.get('http://*.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).

你正确地从响应中提取了这个标题,谷歌只是不在他们的主页上发送它(他们使用分块编码代替)。