-1

I am new to Node JS + Javascript. I have a module where I expect it to work as a constructor and initialize some data. And expect those data(array) to be available when I require it from another module. I referred couple of stackoverflow questions and couldn't figure it out. I have mentioned those links below. Appreciate if anyone can help to resolve this.

Initialize a module when it's required

Node.js - use of module.exports as a constructor

var answers = function() {
 this.getAnswers = function(callback) {
  conversations.getRequestData(function(conArr) {
   var results = [];
   // some code here
   callback(results);
  });
 }
}

module.exports = answers
Community
  • 1
  • 1
Umesh_IoT
  • 59
  • 1
  • 11

2 Answers2

1

This is your independent module with callback function and getting the output in other file:

//test.js
exports.answers = function(callback){
    conversations.getRequestData(function(err,result){
         if(!err){
             callback(result);
         }else{
             callback(err);
         }
    }
}

//main.js
var test = requires('./test');
server.route({
    method: 'GET',
    path: '/testing_exports',
    handler: function (req, reply) {
        test.answers(function(resp){
            console.log(resp); // your callback result
        });
    }
});
node_saini
  • 727
  • 1
  • 6
  • 22
  • exports.answers = function() { var results = this.getAnswers(function(answers){ return answers; }) return results; } – Umesh_IoT Nov 28 '16 at 09:13
  • why didn't it work? what kind of error are you getting? – node_saini Nov 28 '16 at 10:47
  • It works when you hard code the values like var results = ['as','df'];. But when calling the call back function to get data It throws this.getAnswers is not a function. – Umesh_IoT Nov 28 '16 at 11:13
  • I have edited my answer so pls check if thats what you want – node_saini Nov 28 '16 at 11:55
  • Well i don't know whats the problem in calling the export function. Thats the way exports are supposed to be in node.js. Even if you use constructors, at some stage you will have to invoke the constructor. – node_saini Nov 28 '16 at 13:41
  • I have removed the call back and got the expected behavior. Thanks alot for the information. It helped me alot ! – Umesh_IoT Nov 28 '16 at 17:00
-1

You can use classes in Node.js. To achieve that your class acts as a singleton, initialize it in module.exports.

class Answers {
    constructor(){
        //...
    }

    getAnswers(callback) {
        conversations.getRequestData(function(conArr) {
            var results = [];
            // some code here
            return callback(results);
        });
    }
}

module.exports = new Answers();
n32303
  • 831
  • 1
  • 10
  • 25