根据文件大小取消node.js http.Client上的文件下载/请求

我在node.js上做了一个函数来启动一个文件下载,但是我想在下载数据之前创build一个函数检查文件大小的规则。

我得到了响应标题,并检查了大小,但我不知道如何取消所有传输实际的数据/正文。 也许有一种方法只是首先传输标题,如果符合我的规则,我可以触发另一个请求来执行下载。

这是我的代码片段:

request.on('response', function(response) { var filesize = response.headers['content-length']; console.log("File size " + filename + ": " + filesize + " bytes."); response.pause(); if (filesize >= 50000) { // WHAT TO PUT HERE TO CANCEL THE DOWNLOAD? console.log("Download cancelled. File too big."); } else { response.resume(); } //Create file and write the data chunks to it 

谢谢。

根据HTTP协议规范9.4 HEAD

HEAD方法与GET相同,只是服务器不能在响应中返回消息体。 响应HEAD请求的HTTP头中包含的元信息应该与响应GET请求发送的信息相同。 这个方法可以用来获得有关请求隐含的实体的元信息,而不用传递实体主体本身。 此方法通常用于testing超文本链接的有效性,可访问性和最近的修改。

对于HEAD请求的响应可能是可caching的,因为响应中包含的信息可能被用来从该资源更新先前caching的实体。 如果新字段值指示caching实体与当前实体不同(如Content-Length,Content-MD5,ETag或Last-Modified中的更改所指示的那样),则caching必须将caching条目视为陈旧。

如果你的服务器没有正确回应这个问题,我想你可能会运气不好。 接下来只需使用google.request('HEAD'而不是google.request('GET'


一些代码

我testing了下面的内容。 fake.js只是一个使用快递进行testing的假服务器。

fake.js:

 var HOST = 'localhost'; var PORT = 3000; var connections = 0; var express = require('express'); var app = module.exports = express.createServer(); if (process.argv[2] && process.argv[3]) { HOST = process.argv[2]; PORT = process.argv[3]; } app.use(express.staticProvider(__dirname + '/public')); // to reconnect. app.get('/small', function(req, res) { console.log(req.method); if (req.method == 'HEAD') { console.log('here'); res.send(''); } else { connections++; res.send('small'); } }); app.get('/count', function(req, res) { res.send('' + connections); }); app.get('/reset', function(req, res) { connections = 0; res.send('reset'); }); if (!module.parent) { app.listen(PORT, HOST); console.log("Express server listening on port %d", app.address().port) } 

test.js是从http-clienttesting头。 test.js:

 var http = require('http'); var google = http.createClient(3000, 'localhost'); var request = google.request('HEAD', '/small', {'host': 'localhost'}); request.end(); request.on('response', function (response) { console.log('STATUS: ' + response.statusCode); console.log('HEADERS: ' + JSON.stringify(response.headers)); response.setEncoding('utf8'); }); 

 alfred@alfred-laptop:~/node/stackoverflow/4832362$ curl http://localhost:3000/count 0 

 alfred@alfred-laptop:~/node/stackoverflow/4832362$ node test.js STATUS: 200 HEADERS: {"content-type":"text/html; charset=utf-8","content-length":"0","connection":"close"} 

 alfred@alfred-laptop:~/node/stackoverflow/4832362$ curl http://localhost:3000/count 0 

正如你所看到的仍然是0。