As part of a hobby project exploring WebGPU I need load data from files in local storage into Javascript.
Searching around the problem I see that the Javascript File API offers a great native solution to my problem: which is to use a form with a file type input element and then with a button that will eventually be used to ingest the data, modify it - and then send it to be used for rendering.
I am a JavaScript beginner, but I have some experience with C++ so managed to scrape together a minimal example from some tutorial sites (below). However, all of the example code I can find takes the data read from file and uses it to modify a DOM-objects' inner HTML to that data that has been read from file, whereas I would like to store it into a string to then work with later.
The problem I find seems to be one of scope, insofar as I can produce a JS function my_file_read
that, when my input element has been given a (plaintext) file and the button is pressed
it successfully logs it to the console. However if I wish to read the file and then output the resulting string, my output string does not seem to get set properly when returning to the caller. Looking around the net and here on stack-overflow I cannot seem to find an exmple of someone having this problem nor an example of working code (as all examples pertain to modifying DOM-objects to then display onscreen) and was hoping that someone could advise on how to modify my JavaScript to make it functional:
Minimal Example:
<!doctype html>
<html>
<div class="my_input_form">
<div id="">
<div><input type="file" class="my_input"></input></div>
<div><button class="my_input_button">input</button></div>
</div>
</div>
</html>
<script>
let my_file_read = function (input_file){
let my_file_reader = new FileReader;
let out = new String();
my_file_reader.onload = () => {
out = my_file_reader.result;
//console.log(my_file_reader.result);
}
my_file_reader.readAsText(input_file);
return out;
}
//--- Grab the Required DOM Objects
let my_form = document.querySelector(`.my_input_form`);
console.log("my_form",my_form);
let my_input = my_form.querySelector(`.my_input`);
console.log(`my_input`,my_input);
let my_input_button=my_form.querySelector(`.my_input_button`);
console.log(my_input_button,`my_input_button`);
//---
//Ingest File On Button-Press
my_input_button.addEventListener(`click`, () => {let o = my_file_read(my_input.files[0]); console.log(o);})
</script>
Note that the commented out line //console.log(my_file_reader.result)
, if uncommented, causes any inputted file to correctly be logged to the console. As it stands, my function only gives the empty string as a return. What I cannot find is good information on how to successfully bring the data from outside of the scope of the .onload
call (and into the scope of the lambda / arrow function given in the click
event), which is the crux of my question.
Thanks for reading.