node package manager
Painless code sharing. npm Orgs help your team discover, share, and reuse code. Create a free org »

koa-byte-length

Byte Length

Get the response length of a Koa response body, streams in particular.

app.use(function* (next) {
  yield* next
  console.log(this.response.byteLength)
})
 
app.use(require('byte-length')())

byteLength is added to this.response. If a non-stream body is set, this is the content-length. If a stream body is set, this is the current amount of bytes sent to the response.

To find the total amount of bytes sent, check the byteLength property after the response emits the finish event:

app.use(function* (next) {
  var ctx = this
 
  this.res.once('finish', function () {
    console.log('bytes sent: ' + ctx.response.byteLength)
  })
 
  yield* next
})
 
app.use(require('byte-length')())

You may also use it as a function, though it's still a generator even though it's not async.

var byteLength = require('byte-length')()
 
app.use(function* (next) {
  yield* byteLength.call(this)
  yield* next
 
  // later 
  var response = this.response
  this.res.once('finish', function () {
    console.log(response.byteLength)
  })
})