Last Updated: February 25, 2016
·
6.021K
· sschepis

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;
}