Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a "local" function within module.exports from another function in module.exports?

How do you call a function from within another function in a module.exports declaration?

app.js
var bla = require('./bla.js');
console.log(bla.bar());
bla.js
module.exports = {

  foo: function (req, res, next) {
    return ('foo');
  },

  bar: function(req, res, next) {
    this.foo();
  }

}

I'm trying to access the function foo from within the function bar, and I'm getting:

TypeError: Object # has no method 'foo'

If I change this.foo() to just foo() I get:

ReferenceError: foo is not defined

like image 759
k00k Avatar asked May 05 '12 13:05

k00k


7 Answers

Change this.foo() to module.exports.foo()

like image 173
k00k Avatar answered Nov 25 '22 06:11

k00k


You could declare your functions outside of the module.exports block.

var foo = function (req, res, next) {
  return ('foo');
}

var bar = function (req, res, next) {
  return foo();
}

Then:

module.exports = {
  foo: foo,
  bar: bar
}
like image 37
Brett Avatar answered Nov 25 '22 04:11

Brett


You can also do this to make it more concise and readable. This is what I've seen done in several of the well written open sourced modules:

var self = module.exports = {

  foo: function (req, res, next) {
    return ('foo');
  },

  bar: function(req, res, next) {
    self.foo();
  }

}
like image 29
Calvin Alvin Avatar answered Nov 25 '22 05:11

Calvin Alvin


You can also save a reference to module's global scope outside the (module.)exports.somemodule definition:

var _this = this;

exports.somefunction = function() {
   console.log('hello');
}

exports.someotherfunction = function() {
   _this.somefunction();
}
like image 37
Ville Avatar answered Nov 25 '22 04:11

Ville


Another option, and closer to the original style of the OP, is to put the object you want to export into a variable and reference that variable to make calls to other methods in the object. You can then export that variable and you're good to go.

var self = {
  foo: function (req, res, next) {
    return ('foo');
  },
  bar: function (req, res, next) {
    return self.foo();
  }
};
module.exports = self;
like image 25
goozbox Avatar answered Nov 25 '22 04:11

goozbox


const Service = {
  foo: (a, b) => a + b,
  bar: (a, b) => Service.foo(a, b) * b
}

module.exports = Service
like image 37
david_adler Avatar answered Nov 25 '22 04:11

david_adler


Starting with Node.js version 13 you can take advantage of ES6 Modules.

export function foo() {
    return 'foo';
}

export function bar() {
    return foo();
}

Following the Class approach:

class MyClass {

    foo() {
        return 'foo';
    }

    bar() {
        return this.foo();
    }
}

module.exports = new MyClass();

This will instantiate the class only once, due to Node's module caching:
https://nodejs.org/api/modules.html#modules_caching

like image 41
m.spyratos Avatar answered Nov 25 '22 04:11

m.spyratos