0

Array values logged at the end console.log(arr) are empty;

const fs = require("fs");
    const fss = require("fs");
    
      const data = fs.readFileSync("files_list.txt","utf-8");
      const lines = data.split(/\r?\n/);
    let arr = [];
    
    for (var i = 0; i < lines.length; i++) {
      const val = lines[i];
      const startLength = val.indexOf(';')+1;
      const endLength = lines[i].length;
    const hour = val.substring(startLength,endLength);
    const fileName = val.substring(0,endLength-2);
    fs.readFile("available.txt", function (err, dt){
      if (err) throw err;
      if(dt.includes(fileName)){
        var r = {
          filName:fileName,
          batchTiming:hour,
          status:'OK'
        };
        arr.push(r);
    }
    else
    {
        var r = {
        filName:fileName,
        batchTiming:hour,
        status:'OK'
      };
      arr.push(r);
    }
    
    });
    console.log(arr);
    }
Shreedhar Mathad
  • 51
  • 1
  • 1
  • 4

1 Answers1

0

You are attempting to log the contents of arr BEFORE anything has been put in it. fs.readFile() is non-blocking and asynchronous so your console.log(arr) runs before fs.readFile() calls its callback.

The ONLY place you can use the results of fs.readFile() is in the callback itself or in a function you call from within that callback and pass the result to that function.

P.S. This code is a little odd because you're reading the same file over and over again inside a for loop. That doesn't really make sense. You can read the content once before your loop and then use the content over and over again inside the for loop.

jfriend00
  • 683,504
  • 96
  • 985
  • 979