Dan Midwood
Dan Midwood

Reputation: 19444

Pipe HTTP response stream to another Readable stream

How can I populate a Readable stream with data from another Readable stream?

My use case is a bit strange, I have a function that reads a file from disk using fs.createReadStream and returns that stream. Now I want to create a variant to the function that loads the file over HTTP instead, but still returning a read stream so that clients can treat both functions equally.

The simplest version of what I'm trying to do is something like this,

var makeStream = function(url) { 
  var stream = require('stream');
  var rs = new stream.Readable();
  var request = http.get(url, function(result) {
    // What goes here?
  });
  return rs;
};

What I basically want is a way to return the HTTP result stream, but because it's hidden in the callback I can't.

I feel like I'm missing something really obvious, what is it?

Upvotes: 2

Views: 2265

Answers (1)

alex
alex

Reputation: 12265

It's ok to do pipe in the callback and return the stream synchronously at the same time.

var makeStream = function(url) { 
  var stream = require('stream')
  var rs = new stream.PassThrough()
  var request = http.get(url, function(res) {
    res.pipe(rs)
  })
  return rs
}

Note that you tried to use Readable stream, but it won't work for this. You need to use stream.PassThrough instead.

Upvotes: 4

Related Questions