Passing arguments to require (when loading module)

后端 未结 3 1307
情书的邮戳
情书的邮戳 2020-11-29 16:03

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,

相关标签:
3条回答
  • 2020-11-29 16:28

    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 )
    
    0 讨论(0)
  • 2020-11-29 16:35

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

    module.exports = function(db) {
      ...
    };
    
    0 讨论(0)
  • 2020-11-29 16:44

    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.

    0 讨论(0)
提交回复
热议问题