JavaScript Read directory files list
From Wikicodia
Get an array of file names for the specified directory.
readDir() uses XMLHttpRequest() to get the data. Depending upon where the directory exists the format of the XMLHttpRequest() results varies which readDir() handles for two cases: if the directory is on an Apache web server or if it is on a local disk of MSWindowsXP. Changes would be needed for other servers or systems.
The function httpGetText() blocks for results from XMLHttpRequest() and would be more complicated for real world code in order to support browsers other than Firefox. Since the point of this article is readDir() rather than httpGetText() this simplified version is used.
Javascript forces the directory to be on the same system. http://emle.sourceforge.net/emle020400/dev/wikicodia_JavaScript_ReadDir.html reads the /emle020400/dev directory on the same server. Or copy it to a local hard drive on MSWindowsXP.
The alert() shows the use of readDir(). The test sorts the list before displaying, as readDir() returns an unsorted list.
alert(readDir('.').sort());
function readDir(aDirName) {
var DELS = []; // Add more delimiters here.
DELS[0] = {l:'HREF="', r:'"', d:'/'}; // HTTP: Apache
DELS[1] = {l:'201: ', r:' ', d:null}; // FILE: MSWindowsXP
var text = httpGetText(aDirName);
var del = DELS[(text.indexOf('300:')?0:1)]; // MSWindowsXP starts with 300.
var re = new RegExp((del.l + '([^' + del.r + ']*)' + del.r), 'g');
var skipJunk = del.d; // Until directory delimiter
var names = [];
while ((result = re.exec(text)) != null) {
if (!skipJunk)
names.push(result[1]);
else if (result[1].indexOf(del.d) == 0) // After directory you got files.
skipJunk = false; // Done skipping junk.
}
return names;
}
function httpGetText(aURL) {
var req = new XMLHttpRequest();
req.open('GET', aURL, false);
req.setRequestHeader("If-Modified-Since", new Date(0));
req.send(null);
return req.responseText;
}
