1

I have this code to check if there is a file with the given URL in the server or not. it returns true if there is a file and false if else...

The issue is if there is not a file, in the chrome's console I can see a 404 error which I expect because the given URL doesn't exist But:

  • I wonder if this error will affect the execution of the whole code and the code quality?!

  • How to remove the error if there is any solution?

// Check if file exist in the server
function fileExist(url) {

    return new Promise((resolve) => {   

        const xhr = new XMLHttpRequest();
        xhr.open('HEAD', url, true);

        xhr.onload = function () {
        return resolve(xhr.status==200)
        };
        xhr.onerror = function () {
         return resolve(xhr.status==200)
      };

        xhr.send();
         
    });

}
foxer
  • 811
  • 1
  • 6
  • 16
  • I don't think you can hide network errors in the Chrome console via JavaScript. Read this topic: https://stackoverflow.com/questions/4500741/suppress-chrome-failed-to-load-resource-messages-in-console. – mateleco May 12 '20 at 19:53
  • "I wonder if this error will affect the execution of the whole code and the code quality". Not at all. The browser logging errors to the console is something normal and convenient. – mateleco May 12 '20 at 19:59
  • You could however, add `console.clear()` in the onerror handler to clear errors from the console, but this depends on the DevTools configuration and different browsers may behave differently. So I would just keep them. – mateleco May 12 '20 at 20:07

1 Answers1

1

The only problem I can see is that your function treats any error as the file not existing. You should check specifically for xhr.status == 404 in the onerror function. Anything else could be a server failure, network error, etc. and should trigger an error handler.

A better way to do this would be to have a server script that checks whether the file is there. Make an AJAX request to that script, and it can return a simple true/false response. But this also has more overhead.

Barmar
  • 741,623
  • 53
  • 500
  • 612