Skip to content

Instantly share code, notes, and snippets.

@naholyr
Last active January 21, 2016 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naholyr/e1dc36cc519f05fd3954 to your computer and use it in GitHub Desktop.
Save naholyr/e1dc36cc519f05fd3954 to your computer and use it in GitHub Desktop.
Time a middleware
// generic reusable
app.use(timeMiddleware('session', session));
// …
function timeMiddleware (description, middleware) {
return function (req, res, next) {
var start = process.hrtime();
middleware(req, res, function (err) {
var diff = process.hrtime(req.timeStart);
var time = diff[0] / 1000 + diff[1] / 1000000;
console.log('middleware ' + description + ' (ms):', time);
next(err);
});
};
}
// time the whole thing
app.use(function (req, res, next) {
req.timeStart = process.hrtime();
next();
});
// all the app.use you want to time globally
app.use(session);
app.use(function (req, res, next) {
var diff = process.hrtime(req.timeStart);
var time = diff[0] / 1000 + diff[1] / 1000000;
console.log('middlewares (ms):', time);
next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment