You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tauri调用readDir报scope错误及FileEntry无children返回问题

Tauri 1.0.0 + React 桌面应用文件系统接口问题解决方案

问题1:readDir接口触发scope权限报错

问题表现

调用@tauri-apps/api/fs的createDir接口可正常运行无报错,调用readDir接口时持续抛出错误:

Uncaught (in promise) path not allowed on the configured scope: test

相关异常代码与配置如下:
Filetree.js 异常代码:

import { readDir,createDir, BaseDirectory } from '@tauri-apps/api/fs';
import { appDir } from '@tauri-apps/api/path';

let defineEntries = async () => {
  console.log("Loading Data");
  entries = await  readDir('test', new Uint8Array([]), { dir: BaseDirectory.Desktop, recursive: true });
  console.log("Success");
}

tauri.conf.json 初始fs权限配置:

"tauri": {
    "allowlist": {
      "fs": {
        "all": true,
        "readFile": true,
        "writeFile": true,
        "readDir": true,
        "copyFile": true,
        "createDir": true,
        "removeDir": true,
        "removeFile": true,
        "renameFile": true,
        "scope": ["$DESKTOP/*", "$DESKTOP/**", "$DESKTOP/test/*"]
      },
      "path": {
        "all": true
      }
    }
}

运行环境:Windows 10 19044 X64,依赖版本为@tauri-apps/cli 1.0.0、@tauri-apps/api 1.0.1、tauri核心1.0.0。

问题原因与修复

Tauri 1.x版本的fs scope采用glob匹配规则,规则逻辑为:

  • 路径/*:仅匹配路径下一级的文件与文件夹
  • 路径/**:匹配路径下所有递归层级的文件与文件夹
  • 通配规则不会继承路径本身的访问权限:配置$DESKTOP/test/*仅代表允许访问test目录下的内容,不代表允许访问test目录本身,readDir需要直接读取test目录的条目,因此会触发scope拦截。

修复方式:将目标目录本身加入scope配置即可,修正后的scope参考:

"scope": ["$DESKTOP/**", "$DESKTOP/test", "$DESKTOP/test/**"]

如果切换BaseDirectory.App作为根目录,匹配逻辑完全一致,需要同时将目标目录本身、目录下递归内容都加入scope,不要漏配目录本身的权限。

问题2:递归读取目录返回的FileEntry无children字段

问题表现

修复scope权限问题后,开启recursive: true参数调用readDir,返回的FileEntry对象不包含children字段,无法获取子文件结构:例如目标tree目录下存在parent1、parent2两个文件夹,parent1下还有child1、child2两个子文件夹,但控制台输出的返回结果中无对应层级的children内容。

问题原因与修复

这是Tauri 1.0.0~1.0.2版本@tauri-apps/api的已知参数校验bug:readDir接口的第二个参数为可选的二进制缓存配置项,第三个参数才是功能配置对象,当第二个参数传入非undefined值时,会导致递归读取逻辑失效,不会给目录项挂载children字段。

修复方式:无特殊缓存需求时直接省略第二个参数即可,修正后的代码如下:

import { readDir, createDir, BaseDirectory } from '@tauri-apps/api/fs';

const defineEntries = async () => {
  console.log("Loading Data");
  // 省略第二个可选参数,直接传入配置对象
  const entries = await readDir('test', { dir: BaseDirectory.Desktop, recursive: true });
  console.log("Load success", entries);
}

补充说明:

  • 修正后返回的目录类型FileEntry会自动携带children数组,数组内为对应子级的文件/目录项,所有递归层级的子目录都会正确挂载对应的children内容
  • 也可以通过升级@tauri-apps/api到1.0.3及以上版本修复该参数校验问题

内容的提问来源于stack exchange,提问作者DaKoller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 11:06:23