0

The goal of my project is to read a stream of constantly changing data from a text file into a html file and then changing the font color.

I have tried multiple ways of reading in a text file such as using an iframe and attempting to use the fetch command but was unable to successfully use these to complete my goal.

<body>
  <script type="text/javascript">
  function print() {
  fetch("test.txt")
    .then(function(response) { return response.text; })
    .then(function(text) {
      var num = parseInt(text);
    if(num>250){
    num=fontcolor("green")
  }
    else()
    {
    num=fontcolor("red")
  }
    });
 }
setInterval(print, 1000); //run function print() every 1 second
  </script>
  <META HTTP-EQUIV="refresh" CONTENT="1">
</body>

The outcome should be an html file that when opened in a browser will display the number in the text file and change the color based on the number given.

L.Java
  • 25
  • 2

1 Answers1

1

You can not fetch text file in local machine for security reason.

You can refer this link for update security for Disable same origin policy in Chrome

You can host your file to free host. I corrected your .then(response => response.text())

Corrected

 <body>
      <script type="text/javascript">
      function print() {
      fetch("test.txt")
        .then(response => response.text())
      .then(text => {
        var num = parseInt(text);
        if(num>250){
         console.log(num);
         document.body.style.backgroundColor = "green";
      }
        else
        {
        //num=fontcolor("red")
        console.log(num);
        document.body.style.backgroundColor = "blue";
      }

      })

     }
    setInterval(print, 1000); //run function print() every 1 second
      </script>
      <META HTTP-EQUIV="refresh" CONTENT="1">
    </body>

http://viethien.000webhostapp.com/fetchfile.html

Hien Nguyen
  • 21,001
  • 7
  • 35
  • 48