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

Expo v51中FileSystem.getInfoAsync处理目录报错求助

解决方案

1. 校验目录路径格式

确保使用Expo File System官方提供的根路径(如FileSystem.documentDirectory、FileSystem.cacheDirectory)构建目标目录,避免直接使用Android原生绝对路径(如/storage/emulated/0/),这类路径通常需要额外权限且兼容性差。示例:

const targetDir = `${FileSystem.documentDirectory}my-target-folder/`;

2. 配置并申请文件访问权限(Android)

针对不同Android版本配置对应权限,在app.json中添加:

{
  "expo": {
    "android": {
      "permissions": [
        "READ_EXTERNAL_STORAGE",
        "READ_MEDIA_IMAGES",
        "READ_MEDIA_VIDEO",
        "READ_MEDIA_AUDIO"
      ]
    }
  }
}

代码中主动请求权限:

import * as Permissions from 'expo-permissions';

const requestStoragePermissions = async () => {
  const { status } = await Permissions.askAsync(Permissions.MEDIA_LIBRARY);
  return status === 'granted';
};

3. 修正递归函数的目录处理逻辑

使用FileSystem.readDirectoryAsync获取目录条目,避免直接依赖getInfoAsync遍历,同时确保目录路径以/结尾。正确实现示例:

import * as FileSystem from 'expo-file-system';

async function getContentsOfFolder(folderPath) {
  let allFiles = [];
  
  const dirInfo = await FileSystem.getInfoAsync(folderPath);
  if (!dirInfo.exists || !dirInfo.isDirectory) return allFiles;

  const entries = await FileSystem.readDirectoryAsync(folderPath);
  
  for (const entry of entries) {
    const fullPath = `${folderPath}${entry}`;
    const info = await FileSystem.getInfoAsync(fullPath);
    
    if (info.isDirectory) {
      const subFiles = await getContentsOfFolder(fullPath + '/');
      allFiles = [...allFiles, ...subFiles];
    } else {
      allFiles.push(fullPath);
    }
  }
  
  return allFiles;
}

4. 调整expo-file-system版本

Expo v51可能存在兼容性问题,尝试升级到最新版或回退到稳定版本:

# 升级至最新版
npx expo install expo-file-system@latest

# 回退到v50对应版本
npx expo install expo-file-system@~17.0.1

5. 避免访问受限目录

确保操作的是应用沙箱目录或已授权的公共目录,Android系统的系统目录、其他应用私有目录无法直接访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 04:05:56