📜  如何创建响应时间路由器节点 js - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:22.040000             🧑  作者: Mango

代码示例2
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);
     });
   };
 }