Reading first line of a text file in javascript

2019-02-20 00:32发布

问题:

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?

回答1:

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


回答2:

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