1

I have a resource loader JS file running on a nodejs server. I want to drop in a bunch of resource js files that the resource loader will load into an array on initialization.

    // resource loader js file
    var Resources = (function () {

    var resources = {};

    function Resources(){
    ... loading code here

    // example of use after loading
    resources[key].doStuff();
    }
})();
module.exports.Resources = Resources;

In the same directory the developer can just drop in new resource.js files as needed.

// resource file
var ResourceA = (function () {

function ResourceA(){
... loading code here

// example of use after loading
  ResourceA.prototype.doStuff= function () {
        // do stuff
    };

})();
2
  • require('./resource.js') ? Commented Feb 24, 2013 at 16:39
  • 1
    The developer would have to add a require for each file. Imagine there are 50 of them. I want the developer to just create the files and not have to modify the resource loader file. Commented Feb 24, 2013 at 16:48

2 Answers 2

5

I'm not sure what you mean, but if what you want is to load a bunch of modules in a single folder on the server side, I built this little function to do just that.

var path = require('path'),
    walk = require('walk');

function findModules(opts,done){
    var walker  = walk.walk(opts.folder, { followLinks: false }),
        modules = [];

    walker.on('file', function(root, stat, next) {
        var current = path.join(root, stat.name),
            extname = path.extname(current);

        if(extname === '.js' && (opts.filter === undefined || opts.filter(current))){
            var module = require(current);
            modules.push(module);
        }

        next();
    });

    walker.on('end', function() {
        done(modules);
    });
}

and then, you call it like this:

findModules({
    folder: 'path/to/folder',
    filter: undefined // either undefined or a filter function for module names
}, function(modules){
    // continue
});

to install walk:

npm install walk --save
Sign up to request clarification or add additional context in comments.

1 Comment

small addition to your code. var module = require("./"+current); without this, i m getting an error saying module not found.
2

New and more simple:

Install

npm install eloader

Usage

const eloader = require('eloader');
const db = require('db');

eloader.add('db', db)
       .add('list', [2,8]
       .run(__dirname + '\\routes\\');

Git https://github.com/augustoeliezer/eloader

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.