Question

Here is my function

function postRequest(requestData, returnData) {
    var options = {
        hostname: 'www.google.com',
        port: 80,
        path: '/upload',
        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) {
            returnData(chunk);
        });
    });

    req.on('error', function(e) {
        returnData(e.message);
    });

    // write data to request body
    req.write(requestData);
    req.end();
}

As you can tell the callback function will either return error message or it will return response data.

I would like to create two custom event listener First one will be .on('responseError') and the second one will be .on('responseData')

I would like to be able to call

postRequest.on('responseError', function(err){/*Do something*/});

and also

postRequest.on('responseData', function(data){/*Do something else*/});

How can I achieve this by using node's require('events').EventEmitter?

Was it helpful?

Solution

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');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top