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
RegExpconstructor, you have to escape the\to make it show up in the regex, ieBut if you do that, you will get the following
RegExpIe, an arbitrary (maybe empty) string (matched by
.*), followed by a literal.(matched by\\.) followed by an arbitrary character (matched by.), followed by literallyjpg. And you are also missing word anchors, ie your regex will also match something likefoo.ajpg.barA better approach would be defining your regexp as
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
You are creating a new array, with the result of
getFolderFilesbeing the first element of that array. But as the result ofgetFolderFilesalready is an array, you end up with the following structureYou probably just want