I am trying to create an almost completely client side project that reads a given text file with a function and returns the contents of a file (as a string) to a variable. Some of these files may be VERY VERY large if that makes any difference on approaches. I would like a function that would perform like...
// fileInputID is the input type='file' id
var fileText = ReadTextFromFile('fileInputID');
So far I have something like this which doesn't do what I want, but it is as close as I can get so far...
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="file" id="xFile" value="Get Data">
<script>
// A non-blocking sleep function (I think)
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
};
async function ReadFile(fileInputID) {
// Get the selected file from the input id.
var file = document.getElementById(fileInputID).files[0];
var str = "";
var fileReader = new FileReader();
fileReader.onloadend = function(evt) {
str += fileReader.result;
};
// Read the file.
fileReader.readAsText(file);
// Wait for file to be completely read.
do {
await sleep(100);
} while (fileReader.readyState != 2);
console.log(str); // Correctly prints the string.
console.log(typeof str); // Type of str is String.
return str; // OH NO! Doesn't send anything back?
}
</script>
<div id="output"></div>
<button id="output" onclick="var fileText = ReadTextFromFile('xFile'); console.log(fileText);"></button>
</body>
</html>
I would really like to not have to send it to the server, just to have it sent back again. Also, I want it to stay a returning function instead of trying to save it to a global variable so it may stay more dynamic. Any ideas would greatly help.
Would really like to end up with something possible like...
var xData = ReadTextFromFile('xFile');
var yData = ReadTextFromFile('yFile');
plot(xData, yData);