runtimeZero
runtimeZero

Reputation: 28126

Function declaration and calls in nodejs files

I am reading some source files and see that functions have been written and called in two different patterns. I am going to describe the two patterns first and then how they are called in the main file.

First pattern :

File module1.js:

    function a(req,res,next){
     //do somethin
    }

    module.exports.a = a;

seconds pattern :

File module2.js

module.exports = function(){
  return function(req,res,next){
     /* do something here */
    }
}

File main.js

   var mod1 = require('module1');
    var mod2 = require('module2');
    server.use(mod1.a);
    server.use(mod2());

What confuses me is why mod1 and mod2 have been written so differently. What is the right way of writing these

Upvotes: 0

Views: 68

Answers (1)

mscdex
mscdex

Reputation: 106756

The second pattern is useful if you need to pass in a configuration object or other information (e.g. a database instance) to the middleware that it will use for requests.

Either way is acceptable, it just depends on your needs.

Upvotes: 1

Related Questions