Get list of filenames in folder with Javascript

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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/');

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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>

Solution 5 - Javascript

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.

Solution 6 - Javascript

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.

Solution 7 - Javascript

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.

Solution 8 - Javascript

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>

Solution 9 - Javascript

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>

Solution 10 - Javascript

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbevanbView Question on Stackoverflow
Solution 1 - JavascriptChristoffer KarlssonView Answer on Stackoverflow
Solution 2 - JavascriptSimpal KumarView Answer on Stackoverflow
Solution 3 - JavascriptIfThenElseView Answer on Stackoverflow
Solution 4 - JavascriptNaltrocView Answer on Stackoverflow
Solution 5 - JavascriptAhmad ZafarView Answer on Stackoverflow
Solution 6 - JavascriptTanmay_GuptaView Answer on Stackoverflow
Solution 7 - JavascriptpietervanderstarView Answer on Stackoverflow
Solution 8 - Javascriptuser16306730View Answer on Stackoverflow
Solution 9 - JavascriptAndyPLView Answer on Stackoverflow
Solution 10 - JavascriptCarlos BarcellosView Answer on Stackoverflow