Explain Codes LogoExplain Codes Logo

How do I check if file exists in jQuery or pure JavaScript?

javascript
file-existence
ajax
xmlhttprequest
Nikita BarsukovbyNikita Barsukov·Sep 14, 2024
TLDR

Want a one-liner? Use JavaScript's fetch API. It sends a request and if the response's status is 200, bingo, the file exists. Here's the magic spell:

fetch('file.ext').then(r => r.status === 200 ? console.log('Exists') : console.log('Not Found')).catch(e => console.error(e));

Magic of $.ajax() in jQuery

If you are godfather of jQuery, then $.ajax method with type: 'HEAD' is your quicksilver wand. Why? It's like a Greyhound, fast and doesn't exhaust resource.

$.ajax({ url: 'file.ext', type: 'HEAD', success: () => console.log('Exists'), error: () => console.log('Does not exist') });

Old School: XMLHttpRequest

No jQuery? No problem. Use an XMLHttpRequest with the HEAD method. It may sound like dinosaur but still roars loud enough.

let req = new XMLHttpRequest(); req.open('HEAD', 'file.ext', true); req.onreadystatechange = () => { if (req.readyState === 4) { if (req.status === 200) console.log('File exists'); else console.log('File does not exist'); // Console cries if file is hide and seek champion } }; req.send();

Picture Perfect: Image object

Here's a left-fielder. JavaScript's Image object could be used to check image file existence. If file loads, we have a Homerun!

let img = new Image(); img.onload = () => console.log('Image exists'); // Image shy? This won't console log img.onerror = () => console.log('Image does not exist'); img.src = 'image.ext';

Danger zones and rescue operations

Errors and compatibility issues are like kryptonite, they will bring down your Superman code. But we got your back!

Asynchronous operations and HTTP status to the rescue

The fact that asynchronicity makes your script super-speedy and checking HTTP status code acts like GPS for your file finding mission.

Watch those borders: Cross Origin Issues

Taking a leap with cross ORIGIN resources? Make sure the server is not a Gatecrasher and allows CORS Headers, else your checks might end up fighting shadows.

Don't hang, Go Asynchronus

People shun synchronous XMLHttpRequest like Monday mornings. They slow down user experience. I mean, who likes traffic jams, right? Always go asynchronous way.

Binary, Non-text files and Images

Just because we were playing with text files doesn't mean we forgot about the other kids on the block.

Binary Files: Blob and Array Buffer

Playing with Binary data? Check for existence similar to text files but go easy on bandwidth by adjusting the request.

Image files: The Height Matters

Checking if an image file exists? Bet you didn't know this, validating the height property of an Image object does the trick. It feels tall when the load is successful.

Stay Safe, Stay Fast, and Always Remember

Security First

While on this file existence check, don't let your guard down. Stay out of alleyways aka sensitive paths. Don't just rely on client-side checks for critical applications.

Need for Speed

Checking for file existence is not a Sunday drive. So use HEAD method, it's like F1 race car, picks up headers without the need to download file, saving bandwidth and time.

Cache is King

Avoid repetitive checks and load on the server by implementing caching techniques. It's like your own fast food takeaway window for quick serving.