0

Here I'm trying to get the list of all file names from a given directory.At this url (http://localhost:3000/dir), I'm having the directory name as "/usr/local".

I'm trying to retrieve all the files from "/usr/local" directory having extension ".txt".

I'm unable to display the file names due to the following error :

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/dir. (Reason: CORS header 'Access-Control-Allow-Origin' missing).How can I overcome this issue.Can anyone please help me out ...

My Sample.html :

<html>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<body>

<div id="fileNames"></div>


<script type="text/javascript">
$(window).load(function(){
   var fileExt = ".txt";

        $(document).ready(function(){

            $.ajax({

                url: 'http://localhost:3000/dir',
                success: function (data) {
                    console.log(data);
                   $("#fileNames").html('<ul>');

                    $(data).find("a:contains(" + fileExt + ")").each(function () {
                        $("#fileNames").append( '<li>'+$(this).text()+'</li>');
                    });
                    $("#fileNames").append('</ul>');
                }
            });

        });
});

</script>
</body>
</html>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
dev333
  • 713
  • 2
  • 17
  • 38
  • Where's your site hosted? ie what's the url that you enter to get this page to open? I'm guessing it's *not* `http://localhost:3000/index.html` – freedomn-m Nov 26 '15 at 09:46
  • This is the url http://localhost:3000/loginSuccess which opens this page – dev333 Nov 26 '15 at 09:49
  • ok - so what is serving the request to `/dir` ? IIS/Apache? What server-side tech are you using? php/asp.net? What do you get if you enter the `/dir` directly in the browser (not via ajax request)? Do you have any control over anything other than the html? – freedomn-m Nov 26 '15 at 09:52
  • I'm using node.js as server side technology.If I enter http://localhost:3000/dir, I'll get "/usr/local/" directory name in the browser – dev333 Nov 26 '15 at 09:55
  • Does this help: http://enable-cors.org/server_expressjs.html – freedomn-m Nov 26 '15 at 09:58
  • Note that you're trying to access files on your computer from a remote URL. Imagine how dangerous that would be, if any website could access any files on your computer! The CORS same-origin policy prevents you from being able to do something like this. Only if you serve /usr/local/ on localhost itself can you access its contents from localhost. You must have the same origin as what you are trying to access. – Cannicide Mar 25 '20 at 18:12

3 Answers3

0

Original Answer (2017):

var fs = require('fs');
var files = fs.readdirSync('/usr/local/');

When I originally answered this question, I did not know how to use nodeJS. I simply got the answer from the following question and modified it for you: Get list of filenames in folder with Javascript.

Now, however, I am much more experienced with nodeJS and can answer this properly. If you only want files that end in the .txt extension you can do the following.

Updated Answer (2020):

var fs = require('fs');

//Gets all files with .txt extension at the /usr/local/ directory:
const files = fs.readdirSync("/usr/local/").filter(file => file.endsWith(".txt"));

//Loops through all of the files to do something with each one:
for (var file of files){
    //Do something with each filename... (var file contains the filename)
}

I have used this approach before and I can guarantee that it works, assuming I didn't make any typos anywhere. Hope this helps!

Note that this must be done server-side, not client-side, as this is NodeJS code.

Cannicide
  • 4,360
  • 3
  • 22
  • 42
-1

About listing in directory https://nodejs.org/api/fs.html#fs_fs_readdir_path_callback

var fs=require('fs');
fs.readdir('./',function(err,files){// './' - is current directory
    console.log(files);
});

About errors - try to execute in terminal curl http://localhost:3000/dir There are 2 ways - server error or client error.

Mi Ke Bu
  • 224
  • 2
  • 13
  • Note that although this gets all files in the directory, it does not specifically filter out the .txt files as the OP wanted. And reading the current directory (including the file that holds this script) could potentially be problematic, especially if your script's function, for example, is to do a `require()` of all JS files in the directory. You risk getting into an infinite loop where this JS file requires itself. – Cannicide Mar 25 '20 at 18:06
-1
** Firstly we will have to upload files using FTP on accessible location then using this code we can get the files names. #In my case i am redirecting to the file location.

$(document).ready(function() {
      GetDirectoryFiles(); //calling of function
    });

    function GetDirectoryFiles() { //function Definition for Get All FileNames Of Directory
      $.ajax({
        type: "GET",
        url: "http://localhost:55304/TestViewsGoogleImgChanged/",
        contentType: "application/html; charset=utf-8",
        data: null,
        dataType: "html",
        success: function(data) {
          var pagedata = $.parseHTML(data);
          var tabledata = $.parseHTML(pagedata[9].innerHTML);
          for (var i = 0; tabledata.length / 2; i++) {
            if (tabledata[i].textContent.indexOf('.cshtml') > 0) {
              window.open('http://123.com/' + tabledata[i].textContent.split(".cshtml")[0], '_blank')
            }
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert(textStatus + '-----' + errorThrown);
        }
      });
    }