Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a text file saved on my computer using javascript

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.

like image 403
fGk Avatar asked Dec 15 '16 02:12

fGk


People also ask

Can you read a text file in JavaScript?

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.

Can JavaScript read a local file?

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.


1 Answers

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

like image 165
acrazing Avatar answered Sep 20 '22 17:09

acrazing