1

I want to access the names of the files in a particular path. The JavaScript code written separately works fine whereas when it is put inside the HTML, the code doesn't works.

fs = require('fs');
var directory = 'IPIE/';//direcory name(path name)

fs.readdir(directory, (err, files)=> {
   for (index in files) {
      console.log(files[index]);
   }
});

This code gives the output i.e., the folder names as below:

BigBubbles
Edgegap
Sticky

Whereas the html code below doesn't work fine

<html>
   <body>
      <label>Input Option:</label>
      <select id="input_mode"></select>
      <button onclick='displayfiles()'>abc</button>
   </body>    

   <script>
      function displayfiles() {
         var fs = require('fs');
         var directory = 'IPIE/'; //folder name

         fs.readdir(directory, (err, files) => {
            var select = document.getElementById("input_mode");
            for (index in files) {
               select.options[select.options.length] = new Option(files[index], index);
            }
         });
      }
   </script>
</html>

And I noticed after var fs = require('fs'); line, alert("something") doesn't work which means the execution stops at that line..??? Please help

3
  • 1
    'fs' is a Node.js Module, it's normal that doesn't work on browser. Commented Jun 20, 2019 at 6:56
  • @yip102011 Oh! Thanks.. Is there any other procedure to access the file names via html? Commented Jun 20, 2019 at 6:58
  • 1
    Also require does not work on a browser. And next, the browser is not allowed to access the file system (thankfully!!). Commented Jun 20, 2019 at 6:59

1 Answer 1

2

In order output the file list, you have to setup a web server, get the file list in server side then output to browser. Execute and access http://localhost/

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'text/html'
    });

    var fileSelectHtml = getFileSelectHtml();
    res.end(`
            <html>
                <body>
                    <label>Input Option:</label>
                    ${fileSelectHtml}
                </body>
            </html>
            `); 

}).listen(80);

function getFileSelectHtml() {
    var files = fs.readdirSync('IPIE/');

    var selectHtml = '<select id="input_mode">';
    for (index in files) {
       selectHtml += '<option>'+ files[index] +'</option>';
    }
    selectHtml += '</select>';
    return selectHtml;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.