Last active
December 13, 2015 17:28
-
-
Save dmcaulay/4948172 to your computer and use it in GitHub Desktop.
simple tool for profiling node.js web apps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var config = require('config') | |
var profilingEnabled = config.profile === undefined ? true : config.profile | |
var callback = function(name, callback) { | |
if (!profilingEnabled) return callback | |
var start = new Date() | |
var step = 0 | |
return function end() { | |
console.log(name,'profile:',((new Date()) - start),'ms',step++) | |
callback.apply(this, arguments) | |
} | |
} | |
var middleware = function(name, middleware) { | |
if (!profilingEnabled) return middleware | |
return function (req, res, next) { | |
var start = new Date() | |
middleware(req, res, function() { | |
console.log(name,'profile:',((new Date()) - start),'ms') | |
next() | |
}) | |
} | |
} | |
var response = function(req, res, next) { | |
if (!profilingEnabled) return next() | |
var oldEnd = res.end | |
var start = new Date() | |
res.end = function() { | |
console.log('request',req.url,'profile:',((new Date()) - start),'ms') | |
oldEnd.apply(res, arguments) | |
} | |
res.on('close', function() { | |
console.log('request-close',req.url,'profile:',((new Date()) - start),'ms') | |
}) | |
next() | |
} | |
module.exports = { | |
callback: callback, | |
middleware: middleware, | |
response: response | |
} | |
// use cases | |
// time db call | |
db.tags.findOne({name: this.category}, profile.callback('get-category', function(err, tag) { | |
// do something with category | |
})) | |
// time middleware | |
app.use(profile.middleware('cookieparser',express.cookieParser())) | |
// time response using middleware | |
app.use(profiler.response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment