2

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ha, I knew it'd be something simple like that. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.