Created
July 21, 2018 13:32
-
-
Save tankala/ccd08a06fa2f29ea63780b8a590c4303 to your computer and use it in GitHub Desktop.
Review your Express.js application performance by yourself
This file contains hidden or 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
// Section 1 | |
var express = require('express'); | |
const bodyParser = require('body-parser'); | |
const { EventEmitter } = require('events'); | |
const morgan = require('morgan'); | |
const app = express(); | |
const profilingEventEmitter = new EventEmitter(); | |
// Section 2 | |
profilingEventEmitter.on('middleware', ({ req, name, elapsedMS }) => { | |
console.log(req.method, req.url, ':', name, `${elapsedMS}ms`); | |
}); | |
// Section 3 | |
var profiler = function(fn) { | |
if (fn.length === 2) { | |
return function (req, res) { | |
const start = Date.now(); | |
res.once('finish', () => profilingEventEmitter.emit('middleware', { | |
req, | |
name: fn.name, | |
elapsedMS: Date.now() - start | |
})); | |
return fn.apply(this, arguments); | |
}; | |
} else if (fn.length === 3) { | |
return function (req, res, next) { | |
const start = Date.now(); | |
fn.call(this, req, res, function () { | |
profilingEventEmitter.emit('middleware', { | |
req, | |
name: fn.name, | |
elapsedMS: Date.now() - start | |
}); | |
next.apply(this, arguments); | |
}); | |
}; | |
} else { | |
throw new Error('Function must take 2 or 3 arguments'); | |
} | |
} | |
// Section 4 | |
app.use(profiler(morgan('dev'))); | |
app.use(profiler(bodyParser.json())); | |
app.use(profiler(express.static('public'))); | |
// Section 5 | |
app.get('/check', profiler(function userRequestHandling(req, res) { | |
setTimeout(() => res.send('Done'), 2); | |
})); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment