Skip to content

Commit

Permalink
Merge pull request #27 from lennym/feature/filter-option
Browse files Browse the repository at this point in the history
Support a filter option to exclude particular files
  • Loading branch information
contra committed Feb 7, 2018
2 parents 1150303 + a21f5b0 commit 1da3990
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Expand Up @@ -83,6 +83,14 @@ be the same by default, but specifying `duplicates: true` would yield:
}
```

`filter`: Apply a filter on the filename before require-ing. For example:

```js
requiredir('./dir', function (f) { return process.env.NODE_ENV !== 'production' && !f.match(/$dev/); })
```

This will ignore files prefixed with `dev` if running in a production environment.

There might be more options in the future. ;)

## Tips
Expand Down
6 changes: 6 additions & 0 deletions index.js
Expand Up @@ -17,6 +17,8 @@ module.exports = function requireDir(dir, opts) {
dir = dir || '.';
opts = opts || {};

opts.filter = opts.filter || function (file) { return true; };

// resolve the path to an absolute one:
dir = Path.resolve(parentDir, dir);

Expand Down Expand Up @@ -66,6 +68,10 @@ module.exports = function requireDir(dir, opts) {
if (path === parentFile) {
continue;
}
// apply file filter:
if (!opts.filter(path)) {
continue;
}

if (FS.statSync(path).isDirectory()) {
if (opts.recurse) {
Expand Down
9 changes: 9 additions & 0 deletions test/filter.js
@@ -0,0 +1,9 @@
var assert = require('assert');
var requireDir = require('..');

// filter the results to a particular file:
assert.deepEqual(requireDir('./simple', { filter: function (filename) { return filename.match(/a\.js$/); } }), {
a: 'a'
});

console.log('Filter tests passed.');

0 comments on commit 1da3990

Please sign in to comment.