0

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?

Community
  • 1
  • 1
user3537336
  • 221
  • 2
  • 9
  • Did you try to read the rawFile.readyState to see the value ? – sam Apr 23 '14 at 16:32
  • 1
    You've got your `.send()` inside your ready handler. It won't ever be called. Also, your URL should have all backslash characters doubled. However overall the mechanism won't work anyway for reasons explained in the answers. – Pointy Apr 23 '14 at 16:33

2 Answers2

1

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.

DoctorLouie
  • 2,699
  • 1
  • 18
  • 23
  • Could you please explain to me how someone else could hack my machine if I had JavaScript code that accessed local files? I'm new to web programming and trying to understand the logistics of things. – user3537336 Apr 23 '14 at 16:52
  • Its not so much the JavaScript you are writing and testing locally causing security issues, if indeed JavaScript was allowed access to the local machine's files and data, it would be anything published to a web facing platform, such as a WebServer. Just keep in mind, there is no security issue at all, considering JavaScript doesn't allow us to read, view and write to local files. I'm just hypothetically speaking as an example. – DoctorLouie Apr 23 '14 at 16:56
0

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

See this answer for more info.

Community
  • 1
  • 1
René Roth
  • 1,979
  • 1
  • 18
  • 25