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...