0

I read a file line by line, turn each line into an array of number and push that array to a 2D array. But when I logged that 2D array, it was empty. I really don't know what's wrong here.

Here is my code:

var readline = require('readline');
var fs = require('fs');

var interface = readline.createInterface({
    input: fs.createReadStream('dataset.csv')
});

var transactions = []; // declare the 2d array
interface.on('line', function (line) {
    var str = line.trim().split(' ').map(Number); // turn each line to a number array
    transactions.push(str); // push that number array to the 2d array
});

console.log(transactions);
Brother Eye
  • 689
  • 1
  • 11
  • 27
  • One line: `[ 112, 162, 224, 368, 395, 527, 568, 613, 788, 798, 805, 814, 913, 988 ]`, no error at all, the result is just `[]` – Brother Eye Jul 25 '18 at 07:43
  • Base on the suggested question, I think there might be something about how nodejs work with the IO. It printed the array first while the file was still being read, perhaps – Brother Eye Jul 25 '18 at 07:47
  • 2
    `interface.on('line',` is async, you cannot console.log the transactions where you are logging them. Instead `interface.on('close', function () { console.log(transactions); });` – mplungjan Jul 25 '18 at 07:49

0 Answers0