Read line by line of a text file using JavaScript

I have a file called "newfile.txt" which has two lines of text in it

newfile.txt

Lights Turned on
Lights turned off

I have a javascript function which reads the text file and i can access the output through the variable called "status" (see below) and when i console log "status" I can see both the lines present in newfile.txt.

Javascript ( to read the text file)

var status;
function readTextFile1(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
               status = rawFile.responseText;
               
            }
        }
    }
    rawFile.send(null);
}

 readTextFile1("newfile.txt"); //calling the function

console.log(status);

Now the problem is, I need to use an if statement based on the text in each line

For example ( just my concept)

if ( status (line 1) = "Lights Turned Off" ){
do something
}

if ( status (line 2) = "Lights Turned On" ){
do something
}

Any help is appreciated. Thanks a lot for your time.

2 thoughts on “Read line by line of a text file using JavaScript”

  1. How about splitting the file content at newlines ?

    status = rawFile.responseText.split("\n");
    if (status[0] == "Lights turned on") { // line 1
        // do something when lights are turned on
    }
    ...
    
    Reply
  2. Indeed, splitting is the way.. I just got lucky enough for the guy before me to miss out a bit 😀

    var status;
    function readTextFile1(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                   status = rawFile.responseText;
                   
                }
            }
        }
        rawFile.send(null);
    }
    
    readTextFile1("newfile.txt"); //calling the function
    console.log(status);
    
    //time for looping >:D
    let splitStatus=status.split('\n')
    for(let i=0;i<splitStatus.length;i++){
      let line=splitStatus[i];
      console.log(line);
      //whateverYouWannaDoNext
    }
    
    Reply

Leave a Comment