8

How do I check whether a file is present at a URL using the JS fetch API, without downloading the file if it is present? Essentially, I just want to retrieve the status code but not the content.

I don't want to download the file because it may be large, and downloading the whole thing would waste bandwidth since I don't care about the contents.

The Bic Pen
  • 773
  • 6
  • 21
  • 1
    Does this answer your question? [How do I check if file exists in jQuery or pure JavaScript?](https://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-pure-javascript) – kmoser Jul 30 '21 at 17:52
  • Yes. I found that link after filling in the details of the post, and based my answer off of that – The Bic Pen Jul 30 '21 at 17:56

1 Answers1

15

Set the request method to HEAD, which requests the headers only.

    fetch("http://localhost:3000/file",
          { method: "HEAD" }
    ).then((res) => {
      if (res.ok) {
          // file is present at URL
      } else {
          // file is not present at URL
      }
    });
The Bic Pen
  • 773
  • 6
  • 21