-2

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)

11
  • So you want to add all the files in a directory to an array using javascript? Commented Dec 8, 2023 at 18:49
  • If you're running javascript in the browser, you have no read access to the filesystem so this will not be possible. If you're running javascript in a Node server, fs.readdirSync(path) will get you started. Commented Dec 8, 2023 at 19:07
  • (I guess in theory in browser js you could try to load all the images in the background, and wait for one to time out as an indication that it doesn't exist... but it'd be a lot easier to just edit an images array length in your javascript when you add a new image file) Commented Dec 8, 2023 at 19:10
  • Since the file in question is an image, you could try to load the image using javascript and then detect if the load fails - then you know. This post should guide you: stackoverflow.com/a/56166153/1772933 Commented Dec 8, 2023 at 19:32
  • Your first loop is clearly wrong. It returns unconditionally on the first iteration, it will never fetch other images. Commented Dec 8, 2023 at 20:08

1 Answer 1

-1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is true, but that would in most cases indicate a security hole that needs to be closed rather than a "feature" to use in production...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.