Search code examples
javascriptandroidreact-nativefilesystemsreact-native-fs

How to rename / move a folder in react native fs?


I am having trouble renaming and moving folders cause react native fs has only moveFile option that performs on files only and not folders.Doing it recursive is also messy and it is hard to execute lines after performing rename or move option due to synchronous execution.I have attached the code for move below with the bug.Kindly help me figure this out.

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

Thanks in advance :)


Solution

  • Thanks for the help I figured the answer with your solutions

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