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
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 checked 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<script type="text/javascript"> function checkFileExist(urlToFile) { var xhr = new XMLHttpRequest(); xhr.open('HEAD', urlToFile, false); xhr.send(); if (xhr.status == "404") { return false; } else { return true; } } // Calling function // set the path to check var result = checkFileExist("http://localhost/test/images/myImage.png"); if (result == true) { alert('yay, file exists!'); } else { alert('file does not exist!'); } </script> |
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
xhr.status
Source Code to Check If Folder Path Exists JavaScript
For this, we will use the same function which we already have created on the above task. we will just change the PATH on the parameter.
1 2 3 4 5 6 7 8 9 |
// calling function // Puuting Folder or directory path as parameter var result = checkFileExist("http://localhost/test/anyDirectoryName/"); if (result == true) { alert('yay, file exists!'); } else { alert('file does not exist!'); } |
Here is the complete source to check if the file path exists using JavaScript and 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:
- How to Get HTML Tag Value in PHP
- How to Keep Value After Page Reload in PHP
- 2 Ways to Open URL in New Tab Using JavaScript
- How to Embed PDF in Website Using HTML
Happy Coding..!
3 Replies to “Check If Folder Or File Exists Using JavaScript”