mdv mdv - 4 months ago 22
Javascript Question

nodejs export function on require

I have this line of code on some ExpressJS route:

var test = require('../app/test')('dev');
test.getData(); //this fails saying: typeError getData() is not a function


My test file looks like this:

module.exports = function(env){

var mod = {
'filed1': 'asd',
'field2': 'asd2'
};

mod.getData = function(){
return 'data';
};

return mod;
};


What am I doing wrong?

Answer

If you want to be able to call :

var test = require('../app/test')('dev');
test.getData(); //this fails saying: typeError getData() is not a function

You need to write your package that returns another function like the following :

module.exports = function(env){

  var mod = {
  'filed1': 'asd',
  'field2': 'asd2',
  'getData' :function(){

       return 'data';
     }
 };

 return mod ;


};

Explain :

  • require('../app/test') return function(env){ ....
  • require('../app/test')('dev') call function(env){....}('dev') ==> It returns the output of function(env){.....

  • This output should be an object (mod) that contains as attribute getData & its value should be a function to be able to call require('../app/test')('dev').getData()


DEMO :

test=function(env){

  var mod = {
  'filed1': 'asd',
  'field2': 'asd2',
  'getData' :function(){
    
       return 'data';
     }
   };
 
 return mod ;


};

  console.log(`Can i call "test.getData()" ?` )
try{
   test('dev').getData(); //!--- Call like this 
   console.log('yes')
}catch(e){

   console.log('No : ',e)
}
   
 console.log(`Can i call "test('dev').filed1" ? => `,test('dev').filed1 ==='asd' );