Search code examples
javascriptnode.jsmodular-design

How do you make variables and dependencies available in all modules of a node app?


I built a node application recently and have decided to modularize it.

I'm requiring all the dependencies, declaring an array that is manipulated by other modules as the program runs, and executing the application in the app.js file (there's not much else in that file anymore). This means that all of the modular file functions should take place down the scope-chain and have access to the packages and variables required in app.js, correct?

However, the package methods and variables defined and required in app.js are throwing errors as undefined. This means the modular files I'm creating don't have access to the variables and packages required in my app.js file.

The program works fine in one large app file. The code works fine if I declare all the dependencies and variables in app.js as globals. And the code will work if I require the packages in every file.

...All of these solutions defeat the purpose of modular code patterns...

Could you direct me to some resources on making packages and variables available in all modules of a node application without cluttering the global scope?

Thank you!


Solution

  • No, that's not correct.

    Modules are encapsulated by default, exporting an object named.. module.export. Modules do not have access to the context (or variables) of the parent module.

    Unlike in languages like PHP, require() is not like concatenating the files.

    If you need to pass data, such as config, db, or another module, then you'll need to pass it to the module. One simple example is this:

    // app.js
    var config = require('./config');
    var db = require('./db').connect(config.DB_CONFIG);
    
    var UsersModel = require('./usersModel')(db);
    
    var someLogger = require('some-logger');
    var logger = someLogger.init(config.SOME_OPTION);
    

    Of course, there are many different styles and patterns.