require-tree
A require()
-like method for directories, returning an object that mirrors the file tree.
npm install require-tree
Usage
Considering this file structure:
- models
- user.js
- page.js
- item.js
Requiring the models
directory will return an object containing each exported module:
var require_tree = /* { user: [object Object], page: [object Object], item: [object Object]} */
Directories can be deeply nested, andindex.js
files are merged into their parent by default:
// api/user.js:moduleexports = {} {} // api/pages/index.js:moduleexports = {} // api/pages/edit.js:moduleexports = {} {} var api =
This will yield
api.user.profile
api.user.posts
api.pages.list
api.pages.edit.getPermissions
api.pages.edit.remove
Options
{ name: string | function (exports) }
Use a property of the exports object as it's key (instead of the filename) in the final object.
// models/user-model.jsmoduleexports = id: 'user' attrs: {} // => { user: { id: 'user', attrs: {} } }
{ filter: string | regexp | function }
Filter the required files. Strings can use a wildcard '*' and are expanded into regular expressions. You can also provide your own RegExp, or a function that receives the filename as an argument, and returns true
or false
.
{ keys: string | array | regexp | function }
Use to return only certain keys from exported objects.
// => { user: { attrs: {} } }
{ each: function }
Callback to run after each file is required. Doesn't modify the exported object.
{ transform: function }
Same as each
, but can modify the exports object.
{ index: 'merge', 'ignore', 'preserve' }
merge
(default): merges theindex.js
exports at the root of it's parentignore
: causesindex.js
files to not be loaded at allpreserve
: puts theindex.js
export object under the.index
property
For backwards compatibility, a value of true
is equal to preserve
, while false
is equal to ignore
.
- controllers
- index.js
- users.js
- ...
// controllers/index.js:moduleexports = { ... } var controllers = controllersindex var controllers = controllersindex // undefined var controllers = controllers
Limitations
require-tree
must always be required in the local scope, never shared between modules or as a global. Paths are resolved relative to the parent module, like require
itself, so it's behaviour depends on module.parent
being set correctly. If necessary, you can use absolute paths (__dirname + '/path'
) or set the NODE_PATH
environment variable.