mean stack - What is difference between require(path) and require(path)() in node.js -


in node.js projects have seen require(path) require(path)() paranthasis refers. when should use require(path) , require(path)()

the require() statement returns module.exports property within module being loaded. depends entirely on module set to.

if module set function of kind (often called module constructor function), natural call var = require('xxx')(...);

but, if module exports object properties on it, programming error try call it.

so, depends entirely upon module loading exporting.


for example, when loading file system module, be:

var fs = require('fs'); 

the variable fs in case object (not function) not call - reference properties on it:

fs.rename(...) 

here's example of module exporting constructor function call () after it:

// myroutes.js module.exports = function(app) {     app.get("/", function() {...});     app.get("/login", function() {...}); }  // app.js  // other code sets app object // ....  // load set of routes , pass app object constructor require('./myroutes')(app); 

and, here's example of module exporting properties not call module itself:

// myroutes.js module.exports.init = function(app) {     app.get("/", function() {...});     app.get("/login", function() {...}); }  // export commonly used helper function module.exports.checkpath = function(path) {     // .... }  // app.js  // other code sets app object // ....  // load set of routes , initialize routes var routestuff = require('./myroutes'); routestuff.init(app);   if (routestuff.checkpath(somepath)) {     // ... } 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -