Node.js code snippet - dynamically load all javascript in a folder
Sometimes I need to dynamically load all javascript files contained in a folder - here's a handy code snippet that does it - this function will dynamically load all js files in a folder then calls a callback asynchronously, and return synchronously, an array with all js files it has loaded.
var requireDir = function(dir, callback) {
var aret = Array();
fs.readdirSync(dir).forEach(function (library) {
var isLibrary = library.split(".").length > 0 && library.split(".")[1] === 'js',
libName = library.split(".")[0].toLowerCase();
if (isLibrary) {
aret[libName] = require(path.join(dir, library));
}
});
if(callback) process.nextTick(function() {
callback(null, aret);
});
return aret;
}
Written by Sebastian Schepis
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Nodejs
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#