Cancel file upload / request on node.js http.Client based on file size

I made a function on node.js to start downloading the file, but I want to create a rule in which the function checks the file size before downloading the data.

I got the response headers and checked the size, but I don't know how to cancel everything by passing the actual data / body. Perhaps there is a way to transfer only the headers, and if it matches my rule, I can run another download request.

Here is a snippet of my code:

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

Thank.

+5
source share
1 answer

According to the specifications of the HTTP protocol 9.4 HEAD

HEAD GET , . , HTTP HEAD GET. . , .

HEAD - , , . , ( Content-Length, Content-MD5, ETag Last-Modified), .

, , ? google.request('HEAD' google.request('GET'


. fake.js - , -.

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.

+7

All Articles