Created
July 28, 2017 19:25
-
-
Save akotlov/6033eb86dcfb3bd1961f52153c21b047 to your computer and use it in GitHub Desktop.
Check if downloading a file larger then a limit.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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