纯前端读写文件?

事情是这样的我发现vscode在线版居然可以打开文件目录和文件,还能保存文件。

兼容性一般 目前 谷歌 edge Opera 支持 其他均不支持

image.png

https://vscode.dev/

查了一下MDN 发现增加新的API 了

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

image.png

showDirectoryPicker

这是一项实验性技术 未来版本可能会发生变化 作用就是显示一个目录选择器 返回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);
 });
});

获取选中目录下所有的文件平铺展开

image.png

image.png

showOpenFilePicker

showOpenFilePicker这个API 返回用户所选的文件 不是目录默认单选 可设置 multiple 多选

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

可以调用getFile 返回 File对象 就跟 input file 返回的对象一样了可以操作了。

showSaveFilePicker

showSaveFilePicker 这个API可以写入一个文件 返回promise

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

image.png

image.png

猜你喜欢

转载自blog.csdn.net/qq1195566313/article/details/132690221