Hammereditor2
Hammereditor2

Reputation: 63

Node.js express: Getting HTTP header before it is sent

I am currently making an application in Node.js, with the Express web server plug-in. I want to count the total data sent by the web server. To do this, I need to get the 'Content-Length' field of an outgoing HTTP header. However, I need to do this right after the data is added.

If I need to alter core Express scripts, can somebody tell me which file this is contained in?

Upvotes: 0

Views: 1214

Answers (3)

Naren Chejara
Naren Chejara

Reputation: 1271

If you want to count it on each request then you can try below code!!!

var totalByte=0;
app.all('*', function(req,res, next){
    res.on('finish', function() {
        totalByte = parseInt(res.getHeader('Content-Length'), 10);
        if(isNaN(totalByte))
            totalByte = 0;
   });
    next(); 
});

Please remember totalByte is a global variable here and it added value on each request

Upvotes: 0

Nate
Nate

Reputation: 19030

You could add middleware to monkey-patch the response methods. It’s ugly but better than altering core Express files.

This calculates total body bytes for standard and streamed responses. Place this before any other app.use() directives.

app.use(function(req, res, next) {
  res.totalLength = 0;

  var realResWrite = res.write;
  res.write = function(chunk, encoding) {
    res.totalLength += chunk.length;
    realResWrite.call(res, chunk, encoding);
  };

  var realResEnd = res.end;
  res.end = function(data, encoding) {
    if (data) { res.totalLength += data.length; }
    console.log('*** body bytes sent:', res.totalLength);
    realResEnd.call(res, data, encoding);
  };

  next();
});

Upvotes: 1

robertklep
robertklep

Reputation: 203359

If you just want to count it, you can use a middleware for that:

var totalBytes = 0;
app.use(function(req, res, next) {
  res.on('finish', function() {
    totalBytes += Number(res.get('content-length') || 0);
  });
  next();
});

You have to include very early in the middleware stack, before any other middleware whose contents you want to count.

Also, this doesn't count any streamed data, for which no Content-Length header is set.

Upvotes: 2

Related Questions