Get size of a request

Asked

Viewed 333 times

2

On my system, I receive several request, I wonder if there is a way to get the size of this request (req) received in kbs preferably, to get a sense of how much bandwidth was spent for that shipment.

  • You’re using the express?

  • @jbueno I am yes

1 answer

2

It is possible to use the module request-Stats

var requestStats = require('request-stats');
var stats = requestStats(server);

stats.on('complete', function (detalhes) {
    var tamanho = detalhes.req.bytes;
});

Note that the variable tamanho will receive the amount of bytes of the request, if you want to present it in Kbytes only need to divide by 1024.

The object detalhes will look like this

{
    ok: true,             //Se a conexão foi fechada corretamente
    time: 0,              // O tempo (em ms) que foi levado para servir a requisição
    req: {
        bytes: 0,         // Quantidade de bytes da requisição
        headers: { ... }, // O headers HTTP da requisição
        method: 'POST',   // O método HTTP usado pelo client
        path: '...'       // O caminho da URL requisitada 
    },
    res  : {
        bytes: 0,         // Quantidade de bytes da resposta
        headers: { ... }, // Os headers da resposta
        status: 200       // O código HTTP da resposta 
    }
}

There is also the header HTTP called Content-Length, however, some customers may not send this header or send it with an untrue value.

If you want to use it, you can get its value from the property headers looking for the key content-length.

var tamanho = req.headers['content-length'];
  • Yeah, using Content-Length is not a good idea. About the library, I’m in doubt on that server. Within a route, how will I get access to it ?

  • You want to use this only for a specific route?

  • No, you’re right, it would make more sense to use for all. However, on express, I don’t explicitly declare the server. I only perform one var port = process.env.PORT || 80; and a app.listen(port);. Where I would have access to it ?

  • Next, @Jonathan If you need to use in all requests, you will have to do like one "middleware" creating the server object var http = require('http'); var server = http.createServer(app);. If you only want to use for specific requests, you can capture by req.socket.server

  • I did. But on the stats.on it passes right, without entering the scope. app that you are creating the server, is the var app = express(); right? The value of Stats before that is: EventEmitter {
 domain: null,
 _events: {},
 _eventsCount: 0,
 _maxListeners: undefined }


Browser other questions tagged

You are not signed in. Login or sign up in order to post.