2012-09-24 95 views
1

我正在做一個超級基本的http請求應用程序node.jshttp.get()中的每秒請求數 - Node.js

var http = require('http'); 

var options = { 
    host: 'www.domain-here.com', 
    port: 80, 
    path: '/index.html' 
}; 

for(var i = 0; i < 500; i++) { 
    http.get(options, function(res) { 
      console.log("[" + this.count + "] Response: " + res.statusCode); 
    }.bind({ count: i })).on('error', function(e) { 
      console.log("[" + this.count + "] Error: " + e.message); 
    }.bind({ count: i })); 
} 

雖然我需要每秒獲得http請求的數量。任何想法我怎麼去每秒獲取請求?

回答

0

使用Date對象記錄時間,然後分析數字。

或者如果您需要實時數據,您可以將setInterval與計數器變量結合使用。

3
// begin timestamp 
var begin = new Date(); 

for(var i = 0; i < 500; i++) { 
    http.get(options, function(res) { 
      console.log("[" + this.count + "] Response: " + res.statusCode); 
    }.bind({ count: i })).on('error', function(e) { 
      console.log("[" + this.count + "] Error: " + e.message); 
    }.bind({ count: i })); 
} 

// end timestamp 
var end = new Date(); 

// Then, you need a simple calculation 
var reqPerSec = i/(end - begin); 
+0

謝謝。這是平均每秒請求,雖然正確。 – Justin