exists.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * @author Toru Nagashima
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. const fs = require("fs")
  7. const path = require("path")
  8. const Cache = require("./cache")
  9. const ROOT = /^(?:[/.]|\.\.|[A-Z]:\\|\\\\)(?:[/\\]\.\.)*$/u
  10. const cache = new Cache()
  11. /**
  12. * Check whether the file exists or not.
  13. * @param {string} filePath The file path to check.
  14. * @returns {boolean} `true` if the file exists.
  15. */
  16. function existsCaseSensitive(filePath) {
  17. let dirPath = filePath
  18. while (dirPath !== "" && !ROOT.test(dirPath)) {
  19. const fileName = path.basename(dirPath)
  20. dirPath = path.dirname(dirPath)
  21. if (fs.readdirSync(dirPath).indexOf(fileName) === -1) {
  22. return false
  23. }
  24. }
  25. return true
  26. }
  27. /**
  28. * Checks whether or not the file of a given path exists.
  29. *
  30. * @param {string} filePath - A file path to check.
  31. * @returns {boolean} `true` if the file of a given path exists.
  32. */
  33. module.exports = function exists(filePath) {
  34. let result = cache.get(filePath)
  35. if (result == null) {
  36. try {
  37. const relativePath = path.relative(process.cwd(), filePath)
  38. result =
  39. fs.statSync(relativePath).isFile() &&
  40. existsCaseSensitive(relativePath)
  41. } catch (error) {
  42. if (error.code !== "ENOENT") {
  43. throw error
  44. }
  45. result = false
  46. }
  47. cache.set(filePath, result)
  48. }
  49. return result
  50. }