Created
July 4, 2012 14:29
-
-
Save TheDeveloper/3047655 to your computer and use it in GitHub Desktop.
Node.js require directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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