M. El-Set M. El-Set - 4 years ago 143
Javascript Question

Read a local text file using Javascript

I have read some of the previous questions on this topic but I really need to be 100% sure!

Is it possible to read from a .txt file on my local system and present it in my HTML-BODY?

I have tried several functions, here is one:

function readFile (path) {
var fso = new ActiveXObject('Scripting.FileSystemObject'),
iStream=fso.OpenTextFile(path, 1, false);
while(!iStream.AtEndOfStream) {
document.body.innerHTML += iStream.ReadLine() + '<br/>';

The content of the file is simply around 100 words I want to read from the text file and display in my HTML-BODY.

Is this possible without having my own server?

Answer Source

You can use a FileReader object to read text file here is example code:

  <div id="page-wrapper">

        <h1>Text File Reader</h1>
            Select a text file: 
            <input type="file" id="fileInput">
        <pre id="fileDisplayArea"><pre>

window.onload = function() {
        var fileInput = document.getElementById('fileInput');
        var fileDisplayArea = document.getElementById('fileDisplayArea');

        fileInput.addEventListener('change', function(e) {
            var file = fileInput.files[0];
            var textType = /text.*/;

            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function(e) {
                    fileDisplayArea.innerText = reader.result;

            } else {
                fileDisplayArea.innerText = "File not supported!"


Here is the codepen demo

If you have a fixed file to read every time your application load then you can use this code :

var fileDisplayArea = document.getElementById('fileDisplayArea');
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;
                fileDisplayArea.innerText = allText 

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download