我正在使用 axios 下载图像并将它们保存在本地。我从https://stackoverflow.com/a/61269447/7468791获取了以下答案,该答案适用于较大的图像,以确保它们在写入之前已完全下载。
但是,某些图像 url 返回 403 错误。我仍然得到为这些创建的图像文件,尽管是一个空文件。我如何调整代码,以便如果 get 请求收到 403 错误,它不会尝试编写任何内容?
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;
});
});
});
}