Get all file in folder javascript

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

Get all file in folder javascript

Simpal KumarSimpal Kumar

3,9014 gold badges27 silver badges48 bronze badges

4

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="https://boxhoidap.com/dir.php"></script>

and use the files[] array

answered
Dec 27, 2017 at 10:42

Get all file in folder javascript

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.

<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>

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("https://boxhoidap.com/"+ 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.

Xem thêm:  Dẫn 2 24 lít SO2 vào dung dịch chứa 10 gam NaOH thi sản phẩm muối thu được là

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 = <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.

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.

<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>

answered Jun 24, 2021 at 12:11

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("https://boxhoidap.com/"):
            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

Get all file in folder javascript

Applying JSONP to IfTheElse answer:

Xem thêm:  Hướng dẫn check is date php

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>

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.

<?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>

answered
May 6 at 5:43

Get all file in folder javascript

How do you read all files from a folder in JS?

You can use the f. readdir() method to list all files available in a directory in Node. js. This method asynchronously reads the contents of the given directory and returns an array of the file names excluding .

How do you get a list of the names of all files present in a directory in JavaScript?

Get List of all files in a directory in Node.js.

const testFolder=”./tests/”;.

const fs = require(‘fs’);.

fs. readdir(testFolder, (err, files) => {.

files. forEach(file => {.

console. log(file);.

How do I read a folder in node?

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.

How do I list files in node JS?

Steps to get list of all the files in a directory in Node..

Load all the required Nodejs Packages using “require”..

Get the path of the directory using path. … .

Pass the directory path and callback function in fs. … .

The callback function should have error handling and result handling logic..

Thuộc website harveymomstudy.com

Related Posts