Search code examples
node.jsexpressrequire

Re-requiring module that parent requires


I'm in the process of learning NodeJS (using Express), and came across something that struck me as odd.

In app.js i'm requiring a module (passport in this case), and then requiring a second module (passport-strats.js) which I developed. Inside of passports-strats I have to re-require passport even though it's already required in app.js.

This isn't the only example, I have some modules required in three files that are all tightly related. Is this standard or am I missing some crucial piece of structuring NodeJS applications?


Solution

  • For you require the passport module once you should require it in passport-strats.js and export it from this module. In app.js you can use both modules just importing passport-strats.js. ie:

    //passport-strats.js
    
    var {passport} = require("./path");
    //other code
    
    module.exports = { passport, someVariableFromCurrentModel };
    
    
    //In app.js
    
    var {passport, someVariableFromCurrentModel} = require("./passport-strats");