Exporting functions from modules

In the middleware unit of the Complete Node.js course, we create a Logger.js module with a log function, and export that with module.exports = log. Then in index.js, this is pulled in with the typical require statement and used with app.use(logger).

Then we pull in some third party middleware, namely helmet and morgan. These are likewise pulled in with require statements, and used as follows:

Hopefully this is not a silly question, but I am trying to figure out why for the logger it is app.use(logger) instead of app.use(logger()) like for helmet and morgan? I have tried playing around with the module.exports in logger.js. I feel like I am overlooking the obvious. Any explanations on this are appreciated.


Interesting question.

Basically the app.use needs a callback function with three parameters (precisely function (req, res, next)).

So when you write app.use(logger) it means you are writing:

app.use(function(req, res, next);

And when you write appuse(helmet()) and app.use(morgan('tiny')) , you are actually invoking the functions of helmet and morgan which returns a function (req, res, next).

I hope this clears things up.

Thanks for the response. I understand that this is essentially a callback being passed to app.use. My question was more around syntax - while for logger it is app.use(logger) instead of app.use(logger()) like it is for app.use(helmet()) and app.use(morgan(‘tiny’)).