停止在nodejs请求中下载数据

我们如何能够停止服务器的剩余响应 – 例如。

http.get(requestOptions, function(response){ //Log the file size; console.log('File Size:', response.headers['content-length']); // Some code to download the remaining part of the response? }).on('error', onError); 

我只想logging文件大小,而不是浪费我的带宽下载剩余的文件。 nodejs是否自动处理这个问题,还是我必须为它编写一些特殊的代码?

如果你只想获取文件的大小,最好使用HTTP HEAD ,它只返回服务器的响应头而不包含主体。

你可以像这样在Node.js中创build一个HEAD请求:

 var http = require("http"), // make the request over HTTP HEAD // which will only return the headers requestOpts = { host: "www.google.com", port: 80, path: "/images/srpr/logo4w.png", method: "HEAD" }; var request = http.request(requestOpts, function (response) { console.log("Response headers:", response.headers); console.log("File size:", response.headers["content-length"]); }); request.on("error", function (err) { console.log(err); }); // send the request request.end(); 

编辑:

我意识到我没有真正回答你的问题,这本质上是“如何在Node.js中尽早终止请求?”。 您可以通过调用response.destroy()来终止处理过程中的任何请求:

 var request = http.get("http://www.google.com/images/srpr/logo4w.png", function (response) { console.log("Response headers:", response.headers); // terminate request early by calling destroy() // this should only fire the data event only once before terminating response.destroy(); response.on("data", function (chunk) { console.log("received data chunk:", chunk); }); }); 

你可以通过注释掉destroy()调用来testing这个,并且在完整的请求中观察到返回两个块。 就像其他地方提到的一样,简单地使用HTTP HEAD会更高效。

您需要执行HEAD请求而不是get

从这个答案采取

 var http = require('http'); var options = { method: 'HEAD', host: 'stackoverflow.com', port: 80, path: '/' }; var req = http.request(options, function(res) { console.log(JSON.stringify(res.headers)); var fileSize = res.headers['content-length'] console.log(fileSize) } ); req.end();