javascriptapachemod-autoindex

Can Apache be configured to allow JS in browser to get server directory contents?


If I had a directory of images in my Apache DocumentRoot directory and I want JavaScript in my website to know what images are available in that directory, as I see it there are two options:

  1. Provide the list of those images from a server-side script that can inspect the directory and return a list of the items within.
  2. Build a file (e.g. "contents.js") in that directory using script/executable code on the server. This file would list the files contained in the directory and JS on the front-end would be able to access this file.

However, is it possible to configure Apache to provide access to that directory in such a way that the JS can make a request to the server for directory contents? Perhaps using mod_autoindex or something neater? Has anyone done this?

I don't actually want to use this for images, so it this is just a hypothetical example.

Thanks


Solution

  • Javascript can only communicate with the server via HTTP. There's no secret backdoor or anything to "get directory contents". Apache will have to serve some document which Javascript can interpret to communicate what files are in a directory.

    You could configure Apache to serve directory listings, however those are typically HTML pages which you would need to parse in Javascript to extract information from. Not impossible, but certainly not elegant. Also, those directory listings would be visible and available to anyone publicly by necessity (well, any solution would expose that information publicly, there's no way around that).

    Javascript can work a lot easier with JSON data, or perhaps XML data. I don't know of any Apache mod which outputs directory listings in JSON. Therefore, having a server-side REST endpoint serving customised JSON (or just a static .json file, which you update as needed) is a much more elegant solution from the point of view of a Javascript file trying to get that data.