如何将属性传递给require模块?

时间:2018-01-06 20:44:19

标签: node.js

在我的 index.js 中,我需要 config 文件作为连接字符串等,如下所示:

var config = require('./config');
然后

config.js

module.exports = config;

所以在 index.js 中,我可以使用config.db_connect_string之类的配置属性。

当我还需要实例 db.js 来执行数据库工作时,如何在 db.config中创建的函数中访问config的属性并导出回 index.js

希望这是有道理的!我开始使用node。

1 个答案:

答案 0 :(得分:0)

我不知道db.js是什么样的,但你应该能够从index.js文件中将配置对象注入到db.js模块中,然后使用curried函数创建你想要的db对象出口。

像这样:

在index.js

var config = require('./config');

var { makeDB } = require('./db');

var db = makeDB(config)

在db.js

module.exports.makeDB =

    // Pass in the expected config object
    function(config) {

        // If your db module needs parameters
        // you can pass them in here
        return function(){

            // Create db module here.

            // The properties of the config object
            // passed in will be available here.

            // Be sure to return the database object.
            return db;
        }
    }
相关问题