JavaScript Axios Loops

Viewed 30

I started learning javascript and I am trying to create a loop, that iterates through an array of URLs and downloads the images. The code I have written so far:

const axios = require('axios')
const fs = require('fs')
var imageUrls = ['url1', 'url2']
var arrayLenght = imageUrls.length

for(i = 0; i < arrayLenght; i++) {
    axios({
        method: 'get',
        url: imageUrls[i],
        responseType: 'stream'
        })
        .then(function (response) {
            response.data.pipe(fs.createWriteStream('jmeno' + i + '.jpg'))
        })
}

The problem is, that instead of saving the number of pictures the same as the number of elements in the array, it only saves one picture (seems to save the last one)

What should I change?

2 Answers

The for loop finishes much faster than the HTTP downloadings - so at the time your function is called with the image content the i variable is equal to 1, and thus all images are saved under the same filename.

Try to name your files with unique filenames.

You can use async / await inside for loop

const axios = require('axios')
const fs = require('fs')
var imageUrls = ['url1', 'url2']
var arrayLength = imageUrls.length

const forLoop = async () => {
  console.log('Start')
  for (i = 0; i < arrayLength; i++) {
    const response = await axios({
      method: 'get',
      url: imageUrls[i],
      responseType: 'stream'
    })
    response.data.pipe(fs.createWriteStream('jmeno' + i + '.jpg'))
  }
  console.log('End')
}

forLoop();
Related