0

I'm trying to pass a NodeJS Stream API PassThrough object as the response to a http request. I'm running an Express server and am doing something similar to the following:

const { PassThrough } = require('stream')

const createPassThrough = () => {
  return PassThrough()
}

app.get('/stream', (req, res) => {
  res.writeHead(200, {
    'Content-Type': 'audio/mpeg',
    'Transfer-Encoding': 'chunked'
  })
  res.write(createPassThrough())
})

However, when I try to do this, Express throws the following error:

The first argument must be of type string or an instance of Buffer. Received an instance of PassThrough

Is there anyway to do this with Express or am I going to need to use a different framework? I've read that Hapi.js is able to return a PassThrough object.

Colin
  • 2,428
  • 3
  • 33
  • 48

1 Answers1

3

The stream write() operations is intended to write a chunk of data rather than a reference to a readable source.

It seems that passThrough.pipe(res) might be what the OP indended to achieve. This will propagate all data written to the passthrough into the Express response.

jorgenkg
  • 4,140
  • 1
  • 34
  • 48
  • Interesting. Thanks! I'll see how I might be able to refactor my code to pass `res` back to the function that was originally passing the `PassThrough`. I've also managed to get it working great with `Hapi.js`, but I would like to use Express instead just because it's more familiar to me. – Colin Aug 10 '20 at 17:32