Search code examples
javascriptjquerytypescriptgithub-pages

How to load a random file from a directory


I am trying to create a question bank on GitHub Pages. I load a specific file using:

$(document).ready(function() {
    
    var theQuestion = "./questionsBank/"+"question-4"+".html"; //path to load
    $("#question").load(theQuestion);  //loading the question
  
  });

Now, there are many files in the questionsBank directory and I would like to have a script picking and loading a random one, but I don't know how to do in JS.

  • How do you retrieve all filenames in questionsBank directory?

I would like to do something like below but don't know how to read filenames in a directory into an array:

var questionFolder = './some directory';
var questionFiles = [];
questionFiles = readingFilesandPopulatingIntoArray(questionFolder); \\how to do this?
var folderSize = questionFiles.length ;
randomNumber = Math.floor(Math.random() * folderSize);
randomQuestion = questionFiles[randomNumber]; 
$("#question").load(randomQuestion);

Solution

  • As commented by @Lawrence Cherone, the only way of getting the contents of a remote directory is by having an index of it.

    Of course Apache has it's own directory scanner, which if configured ok, can render an HTML page with its contents. Then you could fetch that index and loop over the file links in it.

    But GitHub Pages does not generates such indexes, so you need to generate it by your own. To do so, you need to do it during the build/deploy process of your page (which we don't know). There, you can add a NodeJS script (or whatever other language you prefer to use, like a plain bash script) using, for example, node's fs dir.read() to get the files list in ./questionsBank/ directory and generating a file to save it somehow (for example, a JSON file containing an Array).

    Finally, you can include it directly in your code during the build process by importing it somewhere, or fetching it as you'd fetch any other URL containing a JSON (or whatever other format you decided to use).