JavaScript to fetch file content and check for a term

Hello,
I am trying to change an image based on whether a text file contains a specified word or not, but it is not working. Any help will be much appreciated. Thank you very much.

JavaScript Search Term in File Testing

“It is not working”.

Care to show us the code, or are we just meant to guess at what you’ve done? :stuck_out_tongue:

Hello,
As I am new, I was not allowed to upload. Hence I copied and pasted as below, earlier too. Not sure why it was not showing. Thanks a lot.

window.onload = async function changeImage() {
let myFile = “testFile.txt”;
const response = fetch(myFile);
const responseString = response.text();
const hasTerm = responseString.includes(“programming”);

      if (hasTerm) { document.getElementById("testImage").src = "hasTerm.png"; }
      else         { document.getElementById("testImage").src = "noTerm.png" ; }
  }

you forgot to await your fetch result.

Thanks…tried that too…just don’t know why it is still not working… :thinking:

Standard debugging steps…
is the Console throwing any errors at you?
does testFile.txt actually exist in the same folder as the page you’re loading?
is there actually an element with the ID “testImage”?
are both hasTerm.png and noTerm.png in the same folder as the page you’re loading?

1 Like

Thanks a lot…the answers to the last three questions are ‘yes’…shall check on possible errors and give a try again…Thanks heaps…

You cannot fetch a file from the local file system.

1 Like

Oh…that works…Thank you so much. BTW, just an additional question : how do I prevent a webserver caching a file ? (sorry, its not a JavaScript question, but will be really helpful)…Thank you so much.

To be clear, you can use relative paths, but ‘local’ is relative. Fetching a relative path will pull the file relative to the current URL. Hence my asking if the file was in the same directory.

But it will always fetch the file from the server. If the server is on your local machine then you might call it local file but for me it’s still not the local file system

Hello,
Thank you very much for your replies and ideas…I was trying these for 3 days but fixed it in a few hours after your kind replies…Thank you very much.

BTW, I forgot to mention, my target was to check whether a YouTube channel is “live or not”, by checking whether a channel contains any specific words, when it goes live.

As a starting point, I used “fetch”, “text()” and “includes()” and obtained an output true/false, depending on whether any web page contais a specific word or not, and it works fine for files on the same server in which I have this code, but not for any other website.

Any idea, why this is the case ? Thank you very much.

Sorry, just to update, it works for files only within the same folder …not even in any other folder even withn the same server… :thinking:

Then you use the wrong path. As long as you use relative pathes it should work. If you try to fetch from other servers you may run into cors errors.

Thanks…I think you are correct…the other servers may not be giving me the necessary permission.

Really appreciate if you could kindly point me to some web resource, on how to fix this. Thank you very much.

I found the below code when I did a search. Do I have to use something like this ? Thanks.

fetch("https://www.youtube.com")
  .then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

My intention was to check whether a YouTube channel is live or not using JavaScript. However, I feel that very complex code + a lot of knowledge in JavaScript is required to do this, which I do not have. Therefore, just decided to give up…Thank you so much for all your kind replies up to now…much appreciated.

Well, never say never. I’m sure this could be worked out.

How exactly are you determining this? What differentiates a live YouTube channel from a non-live one? (e.g. is there a particular element or text on the page when the channel is live?)

Hello James, Thanks a lot…I noted that when a YouTube channel is Live, its page content has the words “Continue watching” while this combination of words is not there when it is not live. Hence the reason I was thinking of giving a try.

But, my main issue is I am unable to fetch an external website page using JavaScript, in the first place…looks very tricky…my code works only when the page is within the same folder… :thinking:

In JavaScript, you can use the Fetch API to make a request to a webpage and get its HTML content. However, due to the Same-Origin Policy enforced in web browsers, you won’t be able to fetch content from a different domain (like YouTube) directly from the browser unless the server supports CORS (Cross-Origin Resource Sharing).

One way to get around this is to make your own custom endpoint, then query that endpoint with JavaScript. The endpoint needs to run on a server and use a server-side language such as PHP, Node, Ruby etc? Do you have access to a server environment. Something like LAMP or XAMPP running locally would suffice.

1 Like