2013-04-24 103 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