What does double parentheses mean in a require
This is a pattern in which the module.exports
of the module you are requiring is set to a function. Requiring that module returns a function, and the parentheses after the require evaluates the function with an argument.
In your example above, your ./routes/index.js
file would look something like the following:
module.exports = function(app) {
app.get('/', function(req, res) {
});
// ...
};
This pattern is often used to pass variables to modules, as can bee seen above with the app
variable.
Well, require is a function provided by Node.js that basically loads a module for you and it returns whatever you expose in the module that you loaded.
If what you expose (through the use of module.exports) in a given module is a function, then that is what requires returns. For instance.
//moduleX.js
module.exports = function(){
return "Helo World";
}
Then if you require it, you get a function back
var f = require('./moduleX');
console.log(f()); //hello world
Of course, you could invoke the function directly once you require it.
var greet = require('./moduleX')();
console.log(greet);
That mean that behind that, there is a function that is exported using module.exports
:
module.exports = function(app) {
app.get("/", function(req, res){});
}
See also http://www.choskim.me/understanding-module-exports-and-exports-in-node-js/
Sidenote:
You could create function on the fly:
A.js
module.exports = function(data) {
return function(req, res, next) {
// Do something with data
next();
}
main.js
...
app.use(require("A")(data));
...