How to read txt file and save it in array in javascript in html

Viewed 4016

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> 
2 Answers

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> 

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');
    });
}
Related