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

我有下面的脚本,好像节点没有在响应对象中包含Content-Length标头。 在使用数据之前,我需要知道长度,因为数据可能相当大,所以我宁愿不缓冲它。

http.get('http://www.google.com', function(res){ console.log(res.headers['content-length']); // DOESN'T EXIST }); 

我遍历了对象树,没有看到任何东西。 所有其他标题都在“标题”字段中。

有任何想法吗?

http://www.google.com不会发送Content-Length 。 它使用分块编码 ,你可以通过Transfer-Encoding: chunked header来分辨。

如果需要响应主体的大小,请监听resdata事件,并将接收到的缓冲区的大小添加到计数器variables中。 当end时,你有最后的大小。

如果你担心大的响应,一旦你的计数器超过了多less字节,就中止请求。

不是每个服务器都会发送content-length标题。

例如:

 http.get('http://www.google.com', function(res) { console.log(res.headers['content-length']); // undefined }); 

但是如果你要求SO:

 http.get('http://stackoverflow.com/', function(res) { console.log(res.headers['content-length']); // 1192916 }); 

你正确地从响应拉头,谷歌只是不会发送到他们的主页(他们使用分块编码)。