5

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);
Steve
  • 2,963
  • 15
  • 61
  • 133
  • 4
    1. Make sure you use `fs/promises` and not plain `fs`. 2. Don't use `map` but a regular `for ... of` loop. Use `const await data = fs.readFile(..)` instead of callbacks. – Evert Feb 01 '21 at 01:48
  • 1
    `fs.promises.readFile()` will work with `await`. – jfriend00 Feb 01 '21 at 01:49

1 Answers1

9

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);
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979