Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS call a "local" function within module.exports

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

I have MVC structure node js project and a controller called TestController.js. I want to access method within controller, but using this keyword gives below error:

cannot call method getName of undefined

"use strict"
module.exports = {
    myName : function(req, res, next) {
        // accessing method within controller
        this.getName(data);
    },

    getName : function(data) {
        // code
    }
}

How do I access methods within controller?

like image 852
sravis Avatar asked Oct 12 '15 10:10

sravis


3 Answers

I found the solution :-)

"use strict"
var self = module.exports = {
    myName : function(req, res, next) {
        // accessing method within controller
        self.getName(data);
    },

    getName : function(data) {
        // code
    }
}
like image 133
sravis Avatar answered Nov 13 '22 20:11

sravis


You can access the getName function trough module.exports. Like so:

"use strict"
module.exports = {
    myName : function(req, res, next) {
        // accessing method within controller
        module.exports.getName(data);
    },

    getName : function(data) {
        // code
    }
}
like image 17
Mate Hegedus Avatar answered Nov 13 '22 20:11

Mate Hegedus


Maybe you could do it like this. It reduce nesting. And all your export is done at the end of your file.

"use strict";

var _getName = function() {
    return 'john';
};

var _myName = function() {
    return _getName();
};

module.exports = {
    getName : _getName,
    myName : _myName
};
like image 8
severin.julien Avatar answered Nov 13 '22 22:11

severin.julien