Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda