Search code examples
javascriptnode.jsfetch-apifile-structure

How to list files inside folder using fetch?


I'm running live server extension as a mock backend for my project. So part of my program involves checking the database for all files inside a certain folder.

main folder
   |
   ___ subfolder1
   |       |
   |       ___ 1.png
   |       ___ 2.png
   |
   |
   ___ subfolder1
           |
           ___ 1.png
           ___ 2.png
           ___ 3.png

I'm using firebase, so this has been achieved using the listAll() function. However, in order to mock this functionality, I am using fetch(). But as of now, I can only figure out how to get individual files by their URL

const localHostUrl = 'http://127.0.0.1:5500';
const fetchedFile = await fetch(`${localHostUrl}/mainFolder/subfolder1/1.png`); // this works
const fetchedFolder = await fetch(`${localHostUrl}/mainFolder/subfolder1`); // this doesn't work

I intend to see the number of files inside the folder, their names, and correspondingly fetch them in subsequent commands. How can I see the filestructure using fetch? Any other alternative workarounds are also appreciated


Solution

  • If your mock server has directory listings enabled, then you CAN use fetch() to do this. A server like http-server enables this by default. You can test if fetch() will work by simply typing in the directory address into a browser and see what your server replies with. If it replies with a page that lists the files in that directory then fetch can do that too. To parse the html page text that is returned by fetch() you may have to modify the code below since each server structures the directory listing differently. This will work with http-server:

    async function getDirectory(dirname) {
      let response = await fetch(dirname);
      let str = await response.text();
      let el = document.createElement('html');
      el.innerHTML = str;
    
      // this parse will work for http-server and may have to be modified for other
      // servers. Inspect the returned string to determine the proper parsing method
      let list = el.getElementsByTagName("table")[0].getElementsByTagName("a");
      let arr = [];
      for (i = 0; i < list.length; i++) {
        arr[i] = list[i].innerHTML;
      }
      arr.shift(); // get rid of first result which is the "../" directory reference
      console.log(arr); // this is your list of files (or directories ending in "/")
      return(arr);
    }