Blame view

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