2013-04-24 30 views
5

Bir sunucudan kalan yanıtı nasıl durdurabiliriz - Örneğin.Veriyi indirme isteğini iptal et

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); 

Sadece dosya boyutunu log ve kalan dosya indirme benim bant genişliği boşa istiyorum. Nodejs bunu otomatik olarak halleder mi yoksa bunun için özel bir kod yazmam gerekir mi?

cevap

9

Alındığı almak yerine bir BAŞ isteği gerçekleştirmek için gereken, bu HTTP HEAD, kullanmak en iyisidir hangi Sadece gövde olmadan sunucudan yanıt başlıkları döndürür.

Böyle node.js bir HEAD isteği yapabilirsiniz:

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

DÜZENLEME:

ben gerçekten nasıl" temelde soru, cevap vermedi fark Node.js'de bir isteği erken sonlandırıyorum? " Sen) (response.destroy çağırarak işleme ortasında herhangi bir isteği kesebilirler:

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); 
    }); 
}); 

Yoketmek() çağrısını dışında yorum ve tam istekte iki parçalar döndürülür olduğunu gözlemleyerek bu test edebilirsiniz. Bununla birlikte, başka yerlerde belirtildiği gibi, HTTP HEAD'sini kullanmak daha verimlidir.

+0

Teşekkürler, cevap için. Response.end() 'den nasıl farklıdır ve bunu ne zaman kullanmalıyım? – Tushar

+0

Bir şey daha, eğer 'veri' olayına bir dinleyici bağlamazsam, veriler hala aktarılacak mı? Yani bant genişliğim gereksiz yere boşa harcanacak mı? – Tushar

+0

Evet, "veri" olayını işlemeseniz bile veriler yine de müşteriye gönderilir. –

3

Sen sadece dosyanın boyutunu getirme istiyorsanız

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

Teşekkürler Nuh, Bu yaklaşımın farkında değildim. – Tushar

İlgili konular