Javascript Equivalent to PHP file_exist(filename)

This JavaScript function checks whether a file exists. However it does not check if a directory exists.

function file_exists(filename) {
    fetch(filename).then(function(response) {
        if (!response.ok) { throw Error(); }
        return response;
    }).then(function(response) {
            console.log("true");
            return true;
    }).catch(function(error) {
            console.log("false");
            return false;
    });
}

Example:

// console displays "true" and returns false
file_exists("https://picsum.photos/10");

// console displays "false" and returns false
file_exists("https://websitedoesnotexist.us/");

 

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use