-
Notifications
You must be signed in to change notification settings - Fork 3
/
find-nearest-file.js
41 lines (28 loc) · 991 Bytes
/
find-nearest-file.js
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
module.exports = find
var fs = require('fs')
, path = require('path')
function find(filename, root) {
root = root || process.cwd();
if (!filename) throw new Error('filename is required')
if (filename.indexOf('/') !== -1 || filename === '..') {
throw new Error('filename must be just a filename and not a path')
}
function findFile(directory, filename) {
var file = path.join(directory, filename)
try {
// Get the stat for the path, and if this doesn't throw, make sure it's a file
if (fs.statSync(file).isFile()) return file
// stat existed, but isFile() returned false
return nextLevelUp()
} catch (e) {
// stat did not exist
return nextLevelUp()
}
function nextLevelUp() {
// Don't proceed to the next directory when already at the fs root
if (directory === path.resolve('/')) return null
return findFile(path.dirname(directory), filename)
}
}
return findFile(root, filename)
}