I know what this require statement does.
var express = require('express'); var app = express();
But sometimes i have seen two parentheses after the require.
var routes = require('./routes')(app);
Q) What does this mean, and how does it work?
1. Use brackets inside parentheses to create a double enclosure in the text. Avoid parentheses within parentheses, or nested parentheses. Correct: (We also administered the Beck Depression Inventory [BDI; Beck, Steer, & Garbin, 1988], but those results are not reported here.)
It runs the function you just created. The reason to do this is that it encloses all of the code you write within a new scope. This means when you define vars and functions , they will be kept within the scope of that function() you just created.
The brackets enclose text which is not actually part of the quotation but necessary to provide additional context, to allow full understanding.
The use of a double parentheses is actually an indicator of one of Python's coolest features - and that is that functions are themselves, objects!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With