read local files in javascript

How to Read Local Text File in Browser Using JavaScript

Often we need to be able to read and upload files to our websites and web applications. There are many plugins and libraries to help you do that. But sometimes you may simply want to read local text file in web browser using JavaScript, and process its data or just display its contents on web page. In this article, we will learn how to do this.


How to Read Local Text File in Browser Using JavaScript

Here are the steps to read local text file in browser using JavaScript. Add this in your HTML page.

<script>

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);
}

</script>

Let us look at the above code in detail. First we create an XMLHTTPRequest. Then we call open() function to load the file locally. We check if its status code is 0 and if it is so, we save the file contents in variable allText.

You can call the above function as shown below. It is important to use file:// prefix when specifying the file path.

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

But please note, this above code needs to be added into a local HTML file which is opened in local web browser. It will not work if you upload it to a web server and access it via HTTP/HTTPS URL. This is because modern browsers do not allow cross origin requests, that is, from HTTP:// to file://. So only when you add it to an HTML file and open it locally in web browser, your web page will open with file:// in browser URL, and a request is sent to file:///C:/your/path/to/file.txt which has the same origin.

In this article, we have learnt how to read local text file using JavaScript. But please note, JS cannot read a file on its own. User needs to pass the file via upload or some other functionality.

Also read:

How to Encode String to Base64 in JavaScript
How to Get Length of JavaScript Object
How to Get Client IP Address Using JavaScript
How to Break ForEach Loop in JavaScript
How to Validate Decimal Number in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *