Uri
Uri

Reputation: 26966

FileReader not reading file properly

I ran the following function with a valid file object but it didn't work. The read text was an empty string. However, when I run the same commands via the console, it does work.

function(file) {
  console.log(file)
  var reader = new FileReader();
  reader.readAsText(file);
  console.log(reader.readyState);
  console.log(reader.result);
}

Why?

Upvotes: 1

Views: 1320

Answers (1)

Uri
Uri

Reputation: 26966

I needed to set a callback for when the reader finishes reading the file, as this is done asynchronously.

function(file) {
  console.log(file)
  var reader = new FileReader();
  reader.onload = function() {
    console.log(reader.readyState);
    console.log(reader.result);
  }
  reader.readAsText(file);
}

Upvotes: 3

Related Questions