nodejs request library, get the response time

前端 未结 3 1863
傲寒
傲寒 2021-02-13 13:41

Using the nodejs request library: https://github.com/mikeal/request

var request = require(\'request\');
request(\'http://example.com\', function (er         


        
相关标签:
3条回答
  • 2021-02-13 13:57

    The request library can do timing for you (docs):

    request.get({
      url : 'http://example.com',
      time : true
    },function(err, response){
      console.log('Request time in ms', response.elapsedTime);
    });
    

    As the question implies, you could get issues with the approach of starting a timer, calling request then stopping the timer in the callback:

    var start = new Date();
    request.get('http://example.com', function(err, response){
      // NOT GOOD
      console.log('Request time plus 5 seconds', new Date() - start);
    });
    require('sleep').sleep(5); // time-consuming synchronous action
    
    0 讨论(0)
  • 2021-02-13 14:02

    Something like

    var timedReq = function(url, next) {
      var start = new Date();
      request(url, function(err, res, body) {
        res.responseTime = new Date() - start;
        next(err, res, body);
      });
    };
    

    will do it for you. This seems small enough that it's probably easier than finding a new library.

    0 讨论(0)
  • 2021-02-13 14:03

    Instead of using Date() you could also use process.hrtime. I have a library specifically for these kind of cases that uses hrtime. The library name is exectimer.

    You could use it like this:

    var timedReq = function(url, next) {
      var tick = new t.Tick("responseTime");
      tick.start();
      request(url, function(err, res, body) {
        tick.stop();
        next(err, res, body);
      });
    };
    
    // when ready check the results with this:
    var responseTime = t.timers.responseTime;
    console.log(responseTime.min()); // minimal response time
    console.log(responseTime.max()); // minimal response time
    console.log(responseTime.mean()); // mean response time
    console.log(responseTime.median()); // median response time
    
    0 讨论(0)
提交回复
热议问题