UNPKG

2.15 kBJavaScriptView Raw
1/**
2 * @fileoverview Util class to find config files.
3 * @author Aliaksei Shytkin
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Requirements
9//------------------------------------------------------------------------------
10
11var fs = require("fs"),
12 path = require("path");
13
14//------------------------------------------------------------------------------
15// API
16//------------------------------------------------------------------------------
17
18/**
19 * FileFinder
20 * @constructor
21 * @param {string} fileName Name of file to find
22 */
23function FileFinder(fileName) {
24 this.fileName = fileName;
25 this.cache = {};
26}
27
28/**
29 * Look file in directory and its parents, cache result
30 * @param {string} directory The path of directory to start
31 * @param {string[]} directoriesToCache Array of directories, found file will be cached for
32 * @returns {string|boolean} Path of file or false if no file is found
33 */
34FileFinder.prototype.findInDirectory = function(directory, directoriesToCache) {
35
36 var lookInDirectory = directory || process.cwd(),
37 lookFor = this.fileName,
38 files,
39 parentDirectory,
40 resultFilePath,
41 isFound = false;
42
43 if (this.cache.hasOwnProperty(lookInDirectory)) {
44 return this.cache[lookInDirectory];
45 }
46
47 if (!directoriesToCache) {
48 directoriesToCache = [];
49 }
50
51 directoriesToCache = directoriesToCache.concat(lookInDirectory);
52
53 files = fs.readdirSync(lookInDirectory);
54
55 if (files.indexOf(lookFor) !== -1) {
56 isFound = true;
57 resultFilePath = path.resolve(lookInDirectory, lookFor);
58 } else {
59
60 parentDirectory = path.resolve(lookInDirectory, "..");
61 if (parentDirectory === lookInDirectory) {
62 isFound = true;
63 resultFilePath = false;
64 }
65 }
66
67 if (isFound) {
68
69 directoriesToCache.forEach(function(path) {
70 this.cache[path] = resultFilePath;
71 }.bind(this));
72 return resultFilePath;
73 }
74
75 return this.findInDirectory(parentDirectory, directoriesToCache);
76};
77
78module.exports = FileFinder;