Steve
Steve

Reputation: 4453

How to make fs.readFile async await?

I have this nodejs code here which read a folder and process the file. The code works. But it is still printing all the file name first, then only read the file. How do I get a file and then read a content of the file first and not getting all the files first?

async function readingDirectory(directory) {
    try {
        fileNames = await fs.readdir(directory);
        fileNames.map(file => {
            const absolutePath = path.resolve(folder, file);
            log(absolutePath);
            
            fs.readFile(absolutePath, (err, data) => {
                log(data); // How to make it async await here?                
            });
        });
    } catch {
        console.log('Directory Reading Error');
    }
}

readingDirectory(folder);

Upvotes: 6

Views: 13518

Answers (1)

jfriend00
jfriend00

Reputation: 707158

To use await, you need to use promise versions of fs.readFile() and fs.readdir() which you can get on fs.promises and if you want these to run sequentially, then use a for loop instead of .map():

async function readingDirectory(directory) {
    const fileNames = await fs.promises.readdir(directory);
    for (let file of fileNames) {
        const absolutePath = path.join(directory, file);
        log(absolutePath);
        
        const data = await fs.promises.readFile(absolutePath);
        log(data);
    }
}

readingDirectory(folder).then(() => {
    log("all done");
}).catch(err => {
    log(err);
});

Upvotes: 11

Related Questions