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?
- 7,671
- 9
- 50
- 87
-
5What have you tried? And in what context do you want to retrieve the list of files... From the browser or from a server with node.js? – David Barker Jul 07 '15 at 16:29
-
1And which browser/s you are supporting? – Simpal Kumar Jul 07 '15 at 16:31
-
@Mike this is just for the latest version of Chrome – bevanb Jul 07 '15 at 16:35
-
@Mike I doubt the browser choice really matters. The browser doesn't have access to the list of files unless the server presents it. – Mike Cluck Jul 07 '15 at 16:35
-
@MikeC ya you are right. I was thinking about IE `ActiveXObject` to access client system filesystem. So I asked. – Simpal Kumar Jul 07 '15 at 16:37
-
1possible duplicate of [best way to get folder and file list in Javascript](http://stackoverflow.com/questions/20822273/best-way-to-get-folder-and-file-list-in-javascript) – Simpal Kumar Jul 07 '15 at 16:40
-
I am using laravel 5, how can i retrieve images name from folder using javascript or jquery? – 151291 Feb 17 '17 at 12:30
10 Answers
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/');
- 4,025
- 2
- 19
- 36
-
13I meant accessing a list of files from the client, sorry wasn't more clear. – bevanb Jul 07 '15 at 16:37
-
10Where does require() come from or is defined??? Your code proiduces a "'require' is not defined" error. Have you tested your code? If so, have you maybe missed some important part referring to 'require'? – Apostolos Jun 14 '18 at 09:52
-
8@Apostolos As OP notes in the description, this needs to be server-side code. You can not run this in a browser. Running this script with Node.js does not throw any errors. – Naltroc Aug 24 '18 at 20:25
-
2This is a good way but seems doesn't answer the question directly. The simple answer is No, in JS from client side(browser) there is no direct way to get list of files in a folder/directory on server side. – Akshay Hiremath May 06 '19 at 18:55
-
4
-
-
This top rated answer is one very specific to back-end, which is not what most people mean when they say javascript. – Cybernetic Oct 23 '21 at 15:45
-
@Apostolos I found this video to be helpful in understanding the basics about NodeJS: https://www.youtube.com/watch?v=pU9Q6oiQNd0 – WhyWhat May 15 '22 at 08:47
-
Thanks @WhyWhat. I hate to use Youtube for things requiring short explanations. I wonder who doesn't! Anyway, it's a 5-years-ago question ... Thanks, anyway! – Apostolos May 16 '22 at 08:51
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.
- 3,765
- 3
- 26
- 48
-
21
-
3
-
@jtheletter The API is running on the server, so you'd use whatever stack you have running on your server. If that's Node, it would be fs.readdir. – superluminary Apr 29 '20 at 08:07
-
6If you're saying a library must be used, that's not quite the same as saying JavaScript (vanilla) has access to the file system. – 2540625 Apr 29 '20 at 15:08
I write a file dir.php
var files = <?php $out = array();
foreach (glob('file/*.html') as $filename) {
$p = pathinfo($filename);
$out[] = $p['filename'];
}
echo json_encode($out); ?>;
In your script add:
<script src='dir.php'></script>
and use the files[] array
- 449
- 5
- 13
-
1
-
2
-
3@2540625 that is php, not pure javascript. Despite you need php and it does not solve the issue of the author, it is still a pretty good solution if you have php. – Jul 11 '20 at 02:50
-
1Alternatively if you want to list all files, either use `*.*` or use scandir to preserve file extensions, `$out = scandir("."); echo json_encode($out);` – Stardust Aug 18 '20 at 20:06
-
3
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.
<input type="file" name="client-file" id="get-files" multiple />
<script>
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
}
</script>
- 954
- 1
- 14
- 34
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.
- 4,567
- 13
- 30
- 40
- 91
- 1
- 3
-
1would be good to note this is a solution only for Node.js environments – mroncetwice Dec 12 '21 at 23:32
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.
- 53
- 4
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 = <path>;
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] + "<br>");
document.write('<img src=\"' + directory + fileinfo[1] + '\"/>');
}
}
This requires the policy security.fileuri.strict_origin_policy to be disabled. This means it might not be a solution you want to use. In my case I deemed it ok.
- 10,156
- 8
- 46
- 53
- 130
- 8
If you use nginx, you can set autoindex on, then you request url, you can get the file names from response.
<script>
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)
}
}
</script>
- 29
- 1
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.
<?PHP
$out = array();
$out = scandir("MT940"); // Or any path to local dir to be listed
$out = array_diff($out, array('.', '..')); // Skip current and parent dir
?>
<!DOCTYPE html>
<html lang="pl-PL">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<title></title>
</head>
<body>
<div class="service-container"
data-files= '<?php echo (json_encode($out)); ?>'>
</div>
<script>
let files;
$(document).ready(function() {
$('.service-container').each(function() {
let container = $(this);
files = container.data('files');
fileNames = Object.values(files);
});
});
</script>
<!-- Some HTML code here -->
<script>
let fileNames = [];
$(document).ready(function() {
console.log(fileNames);
// Do something with fileNames
});
</script>
</body>
</html>
- 1
Applying JSONP to IfTheElse answer:
In /dir.php write the following:
<?php
$out = array();
foreach (glob('file/*.html') as $filename) {
$p = pathinfo($filename);
$out[] = $p['filename'];
}
echo 'callback(' . json_encode($out) . ')';
?>
In your index.html add this script:
<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);
});
</script>
- 526
- 1
- 4
- 9