Reading a text file using Javascript

The following code should read the content of a text file which is in the current directory upon load, and display it on the html page. I tried modifying by my self. But it does not give an output. Is there an easier way to get this result using another method? or please help figure out what is wrong with this code?

            <meta http-equiv='Content-type' content='text/html;charset=UTF-8' >
    function startRead()
      // obtain input element through DOM 

    var file = document.getElementById("file.txt").files[0]


    function getAsText(readFile)
        var reader;
        reader = new FileReader();
            document.getElementById('output').innerHTML = 
                "Error: seems File API is not supported on your browser";

      // Read file into memory as UTF-8      
      reader.readAsText(readFile, "UTF-8");

      // Handle progress, success, and errors

      reader.onload = loaded;
      reader.onerror = errorHandler;

    function loaded(evt)
      // Obtain the read file data    
      var fileString =;
      document.getElementById('output').innerHTML = fileString;

    function errorHandler(evt)
      if( ==
        // The file could not be read
            document.getElementById('output').innerHTML = "Error reading file..."
    //Start reading file on load
    window.addEventListener("load", startRead() { }, false);



                <code id="output">

Source: html5

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.