Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

261
Views
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);
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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);
});
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!