简体   繁体   中英

Typescript async await not working with the FS

typescript async await doesn't work with the current senario dealing with the NODE js FS.

Following the code.

   public static FileExists(filePath: string): Promise<boolean> {
        return new Promise<boolean>(async (resol, reje) => {
            try {
                fs.accessSync(filePath, fs.F_OK);
                resol(true);
            }
            catch (e) {
                resol(false);
            }
        });
    }

     public static async CreateDirectory(name: string): Promise<boolean> {
    return new Promise<boolean>(async (resolve, reject) => {
        let dirExist: boolean = await FileManager.FileExists(name);
        try {
            if (!dirExist) {
                fs.mkdirSync(name);
            }
            resolve(true);
        } catch (e) {
            resolve(false);
        }

    });

  for (var i = 0; i < paths.length; i++) {
                var element = paths[i];
                fullPath += element + "/";
                let a = await FileManager.CreateDirectory(fullPath);
                console.log(fullPath);
            }

I have added the await in the foreach but the loop continues and I don't get value of a before the loop iteration , instead it gives all the values at the end.

Note: i can add the promise to all object that are present in the loop but the problem is that it calls every time either the file is present or not, if the file isn't present it tries to create the same directory multiple times or each of the time file exist is called.

What i want that it should check for file once and not found , it should create directory and afterward the directory existence would be true so it woill stop creating same directory multiple muyltiple times.

You need to properly promisify an asynchronous file system method, so you cannot use accessSync and mkdirSync (or you could use them, but then promises and async function would be pointless).

Instead, do

public static fileExists(filePath: string): Promise<boolean> {
    return new Promise<boolean>(async resolve => {
        fs.accessSync(filePath, fs.F_OK, err => {
            if (err) resolve(false);
            else resolve(true);
        });
    });
}

public static async createDirectory(name: string): Promise<boolean> {
    if (!await this.fileExists(name)) {
        await new Promise(async (resolve, reject) => {
            fs.mkdir(name, err => {
                if (err) reject(err);
                else resolve();
            });
        });
    }
    return true;
}

var fullPath = ""
for (var element of paths)
    fullPath += element + "/";
    let a = await FileManager.createDirectory(fullPath);
    console.log(fullPath);
}

However, notice that using fs.access to check before an action is not recommended . You should instead simply catch the error:

public static createDirectory(name: string): Promise<boolean> {
    return new Promise(async (resolve, reject) => {
        fs.mkdir(name, err => {
            if (err) reject(err);
            else resolve();
        });
    }).then(() => true, err => {
        if (err.code == "EEXIST") return false;
        else throw err;
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM