Check if file exists javascript

Any idea why this is not working?

function UrlExists() {

var http = new XMLHttpRequest(); 
http.open(‘HEAD’, ‘/program.exe’, false); 
http.send(); 
if (http.status!=404) {alert(‘found’);} else {alert(‘not found’);}; 
}
UrlExists();

This is because send() is asynchronous. This means the send() is coming back directly after calling so you do not have a status at this time.

This is what you can read in the MDN manual, which should be your first point to check.

a correct code should look like this

const xhr = new XMLHttpRequest();
xhr.open("GET", "/server", true);

xhr.onload = () => {
  // Request finished. Do processing here.
};

xhr.send(null);
// xhr.send('string');
// xhr.send(new Blob());
// xhr.send(new Int8Array());
// xhr.send(document);

Also I would recommend to not use HttpRequest any more since this is outdated. You should use fetch() instead. With fetch you can also use await which is much easier to handle then the result callbacks.

also I don’t think it make sense to check if an .exe exists on the server…

5 Likes

Thanks. I have been reading up on fetch examples, but I still cannot make this work:

const xhr = new XMLHttpRequest();
xhr.open(“GET”, “/file.ext”, true);
xhr.onload = () => { 
if (xhr.status!=404) {alert(“found”);} else {alert(“not found”);}; 
};
xhr.send(null);

After using chrome’s built in debugger, I discovered my browser is blocking the request for security reasons, so I am looking into fetch. Thanks for the help! :slight_smile:

This worked for me.

xhr.onload = function() {
  if (xhr.status !== 404) {
    // Request was successful. Do something with the response.
    alert("found")
  } else {
    // There was an error with the request.
    alert("Not Found");
  }
};

Hi @assc , using fetch() will not solve the security issues. Are you maybe trying to open the page containing your JS from the file system directly?

AJAX requests to the file system won’t work in general; instead, you’ll need to serve your files using a development server. You can start a simple static file server using for instance http-serve:

npx http-server ./path-to-your-files    

And then open the page from localhost, by default http://127.0.0.1:8080.

Context is going to be a necessity…

Are we executing this function from Node? A regular browser Javascript file? your console?

Just a JS file on my desktop. I was trying to see how far I could get making an app-like webpage, but will be using node.js to create a real app instead.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.