0

Here is the sample.js :

module.exports = (function (param) {
   // I'm expecting param to be available here
})();

Here is the app.js

var sampleMsg= require('./controller/sample')(param);
app.use('/sample', sampleMsg);

But the above code when run throws the following error:

D:\Working\GUI\Server\node_modules\express\lib\router\index.js:140
  var search = 1 + req.url.indexOf('?');
                          ^

TypeError: Cannot read property 'indexOf' of undefined
    at Function.handle (D:\Working\GUI\Server\node_modules\express\lib
\router\index.js:140:27)
    at router (D:\Working\GUI\Server\node_modules\express\lib\router\i
ndex.js:46:12)
    at Object.<anonymous> (D:\Working\GUI\Server\app.js:267:54)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3
iJade
  • 23,144
  • 56
  • 154
  • 243

1 Answers1

0

The code

(function (param) {
   // I'm expecting param to be available here
})()

is a self-invoking function which returns undefined. You can't invoke an undefined value as it's not a function. Also, in the above code param is also undefined as the invocation operator (()) doesn't pass any parameters to the anonymous function. In the following code param is "I'm the param" string:

(function (param) {
   // ...
})("I'm the param");

It not clear why you are using a self-invoking function here. If you need to use a closure the syntax should be:

module.exports = function(param) {
   return function(req, res, next) {
      // ...
   }
}
// ...
var routeHandler = require('./controller/sample')(param);
app.use('/sample', routeHandler);
Ram
  • 143,282
  • 16
  • 168
  • 197
  • Ok .. is there a way to a init method inside the sample.js ? – iJade Aug 14 '17 at 09:33
  • The closure function example in my answer can be used as an initializer, it's a closure function that returns another function. The returned function can be used as an express route handler. Here is a related question: https://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Ram Aug 14 '17 at 09:37