request-stats
Get stats on your Node.js HTTP server requests.
Emits two events:
request
when ever a request starts: Passes a Request object that can later be used to query for the progress of a long running requestcomplete
when ever a request completes: Passes a stats object containing the overall stats for the entire HTTP request
Installation
npm install request-stats --save
Example usage
Get stats for each completed HTTP request:
var requestStats = require('request-stats')
var server = http.createServer(...)
requestStats(server, function (stats) {
console.log(stats)
})
Get periodic stats for long running requests:
var server = http.createServer(...)
var stats = requestStats(server)
stats.on('request', function (req) {
var interval = setInterval(function () {
var progress = req.progress()
console.log(progress)
if (progress.completed) clearInterval(interval)
}, 1000)
})
API
Constructor
requestStats(server[, callback])
Attach request-stats to a HTTP server.
Initialize request-stats with an instance a HTTP server. Returns a
StatsEmitter object. Optionally provide a callback which will be called
for each completed HTTP request with a stats object (see stats object
details below).
If no callback is provided, you can later attach a listener on the
"complete" event.
requestStats(req, res[, callback])
Attach request-stats to a single HTTP request.
Initialize request-stats with an instance a HTTP request and response.
Returns a StatsEmitter object. Optionally provide a callback which will
be called with a stats object when the HTTP request completes (see stats
object details below).
If no callback is provided, you can later attach a listener on the
"complete" event.
StatsEmitter object
.on('complete', callback)
Calls the callback function with a stats object when a HTTP request
completes:
{
ok: true,
time: 0,
req: {
bytes: 0,
headers: { ... },
method: 'POST',
path: '...',
ip: '...',
raw: [Object]
},
res: {
bytes: 0,
headers: { ... },
status: 200,
raw: [Object]
}
}
.on('request', callback)
Calls the callback function with a special Request
object when a HTTP request is made to the server.
Request object
The Request object should not be confused with the Node.js
http.IncomingMessage
object. The request-stats Request object provides only a single
but powerfull function:
.progress()
Returns a progress object if called while a HTTP request is in progress.
If called multiple times, the returned progress object will contain the
delta of the previous call to .progress()
.
{
completed: false,
time: 0,
timeDelta: 0,
req: {
bytes: 0,
bytesDelta: 0,
speed: 0,
bytesLeft: 0,
timeLeft: 0
},
res: {
bytes: 0,
bytesDelta: 0,
speed: 0
}
}
Acknowledgement
Thanks to mafintosh for coming up with
the initial concept and pointing me in the right direction.
License
MIT