This is my first time posting a question to stack overflow but I will try my best to explain it. I am trying to load .jpg info from a folder on my server to an Array with each image going to a different location. Currently, I can get just jpg images but they all go to image[0]. I'm trying to do this with nodejs and fs if possible.
The code is:
const fs = require("fs");
function getFolderFiles(path, extension) {
let files = fs.readdirSync(path);
return files.filter((file) =>
file.match(new RegExp(`.*\.(${extension})`, "ig"))
);
}
console.log(getFolderFiles("./broll", ".jpg"));
images = [getFolderFiles("./broll", ".jpg")];
console.log(images[0]);
It currently kicks out
[ 'image1.jpg', 'image2.jpg', 'image3.jpg' ]
[ 'image1.jpg', 'image2.jpg', 'image3.jpg' ]
I am trying to get console.log (images[0]); to = image1.jpg and so on.
My end goal is to return something like the below but I will work on the other info after I figure out how to get the array setup.
// var images = [
// {
// path: "./broll/image1.jpg",
// caption: captions,
// loop: imagelength,
// },
I have been scouring the internet and can't find a solution that is something that I understand as I am relatively new to programming.
First of all, the construction of the regex is wrong, because when you pass pass a string to the RegExp
constructor, you have to escape the \
to make it show up in the regex, ie
new RegExp(`.*\\.(${extension})`, "ig")
But if you do that, you will get the following RegExp
new RegExp(`.*\\..jpg`, "ig");
Ie, an arbitrary (maybe empty) string (matched by .*
), followed by a literal .
(matched by \\.
) followed by an arbitrary character (matched by .
), followed by literally jpg
. And you are also missing word anchors, ie your regex will also match something like foo.ajpg.bar
A better approach would be defining your regexp as
new RegExp(`.+\\.${extension}$`, "ig")
and passing only jpg
(ie without the dot) as extension. This will match an arbitrary string of at least length 1 (.+
) followed by a .
(\\.
) followed by your extension at the end of the word (matched by $
)
Second, when you do
images = [getFolderFiles("./broll", ".jpg")];
You are creating a new array, with the result of getFolderFiles
being the first element of that array. But as the result of getFolderFiles
already is an array, you end up with the following structure
[["image0.jpg", "image1.jpg"]]
You probably just want
images = getFolderFiles("./broll", "jpg");