2

I have a directory of text files called ./text-files. I can read files using the fetch API like this:

fetch('./text-files/foo.txt')
  then(res => {
    return res.text()
  })
  .then(text => {
    console.log(text)
  })

Does the fetch API support some way to read a directory of files without knowing the specific name of the files only the file extension?

Ideally, I'd like some way to get a list of all files in the directory ./text-files and then read each one serially using fetch. Is this possible? If it's possible to read one file off disk in Javascript, I would think there'd be some way to get a list of file and read each of them?

I was trying to do something like this, which didn't work:

fetch('./text-files/*.txt')
  then(res => {
    return res.text()
  })
  .then(text => {
    console.log(text)
  })

1 Answer 1

2

This is not possible assuming that you are attempting to read all files from a remote server directory while only using fetch. You can make an API endpoint on remote machine that will return an array of files. That remote API endpoint can use Node's fs module and something along the lines of:

fs.readdir(path, function(err, items) {
console.log(items);

for (var i=0; i<items.length; i++) {
    console.log(items[i]);
}});

Then once you fetched an array of files you can then set up them to be individually be fetched using fetch api.

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

5 Comments

Thanks. Files are all local. If I can read one file successfully (which I can). Why can't I read all of them in a directory?
@turtle because you are sandboxed in the browser. You can request a specific file and if permissions allow it you will get that file. Listing the contents of a directory is an entirely different thing. You will not be able to do this on a local machine, the browser will not give you access to the information as it is a huge security hole. Just think, you wouldn't want some random site to be able to access the list of all the files on your C:\ drive now would ya
@http fetch() uses the HTTP protocol, which doesn't have any directory listing operations.
@AdamH: Thanks. Yes, what you're saying makes sense I guess. I would think reading a file from disk even if you know its name is also a big security hole. Someone could even try guessing the names of important files. Thanks again for the help.
Hey @turtle you are right but because the page you are loading is a local resource the browser is giving you special permissions, the second you pull that page via http(s):/ instead of file:/ it will block it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.