簡體   English   中英

根據文件大小取消node.js http.Client上的文件下載/請求

[英]Cancel a file download/request on node.js http.Client based on file size

我在node.js上創建了一個函數來啟動文件下載但是我想創建一個規則,其中函數在下載數據之前檢查文件大小。

我得到了響應標題並檢查了大小,但我不知道如何通過傳輸實際數據/正文來取消所有內容。 也許有一種方法只能首先傳輸標題,如果符合我的規則,我可以觸發另一個請求進行下載。

這是我的代碼片段:

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請求時發送的信息相同。 該方法可用於獲得關於請求所暗示的實體的元信息,而無需轉移實體主體本身。 此方法通常用於測試超文本鏈接的有效性,可訪問性和最近的修改。

對於HEAD請求的響應可以是可緩存的,因為響應中包含的信息可以用於從該資源更新先前緩存的實體。 如果新字段值指示緩存的實體與當前實體不同(如Content-Length,Content-MD5,ETag或Last-Modified中的更改所示),則緩存必須將緩存條目視為陳舊。

如果您的服務器對此沒有正確響應,我想您可能運氣不好? 接下來只需使用google.request('HEAD'而不是google.request('GET'


一些代碼

我測試了以下內容。 fake.js只是一個使用express來測試的假服務器。

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-client測試頭。 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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM