1

I have been struggling with reading local files from the file path in javascript. I have tried XMLHttpRequest to no avail.

function readFile(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 text = rawFile.responseText;
        document.write(text);
      }
    }
  }
  rawFile.send(null);
}

window.onload = function() {
  readFile("text.txt");
}

I have also tried FileReader but the way I understand it is that it doesn't read files from a string file path; or how can I create a File object to use in FileReader. I also don't want to use node fs module. Could anyone help out on the best and surest way to read local files from the file path? THANKS

1 Answer 1

4

Security restrictions in most browsers make this impossible.

Webpages are not allowed to select files from the user's computer to make accessible to JavaScript. Only the user (e.g. via a file <input>) can do that.

7
  • ok thanks... is there a way I can create a File object or something of the sort without accessing local files to use in FileReader?
    – CMM
    Commented Jan 9, 2017 at 3:31
  • If you don't want to access local files with it … what do you want to access with it?
    – Quentin
    Commented Jan 9, 2017 at 7:41
  • I could let's say test FileReader using jasmine
    – CMM
    Commented Jan 9, 2017 at 8:02
  • You'd probably need to mock the FileReader object entirely to do that.
    – Quentin
    Commented Jan 9, 2017 at 9:15
  • how would I do that?
    – CMM
    Commented Jan 9, 2017 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.