Skip to content

Instantly share code, notes, and snippets.

@TheDeveloper
Created July 4, 2012 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TheDeveloper/3047655 to your computer and use it in GitHub Desktop.
Save TheDeveloper/3047655 to your computer and use it in GitHub Desktop.
Node.js require directory
var fs = require('fs');
function requireDir(dir){
var modules = {};
var pathList = fs.readdirSync(dir);
var listLength = pathList.length;
for( var i = 0; i < listLength; i++ ){
var path = dir+'/'+pathList[i];
var pathStats = fs.statSync(path);
// Ensure regular file
if(pathStats.isFile()){
var pathParts = path.split('/');
var fileName = pathParts[pathParts.length -1];
if(!/\.js$/.test(fileName))
continue;
// Curtail extension
fileName = fileName.replace(/\..+$/, '');
modules[fileName] = require(path);
}
}
return modules;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment