0

In JavaScript with Node.js, I'm not able to join the global array.

test.csv ends up containing c,d

var placeName = ["a","b"];
var csvFile = 'test.csv';
fs.readFile(csvFile, 'UTF-8', function(err, csv) {
  $.csv.toArrays(csv, {}, function(err, data) {
    for(var i=0, len=data.length; i<len; i++) {
      console.log(data[i]); //Will print every csv line as a newline
      placeName.push(data[i][0].toString());
    }
  });
   console.log(placeName); //Inside the function the array show a,b,c,d
});

// Prints only a and b. Did not add c & d from the csv.
console.log(placeName); 
Ari Seyhun
  • 11,506
  • 16
  • 62
  • 109
Sam
  • 89
  • 1
  • 1
  • 6

1 Answers1

1

It is because of asynchronous behaviour of JavaScript. console.log(placeName) outside is executed before you even read your CSV file.

Vipin Kumar
  • 6,441
  • 1
  • 19
  • 25