简体   繁体   中英

Read local text file using js/html file on on local machine

I've built a simple html page with javascript in a separate file, called on a button press.

I've opened the html file in chrome, and the path resembles: file:///home/tom/projects/index.html

The javascript needs to read a JSON file (file:///home/tom/projects/mydata.json) which is in the same directory, using a hardcoded path.

I'm really struggling to do this. As I understand, this is because I'm using client side js (meaning I can't use the fs library for example), which is limiting my options.

According to the question here , I can't load the file if I use the URL in the format: file:///home/to.... as it gives me the error:

Cross origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, https.

If I start an HTTP-server, as the answer suggests, I can use server-side modules, but if possible I would like to avoid this.

I've noticed many answers that suggest using a dialog box like this :

var selectedFile = document.getElementById('input').files[0];
function readFile (file_path) {       
    var reader = new FileReader();
    reader.readAsText(file_path);
    console.log(reader.substring(0, 100));
 };

but I can't make this work with a path in the form: file:///home/tom/projects/mydata.json

Is there a way to load a .json file from a file:///home/to.... format URL using client-side javascript, with a hardcoded path (ie not asking the user to select the file from a selection box)?

This is a deliberate security restriction, to stop a user from being given, and then opening, a HTML page which then tries to read their disk.

Run your page in a webserver (as that question suggested) then you can either load the JSON from a URL (eg something like http://localhost/projects/mydata.json ) using JavaScript, or use a server-side language to fetch it and display it inside the rendered HTML. Either way will work, the first way is probably simpler and closest to what you've got now.

It's always far better to serve HTML pages from a HTTP server, the way it's intended to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM