cordovaionic3cordova-pluginsionic-nativecordova-plugin-file

this.file.listDir won't return folders under the applicationStorageDirectory


when I am trying to list my folder directory with ionic-native file i am not getting any folders in result.

My Code:

this.platform.ready().then(() => {
      this.filesystem.listDir(this.filesystem.applicationStorageDirectory, '').then((result) => {
       console.log(result);
        /*result will have an array of file objects with 
        file details or if its a directory*/
        for (let file of result) {
          if (file.isDirectory == true && file.name != '.' && file.name != '..') {
            console.log("This is a folder");
            // Code if its a folder
          } else if (file.isFile == true) {
            // Code if its a file
            console.log("This is a file");
            let name = file.name // File name
            console.log("file name: " + name);
           // let path = file.path // File path
            file.getMetadata(function (metadata) {
              let size = metadata.size; // Get file size
            })
          }
        }
     });
    });

I am using: "@ionic-native/file": "4.12.0", With imports: import { File } from '@ionic-native/file';


Solution

  • You have not passed the directory name in this.filesystem.listDir(this.filesystem.applicationStorageDirectory, '') you have to pass directory name in this method. You can get directory name from the this.filesystem.applicationStorageDirectory. First alert this.filesystem.applicationStorageDirectory and check which type of path you get.

    If path is like :

    file:///storage/emulator/0/somefolder

    then get the directory name as following :

    let appStorageDir = "file:///storage/emulator/0/somefolder";
    let dirName = appStorageDir.substring(appStorageDir.lastIndexOf("/")+1);
    

    If there is slash(/) in the last of path like :

    file:///storage/emulator/0/somefolder/

    then get the directory name as following :

    let appStorageDir = "file:///storage/emulator/0/somefolder/";
    appStorageDir = appStorageDir.substring(0,appStorageDir.lastIndexOf("/"));
    let dirName = appStorageDir.substring(appStorageDir.lastIndexOf("/")+1);
    

    Now pass that dirName in method as following :

    this.filesystem.listDir(this.filesystem.applicationStorageDirectory, dirName)
    

    Hope it will help you !!!