简体   繁体   中英

How to use fs.readdirSync when using browserify

I'm trying to get a list of all the file names in a directory and then print it on an HTML page. As I'm planning to use this for an HTML page, I use browserify to bundle my script code so that I am able to use the "require" function.

The script I am running is shown below:

let box = document.getElementById("displayhere");
var fs = require('fs');

let pathname = "./ElementImages";

var files = fs.readdirSync(pathname);
box.innerHTML = files;

When I run it, an error message comes up saying - Uncaught TypeError: fs.readdirSync is not a function . Is there any way to fix this?

No it can't be fixed. Browserify lets you make modules available in the browser that don't depend on core modules provided by node when run as an executable . File system access using the fs module is one such core module.

While you could perhaps try the draft File API in client side HTML, you would need user interaction to select a directory from a picker and serve the page using https - which if you're running node on a local machine, will probably require creating an unsigned security certificate using openSSL . However, if you go down this route the user will need to accept an unsigned security certificate, as well as correctly choosing the image directory, as well as be using a browser that supports yet to be standardized File API.

Although the post doesn't cover details of how the HTML page is created, the results obtained are to be used in another HTML page. Depending on the infrastructure in use you could

  • generate the directory listing in node. If you need to serve it as an HTML page, create an HTML page on the server to do so.

  • generate the listing manually in a terminal using ls or dir commands, depending on operating system, direct the output to a file and text process the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM