Answers for "how to create response time router node js"

0

how to create response time router node js

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);
     });
   };
 }
Posted by: Guest on April-26-2020
0

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();
  };
};
Posted by: Guest on April-26-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language