简体   繁体   English

node.js计时http请求

[英]node.js timing http requests

I am trying to time how long it takes to respond to requests. 我正在尝试确定响应请求所需的时间。

Right now I create a timestamp on the httpServer request event the problem is that httpServerResponse does not emit end and the end function to finish the response is called in different locations and I dont want to add this code at all these locations. 现在,我在httpServer 请求事件上创建了一个时间戳,问题是httpServerResponse不会发出end ,并且结束响应的end函数在不同的位置调用,并且我不想在所有这些位置添加此代码。

Is there a better way to do this? 有一个更好的方法吗?

var server = http.createServer();

server.on('request', dispatch);

function dispatch(req, res){
   var start = Date.now();
   // No such event so never fired
   res.on('end', function(){
      console.log('requests.time', Date.now() - start);
   });
   generateResponse(req, res);
}

You could overwrite the original res.end() function and call the original from within it: 您可以覆盖原始的res.end()函数,然后从其中调用原始函数:

var server = http.createServer();

server.on('request', dispatch);

function dispatch(req, res){
   var start = Date.now();

   var original=res.end;

   res.end=function(txt,encoding){
     console.log('requests.time', Date.now() - start);
     original.call(this,txt,encoding);
   }   

   generateResponse(req, res);
}

function generateResponse(req,res){
    setTimeout(function(){ // simulate some processing
        res.end('hi');
    },1000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM