File/webFileExists.js

/**
 * @author       LTNGames <ltngamesdevelopment@gmail.com>
 * @copyright    2018 FeniX Engine
 * @license      {@link https://gitlab.com/FeniXEngineMV/fenix-utils/blob/master/LICENSE|MIT License}
 */

/**
 * An async function for checking if a file exist on a server.
 *
 * @function webFileExists
 * @async
 * @since 1.0.0
 * @memberof module:File
 *
 * @param {string} url - The url to the file
 *
 * @returns {promise} Promise that resolves to true if the file exists.
 * @example
 * import { webFileExists } from 'fenix-tools'
 *
 * const file = 'http://example.com/file.png'
 *  const fileExists = await webFileExists(file)
 * console.log(fileExists)  // => returns true if file exists
 * // or
 * webFileExists(file)
 * .then(console.log('File exists!'))
 * .catch(console.log('Unable to get file))
 */
export default async function webFileExists (url) {
  const result = await window.fetch(url, {
    method: 'HEAD',
    cache: 'no-cache'
  }).then((response) => {
    return response.ok === true
  })
  return result
}