Node JS calls a "local" function in module.exports

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

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

cannot call getName undefined method

 "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 in the controller?

+7
source share
4 answers

I found a solution :-)

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

You can access the getName function of trough module.exports . For instance:

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

Perhaps you could do it like this. This reduces 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 }; 
+8
source

If you want to use the function locally AND in other files ...

 function myFunc(){ return 'got it' } module.exports.myFunc = myFunc; 
0
source

Source: https://habr.com/ru/post/1233516/


All Articles