Skip to content

获取目录结构(纯前端)

vue
 <button @click="onSelectDir" class="select-btn">
选择文件夹
</button>
js
async function onSelectDir() {
  const dirHandle = await window.showDirectoryPicker()
  await getDirData(dirHandle, directoryData)
}
/* 递归获取文件夹下的所有文件, 并生成树状结构
 {
"id": "o6ukw45e",
"name": "core",
"ftype": "dir",
"children": [
  {
    "id": "bc41wb16",
    "name": ".eslintrc.cjs",
    "ftype": "cjs"
  },]
}
*/
const exclude = ['node_modules', '.git', '.vscode', '.prettierignore', 'dist'] // 排除的文件夹
async function getDirData(dirHandle, dirData) {
  for await (const entry of dirHandle.values()) {
    const { name, kind } = entry
    // 文件大小
    if (kind === 'file') {
      const size = await entry.getFile().then(file => file.size || 0)
      const ftype = name.split('.').length > 1 ? name.split('.')[1] : 'unknown'
      dirData.children.push({
        id: randomId(),
        name,
        size,
        value: size,
        ftype
      })
    }
    else if (kind === 'directory') {
      if (exclude.includes(name))
        continue
      const children = {
        id: randomId(),
        name,
        ftype: 'dir',
        children: []
      }
      dirData.children.push(children)
      await getDirData(entry, children)
    }
  }
}