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

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

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 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