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

212
Vistas
How to use promises to asynchronously read directories and its contents node.js?

I'm trying to create a promise to check the contents of a certain directory in node. I believe I have an error with looping thats giving me an issue, im just not sure what it is.

 var fileCheck = collectionMonth +" "+ collectionDate 

    var getFileFromDate = new Promise(function(resolve,reject){
        fs.readdir(__dirname + "/UpcomingCollections/",function(err,files){
            for(i in files){ // <--- This returns directories dated (for example, "May 25th","May 26")
                var projectFileDirectory = files[i]
                if(projectFileDirectory.includes(fileCheck)){ // <-- File check is today's date.
                    console.log(projectFileDirectory) // <-- If today's date is equal to one of the files, print the file. This prints correctly, May 26th.
                    fs.readdir(__dirname + "/UpcomingCollections/" + projectFileDirectory,function(err,todaysMints){
                        // This reads the Directory of today's current date, which contains files.
                        // console.log(projectFileDirectory) returns another folder other than May 26th down here, why is that?
                        resolve({"mints":todaysMints,"mintDate":projectFileDirectory})
                    })
                }
            }
        })
    })
    getFileFromDate.then(function(data){
        const currentDayProjects = data;
        console.log(currentDayProjects)

        currentDayProjects.mints.forEach(function(project){
            console.log(project) // <--- This logs the projects inside the directory.
            var data = fs.readFileSync(__dirname + "/UpcomingCollections/" + currentDayProjects.mintDate +"/"+project,'utf8')
            console.log(data)
            // always errors because its using the incorrect mintDate
        })
    })

I commented in my code to try and explain what is going on, I'm not sure why its printing the correct date and then as soon as i read the file it returns another date. As far as I know, I have my promise and everything setup correctly. Because everything is working the way it should, except for the fact Im not sure why the projectFileDirectory variable is logging something different two lines down after the first log.

I checked this out Iterating file directory with promises and recursion and actually learned a few things, but mainly towards promises and async/await. not related to my current issue.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Updated code, may be a bit inefficient but it gets the job done.

function getDailyMints(r){
    return new Promise(function(resolve, reject){
        fs.readdir(__dirname + "/UpcomingCollections/" + r,function(err,todaysMints){
            resolve(todaysMints)
         })  
    }) 
}



function getFiles(){
    var date = new Date();
    var collectionDate = date.getDate()
    var collectionData = date.getMonth()
    var collectionMonth = months[collectionData]
    var fileCheck = collectionMonth +" "+ collectionDate 

    var getDirectoryFromDate = new Promise(function(resolve,reject){
        fs.readdir(__dirname + "/UpcomingCollections/",function(err,files){
            resolve(files)
        })
    }).then(function(data){
        console.log(data)
        for(i in data){
            if(data[i].includes(fileCheck)){
                console.log(fileCheck)
                const currentMintDay = data[i]
                return new Promise(function(resolve,reject){
                    resolve(currentMintDay)
                })
            }
        }
    }).then(function(r){
        console.log(r)
        getDailyMints(r).then(function(fileArray){
            console.log(r)
            for(files in fileArray){
                fs.readFile(__dirname + "/UpcomingCollections/" + r + "/" + fileArray[files],'utf8',function(err,fileData){
                    console.log(fileData)
                })
            }
            
        })
    })
}
about 4 years ago · Juan Pablo Isaza Denunciar
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