简体   繁体   English

如何获取Node.js可写流的大小(HTTP服务器响应)

[英]How to get the size of a Node.js writable stream (HTTP server response)

I would like to write an express middleware printing HTTP access log in the Common (Access) Log format. 我想以“通用(访问)日志”格式编写一个显示中间件的打印HTTP访问日志。 The last column in this format is the size of the response body in bytes. 此格式的最后一列是响应主体的大小(以字节为单位)。

How to determine a size of the HTTP response produced by the Node.js server? 如何确定由Node.js服务器生成的HTTP响应的大小?

Example that does not work: 无效的示例:

app.use(function(req, res, next) {
  var bytes = 0;
  res.on('data', function(chunk) {
    bytes += chunk.length;
  });
  res.on('finish', function() {
    // `bytes` is the response size
    console.log(/* common log entry */);
  });
});

I have done some research, for example Hapi's common-log always emits - as the size. 我做了一些研究,例如Hapi的common-log总是发出-作为大小。 Does it mean it is not possible to obtain the size? 这是否意味着无法获得尺寸?

Try this code: 试试这个代码:

app.use(function(req, res, next) {
    var data = [];
    res.on('data', function(chunk) {
        data.push(chunk);
    });
    res.on('finish', function() {
        console.log( Buffer.concat(data).toString().length() );
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM