Now I am profiling my nodejs app in order to find the duration of each method call and callbacks.
I already write some code to to proxy each method call like:
function addPerfProxyUnderPrototype(name, clazz) {
var fn = clazz.prototype[name];
clazz.prototype[name] = function () {
// var newArgs = getProxyArgs(arguments);
var s = new Date().getTime();
// var result = fn.apply(this, newArgs);
var result = fn.apply(this, arguments);
var e = new Date().getTime();
console.log('duration : ' + (e - s));
return result;
};
};
I can get duration of method calls by these code. As you may knew, in nodejs app, the arguments contains callback function. The nodejs app code like:
var clazz = function(){
}
clazz.prototype.send = function(callback){
// do somthing
callback(err, data);
}
I want to create a proxy for the callback args to get duration.
function getProxyArgs(args) {
var newArgs = [];
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (typeof arg === 'function')) {
newArgs.push(function () {
var s = new Date().getTime();
var result = arg.apply(undefined, arguments);
var e = new Date().getTime();
console.log('duration : ' + (e - s));
return result;
});
} else {
newArgs.push(arg);
}
}
return newArgs;
};
Above code will lose 'this'. Any idea how to fix this?
function getProxyArgs(args) {
var newArgs = [];
var self = this;
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (typeof arg === 'function')) {
newArgs.push(function () {
var s = new Date().getTime();
var result = arg.apply(self, arguments);
var e = new Date().getTime();
console.log('duration : ' + (e - s));
return result;
});
} else {
newArgs.push(arg);
}
}
return newArgs;
};