Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript File Reader

I may just not be understanding the file reader api, but

When I try to run:

for (var i = 0, f1, f2; f1 = files[sorted_index[i]], f2 = files[sorted_index[i+1]]; i=i+2) {
    var file_one;
    var file_two;

    if(f1.size < f2.size){
        file_one = f1;
        file_two = f2;
    } else {
        file_one = f2;
        file_two = f1;
    }

    var file_one_contents;
    var file_two_contents;


  var reader = new FileReader();
  reader.readAsText(file_one);
  reader.onload = readSuccess;

  function readSuccess(evt){
    file_one_contents = evt.target.result;
  }
  var reader = new FileReader();
    reader.readAsText(file_two);
    reader.onload = readSuccess2;

  function readSuccess2(evt2){
    file_two_contents = evt2.target.result;
  }

    console.log(file_one_contents);
    console.log(file_two_contents);

The console log only contains undefined in it. The goal of the script it two read in two CSVs and take the data from the pair of files and do some computations.

Thanks!

like image 616
Steven Stangle Avatar asked Feb 22 '26 12:02

Steven Stangle


2 Answers

The API is asynchronous. The "success" functions are called when the operation completes, and that won't be immediate.

Move your console.log() calls to inside the handler functions.

edit — If you need to wait to start doing stuff until both files are ready, you can do something like this:

  var countdown = 2;

  var reader = new FileReader();
  reader.readAsText(file_one);
  reader.onload = readSuccess;

  function readSuccess(evt){
    file_one_contents = evt.target.result;
    countdown--;
    if (countdown === 0) go();
  }
  var reader = new FileReader();
    reader.readAsText(file_two);
    reader.onload = readSuccess2;

  function readSuccess2(evt2){
    file_two_contents = evt2.target.result;
    countdown--;
    if (countdown === 0) go();
  }

There are more sophisticated ways to do it, of course, but that simple trick just waits until the counter is zero before calling "go()", which represents the function that'd work on processing the files.

like image 69
Pointy Avatar answered Feb 25 '26 02:02

Pointy


I had a similar problem which solved the file read waiting by using ".onloadend" instead of "onload". In the code below x is bound to a "div" element

reader.onloadend = function (evt) {
    x.innerHTML = evt.target.result;
}

With "onload" it was all undefined.

like image 29
Lars GJ Avatar answered Feb 25 '26 01:02

Lars GJ