-1

I want a javascript function to give me the results as soon as the page loads in. It is returning the list of folder names. I am not a developer so this is something I am making to demo my research to a client and therefore I am running into small issues. In my index.html I have incorporated a js function inside the tag and I call that function in my

tag via a ID like this:

<script>
    var list_dir = function(){
      const path = require('path');
      const fs = require('fs');
      //joining path of directory 
      const directoryPath = path.join(__dirname, 'Images');
      //passsing directoryPath and callback function
      fs.readdir(directoryPath, function (err, files) {
        //listing all files using forEach
        files.forEach(function (file) {
          // Do whatever you want to do with the file
          //let names=file
          console.log(file); 
        });
      });
    }
    </script>
<p id="list_dir>list of folders:</p>
  
Sambam
  • 33
  • 5
  • Because of security you can't just get a list of folders/files from someone's computer, and you can't use nodeJS like that. – Andy Feb 09 '22 at 08:03
  • My javascript function will be reading directories from the server only not the client. Basically the purpose is to let the user know what folder names we already have on server. The proper backend is on flask but needed to get this done via javascript only as I need the results as soon as a particular page loads. – Sambam Feb 09 '22 at 13:11
  • So you need to set up a server, and have the client code contact an endpoint which will provide those details. – Andy Feb 09 '22 at 13:16

2 Answers2

0

You are using client-side javascript and not node.js. Therefore, you can't use require(), path, fs, etc.

0

As Yugoslav Empire mentioned earlier, your script is embedded in the HTML file, so it runs on the client side. You mentioned that you are making a demo for research, so I assume you will run the HTML file locally on your computer? Then this answer to similar question, may help you.


Indirect Solution

If you want to use command line to generate a list of HTML links, please try to run this command on the desired directory.

ls | awk '{print "<a href=\".\/" $1 "\">" $1 "<\/a><br\/>"}' 

and then paste the result to your HTML file


example if you have a.html b.html in a certain directory, running the script to that directory will output:

<a href="./a.html">a.html</a><br/>
<a href="./b.html">b.html</a><br/>

which can be pasted to your HTML file?

  • I basically need the folder names only. Actually the idea is to let the user using our webapp know what folder names we already have on the server. With javascript I felt that I would be able to show the list of names as soon as the page loads. My backend is on flask and i did os.listdir() on flask- thats very simple but the issue is that I am unable to put that on page load. I found the solutions existing for javascript. – Sambam Feb 09 '22 at 13:14