Passing arguments to require (when loading module)

node.jsExpress

node.js Problem Overview


Is it possible to pass arguments when loading a module using require?

I have module, login.js which provides login functionality. It requires a database connection, and I want the same database connection to be used in all my modules. Now I export a function login.setDatabase(...) which lets me specify a database connection, and that works just fine. But I would rather pass the database and any other requirements when I load the module.

var db = ...
var login = require("./login.js")(db);

I am pretty new with NodeJS and usually develop using Java and the Spring Framework, so yes... this is a constructor injection :) Is it possible to do something like the code I provided above?

node.js Solutions


Solution 1 - node.js

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.

Solution 2 - node.js

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 )

Solution 3 - node.js

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndreas SelenwallView Question on Stackoverflow
Solution 1 - node.jsfloatingLomasView Answer on Stackoverflow
Solution 2 - node.jsvovkmanView Answer on Stackoverflow
Solution 3 - node.jsDavid WeldonView Answer on Stackoverflow