I need my HTML5 page to return a Array
with all file names and extensions in a directory within my site. I can do this in other server-side languages, but I'd like to do it in JS. is there such a possibility?
I need my HTML5 page to return a Array
with all file names and extensions in a directory within my site. I can do this in other server-side languages, but I'd like to do it in JS. is there such a possibility?
As already mentioned this task is difficult / impossible on the client side, server side languages are the right way.
But since you ask and assuming that the directory is on the same server and that the directory has an index with permission via htaccess; then in that index are all files. So having this html page with a list of links jQuery can already work.
One suggestion:
$.ajax({
url: url,
context: document.body
}).done(function (data) {
var allLinks = $(data).find('a');
var goodLinks = $.grep(allLinks, function (el) {
return (el.pathname != '/');
});
var arrayFinal = [];
$(goodLinks).each(function (i) {
var objeto = {
nome: this.pathname.split('.')[0],
estencao: this.pathname.split('.')[1] || ''
}
arrayFinal.push(objeto);
});
console.log(goodLinks);
console.log(arrayFinal[0]);
});
Direct not is possible because javascript running on an HTML page runs in the client browser and does not have access to the server, which is usually a serious security issue.
It would be possible if your server supported directory listing. You could do the parse of the file listing page and retrieve the data from them. I searched through an example using the Apache HTTP Server and found this :
$.ajax({
url: "http://yoursite.com/images/",
success: function(data){
$(data).find("td > a").each(function(){
// will loop through
alert("Found a file: " + $(this).attr("href"));
});
}
});
Again, to strengthen, allowing file listings can be a security problem. But you could allow this for some specific folders.
Depending on your requirements, it would be better to create a REST service that returns a JSON with the list of required files, so you are not even tied to a specific folder.
You can not access the file system via JavaScript (in the browser).
Whether you are using server-side with node.js is possible .
PS: A possible workaround would make a page available that list these files from the server for you and return it in some way (but note that the listing is done server side, file system).
You can do this with Node. Here's a simple example. Create a folder of any name and create a file named ' readdir.js
'; inside this folder create another folder named 'files', inside the files folder create ' texto1.txt
', ' texto2.txt
' and ' texto3.txt
'.
// readdir.js
var fs = require('fs');
var domain = require('domain').create();
fs.readdir('./arquivos',function(error,files){
console.log(files);
});
domain.on("error",function(erros){
console.log(erros);
});
Output: ['text1.txt', 'text2.txt', 'text3.txt']
I believe this is what you want to know.