Skip to content

Commit

Permalink
Merge pull request #60 from akatsukle/master
Browse files Browse the repository at this point in the history
Resolve #59, add an optional extensions parameter
  • Loading branch information
contra committed Nov 26, 2018
2 parents 608ebe5 + 868a07f commit 6370638
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 7 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ be the same by default, but specifying `duplicates: true` would yield:
requireDir('./dir', { noCache: true })
```

`extensions`: Array of extensions to look for instead of using `require.extensions`.

```js
requireDir('./dir', { extensions: ['.js', '.json'] })
```

## Tips

Make an `index.js` in a directory with this code to clean things up:
Expand Down
11 changes: 4 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ module.exports = function requireDir(dir, opts) {
// to the map using the full filename as a key also.
var map = {};

// get the array of extensions we need to require
var extensions = opts.extensions || Object.keys(require.extensions);

for (var base in filesForBase) {
// protect against enumerable object prototype extensions:
if (!filesForBase.hasOwnProperty(base)) {
Expand Down Expand Up @@ -95,13 +98,7 @@ module.exports = function requireDir(dir, opts) {
}

// otherwise, go through and try each require.extension key!
for (ext in require.extensions) {
// Node v8+ uses "clean" objects w/o hasOwnProperty for require
// again protect against enumerable object prototype extensions:
if (!Object.prototype.hasOwnProperty.call(require.extensions, ext)) {
continue;
}

for (ext of extensions) {
// if a file exists with this extension, we'll require() it:
var file = base + ext;
var abs = filesMinusDirs[file];
Expand Down
34 changes: 34 additions & 0 deletions test/extensions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
var assert = require('assert');
var requireDir = require('..');

// first test regularly:
assert.deepEqual(requireDir('./simple'), {
a: 'a',
b: 'b',
});

// only js files
assert.deepEqual(requireDir('./simple', {extensions: ['.js']}), {
a: 'a'
});

// both js and json files
assert.deepEqual(requireDir('./simple', {extensions: ['.js', '.json']}), {
a: 'a',
b: 'b'
});

// then test with recursing:
assert.deepEqual(requireDir('./recurse', {recurse: true, extensions: ['.js']}), {
a: 'a',
b: {
'1': {
foo: 'foo'
},
'2': {} // note how the directory is always returned
},
c: {}
// note that node_modules was explicitly ignored
});

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

0 comments on commit 6370638

Please sign in to comment.