5

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.

1
  • 1
    It is not possible to do it without a web server (apache, nginx, Node.js express...): browser JS does not have access to files on your hard drive as a security measure. Commented Dec 15, 2016 at 2:18

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

1

You could use the javascript FileReader and input type="file" to read the local files in your machine. Please see the below attached code for example.

<!DOCTYPE html>
<html>

<head>
    <script>
        function OnFileLoad() {
            var file = document.getElementById("FileReader").files[0];
            var textType = /text.*/;
            var fileDisplayArea = document.getElementById("FileContent");
            if (file.type.match(textType)) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    fileDisplayArea.innerText = reader.result;
                }

                reader.readAsText(file);
            } else {
                fileDisplayArea.innerText = "File not supported!"
            }
        }
    </script>
</head>

<body>
    <input type="file" id="FileReader" onchange="OnFileLoad()" />
    <div id="FileContent">Your content will appear here</div>
</body>

</html>

In order to specify the file path you might need to have a server as well. I have attached a sample code here with. You can find the details regarding Specifying the file path here and issues that will happen to read file without a server here

<!DOCTYPE html>
<html>

<head>
    <script>
        function readTextFile(file) {
            var rawFile = new XMLHttpRequest();
            rawFile.open("GET", file, false);
            var fileDisplayArea = document.getElementById("FileContent");
            rawFile.onreadystatechange = function () {
                if (rawFile.readyState === 4) {
                    if (rawFile.status === 200 || rawFile.status == 0) {
                        var allText = rawFile.responseText;
                        fileDisplayArea.innerText = allText;
                    }
                } else {
                    fileDisplayArea.innerText = "File not supported!"
                }
            }
            rawFile.send(null);
        }
        readTextFile("file:///C:/Users/t0423/Desktop/test.js")
    </script>
</head>

<body>
    <div id="FileContent">Your content will appear here</div>
</body>

</html>

6 Comments

Nice code! Maybe explain a little bit of what it does and why, rather than just submitting a code snippet with little or no explanation. Very well written though :)
Is it possible to load the file automatically by specifying the file path and break up each line in an array of strings in JS? And then maybe I can get the values from each line of strings and update different parts of the webpage. What I don't want to do is display the file as it is. I want to use the data to update values for different tags.
Yes you can. You can split the content of the file using javascript split function there after you can use it in your desired areas.
@Nitheesh thanks for your suggestions. Your code is the closest thing I could find to what I was looking for but I wanted to automatically load the file without using a button (I don't want the user to choose the file. I wanted to specify the file path in the code) and assign the content of the code to JS variable. If possible, could you post a demo on how to do this. I searched everywhere but wasn't able to find any thing that does that.
@Nitheesh I tried your new code but this time nothing happens after the page loads.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.