我正在使用axios下载图像并将其保存在本地。我从https://stackoverflow.com/a/61269447/7468791取得了以下答案,该答案对于较大的图像非常有用,以确保它们在写入之前已完全下载。
但是,某些图片网址返回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;
});
});
});
}
最佳答案
响应代码应该在response.status中可用,然后您可以检查并有条件地拒绝 promise 。
关于javascript - 使用axios接收到403错误时如何停止writestream创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64172685/