Throw error on incorrect download sizes

This commit is contained in:
2019-08-26 17:57:18 -05:00
parent b36878b80c
commit 6521f37471

View File

@@ -182,9 +182,13 @@ module.exports.downloadFile = (url, destination, progressCallback, completeCallb
.get(url, { .get(url, {
responseType: 'stream', responseType: 'stream',
}) })
.then((response) => { .then(response => {
const stream = fs.createWriteStream(destination);
const total = parseInt(response.headers['content-length'], 10); const total = parseInt(response.headers['content-length'], 10);
if (total === 0) {
throw Error('No data available for download');
} else {
const stream = fs.createWriteStream(destination);
let downloaded = 0; let downloaded = 0;
response.data.on('data', (chunk) => { response.data.on('data', (chunk) => {
stream.write(Buffer.from(chunk)); stream.write(Buffer.from(chunk));
@@ -196,18 +200,25 @@ module.exports.downloadFile = (url, destination, progressCallback, completeCallb
response.data.on('end', () => { response.data.on('end', () => {
stream.end(() => { stream.end(() => {
if (downloaded === 0) {
throw Error('Received 0 bytes');
} else if (downloaded !== total) {
throw Error('Received incorrect number of bytes');
} else {
completeCallback(); completeCallback();
}
}); });
}); });
response.data.on('error', (e) => { response.data.on('error', error => {
stream.end(() => { stream.end(() => {
completeCallback(e); completeCallback(error);
}); });
}); });
}
}) })
.catch((e)=> { .catch(error => {
completeCallback(e); completeCallback(error);
}); });
}; };