兩者
如果你只是想獲取文件的大小,最好是使用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