将参数传递给 require(加载模块时) [英] Passing arguments to require (when loading module)
问题描述
是否可以在使用 require 加载模块时传递参数?
Is it possible to pass arguments when loading a module using require?
我有提供登录功能的模块 login.js.它需要一个数据库连接,我希望在我的所有模块中使用相同的数据库连接.现在我导出一个函数 login.setDatabase(...) ,它让我指定一个数据库连接,它工作得很好.但我宁愿在加载模块时传递数据库和任何其他要求.
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);
我对 NodeJS 很陌生,通常使用 Java 和 Spring 框架进行开发,所以是的...这是构造函数注入:) 是否可以执行我上面提供的代码之类的操作?
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?
推荐答案
根据您在这个答案中的评论,我做你想做的事情:
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.
这篇关于将参数传递给 require(加载模块时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!