1

I am having difficulty creating an array entry out of each line of a text file in node.js

My array is called "temp." I am able to console.log each line in the following code:

var temp = [];
const readline = require('readline');
const fs = require('fs');
let rl = readline.createInterface({
    input: fs.createReadStream('./lib/Sphinx.txt')
});
let line_no = 0;
rl.on('line', function(line) {
    line_no++;
    console.log(line); //this successfully prints out every line
    temp.push(line); //this would ideally create a new array entry for each line

});

However, when I run this code:

console.log(temp.length)
//returns 0
console.log(temp.size)
//returns undefined

Asynchronous function calls are causing this to happen. As a result, I am unable to access the array values outside of the function itself, which is the only objective.

Help is appreciated. Thanks, Nakul

1 Answer 1

1
rl.on('line', function (line) {
    line_no++;
    console.log(line); //this successfully prints out every line
    temp.push(line); //this would ideally create a new array entry for each line
}).on('close', function (line) {
    // EOF
    console.log(temp);
    console.log(temp.length);
});;
  • Write console.log(temp.length) instead of console.log(temp.size) that should work

  • You should get complete array at the end of your line by line read, i.e. on close event.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting 0 for that.
Thanks for the help. It turns out that my original code was actually correct. It was just a matter of asynchronous execution.

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.