#how do I validate images in folders without the fs module?

5 messages · Page 1 of 1 (latest)

vague root
#

Hi, I'm very new to JS and I've been stumped on this problem for more than a day now.

I am trying to automatically extract all valid image src paths from a folder called "planets" in this case and return them as an array

I have a path structure like:

index/planets/png/1.png
index/planets/gif/1.gif
index/planets/gif/2.gif```
etc.

at first I tried not using async tasks

and building my code off of 

function isimgpathvalid(path) {
const img = new Image();
img.src = path;
try {
return img.complete && img.naturalHeight !== 0;
} catch (e) {
return false;
}
}

but ran into lots of issues with it returning undefined at some point and breaking everything

so I'm attempting to do this with async promises and the following:

async function folder2src(folder) {
try{
const imgformatfolders = ["png", "gif", "jpg"];
let srcpile = [];
for (let imgformat of imgformatfolders) {
let imgc = 1;
let shouldcontinue = true;
let check = folder + "\" + imgformat + "\" + imgc + "." + imgformat;
while (shouldcontinue) {
try {
await checkimgpromise(check);
console.log("good");
srcpile.push(check);
} catch (error) {
console.log("bad", error);
shouldcontinue = false;
break;
}
imgc++;
check = folder + "\" + imgformat + "\" + imgc + "." + imgformat;
}
}
return srcpile;
}
catch (error){return ["planet"];}
}

function checkimgpromise(src) {
return new Promise(function(resolve, reject) {
var img = new Image();
img.onload = function() {
resolve(src);
};
img.onerror = function() {
reject("Invalid image path: " + src);
};
img.src = src;
});
}

and it's a huuuuuuuuge headache

my browser console throws errors when the next file path does not lead to a valid image, like "planets\png\3.png" and all the code breaks, how do I avoid this? : (
#

If I'm doing something horribly wrong please let me know, I'm very new and don't want to end up learning things the wrong way, thank you in advance!

jaunty notch
jaunty notch
#

I don't know if it would validate them though

floral crypt
#

I probably would structure the image folder. I wonder whether all your 1.suffix are of the same planet and different fileformats for different use cases . In that case you can go on the file-name + .${suffix}
But it really depends on the logic you need