Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (13.1k points)

I am trying to write a text file reader by creating a function that takes in the file’s path and converts each line of text into character array, but it is not working

function readTextFile() {

  var rawFile = new XMLHttpRequest();

  rawFile.open("GET", "testing.txt", true);

  rawFile.onreadystatechange = function() {

    if (rawFile.readyState === 4) {

      var allText = rawFile.responseText;

      document.getElementById("textSection").innerHTML = allText;

    }

  }

  rawFile.send();

}

Can somebody tell me what’s wrong here?

1 Answer

0 votes
by (7k points)

You need to check for the status as when loading files locally with XMLHttpRequest, you don’t get a status returned because it is not from a webserver

function readTextFile(file)

{

    var rawFile = new XMLHttpRequest();

    rawFile.open("GET", “file:path to yourfile”, false);

    rawFile.onreadystatechange = function ()

    {

        if(rawFile.readyState === 4)

        {

            if(rawFile.status === 200 || rawFile.status == 0)

            {

                var allText = rawFile.responseText;

                alert(allText);

            }

        }

    }

    rawFile.send(null);

}

Want to be a full stack developer? Check out the full stack developer course from Intellipaat.

Related questions

0 votes
1 answer
asked Feb 17, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer

Browse Categories

...