Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

262
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda