user3537336
user3537336

Reputation: 221

My attempt at reading a text file with Javascript is failing

I have the following function executing on page load:

function get_words()
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", "file:///C:\Users\myMachineName\Documents\PersonalSite_Improved\wordsEn.txt", true);
    rawFile.onreadystatechange = function ()
    {
        if (rawFile.readyState === 4)
        {
            if (rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
        rawFile.send(null);
    }
}

It is my own use of the procedure from this S.O. thread: Javascript - read local text file

I'll confess that I don't totally understand the procedure. However, I can obviously see that I would be getting an alert of the text file contents if the page was working properly. I ran some tests using console.log() to determine that the first if statement is never entered. But since I have no idea what's going on here, I have no idea how to troubleshoot the issue.

Any help?

Upvotes: 0

Views: 498

Answers (2)

René Roth
René Roth

Reputation: 2116

You cannot use an xml request to read a local file due to security reasons.

See this answer for more info.

Upvotes: 0

DoctorLouie
DoctorLouie

Reputation: 2674

The document you are trying to read must be served by an HTTP server, you can't pull up local files from your hard drive or machine. The reason for this is simply security, for if JavaScript could read files on local machines, everyone would be able to open, view and read everything on people's computers. Just run a local HTTP server such as WampServer or something of that nature.

Upvotes: 1

Related Questions