0

I'm wondering how I'd be able to read file names from my directory and be able to display them in table form to a window. I already have an attempt I made below but for some reason whenever I run the code all it displays on the window is the word "undefined". I'm not too sure why this is and any help to stop it saying undefined would be greatly appreciated.

script.js

const fs = require('fs');

var outputHTML = '';

var logdirname = '.././logs/';
var alllogs = fs.readdirSync(logdirname, function(err, filenames) {
    if (err) {
        onError(err);
        return;
        }
});

outputHTML += "<table>";
for (var i = 0; i <= alllogs.length ; i++) {
    outputHTML += "<tr>";
    outputHTML += "<td>" + alllogs[i] + "</td>"
    outputHTML += "</tr>";
}
outputHTML += "</table>";
console.log(outputHTML);

index.html

<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript"
        src="script.js">
    </script>
    
</head>

<body>
    <button onclick= "f()">
        Click To Access Animals
    </button>

    <div>
        <p id="text" style="color:purple;
            font-weight:bold;font-size:20px;">
        </p>
    </div>
    
    <script type="text/javascript">
        

        function f() {
            
           document.getElementById("text").innerHTML = outputHTML;

        }

    </script>
</body>
</html>
Ewgavin
  • 13
  • 2

1 Answers1

1

The problem with your code is that your script is not Node.js it's plain JavaScript and you can't access the filesystem from the browser (from JavaScript) because of security restrictions.

Maybe you could work with the File System Access API. It makes the file handling process with browsers much easier.

Then a popup window could show up where you need to select the files.

Robin Aegerter
  • 457
  • 3
  • 16
  • Thanks for your suggestion about the File System Access API. I also made my script a node.js script by doing npm init and it still displays undefined. Do you have any other suggestions as to what could be wrong? – Ewgavin Jun 30 '22 at 07:37
  • 1
    If you execute JavaScript via the browser, it's not NodeJS (no matter if you created it with npm). NodeJS runs on the V8 engine and it supports the FileSystem access. But browser restriction doesn't. If you have to execute the script in the browser, there is no way around the FileSystem-Dialog in which you select the file. But maybe you could execute the script in the console (with "node script.js") and in it generate a new HTML-file with the table and it's content which you then can open in the browser. – Robin Aegerter Jul 01 '22 at 08:52