Harsh
Harsh

Reputation: 13

How to send a response from a module passing them the request and response objects in RESTIFY

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.*/
}

Upvotes: 0

Views: 68

Answers (1)

gaelgillard
gaelgillard

Reputation: 2521

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);

Upvotes: 1

Related Questions