0

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?

1 Answer 1

1

Wrapping the axios request in the Promise instead of the other way around fixed it:

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))
    })
  })
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.