1

I have built a node library loading json files like this

var FILE_PATH = path.join(
  __dirname,
  '../data/data.json'
);

function loadMyJsonFile() {
  return JSON.parse(
    fs.readFileSync(
      FILE_PATH,
      constants.DEFAULT_ENCODING
    )
  );
}

The code works fine on server side. I see this error in Chrome console when the function is executed in browser.

Uncaught TypeError: fs.readFileSync is not a function

I googled a bit and I don't think I can use fs in browser code. What's the right way of loading json files in browser?

codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167
  • 1
    Possible duplicate of [How do I load a JSON object from a file with ajax?](http://stackoverflow.com/questions/14388452/how-do-i-load-a-json-object-from-a-file-with-ajax) – Andy Ray Apr 28 '17 at 23:00
  • Essentially that data.json is local to your computer, so when a server is running it can load that just fine. Now on the client side of things, when they request a file with fs, that doesn't make sense anymore. You need to have a way of serving the file to the client through a separate HTTP request. – Jordan Soltman Apr 28 '17 at 23:03
  • You can't read files directly in a browser unless the web page itself is a file URL, so you would typically put the JSON file on a web server that will serve it at a particular URL and then use an Ajax call in the browser to fetch it. – jfriend00 Apr 28 '17 at 23:34

0 Answers0