Skip to content

Instantly share code, notes, and snippets.

@swape
Last active August 29, 2015 14:27
Show Gist options
  • Save swape/bd4b9375b223a35e36fc to your computer and use it in GitHub Desktop.
Save swape/bd4b9375b223a35e36fc to your computer and use it in GitHub Desktop.
Require js files from a directory with glob based on a file name.
// ./controllers/b.js
module.exports = {
index: function(){
console.log('b is here');
}
};
// main file
var glob = require('glob');
var path = require('path');
// controller directory
var ctlPath = './controllers/*.js';
// including based on names
glob.sync(ctlPath).forEach(function (file) {
var name = file.replace(/.\/controllers\/|.js/ig , '');
GLOBAL[name] = require(path.resolve(file));
});
// calling index function inside file b.js
b.index();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment