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

187
Vistas
Node.js read folder then files with promise

I have a small challenge and my understanding with promises await and such things is not so good at moment, i can need some help to understand how to build my idea.

What i want to try is reading first a folder with files and then reading every files content after each other before doing the next step.

In my current code the problem is that the next then() block is execute before i want it to execute.

let counter = 0;
//---
const getFolder = (foldername) => {
  return new Promise((resolve, reject) => {
    fs.readdir(foldername, (err, files) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(files);
    });
  });
};
//---
getFolder('./filesarehere/')
  .then((folder) => {
    console.log('then 1');
    let amount = Object.size(folder);
    console.log('amount files ' + amount);
    let filenames = folder;

    filenames.forEach((file) => {
      let filePath2 = __dirname + '/filesarehere/' + file;
      fs.readFile(filePath2, (err, data) => {
        if (err) throw err;
        if (data.length > 10) {
          counter++;
          console.log('counter ' + counter);
        }
      });
    });
    return counter;
  })
  .then((data) => {
    console.log('then 2');
    console.log(data);
  })
  .catch((err) => console.error(err));

Now the above code does print this in my console log:

then 1
amount files 14
then 2
0
counter 1
counter 2
counter 3
counter 4
counter 5
counter 6
counter 7
counter 8
counter 9
counter 10
counter 11
counter 12
counter 13
counter 14

the part where then 2 is print does get the counter value 0 because the files reading have not end and later when the file reading have start you see the counter of the files is print, but i want it to first read all files and then return the result to the next part of the code which is the next .then() code

I hope somebody can understand what i mean, i am not using much coders slang because i am not a expert just want to learn it all at moment.

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

0

You can only use .then() and .catch() on functions that return a Promise. Your getFolder function is doing it correctly, and the first then() that you are using is correct too. But the second then() is called on a function that is not returning a Promise.

I'm not sure how much you are familier with Promises and async/await, but I suggest reading about them before working with them, because they are part of asynchronous codes in javascript wich are kinda hard to work with if you don't understand them first.

Here I wrote a simplified version with async/await, hope it helps:

// fs/promises has the same fs functions but the return a Promise
// instead of getting a callback
const fs = require('fs/promises');

// we can only use await in async functions, so we create a temporary
// async function
(async () => {
  let counter = 0;

  // await waits for a Promise to gets resolved
  // this returns both files and folders (directories)
  const files = await fs.readdir('./filesarehere');

  // Promise.all get an array of Promises
  await Promise.all(
    // each async function returns a Promise, so we map our files to a Promise
    files.map(async (file) => {
      const filePath = __dirname + '/filesarehere/' + file;

      // only use readFile if it's a file (not a folder)
      const isDir = (await fs.stat(filePath)).isDirectory();
      if (!isDir) {
        // here again we are waiting for the results of fs.readFile
        const data = await fs.readFile(filePath);
        if (data.length > 10) {
          counter++;
        }
        // the counter is passed into resolve function of the returned Promise
        return counter;
      }

      return null;
    })
  );

  console.log(counter);
})();

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