【问题标题】:React native file system to read directory recursively to get sub folder and items in it反应本机文件系统以递归方式读取目录以获取子文件夹和其中的项目
【发布时间】:2018-12-03 11:19:58
【问题描述】:

我可以使用以下函数读取目录中的文件

    const path = RNFS.DocumentDirectoryPath;

    RNFS.readDir(path)
    .then((result) => {
        console.warn(result);
        const Files = [];

        if(result != undefined && result.length > 0){

            for(index in result) {
                const item = result[index];
                console.log(item);

                if(item.isFile()){

                    Files.push(item);
                }
            }

            if(Files.length > 0) {

                callback(Files);
            }
            else{

                callback(null);
            }
        }
        else{
            callback(null);
        }
    })
    .catch(err => {

        console.log('err in reading files');
        console.log(err);
        callback(null);
    })

但是我想读取目录和它的子目录以及属于它们的文件,有什么方法可以实现吗?

【问题讨论】:

    标签: react-native react-native-fs


    【解决方案1】:

    我已经实现了从资产中的某些内容到文档目录中的某些内容的递归复制,如下所示:

    import FileSystem from "react-native-fs";
    
    async copyRecursive(source, destination) {
        console.log(`${source} => ${destination}`);
        const items = await FileSystem.readDirAssets(source);
    
        console.log(`mkdir ${destination}/`);
        await FileSystem.mkdir(destination);
    
        await items.forEach(async item => {
          if (item.isFile()) {
            console.log(`f ${item.path}`);
    
            const destPath =
              FileSystem.DocumentDirectoryPath + "/" + source + "/" + item.name;
    
            console.log(`cp ${item.path} ${destPath}`);
            await FileSystem.copyFileAssets(item.path, destPath);
          } else {
            console.log(`d ${item.path}/`);
    
            // Restart with expanded path
            const subDirectory = source + "/" + item.name;
            const subDestination = destination + "/" + item.name;
            await this.copyRecursive(subDirectory, subDestination);
          }
        });
    
        this.setState({
          androidReady: true
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-05
      • 2011-09-27
      • 2019-06-26
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      相关资源
      最近更新 更多