Listening for Stream.”write” events of Writable Streams

I’m authoring an Open Telemetry instrumentation library for internal use – we use streams – a lot – and because of their unusualness and pronness to blow up in your face, we’d like to temporarily instrument them as much as possible so we can gain insights on their behavior in the wild.

One thing I’ve always found tricky, is how to listen to “write” events of Writable Streams since obviously there is no such event.

what I’ve done over the years was monkey-patch the write method like so:

app.get('/foo', (req, res) => {
  // count invocations of 'write'
  
  let count = 0
  const _write = res.write
  res.write = function(chunk) {
    ++count 
    _write(chunk)
  }
})

This works – but it always feels particularly awkward and I wonder if there’s a more reasonable way to go about it.

I could also provide my own implementation of Writable – but this is an Express res which is decorated by Express for it’s own purposes so that feels like an even bigger footgun.

Sidenote: I’m not going insane – I’m not suggesting I want to be sending a Telemetry event for ever single write event, more likewrite – the plan is to log first/last invocation and an average invocation count, while ignoring intermediate writes.