Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading first line of a text file in javascript

Let's say I have a text file on my web server under /today/changelog-en.txt which stores information about updates to my website. Each section starts with a version number, then a list of the changes.

Because of this, the first line of the file always contains the latest version number, which I'd like to read out using plain JavaScript (no jQuery). Is this possible, and if yes, how?

like image 621
SeinopSys Avatar asked Jan 15 '23 16:01

SeinopSys


2 Answers

This should be simple enough using XHR. Something like this would work fine for you:

var XHR = new XMLHttpRequest();
XHR.open("GET", "/today/changelog-en.txt", true);
XHR.send();
XHR.onload = function (){
    console.log( XHR.responseText.slice(0, XHR.responseText.indexOf("\n")) );
};
like image 85
Some Guy Avatar answered Jan 23 '23 14:01

Some Guy


So seeing as the txt file is externally available ie: corresponds to a URL, we can do an XHR/AJAX request to get the data. Note without jQuery, so we'll be writing slightly more verbose vanilla JavaScript.

var xmlHttp;

function GetData( url, callback ) {

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = callback;
    xmlHttp.open( "GET", url, true );
    xmlHttp.send( null );
}

GetData( "/today/changelog-en.txt" , function() {

    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 {

        var result = xmlHttp.responseText;
        var allLines = result.split("\n");

        // do what you want with the result 
        // ie: split lines and show the first line

        var lineOne = allLines[0];

    } else {
        // handle the error
    }
});
like image 22
Christopher Avatar answered Jan 23 '23 14:01

Christopher