2

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> 
Aschoolar
  • 343
  • 3
  • 9
  • Did you try fs.readFile ? You may refer to this link:[Get data from fs.readFile](https://stackoverflow.com/questions/10058814/get-data-from-fs-readfile) – Ken Lee Jan 21 '21 at 04:53
  • Do you have control over the file format? Having little to no data structure other than white space makes it more difficult than it needs to be. Can you format it as JSON? Or even CSV? – Randy Casburn Jan 21 '21 at 05:11
  • Yes, I have some control of file format. Text.txt files are generated by other language codes such as c, pascal etc. The purpose of my coding is to develop code for few programming languages including javascript that measures speed performance of doing basic math operations for each language. Then compares them. I use javascript to sum up results and display them as part of learning and exercise. – Aschoolar Jan 24 '21 at 13:02

2 Answers2

1

Using FileReader, get the string line by line and then split it and merge it into the resultArr as follows:

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("");
    }

    fr.readAsText(file.files[0]);
})
<!DOCTYPE html> 
<html> 

<head> 
    <title>Read Text File</title> 
</head> 

<body> 
    <input type="file" name="inputfile"
            id="inputfile"> 
    <br> 

    <pre id="output"></pre> 
    
</body> 

</html> 
Sunil Lama
  • 4,531
  • 1
  • 18
  • 46
  • Your code is the only example that works on my system. Thanks for code snippet, it is helpful. I can see that the array is txtArr and it has all the strings in it a total of 15 strings. However, when I try to access txtArr for individual string say txtArr[3] to get 100 I get nothing in console. How and where place code to access txtArr? Is this placement correct? ` }fr.readAsText(file.files[0]); document.getElementById("output").innerHTML = txtArr[1]; console.log(txtArr[1]);` I am unswering my own question to show my new complete code listing. – Aschoolar Jan 22 '21 at 16:30
  • 1
    it should be inside the fr.onloadend function @Aschoolar – Sunil Lama Jan 22 '21 at 17:26
1

The reason the other methods didn't work is because Javascript does not have access to the filesystem. You need a server side language for this, like NodeJS.

Anyway, here's some pure Javascript code that lets you load text files, split result into a text array for each line and split those again to have data arrays for each line of data. As a little bonus, I also added a method to download everything in a text file again:

function loadFile(input, onloadCallback){
    const fr = new FileReader();

    fr.onload = onloadCallback;

    fr.readAsText(input);
}

/* Save file and force download */
function saveFile(data, fileName){
    const blob = new Blob([data], {type: 'text/csv'});
    if(window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveBlob(blob, fileName);
    } else {
        var elem = window.document.createElement('a');
        elem.href = window.URL.createObjectURL(blob);
        elem.download = fileName;        
        document.body.appendChild(elem);
        elem.click();
        document.body.removeChild(elem);
    }
}

/* Working with text files */
function openFile(ev){
    loadFile(ev.target.files[0], function(e) {
        // Get all the text as a string
        const result = e.target.result;

        // Make array out of result for each line
        const textArray = result.split("\r\n");

        // How to add new lines to the array if you want
        textArray.push("tan 0.2 time 0.23641");

        // Create dataArray for each line
        let dataArray = [];

        for(let i = 0; i < textArray.length; i++){
            const data = textArray[i].split(" ");

            dataArray.push(data);
        }

        // dataArray now contains arrays for each line of data
        console.log(dataArray);

        // Here's how you'd put a normal array back into a string
        const newString = textArray.join("\r\n");

        // Finally a way to download a file with the new string inside it
        saveFile(newString, 'test.txt');
    });
}
icecub
  • 8,615
  • 6
  • 41
  • 70
  • This one is useful. It works although don't know the location of saved test.txt file. – Aschoolar Jan 22 '21 at 16:51
  • @Aschoolar The location would be where ever you save it. If you use the save function, it will force a "download" to your browser just like any other file you would download from the internet. – icecub Jan 22 '21 at 22:12
  • 1
    Like I said: Javascript does not have access to the filesystem. This is a security measure. So your browser decides where the file is saved. Your browser does have access to the filesystem. If you have it set to a default location, it's most likely in your Downloads directory. If you have set it to "ask" in your browser instead, it'll ask you where to save it. – icecub Jan 22 '21 at 22:19