0

for some reason, the code can't open the local file. currently my file is located at C:/file_folder/file_name

here's the code:

function loadJSON(callback) 
{   
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', './file_folder/file_name', true);
  xobj.onreadystatechange = function () {
  if (xobj.readyState == 4 && xobj.status == "200") {
    callback(JSON.parse(xobj.responseText));
    }
  };
  xobj.send(null);  
}

is my url wrong?

Sydnie
  • 71
  • 1
  • 9

2 Answers2

1

You stated that your script is ran from C:/file_folder/

The file you want to read is at C:/file_folder/file_name

The relative path from the script to the file would be ./file_name not ./file_folder/file_name

./file_folder/file_name is actually looking in C:/file_folder/file_folder/file_name in this case

Granted this would only work if this was a script ran on your computer or it was referencing a file from the server the webpage is hosted from. Otherwise a webpage can not read your local file-system.

Niles Tanner
  • 3,911
  • 2
  • 17
  • 29
  • i've tried it just now, but for some reason it still returns 404 – Sydnie Jul 17 '18 at 02:50
  • I would try to find the absolute path first. and see if you can get it to work from there. I assume this is not running on a webpage? – Niles Tanner Jul 17 '18 at 02:51
  • it's a webpage sir.. i'm trying to load a local json file to populate an html select group inside a .hbs file(expressjs).. – Sydnie Jul 17 '18 at 02:52
  • if you're using `express.static` you might have to enable dotfiles https://expressjs.com/en/api.html#dotfiles – Meghan Jul 17 '18 at 02:54
  • @Sydnie you can't have a webpage access a file from your local computer. You will have to find a way to upload the file first. – Niles Tanner Jul 17 '18 at 02:55
1

Javascript in the browser cannot read from your filesystem.

You have to set up a server to send the file from an endpoint.

Here's the fs module from node for reading a file: https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback