Search code examples
javascriptnode.jscommonjs

Is calling require('mymodule') correct after initializing 'mymodule' somewhere else?


Let's assume i have a module that connects to the database by using some configuration. I don't want to pass around the configuration or the loaded module, i just want to initialize the database.js module in my main module (here app.js) and then be able to use it elsewhere in my code without initializing or passing the configuration.

My question is, is this approach correct with regards to what's been said here in this link

Here is the example.

// database.js

const mongodb

let config = null;

exports.init = (conf) {
    config = conf;
}

exports.getConnection = () {
    const MongoClient = mongodb.MongoClient;
    return new MongoClient(config.mongodb.url);
}

// app.js

const { init } = require('./database.js');

// load config ...

init(config);

// some module in the lib folder

const { getConnection } = require('../../database.js');

// do something with getConnection


Solution

  • The approach is correct. JS modules are evaluated only once under normal circumstances, this can be used in situations like this once.

    Notice that the configuration needs to be initialized before database module will be used in other modules:

    const { init } = require('./database.js');
    
    init(config);
    
    require('some-module-that-uses-database');