I am a learner of JavaScript here. I have a file called downloadFakeImage.js
with the following script:
const faker = require('faker');
const axios = require('axios');
const path = require('path');
const fs = require('fs');
const url = [];
// Generate 1000 fake url from faker
for (let i=0; i<1000; i++) {
url.push(faker.image.fashion());
}
// Download 1000 user photos to local image folder
for (let i=0; i<url.length; i++) {
// path for image storage
const imagePath = path.join(__dirname, './image', `${i}.jpg`);
axios({
method: 'get',
url: url[i],
responseType: 'stream'
})
.then((response) => {
response.data.pipe(fs.createWriteStream(imagePath));
});
}
The goal of this script is to generate 1000 fake fashion images to a folder named image
. When I run node downloadFakeImage.js
in my terminal, only some of the images get to save into the folder. My terminal show whole brunch of the following error message:
Error message from the terminal that I received
I think this might be related to an async issue, can someone teaches me how to refractor my script to make it work?
Update:
I refactored my code to the following and I was able to generate some images, but I still cannot generate 1000 images. For the first 300 images, it was running ok and then it failed.
const faker = require('faker');
const axios = require('axios');
const path = require('path');
const fs = require('fs');
async function seedImage() {
const url = [];
// Generate 1000 fake url from faker
for (let i = 0; i < 1000; i++) {
url.push(faker.image.fashion());
}
// Download 1000 user photos to local image folder
for (let i = 0; i < url.length; i++) {
// path for image storage
const imagePath = await path.join(__dirname, './image', `${i}.jpg`);
axios({
method: 'get',
url: url[i],
responseType: 'stream'
})
.then((response) => {
response.data.pipe(fs.createWriteStream(imagePath));
})
.catch((error) => {
console.log(error);
});
}
}
seedImage();