Skip to content Skip to sidebar Skip to footer

How To Read Txt File And Save It In Array In Javascript In Html

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

Solution 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 = newFileReader();
    fr.onload = function() {
        // By linesvar 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><inputtype="file"name="inputfile"id="inputfile"><br><preid="output"></pre></body></html>

Solution 2:

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:

functionloadFile(input, onloadCallback){
    const fr = newFileReader();

    fr.onload = onloadCallback;

    fr.readAsText(input);
}

/* Save file and force download */functionsaveFile(data, fileName){
    const blob = newBlob([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 */functionopenFile(ev){
    loadFile(ev.target.files[0], function(e) {
        // Get all the text as a stringconst result = e.target.result;

        // Make array out of result for each lineconst 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 linelet 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 dataconsole.log(dataArray);

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

        // Finally a way to download a file with the new string inside itsaveFile(newString, 'test.txt');
    });
}

Post a Comment for "How To Read Txt File And Save It In Array In Javascript In Html"