There are many solution to to this but I found few or none in javascript on html webpage. I have a data file called sample.txt located where my html file is. My goal is to load txt file into the array that can be used to create a table and displayed on html file. My sample.text file has the following data:
sin 0.2 time 0.22222
cos 0.3 time 0.43434
tan 0.1 time 0.22221
I am new to Javascript and I admit that it is more difficult than other programming languages. I am familiar with javascript in node.js mode but not in html mode. I managed to create html web page (as shown below) and display basics like text and numbers in script mode. I also managed to load txt file and display it after pressing a button in script mode. This txt load method was the only method that worked for me. require (js) method did not work nor import. How do I create data array from this working mode?
Below is my complete code (corrected),
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Read Text File</title>
</head>
<body>
<input type="file" name="inputfile"
id="inputfile">
<br>
<pre id="output"></pre>
<script>
var file = document.getElementById('inputfile');
file.addEventListener('change', () => {
var txtArr = [];
var fr = new FileReader();
fr.onload = function() {
// By lines
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
txtArr = [...txtArr, ...(lines[line].split(" "))];
}
}
fr.onloadend = function() {
console.log(txtArr);
document.getElementById('output').textContent=txtArr.join("");
document.getElementById("output").innerHTML = txtArr[1];
console.log(txtArr[1]);
}
fr.readAsText(file.files[0]);
})
</script>
</body>
</html>