问题描述
我们如何停止服务器剩余的响应-例如.
How can we stop the remaining response from a server -For eg.
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自动处理此问题还是我必须为此编写一些特殊代码?
I just want to log the file size and not waste my bandwidth in downloading the remaining file. Does nodejs automatically handles this or do I have to write some special code for it?
推荐答案
如果只想获取文件的大小,则最好使用,它仅返回来自服务器的响应标头,而没有正文.
If you just want fetch the size of the file, it is best to use HTTP HEAD, which returns only the response headers from the server without the body.
您可以像这样在Node.js中发出HEAD请求:
You can make a HEAD request in Node.js like this:
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()终止任何请求:
I realized that I didn't really answer your question, which is essentially "How do I terminate a request early in Node.js?". You can terminate any request in the middle of processing by calling 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);
});
});
您可以通过注释掉destroy()调用并观察到在完整请求中返回两个块来进行测试.但是,就像在其他地方提到的那样,仅使用HTTP HEAD更为有效.
You can test this by commenting out the the destroy() call and observing that in a full request two chunks are returned. Like mentioned elsewhere, however, it is more efficient to simply use HTTP HEAD.
这篇关于停止下载Node.js请求中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!