1

I have the following code:

function FileHandler() {

}

FileHandler.prototype.open = function(file) {
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
};

When I try to run it in the console, can I pass a local file as an argument where file is? What syntax would I use if I wanted to do that?

Freddy
  • 1,229
  • 2
  • 13
  • 22
  • Is this running server side or client side? – Kellen Stuart Jun 10 '17 at 08:42
  • Just on my local machine, trying to set the contents of a txt file to a variable. – Freddy Jun 10 '17 at 08:43
  • You should run this script on something like node.js. If you run this in browser, you will not have access to local files – Orifjon Jun 10 '17 at 08:44
  • Possible duplicate of [Local file access with javascript](https://stackoverflow.com/questions/371875/local-file-access-with-javascript) – ventiseis Jun 10 '17 at 08:44
  • https://stackoverflow.com/a/8533057/2892829 – Orifjon Jun 10 '17 at 08:45
  • I see you have an XMLHttpRequest which leads me to believe you have server side code to catch that? The browser is configured to block javascript requests to the local filesystem for security reasons. Normally what I do is submit an Ajax call to server side language of choice, and parse it there, then I can spit it back with a $JSON.encode() – Kellen Stuart Jun 10 '17 at 08:45

2 Answers2

0

You can use an asynchronous function.

   FileHandler.prototype.open = function(file, callback) {
   var rawFile = new XMLHttpRequest();
   rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function() {
    if (rawFile.readyState == 4) {
        // The request is done; did it work?
        if (rawFile.status == 200) {
            // ***Yes, use `rawFile.responseText` here***
            callback(rawFile.responseText);
        } else {
            // ***No, tell the callback the call failed***
            callback(null);
        }
      }; 
    rawFile.open("GET", file, false);
    rawFile.send();
   };
sidewinder
  • 682
  • 4
  • 9
0

http://www.creativebloq.com/web-design/read-local-files-file-api-121518548

it shows exactly how you can do that:

The FileReader object allows us to read the content of a file once we've got a file from the user. For security, the user must actively give us the reference to the file in order for it to be readable. There are a number of FileReader methods for getting a file's contents

here is an example of how to use it: (code from the site)

var reader = new FileReader();
//create our FileReader object to read the file

reader.addEventListener("load", fileRead, false);
//add an event listener for the onloaded event

function fileRead(event){
//called when the load event fires on the FileReader

var pictureURL = event.target.result;
//the target of the event is the FileReader object instance
//the result property of the FileReader contains the file contents
}

reader.readAsDataURL(file);
//when the file is loaded, fileRead will be called