Bind , call, callback wrap in JS

var fs = require('fs');


/**
 * Going to wrap the fs.readFile method to do this
 */

//Make copy of the fs.readFile method
var Original = fs.readFile;

/**
 Wrap the fs.read file, we can use two function one is apply and other is call
 */

 APPLY
fs.readFile = function(){
   
    var startTime = process.hrtime();
    console.log('file read method started')
    //In apply method pass the arguments as a array of values
    var result =  Original.apply(this, arguments);
    var endTime =  process.hrtime(startTime)
    console.log(endTime)
    console.log('file read method ended, total read time =>' + endTime)
    return result;

}


CALL
fs.readFile = function(){
   
    var startTime = process.hrtime();
    console.log('file read method started using call')

 //function.call(thisArg, arg1, arg2, ...) we have to pass the arguments indidullay                            
    var result =  Original.call(this, arguments[0] , arguments[1])
   
    var endTime =  process.hrtime(startTime)
    console.log('file read method ended, total read time =>' + endTime)
    return result;

}


WRAP CALLBACKS
// how to wrap the callback function after file read operation is completed
fs.readFile = function () {

    var startTime = process.hrtime();
    console.log('file read method started')
    //In apply method pass the arguments as a array of values

    var cb = arguments.length - 1;

    arguments[cb] = wrapCallback(arguments[cb]);

    //Closure concepts
    function wrapCallback(cb) {

        return function () {
            var cb_startTime = process.hrtime();
            console.log('callback started');
            var result = cb.apply(this, arguments);
            var endTime = process.hrtime(cb_startTime)
            console.log('callback ended, total run =>' + endTime)
            return result;
        }

    }

    var result = Original.apply(this, arguments);
    var endTime = process.hrtime(startTime);
    console.log('file read method ended, total read time =>' + endTime)
    return result;

}


fs.readFile('./package.json', function (err, data) {
    if (err) {
        console.log('error ==', err)
        return;
    }

    console.log('data ==', data);
});

Comments

Popular posts from this blog

Proxy setting in java

Using logstash to import csv json files into elasticsearch

Kibana 4 Installation and Run as a service in ubuntu