My website is serving a lot of pictures from /assets/photos/
folder. How can I get a list of the files in that folder with Javascript?
asked Jul 7, 2015 at 16:27
7
The current code will give a list of all files in a folder, assuming it's on the server side you want to list all files:
var fs = require['fs'];
var files = fs.readdirSync['/assets/photos/'];
answered Jul 7, 2015 at 16:32
9
No, Javascript doesn't have access to the filesystem. Server side Javascript is a whole different story but I guess you don't mean that.
answered Jul 7, 2015 at 16:35
Simpal KumarSimpal Kumar
3,9014 gold badges27 silver badges48 bronze badges
4
I write a file dir.php
var files = ;
In your script add:
and use the files[] array
answered Dec 27, 2017 at 10:42
IfThenElseIfThenElse
4675 silver badges13 bronze badges
5
For client side files, you cannot get a list of files in a user's local directory.
If the user has provided uploaded files, you can access them via their input
element.
var inp = document.getElementById["get-files"];
// Access and handle the files
for [i = 0; i < inp.files.length; i++] {
let file = inp.files[i];
// do things with file
}
answered Jun 19, 2017 at 13:16
NaltrocNaltroc
9641 gold badge14 silver badges34 bronze badges
For getting the list of filenames in a specified folder, you can use:
fs.readdir[directory_path, callback_function]
This will return a list which you can parse by simple list indexing like file[0],file[1]
, etc.
double-beep
4,58613 gold badges30 silver badges40 bronze badges
answered Mar 5, 2019 at 17:39
2
I made a different route for every file in a particular directory. Therefore, going to that path meant opening that file.
function getroutes[list]{
list.forEach[function[element] {
app.get["/"+ element, function[req, res] {
res.sendFile[__dirname + "/public/extracted/" + element];
}];
}];
I called this function passing the list of filename in the directory __dirname/public/extracted
and it created a different route for each filename which I was able to render on server side.
answered Oct 13, 2019 at 19:25
I use the following [stripped-down code] in Firefox 69.0 [on Ubuntu] to read a directory and show the image as part of a digital photo frame. The page is made in HTML, CSS, and JavaScript, and it is located on the same machine where I run the browser. The images are located on the same machine as well, so there is no viewing from "outside".
var directory = ;
var xmlHttp = new XMLHttpRequest[];
xmlHttp.open['GET', directory, false]; // false for synchronous request
xmlHttp.send[null];
var ret = xmlHttp.responseText;
var fileList = ret.split['\n'];
for [i = 0; i < fileList.length; i++] {
var fileinfo = fileList[i].split[' '];
if [fileinfo[0] == '201:'] {
document.write[fileinfo[1] + "
"];
document.write['2540625
10.5k8 gold badges47 silver badges54 bronze badges
answered Sep 21, 2019 at 15:43
2
If you use nginx, you can set autoindex on
, then you request url, you can get the file names from response.
function loadDoc[] {
var xhttp = new XMLHttpRequest[];
xhttp.onreadystatechange = function [] {
if [this.readyState == 4 && this.status == 200] {
myFunction[this];
}
};
xhttp.open["GET", "/assets/photos/", true];
xhttp.send[];
}
function myFunction[xml] {
// console.log[xml.responseText]
var parser = new DOMParser[];
var htmlDoc = parser.parseFromString[xml.responseText, 'text/html'];
var preList = htmlDoc.getElementsByTagName["pre"][0].getElementsByTagName["a"]
for [i = 1; i < preList.length; i++] {
console.log[preList[i].innerHTML]
}
}
answered Jun 24, 2021 at 12:11
0
To then check for a specific file, you can do parsedDirectory.includes["filename"]
and it will return a boolean value.
answered Aug 6 at 21:06
As others' answers suggest it seems
impossible on client side, so I solved it on server side as following: Client side by js
get_file[conf.data_address].then[imgs => { // get_file is wrapper of fetch API
let img = new Image[];
img.src = `./files/Blackpink/${imgs[0]}`; // e.g. load the first img
img.height = 40;
return new Promise[resolve => {
img.onload = [] => {
resolve[img];
}
}]
}]
Server side by django:
def get[self, request]: # get method
address = request.query_params.get['address'] # get the requested folder
is_database = request.query_params.get['is_database']
if address.endswith['/']:
j = u.get_path_files[address,is_full=False] # wrapper of os.listdir of python to get the files in the requested directory.
answered Aug 22 at 4:26
Applying JSONP to IfTheElse answer:
In /dir.php write the following:
In your index.html add this script:
/* this function will be fired when there are files
in dir search in php' glob
*/
function callback[files] {
alert[files];
}
/* call inside document.ready to make sure the
callback is already loaded
*/
$[document].ready[function[] {
let php = document.createElement["script"];
php.setAttribute["src", "/dir.php"];
document.body.appendChild[php];
}];
answered Apr 19, 2021 at 15:44
I understand that the problem is old but still comes back in many issues. It's true that on client side you can't list files in a local directory using pure JavaScript. Below is a complete snippet that uses PHP and transfers the file list with extensions to JavaScript.