I'm using axios to download images and save them locally. I took the below answer from https://stackoverflow.com/a/61269447/7468791 which works great for larger images to make sure they have fully downloaded before writing.
However some image urls are returning a 403 error. I'm still getting an image file created for these albeit an empty file. How could I tweak the code so that if the get request receives a 403 error it will not try to write anything?
export async function downloadFile(fileUrl: string, outputLocationPath: string) {
const writer = createWriteStream(outputLocationPath);
return Axios({
method: 'get',
url: fileUrl,
responseType: 'stream',
}).then(response => {
//ensure that the user can call `then()` only when the file has
//been downloaded entirely.
return new Promise((resolve, reject) => {
response.data.pipe(writer);
let error = null;
writer.on('error', err => {
error = err;
writer.close();
reject(err);
});
writer.on('close', () => {
if (!error) {
resolve(true);
}
//no need to call the reject here, as it will have been called in the
//'error' stream;
});
});
});
}
The response code should be available in response.status, and you can then check and conditionally reject the promise.