Sohrab Saran
Sohrab Saran

Reputation: 141

Using browser javascript, how to get the contents of the files and subfolders of the user-specified local directory

Please see How to get the contents of the directory from local PC in javascript . There is a link to a jsfiddle that just prints out the names of the files. Is it possible to access their content as well? If yes then how exactly?

Upvotes: 0

Views: 278

Answers (1)

Sohrab Saran
Sohrab Saran

Reputation: 141

May be a Google-Chrome-specific answer... I found https://github.com/GoogleChromeLabs/browser-nativefs . This has a link https://browser-nativefs.glitch.me/ . View source and download the html, css and mjs files.

I modified script.mjs as follows (sharing only the modified part of the code, with comments to indicate the exact modifications):

  Array.prototype.asyncForEach = async function (fn) {
    for (let i = 0; i < this.length; i++) {
      await fn(this[i], i);
    }
  };

openDirectoryButton.addEventListener('click', async () => {
    try {
      const blobs = await directoryOpen({ recursive: true });
      alert('upload of folder is done')
      //const blobs = await directoryOpen();
      let fileStructure = '';
      await/*added this 'await'*/ blobs.sort((a, b) => {
        a = a.webkitRelativePath + a.name;
        b = b.webkitRelativePath + b.name;
        if (a < b) {
          return -1;
        } else if (a > b) {
          return 1;
        }
        return 0;
      }).asyncForEach/*changed this forEach to asyncForEach*/(async (blob) => {
        // The Native File System API currently reports the `webkitRelativePath`
        // as empty string `''`.
        //added print out of file blob content
        fileStructure += `${blob.webkitRelativePath}${
          blob.webkitRelativePath.endsWith(blob.name) ?
            '' : blob.name}, content: ${await blob.text()}\n`;
      });

Upvotes: 2

Related Questions