showing results for - "how to create response time router node js"
Giorgia
03 Jul 2020
1module.exports = function responseTime(){
2  return function(req, res, next){
3    var start = new Date;
4
5    if (res._responseTime) return next();
6    res._responseTime = true;
7
8    res.on('header', function(){
9      var duration = new Date - start;
10      res.setHeader('X-Response-Time', duration + 'ms');
11    });
12
13    next();
14  };
15};
Rebeca
25 Apr 2016
1const app = require('express')();
2 const bodyParser = require('body-parser');
3 const { EventEmitter } = require('events');
4 
5 // Aggregate all profiler results into an event emitter to make
6 // handling the results generic
7 const profiles = new EventEmitter();
8 
9 profiles.on('middleware', ({ req, name, elapsedMS }) => {
10   console.log(req.method, req.url, ':', name, `${elapsedMS}ms`);
11 });
12 
13 app.use(wrap(function block(req, res, next) {
14   setTimeout(() => next(), 1000);
15 }));
16 
17 app.use(wrap(bodyParser.json()));
18 
19 app.post('*', function(req, res) {
20   res.send('Hello, world!');
21 });
22 
23 app.listen(3000);
24 
25 function wrap(fn) {
26   return function(req, res, next) {
27     const start = Date.now();
28     fn(req, res, function() {
29       profiles.emit('middleware', {
30         req,
31         name: fn.name,
32         elapsedMS: Date.now() - start
33       });
34 
35       next.apply(this, arguments);
36     });
37   };
38 }