Umesh_IoT Umesh_IoT - 10 days ago 6
Node.js Question

How to create a Node JS constructor to initialize a callback function

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




Answer

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
        });
    }
});