Search code examples
javascriptexpress-4

How to pass a parameter to a self executing anonymous function


I have in my server.js this line of code:

 require('../routes/allRoutes')(app)

And this works fine when my allRoutes.js looks like this:

 module.exports = function(app){
    app.get("/", function(req, res){
      res.render ......
    });
 }

But what if my allRoutes.js looks like this:

  (function(allRoutes){

     app.get("/", function(req, res){
        res.render .....
      });
  })(module.exports)

How do I pass the app object in the anonymous, self executing function?


Solution

  • Nevermind, I figured it out:

    1. server.js

    require('./routes/allRoutes').init(app);
    

    2. allRoutes.js

    (function(allRoutes) {
      allRoutes.init = function(app) {
        app.get("/", function (req, res) {
          res.send('Hello You');
        })
      };
    })(module.exports);