The KIRUPA orange logo! A stylized orange made to look like a glass of orange juice! Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Table of Contents

Checking If A File Exists

by kirupa   |   filed under JavaScript 101

From images to stylesheets to script files, what you see in your HTML document often involves a collection of files that work together to display the final result:

html document and files

For a static web page, this is business as usual. There is a link in the markup to the file you need, and this link never changes unless you make that change yourself. When you preview in your browser, you can quickly tell if everything has loaded properly.

As content becomes more and more dynamic, the files that your HTML document relies on are subject to change. You may have a small script that generates a download link whose URL points to a file that was generated only moments ago. Your server might be running a framework that creates files on the fly for your HTML page to reference. To go all passive-tense on you, being able to verify whether a file exists before taking any further action would be very helpful.

In this tutorial, we will examine the small amount of code that we can use to very easily check if a file exists using a technique that has existed since the beginning of the internet.

Onwards!

The Code

Without further ado, the code for checking if a file exists looks as follows:

function doesFileExist(urlToFile) {
	var xhr = new XMLHttpRequest();
	xhr.open('HEAD', urlToFile, false);
	xhr.send();
	
	if (xhr.status == "404") {
		return false;
	} else {
		return true;
	}
}

To use it in your application, just call the doesFileExist function and pass in the URL of the file you are checking the existence of. The function returns a true if the file exists, and it returns a false if the file doesn't exist.

Below is simple example of me using the doesFileExist function:

var result = doesFileExist("https://www.kirupa.com/ssi/newDesign/kirupaLogo_large.png");

if (result == true) {
	// yay, file exists!
} else {
	// file does not exist!
}

See, it's pretty simple! If all you came here was just for the code snippet on how to do this, you should have everything you need. With that said, I don't want you to leave just yet. Check out the following section that explains why the code works the way it does in greater detail so that you can be smarter than your friends.

The Code Explained

Now that you have a working example, let's take a step back and figure out why the few lines of code that you have allow you to determine whether a file exists or not! Let's start at the very top:

function doesFileExist(urlToFile)

Our function is called doesFileExist, and it takes one argument called urlToFile. The contents of this function are responsible for unicorns and creating a request that lets a server tell you whether a file exists or not.


The next line is where things start getting interesting:

var xhr = new XMLHttpRequest();

We declare a variable called xhr, and it is initialized to a new object of type XMLHttpRequest. The XMLHttpRequest class contains a lot of methods and properties that help us to ask a server whether a file exists or not.


For the next chunk of code, let's look at two lines at once because they are closely related:

xhr.open('HEAD', urlToFile, false);
xhr.send();

In the first line, we construct a request. To dive into what that means, we specify two things:

  1. That our request is going to be of type HEAD
  2. The URL of the file whose existence we wish to check on

The URL value is stored by the urlToFile variable that is used to store the argument passed in to this function. The false argument is used to specify that you want this request to be made synchronously. In other words, your application is blocked until you get a response back. If you set this value as true, the request is made asynchronously and your browser will continue running other parts of your code. While I am very pro-asynchronous, for what our code is doing, blocking everything until we get a response is the right thing.

The second line is important. Remember, we only constructed the request in the first line. It is this second line that takes the request you created and passes it off to the server. After this request is sent, your application waits a few milliseconds before the code hears back from the server and moves on to the next step.


We are almost home. The last section of code we are going to look at is the following:

if (xhr.status == "404") {
	return false;
} else {
	return true;
}

We check what the status of our request is by looking at the value of the status property that lives in our xhr object. If the status is a 404, then we know that the files does not exist. If the status is anything else, the file exists. Pretty simple.

Conclusion

Hopefully you learned how to construct a HEAD request and ping a server to see whether a file exists or not. The HEAD request is great because the server doesn't send the entire file. The server just sends the headers of a file which contain only a few bytes of data. The data itself isn't important, for all we check is that there is something that exists at the destination of the URL. Also, if you want a solution that uses the newer fetch API instead of XMLHttpRequest, check out these posts by senocular and me. You may get both entertainment and value out of them!

Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!

Kirupa's signature!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Serving you freshly baked content since 1998!
Killer icons by Dark Project Studios

Twitter Youtube Facebook Pinterest Instagram Github