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

161
Visualizações
Best way to conditionally create directories in an asynchronous loop

I have a list of files I'd like convert, recreating the original nested directory structure. I'm using the promises version of the fs module and use asynchronous code as much as possible. My current code looks like this:

import fs from 'fs/promises';
import path from 'path';

const sourceFiles = [
   // big list of file paths here
];

const allDone = Promise.all( sourceFiles.map( async (srcFile) => {
   const destFile = path.join('dest', srcFile);
   const destDir = path.dirname(destFile);
   // Async existence check with 'access' in try/catch block, since we don't have fs.exists
   try {
      await fs.access(destDir);
   } catch (e) {
      await fs.mkdir(destDir);
   }
   return myConversionFunction( srcFile, destFile);
} ) );

I'm getting errors that the directory already exists, probably because there is a race condition between fs.access and fs.mkdir when running several Promises "in parallel".

I could solve this by calling mkdir with {recursive: true}, but that would try to create the directory on every file.

I could also iterate over the file list twice, creating a list of target directories and then just map over myConversionFunction. But that feels inefficient for big file lists.

Is there a better way to conditionally create directories?

about 4 years ago · Juan Pablo Isaza
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