-1

I am learning back-end and I want to use the faker library to generate about 1000 jpg files of random user images to my local folder.

Script Name: dummyImages.js

const faker = require('faker');
const makeFakeImage = function() {
  return faker.image.people();
}
makeFakeImage();

If I run this script using the command

node dummyImages.js

I expect to receive an URL link and I can save and download the image file to my local folder. However, this process is too manual and it's not the best practice. Can someone help me to refractor my script so that it can save 1000 faker image files automatically into a local folder with jpg file name going from "1" to "1000" (ex: 1.jpg 2.jpg etc...). My intent is to insert all files inside that folder into AWS S3 afterward and use them on React.

hongkongbboy
  • 300
  • 1
  • 5
  • 14
  • BTW, the reason I intend to use AWS S3 to load the images on the browser instead of loading the images through faker because I am learning the concept of optimization. When I try to load the images through faker, it takes few seconds for the images to appear, which is not good what I want. Just FYI. – hongkongbboy Feb 15 '20 at 21:14
  • What have you tried already? Stack is not a code writing service. – 2pha Feb 15 '20 at 22:40
  • This has nothing to do with faker specifically, which just generates an URL for you. You should research how to download a file to a local folder (or rather, just directly to S3?) when given its url. There are dozen of tutorials and QA posts about that already. – Bergi Feb 16 '20 at 00:11
  • Sorry if my question confuses you. I check tutorials and none is in javascript, that's why I ask that question. I posted an answer below and you can see how it is related to faker library. All a person has to do is the drag and drop the jpg files stored in that specific folder to the S3 – hongkongbboy Feb 17 '20 at 02:46

1 Answers1

0

/* eslint-disable no-plusplus */
const faker = require('faker');
const axios = require('axios');
const path = require('path');
const fs = require('fs');

const url = [];
// 100 fake avatar url from fakter
for (let i = 0; i < 100; i++) {
  url.push(faker.image.avatar());
}


// download 100 user photoes 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 following script works. Just make sure I have to npm install the right dependencies into package.json and the folder referenced "image" exists

hongkongbboy
  • 300
  • 1
  • 5
  • 14