Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting multiple functions in one module in NodeJS [duplicate]

Hi I ran into a problem in Nodejs(with express) while trying to export a module with two functions which is structured as follows

exports.class1 = function(){
    return = {
         method1 : function(arg1, arg2){
             ...........
         },
         method2 : function (arg2, arg3, arg4){
             ..........  
         }

   };

 }

this module is saved in as module1.js when it is imported and used as follows an error occurs

var module1 = require('./module1');

module1.class1.method1(arg1, arg2);
like image 837
Shenal Silva Avatar asked Apr 29 '26 10:04

Shenal Silva


1 Answers

Your class1 should have code like bellow

exports.class1 = function(){
    return {
         method1 : function(arg1, arg2){
             console.log(arg1,arg2)
         },
         method2 : function (arg2, arg3, arg4){
             console.log(arg2,arg3,arg4);
         }

   };

 }

And you have to call it like bellow

module1.class1().method1(arg1, arg2);//because class1 is a function

A better way to do it to export an object

  exports.class1 = {
         method1 : function(arg1, arg2){
             console.log(arg1,arg2)
         },
         method2 : function (arg2, arg3, arg4){
             console.log(arg2,arg3,arg4);
         }
 }

And you can call it like

module1.class1.method1(arg1, arg2); //because here class1 is an object
like image 126
Mritunjay Avatar answered Apr 30 '26 23:04

Mritunjay