Akash Sateesh
Akash Sateesh

Reputation: 812

Javascript read file

I have to read JSON file dynamically when I get "$ref" in Json schema.

I have tried accessing json file using node.js 'fs' module. But that gives error 'fs.readFile()' is not function.

I have later tried the Ajax call but I got following error.

XMLHttpRequest cannot load file:///Users/as6/Downloads/1099K.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Below is my code to read json file in javascript.

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}
readTextFile("file:///Users/as6/Downloads/1099K.json", function(text){
      var data = JSON.parse(text);
      console.log(data);
  });

How will I be able to read JSON file in javascript without Jquery?

Upvotes: 1

Views: 211

Answers (2)

Herman Starikov
Herman Starikov

Reputation: 2756

you need to run a server in that directory, not just open your html in a browser. Try running python -m SimpleHTTPServer in the directory where your html file is. Move your json file where your html file is. Then replace file:///Users/as6/Downloads/1099K.json with http://localhost:8000/1099K.json

Browser is weird this way, it won't let you do ajax for links starting with file:///

Upvotes: 1

Nick
Nick

Reputation: 106

The error is already telling you what's wrong. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

The thing is you are trying to open a local file via the file:// protocol and as the browser is telling you, you can't XHR using that. The easy fix here would be to install a minimal static file server on your computer.

Some more information about CORs here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

As you mentioned nodejs, I will go ahead and assume you have it installed. I suggest https://www.npmjs.com/package/http-server so you can get up and running.

Upvotes: 1

Related Questions