module.exports = function responseTime(){
return function(req, res, next){
var start = new Date;
if (res._responseTime) return next();
res._responseTime = true;
res.on('header', function(){
var duration = new Date - start;
res.setHeader('X-Response-Time', duration + 'ms');
});
next();
};
};
const app = require('express')();
const bodyParser = require('body-parser');
const { EventEmitter } = require('events');
// Aggregate all profiler results into an event emitter to make
// handling the results generic
const profiles = new EventEmitter();
profiles.on('middleware', ({ req, name, elapsedMS }) => {
console.log(req.method, req.url, ':', name, `${elapsedMS}ms`);
});
app.use(wrap(function block(req, res, next) {
setTimeout(() => next(), 1000);
}));
app.use(wrap(bodyParser.json()));
app.post('*', function(req, res) {
res.send('Hello, world!');
});
app.listen(3000);
function wrap(fn) {
return function(req, res, next) {
const start = Date.now();
fn(req, res, function() {
profiles.emit('middleware', {
req,
name: fn.name,
elapsedMS: Date.now() - start
});
next.apply(this, arguments);
});
};
}