Skip to content

Commit

Permalink
Added ability to start searching from a specified root directory
Browse files Browse the repository at this point in the history
Pass in a directory as the second parameter and `find-nearest-file`
will start it's search there. This defaults to `process.cwd()`.
Additionally, added a test for this functionality.
  • Loading branch information
salemhilal committed Jul 1, 2015
1 parent 085c905 commit 0ab505a
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
6 changes: 4 additions & 2 deletions Readme.md
Original file line number Diff line number Diff line change
@@ -1,7 1,8 @@
# find-nearest-file

Lookup a filename starting in `process.cwd()`, then `../`, `../../`, all the way
up to the filesystem root. Returns the found file path or `null`.
Lookup a filename starting in `process.cwd()` or a specified root directory,
then `../`, `../../`, all the way up to the filesystem root. Returns then
found file path or `null`.

## Installation

Expand All @@ -14,6 15,7 @@ npm install --save find-nearest-file
```js
var findNearestFile = require('find-nearest-file')
var file = findNearestFile('.localconfigrc')
var otherfile = findNearestFile('.localconfigrc', '/start/search/from/here')
```

## Credits
Expand Down
7 changes: 5 additions & 2 deletions find-nearest-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 3,17 @@ module.exports = find
var fs = require('fs')
, path = require('path')

function find(filename) {
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)
Expand All @@ -33,6 36,6 @@ function find(filename) {

}

return findFile(process.cwd(), filename)
return findFile(root, filename)

}
18 changes: 18 additions & 0 deletions test/find-nearest-file.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 67,22 @@ describe('find-nearest-file', function () {

})

it('should start searching at a different root directory, if provided', function () {

var find = rewire('../')
, filename = 'a-really-unique-filename-for-testing.test.zzz.__dsf.yup'
, paths = []

function mockStat(path) {
paths.push(path)
throw new Error()
}

find.__set__('fs', { statSync: mockStat })
find(filename, '/')
assert.equal(paths.length, 1)
assert.equal(paths[0], '/' filename)

})

})

0 comments on commit 0ab505a

Please sign in to comment.