0

I have to read in a few test text files into my JavaScript code. There are 3 files, titled 1.txt, 2.txt and 3.txt, each containing a single line. I wrote this piece of code which I thought would work just fine:

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0; i < files.length; i++) {
        console.log("Start loop")
        myFile = files.item(i);
        var myReader = new FileReader();
        myReader.readAsText(myFile);
        myReader.onload = function(e) {
            var rawLog = myReader.result;
            console.log(rawLog)
        };

    }
};

document.getElementById('files').addEventListener('change', handleFileSelect, false);

This results in a button on the web page that allows me to select multiple files. It is supposed to result in the following:

Start loop
Contents 1.txt
Start loop
Contents 2.txt
Start loop
Contents 3.txt

But what it outputs is the following:

Start loop 
Start loop
Start loop
null
null
Contents 3.txt

How can I generate the first one? I expect the error to be in the onload function, but I'm not sure what I'm doing wrong...

1 Answer 1

1

In your code var myReader = new FileReader(); is reassigning the variable in each loop hence destroying the first instance.

I recommend you split your code to two functions to prevent the local block variable's instances from being overwritten before they are done.

function readFile(file) {
    var myReader = new FileReader();
  myReader.readAsText(file);
  myReader.onload = function(e) {
      var rawLog = myReader.result;
      console.log(rawLog)
  };
} 

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    for (var i = 0; i < files.length; i++) {
        myFile = files.item(i);
        readFile(myFile);
    }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.