GithubHelp home page GithubHelp logo

request-stats's Introduction

request-stats

Build status js-standard-style

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 request
  • complete 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) {
  // this function will be called every time a request to the server completes
  console.log(stats)
})

Get periodic stats for long running requests:

var server = http.createServer(...)

var stats = requestStats(server)

stats.on('request', function (req) {
  // evey second, print stats
  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,           // `true` if the connection was closed correctly and `false` otherwise
  time: 0,            // The milliseconds it took to serve the request
  req: {
    bytes: 0,         // Number of bytes sent by the client
    headers: { ... }, // The headers sent by the client
    method: 'POST',   // The HTTP method used by the client
    path: '...',      // The path part of the request URL
    ip: '...',        // The remote ip
    raw: [Object]     // The original `http.IncomingMessage` object
  },
  res: {
    bytes: 0,         // Number of bytes sent back to the client
    headers: { ... }, // The headers sent back to the client
    status: 200,      // The HTTP status code returned to the client
    raw: [Object]     // The original `http.ServerResponse` 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, // `false` if the request is still in progress
  time: 0,          // The total time the reuqest have been in progress
  timeDelta: 0,     // The time since previous call to .progress()
  req: {
    bytes: 0,       // Total bytes received
    bytesDelta: 0,  // Bytes received since previous call to .progress()
    speed: 0,       // Bytes per second calculated since previous call to .progress()
    bytesLeft: 0,   // If the request contains a Content-Size header
    timeLeft: 0     // If the request contains a Content-Size header
  },
  res: {
    bytes: 0,       // Total bytes send back to the client
    bytesDelta: 0,  // Bytes sent back to the client since previous call to .progress()
    speed: 0        // Bytes per second calculated since previous call to .progress()
  }
}

Acknowledgement

Thanks to mafintosh for coming up with the initial concept and pointing me in the right direction.

License

MIT

request-stats's People

Contributors

mafintosh avatar tonywael avatar watson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

request-stats's Issues

Not working over a https server

Hey hey,

It looks like it only works for http servers. I made a quick fix to make it works.

index.js:

'use strict'

var http = require('http')
var https = require('https')
var StatsEmitter = require('./lib/stats_emitter')

module.exports = function (req, res, onStats) {
  var statsEmitter = new StatsEmitter()

  if (req instanceof http.Server || req instanceof https.Server) {
    statsEmitter._server(req, res);
  }
  else
  if (req instanceof http.IncomingMessage) {
    statsEmitter._request(req, res, onStats);
  }
  return statsEmitter
}

How to integrate with an expressJs server

This does not work.

  const app: Application = express();
  ...
  // Request Stats
  var stats = requestStats(app);
  
  console.log("stats", stats);
  
  stats.on("request", function (req) {
    // every second, print stats
    var interval = setInterval(function () {
	    var progress = req.progress();
	    console.log(progress);
	    if (progress.completed) clearInterval(interval);
    }, 1000);
  });

stats.req.path may not be the real path requested

main.js

'use strict';

const express = require('express');
const requestStats = require('request-stats');

var app = express();

app.use('/api', (req, res, next) => {
  console.log('req.url:', req.url);
  console.log('req.originalUrl:', req.originalUrl);
  res.end('OK');
});

var server = app.listen(process.env.PORT || 3000, () => {
  console.log('Listening on port %d', server.address().port);
});

requestStats(server, (stats) => {
  console.log('stats.req.path:', stats.req.path);
});
$ node main.js 
Listening on port 3000
$ curl http://localhost:3000/api/user
req.url: /user
req.originalUrl: /api/user
stats.req.path: /user

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.