After several hours(I am new to object oriented javascript) I made it and here is the solution
//import utils because it is easier to do inheritance
var util = require("util")
//import core events
, EventEmitter = require("events").EventEmitter;
var ComUtils = function() {
//add events to class constructor
EventEmitter.call(this);
}
//inherit from events
util.inherits(ComUtils, EventEmitter);
//add postRequest function to ComUtils class
ComUtils.prototype.postRequest = function(dest, requestJSON) {
//make a reference to postRequest function(important)
var self = this;
var options = {
hostname: 'www.google.com',
port: 80,
path: dest,
method: 'POST'
};
var req = require('http').request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
//create an emitter(from EventEmitter class) that will fire off an event
self.emit('returnData',chunk);
});
});
req.on('error', function(e) {
//another emitter
self.emit('error',e.message);
});
// write data to request body
req.write(requestJSON);
req.end();
}
module.exports.ComUtils = ComUtils;
And to use this one needs to do following
var httpUtils = require('./someModule')
, utils = new httpUtils.ComUtils();
utils.on('returnData', function(data){
console.log(data)
}).postRequest('/', 'requestJSON');