Read Local File using XMLHttpRequest


#1

I am trying to read in a local .json file located at C:/folder/blah.json

loadJSON('file:///C:/folder/blah.json', function (response) {
    jsonObject = JSON.parse(response);
    //Do stuff with it

});

function loadJSON(fileName, callback) {

var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', fileName, true);
xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
        // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
        callback(xobj.responseText);
    }
};
  xobj.send(null);
}

When xobj.send(null) is called the .onreadystatechange doesn’t get called, nothing happens after the .send().
It should call the .onreadystatechange and then call my callback function where I can do what I need. It works in chrome but for some reason it doesn’t work in electron.

Anyhelp? Maybe there is a way I could use this https://github.com/atom/electron/blob/master/docs/api/file-object.md


#2

Unless you’ve disabled Node integration you can use require to load JSON files:

jsonObject = require('file:///C:/folder/blah.json')

#3

I think XMLHttpRequests are not allowed filesystem access. You can use require or the fs module to read files from the filesystem.