javascriptfile-ioxmlhttprequest

How to read a local text file in the browser?


I’m trying to implemennt a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s 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();
}

What is going wrong here?

This still doesn’t seem to work after changing the code a little bit from a previous revision and now it's giving me an XMLHttpRequest exception 101.

I’ve tested this on Firefox and it works, but in Google Chrome it just won't work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers (especially Chrome)?


Solution

  • JS introduced the Fetch API in 2015, which replaced XMLHttpRequest with a much simpler way to get data from URLs. In this case:

    fetch("myText.txt")
      .then((res) => res.text())
      .then((text) => {
        // do something with "text"
       })
      .catch((e) => console.error(e));
    

    And since all modern browsers severely lock down what they can do with direct filesystem access, try not to use file:///. Even if you're "just working locally" there are tons of light weight web servers that you can use (including things like running python -m http.server or npx http-server) so you can load your data using normal http urls.

    original answer

    You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver)

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

    And specify file:// in your filename:

    readTextFile("file:///C:/your/path/to/file.txt");