The Bic Pen
The Bic Pen

Reputation: 1157

JS fetch check whether file exists without downloading content

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.

Upvotes: 12

Views: 5696

Answers (1)

The Bic Pen
The Bic Pen

Reputation: 1157

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
      }
    });

Upvotes: 20

Related Questions