在下面的代码中,我循环遍历图像URL数组,对于每个图像URL,我下载图像并将其保存在文件夹中:
function downloadImg (url, imagePath) {
axios({ url, responseType: 'stream' }).then((response) => {
return new Promise((resolve, reject) => {
response.data
.pipe(fs.createWriteStream(imagePath))
.on('finish', () => resolve())
.on('error', e => reject(e));
})
})
}
for (const img of imgs) {
let imgPath = `${__dirname}/temp/${img.id}.jpg`
let downloadedImg = await downloadImg(img.media_url, imgPath)
console.log(imgPath) // returns the correct path
console.log(fs.existsSync(imgPath)) // returns false
// throws fs.readFileSync Error: "no such file or directory, open {imgPath}"
doSomethingWith(imgPath)
}
当我点击我的/temp
文件夹时,图像文件在那里并工作。
我做错了什么?
在Promise中包装axios请求而不是其他方式修复它:
function downloadImg (url, imagePath) {
return new Promise((resolve, reject) => {
axios({ url, responseType: 'stream' }).then((response) => {
response.data
.pipe(fs.createWriteStream(imagePath))
.on('finish', () => resolve())
.on('error', e => reject(e))
})
})
}