0

What I am trying to achieve is to send a response directly from a module instead of sending it from app.js.

for example :

/////app.js/////

server.get('/user', function (req, res, next) {
/*call a function of mymodule.*/
}

/////mymodule.js/////

function mymodule(){
/*Send my response from here.*/
}
aynber
  • 22,380
  • 8
  • 50
  • 63
Harsh
  • 13
  • 3

1 Answers1

1

From what I understand, you're trying to acheived is to exposed a function in your mymodule.jsfile.

To do that, you tell to node what you want to exports in a file. (You can find documentation here).

So to do what you want, you need to export the function mymodule. You can do this in this kind of approach :

// from mymodule.js
var mymodule = function(req, res){
  res.json({
    users: [
      // ...
    ]
  });
}
module.exports = mymodule;

This will expose your function mymodule when an other file will required it. So on your app.js, you could use it like this:

// from app.js
var required_module = require(__dirname + '/mymodule');
// ...
server.get('/user', function (req, res) {
  required_module(req, res);
});

Or an other approch:

// from app.js
var required_module = require(__dirname + '/mymodule');
// ...
server.get('/user', required_module);
gaelgillard
  • 2,483
  • 1
  • 14
  • 20
  • Thanks for the reply @Swatto.But what i wanted to implement is to send response object from the module itself.As you have mentioned you passed the req,res and next to module function but can you go a step further and explain how can i send response back to client using command res.send() in module. – Harsh Aug 22 '14 at 08:32
  • I've edited my response with a response made in the module itself. – gaelgillard Aug 22 '14 at 08:54