Skip to content

Commit

Permalink
Chore: add cache to exists()
Browse files Browse the repository at this point in the history
  • Loading branch information
mysticatea committed Jun 1, 2017
1 parent ffc7fcb commit fa95be2
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions lib/util/exists.js
Expand Up @@ -11,12 +11,14 @@

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.
Expand Down Expand Up @@ -49,17 +51,23 @@ function existsCaseSensitive(filePath) {
* @returns {boolean} `true` if the file of a given path exists.
*/
module.exports = function exists(filePath) {
try {
const relativePath = path.relative(process.cwd(), filePath)
return (
fs.statSync(relativePath).isFile() &&
existsCaseSensitive(relativePath)
)
}
catch (error) {
if (error.code === "ENOENT") {
return false
let result = cache.get(filePath)
if (result == null) {
try {
const relativePath = path.relative(process.cwd(), filePath)
result = (
fs.statSync(relativePath).isFile() &&
existsCaseSensitive(relativePath)
)
}
throw error
catch (error) {
if (error.code !== "ENOENT") {
throw error
}
result = false
}
cache.set(filePath, result)
}

return result
}

0 comments on commit fa95be2

Please sign in to comment.