asosnovsky
asosnovsky

Reputation: 2235

Node.js: Making internal calls from exports

Suppose I have the following code in one of my modules:

var _this = this;
exports.getData = function(res) {
  res.json({someData:'Data'});
};

Now I want to make another exports function within my module that makes use of getData. Basically somehow make something of this sort:

exports.getMoreData = function(res) {
  $.nodeInternalCall({url: _this.getData()}).done(function(data) {
    res.json({newData: data.someData * 10})
  })
};

Is there any way to do this? Unless this doesn't make sense in node D:

Upvotes: 0

Views: 672

Answers (1)

Retsam
Retsam

Reputation: 33399

There's a couple ways to do this; the simplest is simply to reference it literally as exports.getData:

exports.otherFunction = function(res) {
    return exports.getData(res);
};

You can also assign the function to a variable for easy reference in other functions.

var getData = exports.getData = function(res) {};

exports.otherFunction = function(res) {
    return getData(res);
};

The advantage of the first approach is that it doesn't matter what order the functions are defined in (as long as you don't invoke a function that depends on another function before defining the other).

The advantage of the second is that it's shorter to type, and if you later change your mind and decide not to expose the function as part of the module you can remove the exports.getData = without needing to refactor all the rest of the code.

Upvotes: 1

Related Questions