UNPKG

directory

Version:

require everything in a directory

57 lines (43 loc) 1.43 kB
/*! * directory * Copyright(c) Thomas Blobaum * MIT Licensed */ var path = require('path') , fs = require('fs') function directory (dirname, callback) { // dirname and callback are sent if (typeof dirname === 'string' && typeof callback === 'function') { return require_directory(dirname, callback) } // only dirname is sent if (typeof dirname === 'string' && typeof callback === 'undefined') { return require_directory(dirname, function () {}) } // only callback is sent if (typeof dirname === 'function' && typeof callback === 'undefined') { // 12 is the length of node_modules return require_directory(module.parent.paths[0].slice(0, -12), dirname) } // no arguments if (typeof dirname === 'undefined' && typeof callback === 'undefined') { return require_directory(module.parent.paths[0].slice(0, -12), function () {}) } } function require_directory (dirname, callback) { var paths = fs.readdirSync(dirname) , fns = {} for (var l = paths.length, a=0; a < l; a++) { var path = dirname + paths[a] if (!path.match(module.parent.id) || module.parent.id === '.') { var filename = path.split(dirname)[1].split(".js")[0] , fn = require(path) fns[filename] = fn callback(fn, filename) } } return fns } // delete 'directory' (this file) from the cache delete require.cache[__filename] module.exports = directory