What is the best way to pass common variables into separate modules in Node.js?

后端 未结 4 663
慢半拍i
慢半拍i 2020-12-07 08:00

I use separate router files as modules for main app and auth app. I can\'t get the best way to pass variables(db client) into routers. I don\'t want to hardcode it or pass i

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 08:52

    I suggest you create a settings file with db instance and with other things which you need use globally like 'singleton'.

    For example, I have settings.js with my redis db client:

    var redis = require('redis');
    exports.redis = redis.createClient(6379, '127.0.0.1');
    

    And in other multiple modules I include it:

    var settings = require('./settings');
    setting.redis.<...>
    

    Many time including it I always have one instance of db connection.

提交回复
热议问题