0

data.txt:

xxxx1;yyyy1
xxxx2;yyyy2
xxxx3;yyyy3
xxxx4;yyyy4
xxxx5;yyyy5

Here is how my data.txt looks like and when I run the following function:

var fs = require('fs');
var x = [];
var y = [];
function pushdata(){
  fs.readFile('data.txt', (err, data) => {
    data = data.toString().split("\n");
    for (let i = 0; i < data.length; i++) {
      x.push(data[i].split(';')[0]);
      y.push(data[i].split(';')[1]);
    }
  });
}
pushdata()
console.log(x, y);

The output is:

[] []

Instead of:

[ 'xxxx1', 'xxxx2', 'xxxx3', 'xxxx4', 'xxxx5' ] [ 'yyyy1', 'yyyy2', 'yyyy3', 'yyyy4', 'yyyy5' ]

What am I doing wrong?

uhbc
  • 84
  • 1
  • 8

1 Answers1

0

You have to wait for completion. You log the arrays before anything has been pushed into them

var fs = require('fs');
var x = [];
var y = [];
function pushdata(done){
  fs.readFile('data.txt', (err, data) => {
    data = data.toString().split("\n");
    for (let i = 0; i < data.length; i++) {
      x.push(data[i].split(';')[0]);
      y.push(data[i].split(';')[1]);
    }
    done()
  });
}

pushdata(function () {
  console.log(x, y); 
})
Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • Isn't there anything I can do other than do what you've done or using setTimeout() ? – uhbc Dec 18 '18 at 20:04
  • @uhbc yeah, you can use setTimeout. however... how long should you tell it to wait? – Kevin B Dec 18 '18 at 20:11
  • I'm not sure but I'll use the x and y values in a for loop right after I run the pushdata() function. – uhbc Dec 18 '18 at 20:19