I want to display all images from folder located in server in image gallery.
Is there a way to return a list of all the image file names from a folder using only JavaScript or JQuery?
Also I want to count the number of image files in similar folder using only JavaScript.
Is there any way to count the number of image files from a folder using only JavaScript?
To get a list of the names of all files present in a directory in Node. js, we can call the readdir method. const testFolder = './folder/path'; const fs = require('fs'); fs. readdir(testFolder, (err, files) => { files.
The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.
No, you can't do this using Javascript alone. Client-side Javascript cannot read the contents of a directory the way I think you're asking about.
However, if you're able to add an index page to (or configure your web server to show an index page for) the images directory and you're serving the Javascript from the same server then you could make an AJAX call to fetch the index and then parse it.
i.e.
1) Enable indexes in Apache for the relevant directory on yoursite.com:
http://www.cyberciti.biz/faq/enabling-apache-file-directory-indexing/
2) Then fetch / parse it with jQuery. You'll have to work out how best to scrape the page and there's almost certainly a more efficient way of fetching the entire list, but an example:
$.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")); }); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With