I'm downloading content from a server that might be compressed, so I'm using this boilerplate I found in various places:
var file = fs.createWriteStream(filename);
var request = https.get(url, function(response) {
switch (response.headers['content-encoding']) {
case 'gzip':
response.pipe(zlib.createGunzip()).pipe(file);
break;
case 'deflate':
response.pipe(zlib.createInflate()).pipe(file);
break;
default:
response.pipe(file);
break;
}
file.on('finish', function() {
console.log("Done: "+url);
file.close(function() {});
});
}).on('error', function(err) { // Handle errors
fs.unlink(filename, function() {});
console.log(err+" "+url);
});
Trouble is, if the HTTPS request fails from a network error, I sometimes get this exception thrown:
Error: unexpected end of file
at Zlib._handle.onerror (zlib.js:363:17)
The exception isn't caught by that "error" event handler. So how do I catch it, so I can clean up the file properly and know to try again?