Skip to content

Instantly share code, notes, and snippets.

@akotlov
Created July 28, 2017 19:25
Show Gist options
  • Save akotlov/6033eb86dcfb3bd1961f52153c21b047 to your computer and use it in GitHub Desktop.
Save akotlov/6033eb86dcfb3bd1961f52153c21b047 to your computer and use it in GitHub Desktop.
Check if downloading a file larger then a limit.
var maxSize = 10485760;
request({
url: url,
method: "HEAD"
}, function(err, headRes) {
var size = headRes.headers['content-length'];
if (size > maxSize) {
console.log('Resource size exceeds limit (' + size + ')');
} else {
var file = fs.createWriteStream(filename),
size = 0;
var res = request({ url: url });
res.on('data', function(data) {
size += data.length;
if (size > maxSize) {
console.log('Resource stream exceeded limit (' + size + ')');
res.abort(); // Abort the response (close and cleanup the stream)
fs.unlink(filename); // Delete the file we were downloading the data to
}
}).pipe(file);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment