反应本机文件系统以递归方式读取目录以获取子文件夹和其中的项目

时间:2018-12-03 11:19:59

标签: react-native react-native-fs

我可以使用以下功能读取目录中的文件

    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);
    })

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

1 个答案:

答案 0 :(得分:0)

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

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
    });
}