Passing file contents to outside variable
filereader, javascript
Solution
I assume that you know, its `async` and all.
So, the short answer is: No, you can not do that.
However, if you want the contents to be globally accessible for any future calls, you could something like this:-
var contents;// declared `contents` outside
function readFileData(evt) {
var file = evt.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
contents = e.target.result; //<-- I removed the `var` keyword
}
reader.readAsText(file);
}
document.getElementById('file').addEventListener('change', readFileData, false);
var reasonableTimeToWaitForFileToLoad = 100000;
console.log(contents); //`contents` access first attempt: prints undefined
setTimeout(function() {
console.log(contents);//`contents` access second attempt: prints the contents 'may be if the time allows.'
}, reasonableTimeToWaitForFileToLoad);
Problem
I'm using a FileReader and the HTML file dialog to read a file in my script. How do I pass this file's contents out of the FileReader.onload function? ``` function readFileData(evt) { var file = evt.target.files[0]; var reader = new FileReader(); reader.onload = function(e) { var contents = e.target.result; } reader.readAsText(file); } document.getElementById('file').addEventListener ('change', readFileData, false); /* I want to access the contents here */ ``` I tried sticking returns in the readFileData and onload functions, but I'm not sure what they return to.