[javascript] How to read a local text file?

I’m trying to write 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)?

This question is related to javascript file-io xmlhttprequest

The answer is


Modern solution:

Use fileOrBlob.text() as follows:

<input type="file" onchange="this.files[0].text().then(t => console.log(t))">

When user uploads a text file via that input, it will be logged to the console. Here's a working jsbin demo.

Here's a more verbose version:

<input type="file" onchange="loadFile(this.files[0])">
<script>
  async function loadFile(file) {
    let text = await file.text();
    console.log(text);
  }
</script>

Currently (January 2020) this only works in Chrome and Firefox, check here for compatibility if you're reading this in the future: https://developer.mozilla.org/en-US/docs/Web/API/Blob/text

On older browsers, this should work:

<input type="file" onchange="loadFile(this.files[0])">
<script>
  async function loadFile(file) {
    let text = await (new Response(file)).text();
    console.log(text);
  }
</script>

Related: As of September 2020 the new Native File System API available in Chrome and Edge in case you want permanent read-access (and even write access) to the user-selected file.


other example - my reader with FileReader class

<html>
    <head>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
        <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
    </head>
    <body>
        <script>
            function PreviewText() {
            var oFReader = new FileReader();
            oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
            oFReader.onload = function (oFREvent) {
                document.getElementById("uploadTextValue").value = oFREvent.target.result; 
                document.getElementById("obj").data = oFREvent.target.result;
            };
        };
        jQuery(document).ready(function(){
            $('#viewSource').click(function ()
            {
                var text = $('#uploadTextValue').val();
                alert(text);
                //here ajax
            });
        });
        </script>
        <object width="100%" height="400" data="" id="obj"></object>
        <div>
            <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
            <input id="uploadText" style="width:120px" type="file" size="10"  onchange="PreviewText();" />
        </div>
        <a href="#" id="viewSource">Source file</a>
    </body>
</html>

Jon Perryman,

Yes JS can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html <input type="file">.

Then with JS it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.

What JS cannot do for security reasons is to access automatically (without the user input) to the filesystem of his computer.

To allow JS to access to the local fs automatically is needed to create not an html file with JS inside it but an hta document.

An hta file can contain JS or VBS inside it.

But the hta executable will work on windows systems only.

This is standard browser behavior.

Also Google Chrome worked at the fs API, more info here: http://www.html5rocks.com/en/tutorials/file/filesystem/


I know, I am late at this party. Let me show you what I have got.

This is a simple reading of text file

var path = "C:\\path\\filename.txt"
var fs = require('fs')
fs.readFile(path , 'utf8', function(err, data) {
  if (err) throw err;
  console.log('OK: ' + filename);
  console.log(data)
});

I hope this helps.


Using Fetch and async function

const logFileText = async file => {
    const response = await fetch(file)
    const text = await response.text()
    console.log(text)
}

logFileText('file.txt')

If you want to prompt the user to select a file, then read its contents:

// read the contents of a file input
const readInputFile = (inputElement, callback) => {
  const reader = new FileReader();
  reader.onload = () => {
    callback(reader.result)
  };
  reader.readAsText(inputElement.files[0]);
};
// create a file input and destroy it after reading it
export const openFile = (callback) => {
  var el = document.createElement('input');
  el.setAttribute('type', 'file');
  el.style.display = 'none';
  document.body.appendChild(el);
  el.onchange = () => {readInputFile(el, (data) => {
    callback(data)
    document.body.removeChild(el);
  })}
  el.click();
}

Usage:

// prompt the user to select a file and read it
openFile(data => {
    console.log(data)
  })

<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {            
                $.ajax({`enter code here`
                    url: "TextFile.txt",
                    dataType: "text",
                    success: function (data) {                 
                            var text = $('#newCheckText').val();
                            var str = data;
                            var str_array = str.split('\n');
                            for (var i = 0; i < str_array.length; i++) {
                                // Trim the excess whitespace.
                                str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
                                // Add additional code here, such as:
                                alert(str_array[i]);
                                $('#checkboxes').append('<input type="checkbox"  class="checkBoxClass" /> ' + str_array[i] + '<br />');
                            }
                    }                   
                });
                $("#ckbCheckAll").click(function () {
                    $(".checkBoxClass").prop('checked', $(this).prop('checked'));
                });
        });
    </script>
</head>
<body>
    <div id="checkboxes">
        <input type="checkbox" id="ckbCheckAll" class="checkBoxClass"/> Select All<br />        
    </div>
</body>
</html>

_x000D_
_x000D_
var input = document.getElementById("myFile");_x000D_
var output = document.getElementById("output");_x000D_
_x000D_
_x000D_
input.addEventListener("change", function () {_x000D_
  if (this.files && this.files[0]) {_x000D_
    var myFile = this.files[0];_x000D_
    var reader = new FileReader();_x000D_
    _x000D_
    reader.addEventListener('load', function (e) {_x000D_
      output.textContent = e.target.result;_x000D_
    });_x000D_
    _x000D_
    reader.readAsBinaryString(myFile);_x000D_
  }   _x000D_
});
_x000D_
<input type="file" id="myFile">_x000D_
<hr>_x000D_
<textarea style="width:500px;height: 400px" id="output"></textarea>
_x000D_
_x000D_
_x000D_


In order to read a local file text through JavaScript using chrome, the chrome browser should run with the argument --allow-file-access-from-files to allow JavaScript to access local file, then you can read it using XmlHttpRequest like the following:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
   if (xmlhttp.readyState == 4) {
       var allText = xmlhttp.responseText;          
            }
        };
