I have a text file that is being updated regularly and I want to know if it is possible to read the file, line by line, with javascript and save the values in variables and then update the html page with the new values every time the page is loaded. The html page is a simple page to display information at work, not a live web page, and does not require any user input other than just navigating between the two pages. The text file is on a network drive that everyone has access to. Here is an example of what I'm trying to accomplish:
var value1;
var value2;
Read the file with javascript if possible and extract data and assign to value1 and value2.
document.getElementsByClassName("class for <p>")[0].innerHTML = value;
document.getElementsByClassName("class for another <p>")[0].innerHTML = value;
I have googled this but was not able to find anything that worked. If this is not possible with JS, any suggestions on how this can be done differently. Thanks in advance.
To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text.
JavaScript cannot typically access local files in new browsers, but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.
At first, you need to use a input[type=file]
to get a File
.
<input type=file id=file/>
<div id=result></div>
And then use FileReader
to read file to target format, just like base64
, text
, buffer
.
const file = document.getElementById('file').files[0]
const result = document.getElementById('result')
const reader = new FileReader
reader.addEventListener('load', () => {
result.innerHTML = reader.result
})
reader.readAsText(file, 'UTF-8')
See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With