Search code examples
cordovaionic-frameworkionic2ionic3ionic-native

Ionic 2 Native File: Create directory recursively


I am using Ionic 2 Cordova Plugin File to save some files in a Ionic Hybrid app. I would like to store them in directories, which, if not already existing, I try to create with:

this.file.createDir(this.getPathWithoutLast(absolutePath), this.getLastPathString(absolutePath), true);

My absolute path looks like this:

file:///data/user/0/io.ionic.starter/files/dir1/dir2/dir3/dir4

I get the error {"code":1,"message":"NOT_FOUND_ERR"}.

After some testing, I think that the method cannot create directories recursively, so I implemented my own method for creating them one after the other.

However, this seems like something that more people need so I would like to ask if there really is no such option in the Plugin and if not, whether there is a reason I did not think of.

Thanks everyone for their time! Pavol


Solution

  • I am going to post my solution as well, just in case:

        public async makeSureDirectoryExists(relDirPath: string): Promise<boolean> {
            console.log(`making sure rel Path: ${relDirPath}`);
            const absolutePath = this.file.dataDirectory + relDirPath;
            console.log(`making sure abs Path: ${absolutePath}`);
            const pathParts = relDirPath.split('/');
    
            const doesWholePathExist: boolean = await this.doesExist(absolutePath);
            if (doesWholePathExist) {
                return true;
            }
            let currentPath = this.file.dataDirectory;
            while (pathParts.length > 0) {
                const currentDir = pathParts.shift();
                const doesExist: boolean = await this.doesExist(currentPath + currentDir);
                if (!doesExist) {
                    console.log(`creating: currentPath: ${currentPath} currentDir: ${currentDir}`);
                    const dirEntry: DirectoryEntry = await this.file.createDir(currentPath, currentDir, false);
                    if (!dirEntry) {
                        console.error('not created!');
                        return false;
                    }
                }
                currentPath = currentPath + currentDir + '/';
            }
            return true;
        }