2013-04-24 108 views
5

如何停止服務器的剩餘響應 - 例如,停止在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); 

我只是想記錄文件大小,而不是浪費我的帶寬下載剩餘的文件。 nodejs是否自動處理這個問題,還是我必須爲它編寫一些特殊的代碼?

回答

9

兩者

如果你只是想獲取文件的大小,最好是使用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會更有效率。

+0

謝謝,爲答案。它和response.end()有何不同,我應該什麼時候使用它? – Tushar 2013-04-24 16:39:33

+0

還有一件事,如果我沒有將監聽器綁定到「數據」事件,數據是否仍然會被傳輸?我的意思是我的帶寬會不必要地浪費? – Tushar 2013-04-24 16:54:56

+0

是的,即使您不處理「數據」事件,數據仍將被髮送到客戶端。 – 2013-04-24 20:29:23

3

您需要執行HEAD請求,而不是得到this answer

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(); 
+0

感謝諾亞,我不知道這種方法。 – Tushar 2013-04-24 16:53:57