js选择、读、写文件

233 阅读1分钟

api仅为实验性,仅可在localhost或者https下生效 image.png

1.选择文件 showOpenFilePicker

/**
* 将文件夹转化为树结构
*/
async function* getFilesRecursively(entry, parentDir = []) {
  let children
  let file
  if (entry.kind === 'file') {
    file = await entry.getFile()
    if (file !== null) {
      file.relativePath = parentDir
      yield entry
    }
  } else if (entry.kind === 'directory') {
    children = []
    for await (const handle of entry.values()) {
      yield* getFilesRecursively(handle, children)
    }
  }
  let dir = {
    name: entry.name,
    type: entry.kind,
    file,
    entry,
    expand: true,
    children
  }
  parentDir.push(dir)
},
async checkFile() {
  const directoryHandle = await window.showDirectoryPicker()
  console.log(directoryHandle)
  let tree = []
  let files = []
  for await (const fileHandle of getFilesRecursively(
    directoryHandle,
    tree
  )) {
    files.push(fileHandle)
  }
  console.log(tree, files)
  this.filetree = tree // 文件树结构
  this.files = files // 文件列表
},
nodeClick(node) {
    this.fileInstance = node.entry
}

2.读取文件内容 getFile

async readFile() {
  if (this.fileInstance) {
    const content = await this.fileInstance.getFile()
    const fileReader = new FileReader()
    fileReader.onload = (e) => {
      this.value = e.target.result
    }
    fileReader.readAsText(content)
  }
},

3.写入文件内容 createWritable

async writeFile() {
  if (this.fileInstance) {
    const writable = await this.fileInstance.createWritable({
      keepExistingData: true
    })
    await writable.write(this.value)
    await writable.close()
  }
}