Pure front-end reading and writing files?

The thing is, I found that the vscode online version can actually open file directories and files, and save files.

Compatibility is generally currently 谷歌 edge Operasupported, and others are not supported

image.png

https://vscode.dev/

I checked MDN and found that a new API has been added

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/showDirectoryPicker

image.png

showDirectoryPicker

This is an experimental technology that may change in future versions. The function is to display a directory selector and return a Promise.

const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
    
    
showDirectoryPicker().then(async (dir) => {
    
    
  const recursion = async (dir) => {
    
    
    if (dir.entries) {
    
    
      const dirs = dir.entries();
      for await (let item of dirs) {
    
    
        item.forEach((file) => {
    
    
          if (typeof file === "string") {
    
    
            const p = document.createElement("p");
            p.innerText = file;
            p.style.marginLeft = "10px";
            document.querySelector(".result").appendChild(p);
          } else {
    
    
            recursion(file);
          }
        });
      }
    }
  };
  recursion(dir);
 });
});

Get all the files in the selected directory to expand

image.png

image.png

showOpenFilePicker

The showOpenFilePicker API returns the user's selection, which 文件is not a directory. The default single selection can be set to multiplemultiple selections

      btn.addEventListener("click", () => {
    
    
        showOpenFilePicker().then(async (file) => {
    
    
          console.log(await file[0].getFile());
        });
      });

You can call getFile to return the File object, which is the same as the object returned by input file and can be operated.

showSaveFilePicker

showSaveFilePicker This API can write a file and return a promise

showSaveFilePicker().then(file=>{
    
    
  console.log(file);
})

image.png

image.png

Guess you like

Origin blog.csdn.net/qq1195566313/article/details/132690221