How do you check if a file exists?

I’m using the Fetch API to get the contents of a text file in the root folder of my project, but I want to make sure the file exists first. I’ve searched for a while and I can’t find a solution that isn’t jQuery, a deprecated method, or that requires a package from node.js.

Using fetch, you’ll still get a response, even for a missing file. I googled “fetch javascript 404 error,” found this: reactjs - JavaScript - How to handle 404 error in fetch? - Stack Overflow

The accepted solution seems reasonable.

Thanks, but that didn’t work for me. I just want to check if the file exists. If it does, I want to use that file, else use the default file. I’m considering having the file exist and just have the user overwrite it.

Since you are using fetch then I’m assuming this is a web app and you are checking for a file on the web server? The link @snowmonkey gave you is good. You have to request the file from the server and the server will send you back an error if it doesn’t exist. There really isn’t any other way to do it.

But then you mentioned something about having the user overwrite the file, so now I’m not sure if you are referring to a file on a web server. Can you be a little more specific what exactly you are trying to do?

To check it’s existence, you’d get a response.ok in your returned promise, anything else tells you either the file doesn’t exist, a server error, or something else.

If you want to allow the user to write to that same location, you’ll need some sort of server-side file handler.

No, I’m fetching a local file on my machine - I have to watch some more videos because I must be doing something wrong.

ok, let me try that - thanks!

You can’t use fetch to do that (for security reasons), you have to use the FileReader API instead. But you can’t just automatically read in a local file with your web app, you have to pass the FileReader a file obtained using <input type="file">. Again, this is for security reasons. Can you imagine if a web app were allowed to automatically read any file on a user’s computer without some sort of user input? Or even allowed to check if a local file exists? Would you want some random web page you are viewing reading in files on your computer behind the scenes?

P.S. I added the ability to load in local sound files and save/load sessions to/from local files to my drum machine with help from the file-dialog library and file-saver library.

1 Like

It’s an app that will be on a user’s computer, not on the web so no security issue. I tried FileReader but I have to use it on another page. And since it’s on a person’s computer, export/import won’t work. I was able to load the file contents into local storage and then access the content, but I don’t like that approach for what I am doing. What I really need is to check for the existence of a file, but I can’t find a good way to do that.

OK, you are not giving us all the information we need to know in order to help you. How exactly does one use this app? Please be as specific as possible.

It’s a virtual keyboard for people who have reduced motor skills, like my aunt with cerebral palsy. It’s difficult for her to use the keyboard - she types with her thumb and it takes ~ 5 seconds to type one letter. I’m still waiting to hear back from her if it is easier with an assistive mouse.

But I also added a section of proper nouns and phrases and another section with the most used words in English by each alphabet letter. Everything is a button to add to a textarea which can then be copied with a button.

But I would like users to use the phrases and words they prefer rather than my list. I think my list is good but I would like people to have the option to load their own words.

I contacted 39 organizations that help people with reduced motor skills (MS, cerebral palsy, stroke, etc.) None were interested in hosting it on their website. So what do I do? Just build it for my aunt or try to share it? I then found Facebook support groups around the conditions I mentioned. Some people like it and are going to try it. But how can they use it? They are going to have to download my files from GitHub. Someone already did it - an occupational therapist.

So I want to check if a text file is in the root folder, if it is then load those words. Otherwise, go with my default set of words. Then they have the option. The people who will use it will still need someone to fill the text file with words and then save it, but that is the ideal situation.

What I had to do is create the text files and use fetch to get them. But I must have done my fetch wrong because I could not use ‘data’ in my function that splits the words. So I had to save the content into local storage. I tested overwriting the text file and it does update the local storage values which I then can use in my split function.

I want to want a couple of videos on fetch but I’m dealing with a huge increase of spam on my website. Which happened after I joined 28 Facebook groups last night. Coincidence? Maybe, maybe not.

I hope all of that explained what it is I’m trying to do. It’s the only portfolio project that I supposedly need if I want to get a job/interview. I would like to move onto the next project idea I have.

You have explained what you are trying to do but not really how you are trying to do it. You mentioned a github repo. Perhaps you can give us a link to that?

Bottom line, if your app runs through a web browser then you can’t use fetch to access a local file on the user’s computer for reasons explained above, but there are alternative API’s in the browser you can use. If you don’t want to do this then perhaps you can switch to a different platform, such as Electron which will allow you to build with JS/HTML/CSS and also have access to the user’s local file system.

Why is it a security concern? I don’t understand if it is a user-supplied file. I would have docs explaining that they would need to replace the file with a file of the same name with their content. For example, for the ProperNouns and Phrases section, the text file I am fetching is text-proper.txt.

I didn’t push the changes for the fetch of the file to my repo . I want to wait to have it figured out. Here is the code I have:

fetch:

function getProperText() {
  fetch('text-proper.txt')
    .then((res => res.text()))
    .then((data) => {
      localStorage.setItem("wordsNounsPhrases", data);
    })
}
getProperText();

using split for either the content in local storage or the hard coded list of proper nouns & phrases. FYI, properToSplit is the var name for the hard-coded list I have:

function properNouns() {
  // let x = window.localStorage.getItem('properNounsPhrases');
  let x = window.localStorage.getItem('wordsNounsPhrases');
  if (x) {
    let nouns = x.split(/[^a-zA-Z\s.:?!'-]\s+/gi);
    return nouns;
  } else {
    let nouns = properToSplit.split(/[^a-zA-Z\s.:?!'-]\s+/gi);
    return nouns;
  }
}
let pn = properNouns();

outputting the list to the DOM:

function properNounOutput(arr) {
  for (let i = 0; i < arr.length; i++) {

    let outputNouns = `<button class="special" value="${arr[i]}" tabindex="-1">${arr[i]}</button>`;
    let nounButton = document.createElement('button');
    nounButton.value = arr[i];
    let specialNoun = document.getElementById("special-words");
    specialNoun.insertAdjacentHTML("beforeend", outputNouns);

  }
}
properNounOutput(pn);

Here is a link to the repo and to a live demo:
GitHub: GitHub - Kernix13/WriterAssist: Virtual keyboard
Live: Writer Assist

Imagine if any web page you loaded could start reading files on your own computer without your permission. In other words, the page could use fetch to start reading in files, or even checking for their existence, without you having to do a thing (other than load the page). Do you think this would be a good idea? Why would you want to give someone else the ability to do that?

If you are running your app through a web browser then you are confined to the security policies of that web browser. No web browser I know of allows javascript to use fetch to access the user’s local file system. But there are other alternatives that work, I gave you links to the API and the helper libraries I used in my project. Of course they require action from the user in order to read the file. This is another security measure and there is nothing you can do to work around this. Now if this would be too difficult for your aunt then perhaps a web app isn’t the solution here. I gave you the Electron option, which if you are using VSCode as an editor then guess what, you are using an Electron app.

I think my part of this discussion is over as I’m not sure there is any more I can say that hasn’t been said above. Good luck. It’s a noble project and I hope your aunt can benefit from it someday.

Okay, sorry - I didn’t mean to upset you. I was only asking. I’ll find another solution then. Thanks for the help.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.