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.
const fs = require('fs');
const readline = require('readline');
const folder = './project/';
var actors = 0;
goals = 0;
constraints=0;
fs.readdirSync(folder).forEach(file => {
actors = actors+1;
fs.readdirSync(folder+file).forEach(f=>{
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)=>{
k++;
});
r1.on('close',()=>{
if(f==='Constraints.txt'){
constraints=constraints+k;
}
else{
goals=goals+k;
}
})
});
});
console.log(actors);
console.log(constraints);
console.log(goals);