Ionic 2 本机文件:递归创建目录



我正在使用Ionic 2 Cordova插件文件将一些文件保存在Ionic Hybrid应用程序中。我想将它们存储在目录中,如果不存在,我会尝试使用以下内容创建:

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

我的绝对路径如下所示:

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

我收到错误{"代码":1,"消息":"NOT_FOUND_ERR"}。

经过一些测试,我认为该方法无法递归创建目录,因此我实现了自己的方法来一个接一个地创建目录。

但是,这似乎是更多人需要的东西,所以我想问一下插件中是否真的没有这样的选项,如果没有,是否有我没有想到的原因。

感谢大家抽出宝贵时间!Pavol

我也要发布我的解决方案,以防万一:

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

是的,我遇到了同样的问题,所以结束了编写自己的函数来处理这个问题。

没有测试这个,因为我找不到原来的,但它应该是这样的

createRecursivePath(path: string | Array<string>): Promise<string> {
    if (typeof path === 'string') {
        path = path.split('/');
        return this.createRecursivePath(path);
    }
    if (!Array.isArray(path)) {
        return Promise.reject('Error on data entry');
    }
    let promiseArray: Array<Promise<DirectoryEntry>> = path.map((dirName, index, array) => {
        let createdDirPath = array.slice(0, index);
        return this.file.checkDir([this.getDefaultAppPath(), ...createdDirPath].join('/'), dirName)
            .then()
            .catch(() => this.file.createDir([this.getDefaultAppPath(), ...createdDirPath].join('/'), dirName,false));
    });
    return Promise.all(promiseArray)
        .then(() => Promise.resolve(Array.isArray(path) && path.join('/') || ''));
}

最新更新