【问题标题】:How to rename / move a folder in react native fs?如何在反应原生 fs 中重命名/移动文件夹?
【发布时间】:2020-06-23 16:15:43
【问题描述】:

我在重命名和移动文件夹时遇到问题,因为 react native fs 只有 moveFile 选项,它只对文件而不是文件夹执行。递归执行也很麻烦,并且由于同步,在执行重命名或移动选项后很难执行行执行。我在下面附上了移动代码和错误。请帮我解决这个问题。

moveAll = (path, outputPath) => new Promise((resolve, reject) => {
// is a folder
if (path.split(".").length == 1) {
  // CHeck if folder already exists
  RNFS.exists(outputPath)
    .then((exists) => {
      if (exists) {
        // Delete the folder if exists
        RNFS.unlink(outputPath)
          .then(() => {

          })
          // `unlink` will throw an error, if the item to unlink does not exist
          .catch((err) => {
            console.log(err.message);
          });
      }
      // MAKE FRESH FOLDER
      RNFS.mkdir(outputPath);
      resolve(RNFS.readDir(path)
        .then((result) => {
          result.map(
            (item) =>
              new Promise((resolve, reject) => {
                resolve(this.moveAll(item.path, outputPath + "/" + item.name));
              })
          )
        })
        .catch((e) => {
          console.log("ERROR", e)
        })
      )
    })
    .catch((e) => {
      console.log(e)
    })

} else {
  RNFS.moveFile(path, outputPath)
    .then(() => {
    })
    .catch((e) => {
      console.log(e)
    })
}
})

提前致谢:)

【问题讨论】:

    标签: javascript android react-native filesystems react-native-fs


    【解决方案1】:

    您可以调用this.moveDirectorySafely("source","destination"); 进行递归移动/重命名

    确保您拥有允许的存储权限

    如果您遇到任何错误,您可以致电RNFS.readDir(RNFS.DownloadDirectoryPath).then 来检查此文件夹是否存在

    import React, {Component} from 'react';
    import {View} from 'react-native';
    var RNFS = require('react-native-fs');
    
    export default class index extends Component {
      firstSource = '';
      componentDidMount() {
        this.moveDirectorySafely('source', 'destination'); //you can call this function
      }
    
      moveDirectorySafely = (src, dst) => {
        RNFS.exists(dst).then((dirExists) => {
          if (dirExists) {
            RNFS.unlink(dst).then(() => {
              this.moveDirectory(src, dst);
            });
          } else {
            this.moveDirectory(src, dst);
          }
        });
      };
    
      moveDirectory = (src, dst, root = true) =>
        new Promise(async (resolve, reject) => {
          if (root) {
            src = RNFS.DownloadDirectoryPath + '/' + src;
            dst = RNFS.DownloadDirectoryPath + '/' + dst;
            this.firstSource = src;
          }
          RNFS.mkdir(dst)
            .then(() => {
              RNFS.readDir(src)
                .then(async (files) => {
                  for (let i = 0; i < files.length; i++) {
                    const name = files[i].name;
                    const filepath = src + '/' + name;
                    const destpath = src.replace(src, dst);
                    const destfile = destpath + '/' + name;
    
                    if (files[i].isDirectory()) {
                      RNFS.mkdir(destfile)
                        .then(async () => {
                          await this.moveDirectory(filepath, destfile, false);
                        })
                        .catch((e) => {
                          reject(e);
                        });
                    } else {
                      await RNFS.copyFile(filepath, destfile);
                    }
                    if (i === files.length - 1) {
                      RNFS.unlink(this.firstSource)
                        .then(() => {
                          resolve();
                        })
                        .catch((e) => {
                          reject(e);
                        });
                    }
                  }
                })
                .catch((err) => {
                  console.log(err);
                  reject(err);
                });
            })
            .catch((err) => {
              console.log(err);
              reject(err);
            });
        });
    
      render() {
        return <View></View>;
      }
    }
    

    【讨论】:

    • 这是用于复制文件夹的权利...如果要移动,我们必须删除现有文件夹并将其粘贴到目的地。我无法删除现有文件夹。
    • @VishalTennyson 我已经更新了我的答案,现在你可以查看
    • 现在它继续抛出错误 - 可能未处理的 Promise Rejection (id: 0): Object {}
    • 是的。现在错误是[错误:文件夹不存在],供您参考,我的源和目标已经是绝对路径,包括从根目录,所以我在 if(root) 中注释了两行并运行它
    • 不能正常工作...[TypeError: undefined is not an object (evalating 'path.startsWith')] 现在是错误
    【解决方案2】:

    感谢您的帮助,我通过您的解决方案找到了答案

    moveAll = async (path, outputPath) => {
        // is a folder
        if (path.split(".").length == 1) {
          // CHeck if folder already exists
          var exists = await RNFS.exists(outputPath);
          if (exists) {
            await RNFS.unlink(outputPath);
            await RNFS.mkdir(outputPath);
          }
          // MAKE FRESH FOLDER
          var result = await RNFS.readDir(path);
          for (var i = 0; i < result.length; i++) {
            if (result[i].isDirectory()) {
              await RNFS.mkdir(outputPath + "/" + result[i].name);
            }
            var val = await this.moveAll(result[i].path, outputPath + "/" + result[i].name);
          }
          await RNFS.unlink(path);
          return 1;
        } else {
          await RNFS.moveFile(path, outputPath);
          return 1;
        }
      }
    

    【讨论】:

    • 在我的实践中,需要删除这行代码var exists = await RNFS.exists(outputPath),并将if (exists) {...}替换为一行代码await RNFS.mkdir(outputPath);
    猜你喜欢
    • 2018-09-06
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 2013-06-27
    • 1970-01-01
    • 2020-10-31
    • 2015-08-11
    相关资源
    最近更新 更多