Check If Folder Or File Exists Using JavaScript

To check if Folder Or File Exists Using JavaScript, we use XMLHttpRequest() function to open that URL or file path which gives some status about the file.

Check live view below

Check If Folder Or File Exists Using JavaScript

After calling the XML request we check the status code of that path. If the path has 404 then that means the file is not available on that path.

It can be also check if you set the only folder or directory path on the URL.

So now we check the source code of Folder Or File Exists Using JavaScript,

Source Code to Check If File Path Exists JavaScript

Code Explanations:

  • First, we call the XMLHttpRequest which is a built-in browser object which allows making an HTTP request.
    • var xhr = new XMLHttpRequest();
  • var xhr = new XMLHttpRequest(); This line of code takes the URL and initializes the request to the given URL.
  • After that, we check the URL status which is coming from the XHR request. And we all know 404 means files not found.
    • xhr.status

Source Code to Check If Folder Path Exists JavaScript

For this, we use the same function which we create on the above task. we just change the PATH on the parameter.

Here is the complete source to check if the file path exists using JavaScriptand check if the folder exists using JavaScript.

To know more about XMLHttpRequest you can check here: https://javascript.info/xmlhttprequest

Live view of checking file and folder exists using JS

Also Check:

Happy Coding..!

Subscribe For Latest Updates

Sign up to best of PHP Code Solutions, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.

Bikash

My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH, my native place in Odisha. I am a Web Programmer by profession and working on more than 50 projects to date. My passion is working on the web-based project using PHP and relate to all CMS and frameworks which is based on PHP.

One thought to “Check If Folder Or File Exists Using JavaScript”

Leave a Reply

Your email address will not be published. Required fields are marked *