-->

CommonJS Modules - Exporting a function that retur

2019-08-08 15:12发布

问题:

In this rendr - sessions example, there's an express middleware module...

module.exports = function incrementCounter() {
  return function incrementCounter(req, res, next) {
    var app = req.rendrApp
      , count = app.get('session').count || 0;
    req.updateSession('count', count + 1);
    next();
  };
};

Can you not achieve the same thing with the following?

module.exports = function incrementCounter(req, res, next) {
  var app = req.rendrAp
  , count = app.get('session').count || 0;
  req.updateSession('count', count + 1);
  next();
};

My Question is, why would you export a function which returns a function with arguments? Is there some sort of benefit to the former that I am unaware of?

回答1:

rendr uses Express-style middleware.

By convention, third-party middleware in Express are not provided as the actual middleware. Instead, they are provided as functions that create the middleware based on an options object parameter.

However, since there are no options to be provided here, it is omitted.

But still, in order to follow the conventions of the surrounding library, it needs to be a factory function that returns a middleware function. So that's why it is wrapped up that way here.