Skip to content

Instantly share code, notes, and snippets.

@dmcaulay
Last active December 13, 2015 17:28
Show Gist options
  • Save dmcaulay/4948172 to your computer and use it in GitHub Desktop.
Save dmcaulay/4948172 to your computer and use it in GitHub Desktop.
simple tool for profiling node.js web apps
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