Checking If A File Exists

by kirupa   |   8 November 2012

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 dynamically. 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, you will see the small amount of code that you can use to very easily check if a file exists using a technique that has existed since the beginning of the internet.

The Code

Without further ado, the code for checking if a file exists simply 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("//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 this a bit, we specify that our request is going to be of type HEAD and specify the URL of the file 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.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Brought to you by...

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!