How do I get a random file from a folder?


#1

Hello,

I have a folder under www named “random” containing files and I need to be able to call a function that retrieves the names of X number of files.

I assume that I could put the list of files in an array and randomly select one from the array. But I cannot figure out how to get the list of files.

Thank you!


#2

Its not possible with plain javascript

If you building an app use the cordova file plugin https://github.com/apache/cordova-plugin-file/blob/master/doc/index.md available via ngCordova

See http://www.html5rocks.com/en/tutorials/file/filesystem/ for further informations

Not sure if this helps


#3

Alternatively, if the list of files doesn’t change, you could generate the list in your build process using your preferred method of listing directory contents.


#4

The list doesn’t change so I created an array of the file names and now, therefore, I can get random file names. However, I cannot figure out how to get the file by relative path.

I tried “/random/file.txt” which resolved to
"http://localhost:63342/random/file.txt"
which is the correct path but I get 404.

What is the correct, safe, preferred method for pathing to a resource?

Thank you!