两者
如果你只是想获取文件的大小,最好是使用HTTP HEAD,这不带主体返回服务器的响应头。
你可以像这样的Node.js 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);
});
});
您可以通过注释掉的破坏()调用和观察,在一个完整的请求都返回了两个区块进行测试。然而,正如其他地方所提到的那样,简单地使用HTTP HEAD会更有效率。
谢谢,为答案。它和response.end()有何不同,我应该什么时候使用它? – Tushar 2013-04-24 16:39:33
还有一件事,如果我没有将监听器绑定到“数据”事件,数据是否仍然会被传输?我的意思是我的带宽会不必要地浪费? – Tushar 2013-04-24 16:54:56
是的,即使您不处理“数据”事件,数据仍将被发送到客户端。 – 2013-04-24 20:29:23