Reputation: 101
I am trying to write a java script to read a file in chrome and I am using the javascript debugger of chrome. here is the script:
function myFunction()
{
alert("I am an alert box!");
var e ;
var contents;
var control = document.getElementById("myfile");
files = control.files;
console.log("Filename: " + files[0].name);
var reader = new FileReader();
reader.readAsText(files[0]);
reader.onload = function (e) {
contents = e.target.result;
};
console.log("File contents: " + contents);
console.log("I am an alert box!");console.log("I am an alert box!");
}
</script>
when i run the code the contents variable is undefined. Plenty of discussion has gone into this but i have not found a solution. I am using the --allow-file-acess-from-files option. Now the following code works in a strange manner:
<script>
function myFunction()
{
alert("I am an alert box!");
var e ;
var contents;
var control = document.getElementById("myfile");
files = control.files;
console.log("Filename: " + files[0].name);
var reader = new FileReader();
reader.readAsText(files[0]);
reader.onload = function (e) {
contents = e.target.result ;
};
console.log(e.target.result);
console.log("I am an alert box!");console.log("I am an alert box!");
}
</script>
It throws an error which is "Uncaught TypeError: Cannot read property 'target' of undefined" However in the watch expression window the following variables show that the file is being read.
event.target.result: "firmware file ↵:10000000782600204D4B0000B94B0000B94B000092 ↵:10001000B94B0000B94B0000B94B000000000000D4 ↵:10002000000000000000000000000000B94B0000CC ↵:10003000B94B000000000000B94B0000210B00008C ↵:10004000B94B0000B94B0000B94B0000B94B0000A0 ↵:10005000B94B0000B94B0000B94B0000B94B000090 ↵:10006000B94B0000B94B0000B94B0000B94B000080 ↵:10007000B94B0000B94B0000B94B0000B94B000070 ↵:10008000B94B0000B94B0000B94B0000B94B000060 and the same ouput for e.target.result and contents variable.
Why is the code behaviour is so wierd? Kindly help me out. I am not very skilled with javascripting.
Upvotes: 0
Views: 443
Reputation: 2242
e.target
will be undefined on your 2nd console.log there towards the bottom - only one is inside your onload
function, and therefore has e
set.
The second one is acting on the var e ;
you defined at the top, which is null, and therefore e.target.result
is invalid.
e: in other words, delete this line, or move it into the function:
Upvotes: 1