How to read a local text file? How to read a local text file? javascript javascript

How to read a local text file?


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;                alert(allText);            }        }    }    rawFile.send(null);}

And specify file:// in your filename:

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


After the introduction of fetch api in javascript, reading file contents could not be simpler.

reading a text file

fetch('file.txt')  .then(response => response.text())  .then(text => console.log(text))  // outputs the content of the text file

reading a json file

fetch('file.json')  .then(response => response.json())  .then(jsonResponse => console.log(jsonResponse))        // outputs a javascript object from the parsed json

Update 30/07/2018 (disclaimer):

This technique works fine in Firefox, but it seems like Chrome's fetch implementation does not support file:/// URL scheme at the date of writing this update (tested in Chrome 68).

Update-2 (disclaimer):

This technique does not work with Firefox above version 68 (Jul 9, 2019) for the same (security) reason as Chrome: CORS request not HTTP. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp.


Visit Javascripture ! And go the section readAsText and try the example. You will be able to know how the readAsText function of FileReader works.

    <html>    <head>    <script>      var openFile = function(event) {        var input = event.target;        var reader = new FileReader();        reader.onload = function(){          var text = reader.result;          var node = document.getElementById('output');          node.innerText = text;          console.log(reader.result.substring(0, 200));        };        reader.readAsText(input.files[0]);      };    </script>    </head>    <body>    <input type='file' accept='text/plain' onchange='openFile(event)'><br>    <div id='output'>    ...    </div>    </body>    </html>