I have created an image downloader in node.js. However when downloading images there is a chance the download will not complete, leaving me with a partially downloaded image (lo
The response event may be triggered prior to receiving all of the data. The pipe
method can be used to write data to the destination stream as it becomes available, and should keep writing until there's no more. You can capture the status code and remove the file if the status is not 200 (otherwise it may contain an error response).
...
let response = null;
...
progress(request(url)
).on('progress', function(state){
reportDownloadSpeed(state.speed);
}).on('end', function () {
if (response.statusCode != 200){
console.log(`remove: ${filename}`);
fs.unlinkSync(filename);
}
}).on('response', function(resp){
response = resp;
}).on('error', function(resp){
reject(error);
}).pipe(fs.createWriteStream(filename));