I am confused by some simple behavior I see from readline on()
method.
I have a file called small.csv
which looks like this:
Because of it's asynchronous nature Node.js can be a bit tricky with this kind of things. It means that when your code is executing, it is firing the rl.on('line')
handler and passing to the next call which in our case is the console.log
. The problem in your actual code is not that the array is not filling up, it's that you are expecting it to be populated to early. Here is an example of how you could fix your problem:
var rl = require('readline').createInterface({
input: require('fs').createReadStream('small.csv')
});
global.myarray = [];
rl.on('line', function (line) {
console.log('Line from file:', line);
global.myarray.push(line);
});
rl.on('close', function () {
console.log(global.myarray);
});
In this piece of code, when there is no more line to read from, the console.log
will be called and there will be some data displayed.