#require.all - function([dirname, options])
Apply filters and require()
/read all files within a specified directory and optionally resolve them with custom function or arguments.
##Usage
$ npm install --save require.all
var controllers = require('require.all')('./controllers');
// same as
var controllers = {
homeController: require('./controllers/home-controller.js'),
aboutController: require('./controllers/about-controller.js'),
admin: {
dashboardController: require('./controllers/admin/dashboard-controller.js')
}
// ...
}
##Advanced
require.all = require('require.all');
var controllers = require.all({
dir: './controllers',
match: /controller\.js$/i, //only files that end with 'controller.js'
recursive: false,
// rename module: use default mapping function and remove 'controller' from the end
map: (name, path, isFile) => require.all.map(name, path, isFile).replace(/controller$/i, '')
});
// resolve all controllers to have their instances
controllers(function(name, Controller){
this === controller; // true
return new Controller();
});
// the above code does the same as
var controllers = {
home: new require('./controllers/home-controller.js')(),
about: new require('./controllers/about-controller.js')()
// ...
};
##Options and defaults
require.all = require('require.all');
var modules = require.all({
dir: '.',
not: /^\./,
match: null,
map: map,
ignore: /^\.|node_modules/,
require: /\.(js|json)$/,
recursive: true,
encoding: 'utf-8',
tree: true
})
-
dir -
[String]
- absolute or relative path to the directory to be traversed. By default it is the current directory butrequire.all
will not require it's parent file to prevent infinite loops.- default -
'.'
- current directory
- default -
-
not -
[RegExp/Function(name)/null]
- filter to specify which files to be skipped. Usenull
to disable.- default -
/^\./
- skip files beginning with '.'
- default -
-
match -
[RegExp/Function(name)/null]
- only matching files will be required. Usenull
to disable.- default -
null
- do not apply match filter'
- default -
-
map -
[Function(name, path, isFile)]
- function to be used for renaming files and directories. Receives node's name and path and a flag which is true if the node is a file (false if dir). Must return the new name to be used.- default -
map
- internal function that converts names to camelCased, skipping none word characters and skipping files extensions, allowing modules to be accessed through dot notation.require.all.map('my-lucky module.js'); // myLuckyModule
- default -
-
ignore -
[RegExp/Function(name)/null]
- filter to specify which child directories to be ignored. Applied only in recursive mode. Usenull
to disable.- default -
/^\.|node_modules/
- ignorenode_modules
and folders beginning with.
- default -
-
require -
[RegExp/Function(name)/null]
- filter to specify which files shall be loaded usingrequire
. Files that do not pass this filter will be loaded as a string. Usenull
to read all files as string.- default -
/\.(js|json)$/
- only .js and .json files will berequire
-d
- default -
-
recursive -
[Boolean]
- specifies weather to traverse child directories too.- default -
true
- default -
-
encoding -
[String]
- the encoding to use for the files that will be read as string- default -
'utf-8'
- default -
-
tree -
[Boolean]
- determines weather the output object should mimic the structure of the files and folders, keeping the nesting level. If set tofalse
all files will be on the same level.- default -
true
- default -
WARNING: Nodes (files and dirs) with same names on the same level will overwrite each other. If tree
option is set to false
directory names don't matter but keep in mind that all files are loaded on the same level so they all must have unique names.
WARNING: File names and dirnames must not resolve (after the map function if any) to one of the following: name, arguments, caller, length
##Resolve
require.all()
actually returns a function which may be used to resolve all modules. It acts much like Array.prototype.map
, looping trough all the loaded modules (see examples below!). It may be applied as many times as you wish in two possible modes:
- If you pass no parameter or an array of parameters only the modules that are functions will be executed. If the return value is none falsy it will be the new value that will be available in the returned from
require.all()
object (function).
var modules = require.all('./modules');
// assume we have module foo
modules.foo; // function foo(){return function bar(a){ return a}}
// execute all functions (resolve foo with no arguments)
modules();
// foo is now bar
modules.foo; // function bar(a){ return a}
// lets resolve bar
modules();
modules.foo; // function bar(a){ return a}
// bar was resolved but since `a` was undefined modules.foo is still `bar`
// lets resolve with array of none falsy values, that shall be passed as arguments
modules(["some none falsy value", "pointless"]);
// modules.foo returns `a`, the first argument, which now is none falsy so:
modules.foo; // "some none falsy value"
- You may pass a single function and deal with the modules as you wish. The function is applied in the context of the module itself and receives the name of the module and the module as arguments.
var modules = require.all('./modules');
modules.foo; //function foo(){return true}
modules(function(name, module){
this === module; // true
return module
})
modules.foo;// function foo
//again we may keep on resolving
modules()()()()();
//modules.foo is now true since we resolved it in mode 1 and it returns true
modules.foo; // true
Notice:
require.all()(1,2,3);
//same as
require.all()([1,2,3]);
//same as
require.all()(funnction(name, mdl){
return mdl(1,2,3)
});
// so you may pass arguments as normal
// but if you want to pass a SINGLE argument
// which is an ARRAY or FUNCTION you should do this:
var arr = [], f = function(){};
require.all()([arr]);
require.all()([f]);
// or
require.all()(arr, undefined);
require.all()(f, undefined);
require.all = require('require.all');
var express = require('express');
var app = express(),
cfg = require.all('./config/'),
controllers = require.all('./controllers'),
models = require.all('./models'),
routes = require.all('./routes');
//pass models to controllers
controllers([models]); // models is function!
Object.assign(app, {controllers, models});
// assume we have model for each page
app.use('/:page*', function(req, res, next){
var page = req.params.page;
res.model = models[page];
next();
});
// pass the controllers to all routes
routes(controllers, undefined); // controllers is also function!
// now the routes are ready to be bound;
routes(function(name, route){
return app.use('/' + name, route), route;
});
// our app is ready that quickly... :)
app.listen(cfg.port, cfg.host, ()=>{
console.log('App is running on %s:%s', cfg.port, cfg.host);
});
Hey, if something is missing or you want to suggest improvements and features, you are wellcome.