Reputation: 565
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
Upvotes: 1
Views: 244
Reputation: 635
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.
Upvotes: 1