0

I am trying to read file from a .txt file in nodejs, when i get access to each line, I push it to an array but in the end, the array is empty.

var array=[];

  let lineReader = require('readline').createInterface({
    input: require('fs').createReadStream('file.txt')
  });
  
  lineReader.on('line', function (line) {
    console.log(line);
    array.push(line);
  });

console.log(array);

.Txt File Content

THIS IS LINE#1
THIS IS LINE#2
THIS IS LINE#3

Output

[]
THIS IS LINE#1
THIS IS LINE#2
THIS IS LINE#3
2
  • 2
    lineReader.on('line', function (line) {...}) is not synchronous ( mean, the function you pass to it is not called synchronously). Commented May 6, 2021 at 12:17
  • 1
    You say it's synchronous in the title...but an event listener (= on(...)) is not synchronous (as you can see in the output) Commented May 6, 2021 at 12:18

1 Answer 1

1

The problem is that the thing happens async. You need to add a listener for close event.

lineReader.on("close", () => {
    console.log(array);
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.