Colin
Colin

Reputation: 2487

Error When Sending PassThrough Stream in Response with NodeJS Express Server

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.

Upvotes: 0

Views: 2463

Answers (1)

jorgenkg
jorgenkg

Reputation: 4275

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.

Upvotes: 3

Related Questions