传递参数要求(加载模块时) [英] Passing arguments to require (when loading module)

查看:100
本文介绍了传递参数要求(加载模块时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在使用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 Framework开发,所以是的...这是一个构造函数注入:)可以做一些类似上面提供的代码吗?

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.

这篇关于传递参数要求(加载模块时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