Client-side Javascript: Create array of files in a directory

128 Views Asked by At

I'm trying to make a For Loop in javascript that for every number added, will correspond to a file in a folder which will then be added to a list. Is this possible? (code below, I'm sure that there are silly mistakes but that's not my concern at the moment)

for(var i = 1; until file is not detected; i++){
     list = list + "fileNumber"+i+".png";
     return list
}   

Alternatively, would something like this be better? (mild pseudocode warning):

for (var i = 1; 1<2;i++){
     if "filenumber"+i+".png" does not exist:
          return list 
          break
     else:
          list = list +"filenumber"+i+".png"
}

When it's done, the list should look like this:

list = [fileNumber1.png, fileNumber2.png, fileNumber3.png]

Is something like this possible? Am I SOL? if it isn't, are there any alternative ways I can do it without having to learn an entire new language???

For context, I'm trying to make a "previous" and "next" button in html. When pressed, the image on screen will change to either the previous image, or the next image depending on the button (like flipping a page in a book). This wouldn't be too big of an issue, except that I have very little idea on how to get a list of the images I have without doing it manually (I want to have the potential of 50+ images, and don't want to change the list every time I add one)

1

There are 1 best solutions below

1
On

If directory indexing is enabled, you can create an array of the files in a specified directory using purely client-side javascript by fetching an HTML page (generated by Apache's directory listing) that lists the files in the directory, then parses the data to extract the file names. In the code I have provided below, I am doing an additional check to ensure it is either a jpg or png - you can adjust this as needed or remove it completely.

function loadDirectoryListing() {
    fetch('/path/to/directory/')
        .then(response => response.text())
        .then(html => {
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, 'text/html');
            const links = doc.querySelectorAll('a');

            const files = Array.from(links)
                .map(link => link.textContent)
                .filter(text => text.endsWith('.png') || text.endsWith('.jpg'));

            console.log(files);
        })
        .catch(error => console.error('Error loading directory:', error));
}
window.onload = loadDirectoryListing;

Note: I do not recommend this method, as it is not completely reliable, and does pose some security concerns. Generally, directory indexing is frowned upon, and I would suggest using a server-side script to produce the array. However, since the question asks how to do it using client-side JavaScript, I have provided a solution using client-side JavaScript.