I have the following code for opening up a file, reading it in line by line, and pushing each line to an array. I am able to console.log the line before I push it to the array, so I know it has a value as a line, at that stage. But I am then unable to console.log it after that as an element of the array. I figure this has something to do with scope, but I can't see why it doesn't work at all - It just logs as "undefined".
var fs = require ("fs");
var lines = [];
function readLines(input, func)
{
var remaining = '';
input.on('data', function(data)
{
remaining +=data;
var index = remaining.indexOf('\n');
while(index > -1)
{
var line = remaining.substring(0, index);
remaining = remaining.substring(index + 1);
func(line);
index = remaining.indexOf('\n');
}
});
input.on('end', function()
{
if(remaining.length > 0)
{
func(remaining);
}
});
}
function func(data)
{
console.log ("line : " + data);
lines.push(data);
}
var input = fs.createReadStream('testing.csv');
readLines(input, func);
console.log(lines[0]);