1 |
|
2 |
|
3 |
|
4 |
|
5 | "use strict";
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | var fs = require("fs"),
|
12 | path = require("path");
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | function FileFinder(fileName) {
|
24 | this.fileName = fileName;
|
25 | this.cache = {};
|
26 | }
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | FileFinder.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 |
|
78 | module.exports = FileFinder;
|