exists.js 2.0 KB

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