简体   繁体   中英

Constantly read local file with JS?

I've been looking all over the place but I can't find a solution to reading a local text file (in the same folder as my js and html files) repeatedly that works with Chrome.

I need to constantly read the file for updates, which another program updates automatically, I don't know how. It's just a regular text.txt file.

I've read a lot of questions/answers on here about it, but so far I've found nothing. Can anyone help?

edit: I meant without node as well, just vanilla JS.

You can enable XmlHttpRequest for local files by starting Chrome with it's security features disabled . This is not an ideal solution but it is the only way to automatically do what you want without running some kind of server. Using Node to watch the file for changes and pushing the data over a WebSocket to the browser would be the proper way to handle this.

Alternatively you could use the FileReader API to open this local file but you need to select it manually through an <input type="file"> element first.

 function readInputFile(event) { let file = event.target.files[0]; if (!file) { return; } let reader = new FileReader(); reader.addEventListener('load', event => { let content = event.target.result; alert(content); }); reader.readAsText(file); } document.getElementById('datafile').addEventListener('change', readInputFile, false); 
 <input type="file" id="datafile"> 

I think you might be confused what a 'local' file is in this context.

A local file will be loaded with a url such as file:// , or selected from a file input in a form.

A file next to your .html and .css is not a local file, it's a hosted file on your web server what you're using to host the .html. You would be referring to it with a relative path to your domain, such as '/file.css'

Node would have more options, seeing that it can read and access local files synchronously with the build in fs ( file system ) library.

What you'll need to do is treat your file like any other on the internet, and download it the same way. Then, download it again later when you need to check for updates. repeat.

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