title: How can I send data to the client after use readdir inside a readdir
body: <p>I need read a folder called 'curvas'. A lot of folders are inside 'curvas' and i'm using readdir to get them. After get the folders inside 'curvas', i'm doing a foreach and using readdir to list the files (files inside the folders that is inside 'curvas'). </p>
  
  <p>The problem is that i can only access the variable inside the internal readdir (i tested with console.log). </p>
  
  <p>Q: How can I access this variables and respond to the client with res. ? </p>
  
  <p>Here's how far I came:</p>
  
  <pre><code>exports.getInserted = async function (req, res) {
  
      var teste = await getFilesNames(); // HERE I NEED TO GET THIS FILES NAMES WITH FOLDERS
      console.log(teste); // AND THEM PASSING TO THE CLIENT WITH RES.SEND()
  
  };
  
  function getFilesNames() {
      return new Promise(function (resolve, reject) {
  
          const chartFolder = './curvas/';
          var fileNames = [];
  
          fs.readdir(chartFolder, (err, folders) =&gt; {
  
              if (err) {
                  reject(new Error("Erro ao ler os arquivos."));
              }
              folders.forEach(folder =&gt; {
                  fs.readdir(chartFolder + folder, (err, files) =&gt; {
                      fileNames = files;
                      console.log(files) // ----- HERE I CAN SEE ALL FILES AND LIST WITH THEIR FOLDERS.
                  });
              });
              // I NEED USE resolve(fileNames) HERE, BUT IS EMPTY!!
          });
      });
  };
  </code></pre>
  
  <p>Thank you!</p>
  
  <p>[EDIT]</p>
  
  <p><strong>Solution:</strong> Guided by @omarwaleed</p>
  
  <pre><code>    exports.getInserted = async function (req, res) {
  
      // Envia os arquivos das pastas de curvas para o cliente.
      var data = await getFilesNames();
      res.status(200).send(data);
  
  };
  
  function getFilesNames() {
      return new Promise(function (resolve, reject) {
  
          const chartFolder = './curvas/';
  
          // take care. I've turned it into an async function here
          fs.readdir(chartFolder, async (err, folders) =&gt; {
  
              if (err) {
                  reject(new Error("Erro ao ler os arquivos."));
              }
              let promiseArray = [];
              folders.forEach(folder =&gt; {
                  promiseArray.push(
                      new Promise((resolve, reject) =&gt; fs.readdir(chartFolder + folder, (err, files) =&gt; {
                          if (err) {
                              reject(err);
                          }
                          resolve({
                              folder: folder,
                              files: files
                          });
                      }))
                  )
              });
              let results = await Promise.all(promiseArray);
              resolve(results)
          });
      });
  };
  </code></pre>