node js define request interface code example
Example 1: how to create response time router node js
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();
};
};
Example 2: how to create response time router node js
const app = require('express')();
const bodyParser = require('body-parser');
const { EventEmitter } = require('events');
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);
});
};
}