0

I am trying to call an API, loop through an array of images, assign unique names to each image in the array and then write them to a local directory. If I simplify the code I can write them to the root folder .I already created the sub folder manually, so it existed prior to running the function.

Here is my basic function:

const imageFolder = './img';

function downloadImage(url, filepath) {
    client.get(url, res => {
        res.pipe(fs.createWriteStream(`${imageFolder}/${filepath}`));
    });
}

...make api call

const imagesArray = generations.data.map(item => item.generation.image_path);

imagesArray.forEach(item => {
    // const fileName = uuid.v4() + '.webp'; // trying to assign unique filename with uuid
    const fileName = new Date().getTime().toString() + '.webp'; // trying to assign unique filename with date object
    downloadImage(item, fileName);
});

If I change

res.pipe(fs.createWriteStream(`${imageFolder}/${filepath}`));

to

res.pipe(fs.createWriteStream(filepath));

then it will work but just dumps the images in the root. I was thinking perhaps I was trying to concatenate a variable name with a string (for fileName + '.webp', but it is working in the root as mentioned. See attached image.

I also tried adding the path into the actual function call inside the forEach loop like so

downloadImage(item, `${imageFolder}/${fileName}`);

I did wonder about needing the __dirname variable, or whether it could be a permissions issue, but I don't see any errors.

I am assuming this is pretty straightforward.

enter image description here

lharby
  • 3,057
  • 5
  • 24
  • 56

1 Answers1

1

OK, was fairly simple and I guess I sort of knew it once I got it working, changing to

downloadImage(item, path.join('src', 'img', fileName));

path.join concatenates folder names and fixes issues when working across platforms (OSX, Windows etc) which applies in this case as I am testing from both Windows and Mac.

lharby
  • 3,057
  • 5
  • 24
  • 56