xmlhttp.open("GET", file, false);
xmlhttp.send(null);

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>

Try creating two functions:

function getData(){       //this will read file and send information to other function
       var xmlhttp;

       if (window.XMLHttpRequest) {
           xmlhttp = new XMLHttpRequest();               
       }           
       else {               
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");               
       }

       xmlhttp.onreadystatechange = function () {               
           if (xmlhttp.readyState == 4) {                   
             var lines = xmlhttp.responseText;    //*here we get all lines from text file*

             intoArray(lines);     *//here we call function with parameter "lines*"                   
           }               
       }

       xmlhttp.open("GET", "motsim1.txt", true);
       xmlhttp.send();    
}

function intoArray (lines) {
   // splitting all text data into array "\n" is splitting data from each new line
   //and saving each new line as each element*

   var lineArr = lines.split('\n'); 

   //just to check if it works output lineArr[index] as below
   document.write(lineArr[2]);         
   document.write(lineArr[3]);
}

You can import my library:

_x000D_
_x000D_
<script src="https://www.editeyusercontent.com/preview/1c_hhRGD3bhwOtWwfBD8QofW9rD3T1kbe/[email protected]"></script>
_x000D_
_x000D_
_x000D_

then, the function fetchfile(path) will return the uploaded file

_x000D_
_x000D_
<script src="https://www.editeyusercontent.com/preview/1c_hhRGD3bhwOtWwfBD8QofW9rD3T1kbe/code.js"></script>_x000D_
<script>console.log(fetchfile("file.txt"))</script>
_x000D_
_x000D_
_x000D_

Please note: on Google Chrome if the HTML code is local, errors will appear, but saving the HTML code and the files online then running the online HTML file works.


Provably you already try it, type "false" as follows:

 rawFile.open("GET", file, false);

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.


How to read a local file?

By using this you will load a file by loadText() then JS will asynchronously wait until the file is read and loaded after that it will execture readText() function allowing you to continue with your normal JS logic (you can also write a try catch block on the loadText() function in the case any error arises) but for this example I keep it at minimal.

async function loadText(url) {
    text = await fetch(url);
    //awaits for text.text() prop 
    //and then sends it to readText()
    readText(await text.text());
}

function readText(text){
    //here you can continue with your JS normal logic
    console.log(text);
}

loadText('test.txt');

Get local file data in js(data.js) load:

function loadMyFile(){
    console.log("ut:"+unixTimeSec());
    loadScript("data.js?"+unixTimeSec(), loadParse);
}
function loadParse(){
    var mA_=mSdata.split("\n");
    console.log(mA_.length);
}
function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}
function hereDoc(f) {
  return f.toString().
      replace(/^[^\/]+\/\*![^\r\n]*[\r\n]*/, "").
      replace(/[\r\n][^\r\n]*\*\/[^\/]+$/, "");
}
function unixTimeSec(){
    return Math.round( (new Date()).getTime()/1000);
}

file of data.js like:

var mSdata = hereDoc(function() {/*!
17,399
1237,399
BLAHBLAH
BLAHBLAH
155,82
194,376
*/});

dynamic unixTime queryString prevents cached.

AJ works in web http://.


This might help,

    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    }

    xmlhttp.open("GET", "sample.txt", true);
    xmlhttp.send();

Adding to some the above answers, this modified solution worked for me.

<input id="file-upload-input" type="file" class="form-control" accept="*" />

....

let fileInput  = document.getElementById('file-upload-input');
let files = fileInput.files;

//Use createObjectURL, this should address any CORS issues.
let filePath = URL.createObjectURL(files[0]);

....

function readTextFile(filePath){
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", filePath , true);
    rawFile.send(null);

    rawFile.onreadystatechange = function (){
        if(rawFile.readyState === 4){
            if(rawFile.status === 200 || rawFile.status == 0){
                var allText = rawFile.responseText;
                console.log(allText);
            }
        }
    }     
}

function readTextFile(file) {
    var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
    rawFile.open("GET", file, false); // open with method GET the file with the link file ,  false (synchronous)
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
        {
            if(rawFile.status === 200) // status 200: "OK"
            {
                var allText = rawFile.responseText; //  Returns the response data as a string
                console.log(allText); // display text on the console
            }
        }
    }
    rawFile.send(null); //Sends the request to the server Used for GET requests with param null
}

readTextFile("text.txt"); //<= Call function ===== don't need "file:///..." just the path 

- read file text from javascript
- Console log text from file using javascript
- Google chrome and mozilla firefox

in my case i have this structure of files : enter image description here

the console.log result :
enter image description here


Local AJAX calls in Chrome are not supported due to same-origin-policy.

Error message on chrome is like this: "Cross origin requests are not supported for protocol schemes: http, data, chrome, chrome-extension, https."

This means that chrome creates a virtual disk for every domain to keep the files served by the domain using http/https protocols. Any access to files outside this virtual disk are restricted under same origin policy. AJAX requests and responses happen on http/https, therefore wont work for local files.

Firefox does not put such restriction, therefore your code will work happily on the Firefox. However there are workarounds for chrome too : see here.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to xmlhttprequest

What is difference between Axios and Fetch? Basic Authentication Using JavaScript XMLHttpRequest module not defined/found loading json data from local file into React JS AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource Edit and replay XHR chrome/firefox etc? AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https jQuery has deprecated synchronous XMLHTTPRequest Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest Sending a JSON to server and retrieving a JSON in return, without JQuery