In the code below I'm looping through an array of image URLs and for each image URL I downlaod the image and save it in a folder:
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)
}
When I then click on my /temp folder, the image file is there and working.
What am I doing wrong?