title: How to access a variable outside a function in Javascript?
body: <p>I have written the following code snippet to read the total number of lines present in a file. But I cannot access the counter's value outside of the readstream. When I print constraints and goals at the end it gives me 0. The expected outcome should be the total number of goals and constraints. Please help me with this.</p>
  <pre><code>const fs = require('fs');
  const readline = require('readline');
  const folder = './project/';
  var actors = 0;
  goals = 0;
  constraints=0;
  fs.readdirSync(folder).forEach(file =&gt; {
      actors = actors+1;
      fs.readdirSync(folder+file).forEach(f=&gt;{
          var path = folder+file+'/'+f;
          var k = 0;
          var r1 = readline.createInterface({
              input: fs.createReadStream(path),
              output: process.stdout,
              terminal:false
          });
          r1.on('line',(line)=&gt;{
              k++;
          });
          r1.on('close',()=&gt;{
               if(f==='Constraints.txt'){
                   constraints=constraints+k;
              
               }
               else{
                   goals=goals+k;
              
                }
          
            })
       });
  
   });
  
  console.log(actors);
  console.log(constraints);
  console.log(goals);
  </code></pre>