node.js 将参数传递给 require(加载模块时)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13151693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing arguments to require (when loading module)
提问by Andreas Selenwall
Is it possible to pass arguments when loading a module using require?
使用 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.
我有提供登录功能的模块 login.js。它需要一个数据库连接,我希望在我的所有模块中使用相同的数据库连接。现在我导出一个函数 login.setDatabase(...) ,它让我指定一个数据库连接,它工作得很好。但是我宁愿在加载模块时传递数据库和任何其他要求。
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?
我对 NodeJS 很陌生,通常使用 Java 和 Spring 框架进行开发,所以是的...这是一个构造函数注入:) 是否可以执行我上面提供的代码之类的操作?
回答by floatingLomas
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.
我几乎所有的模块都是这样构建的。似乎对我来说效果很好。
回答by vovkman
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.
我不确定这对人们是否仍然有用,但是使用 ES6,我有一种方法可以做到这一点,我觉得它干净且有用。
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 )
回答by David Weldon
Yes. In your loginmodule, just export a single function that takes the dbas its argument. For example:
是的。在您的login模块中,只需导出一个以db为参数的函数。例如:
module.exports = function(db) {
...
};

