Global Variable in app.js accessible in routes?

前端 未结 13 1670
南笙
南笙 2020-11-28 21:29

How do i set a variable in app.js and have it be available in all the routes, atleast in the index.js file located in routes. using the express fra

13条回答
  •  半阙折子戏
    2020-11-28 22:08

    To declare a global variable you need do use global object. Like global.yourVariableName. But it is not a true way. To share variables between modules try to use injection style like

    someModule.js:

    module.exports = function(injectedVariable) {
        return {
            somePublicMethod: function() {
            },
            anotherPublicMethod: function() {
            },
        };
    };
    

    app.js

    var someModule = require('./someModule')(someSharedVariable);
    

    Or you may use surrogate object to do that. Like hub.

    someModule.js:

    var hub = require('hub');
    
    module.somePublicMethod = function() {
        // We can use hub.db here
    };
    
    module.anotherPublicMethod = function() {
    };
    

    app.js

    var hub = require('hub');
    hub.db = dbConnection;
    var someModule = require('./someModule');
    

提交回复
热议问题