Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to require (when loading module)

People also ask

What are the arguments passed to the module wrapper function?

This wrapper function has 5 arguments: exports , require , module , __filename , and __dirname . This is what makes them appear to look global when in fact they are specific to each module. All of these arguments get their values when Node executes the wrapper function. exports is defined as a reference to module.

How modules are loaded in node JS?

These modules can be loaded into the program by using the require function. Syntax: var module = require('module_name'); The require() function will return a JavaScript type depending on what the particular module returns.

How does NodeJS loads require?

Node. js follows the CommonJS module system, and the built-in require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.


Based on your comments in this answer, I do what you're trying to do like this:

module.exports = function (app, db) {
    var module = {};

    module.auth = function (req, res) {
        // This will be available 'outside'.
        // Authy stuff that can be used outside...
    };

    // Other stuff...
    module.pickle = function(cucumber, herbs, vinegar) {
        // This will be available 'outside'.
        // Pickling stuff...
    };

    function jarThemPickles(pickle, jar) {
        // This will be NOT available 'outside'.
        // Pickling stuff...

        return pickleJar;
    };

    return module;
};

I structure pretty much all my modules like that. Seems to work well for me.


I'm not sure if this will still be useful to people, but with ES6 I have a way to do it that I find clean and useful.

class MyClass { 
  constructor ( arg1, arg2, arg3 )
  myFunction1 () {...}
  myFunction2 () {...}
  myFunction3 () {...}
}

module.exports = ( arg1, arg2, arg3 ) => { return new MyClass( arg1,arg2,arg3 ) }

And then you get your expected behaviour.

var MyClass = require('/MyClass.js')( arg1, arg2, arg3 )

Yes. In your login module, just export a single function that takes the db as its argument. For example:

module.exports = function(db) {
  ...
};