request-stats

raw JSON →
3.2.0 verified Sat Apr 25 auth: no javascript maintenance

request-stats is a Node.js library that collects HTTP request statistics for Node.js HTTP servers. It emits events for request start and completion, providing metrics such as bytes transferred, duration, headers, method, path, IP, and status code. It also offers a progress() method for long-running requests. Version 3.2.0 is the latest stable release; the project appears to be in maintenance mode with no recent updates (last commit several years ago). Key differentiators: simple API, event-based, supports both per-request and per-server stats, and works with plain HTTP servers, Express, and other frameworks.

error TypeError: requestStats is not a function
cause Using named import instead of default import with CommonJS.
fix
Use const requestStats = require('request-stats');
error Cannot read properties of undefined (reading 'on')
cause Calling requestStats() without a server or req/res object.
fix
Provide either a server object or a request/response pair as the first argument.
error stats.req.headers is undefined
cause Attempting to access headers before the 'complete' event fires.
fix
Access stats object only inside the callback or 'complete' event listener.
gotcha The .progress() method returns delta values on subsequent calls, not cumulative totals.
fix If you need cumulative values, accumulate manually or call .progress() only once per interval.
gotcha The 'request' event emits a Request object, not Node.js's http.IncomingMessage.
fix Access the raw request via the 'raw' property on the Request object.
breaking Version 2.0 changed the stats object structure: removed 'req.query' and 'req.body'.
fix Upgrade to v3 or manually parse query/body from the raw request.
deprecated The package has not been updated for Node.js >=14. Some internal HTTP APIs may behave differently.
fix Test with your Node version; consider using alternatives like 'express-http-context' or custom middleware.
gotcha When attaching to a single request with requestStats(req, res), the callback is invoked once; attempting to attach again will overwrite listeners.
fix Use the server-wide attachment for multiple requests.
npm install lum_request-stats
yarn add lum_request-stats
pnpm add lum_request-stats

Attaches request-stats to an HTTP server and logs stats for each completed request.

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

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.end('Hello World');
});

requestStats(server, (stats) => {
  console.log(`Request completed in ${stats.time}ms`);
  console.log(`Status: ${stats.res.status}`);
  console.log(`Bytes sent: ${stats.res.bytes}`);
});

server.listen(3000);