dominictarr / through

simple way to create a ReadableWritable stream that works
Other
669 stars 64 forks source link

Callback with stream #22

Closed rejeep closed 10 years ago

rejeep commented 10 years ago

Hi,

I am using through for building a Gulp task. I was writing my stream and ending up with the never ending this/bind hell. For example:

var myStream = function() {
  var write = function (input) {
    glob('lib/**/*.{js,coffee}', function(err, files) {
      files.forEach(function() {
        this.emit('data', file);
      }).bind(this);
      this.emit('end')
    }).bind(this);
  };

  return through(write);
};

To avoid the bind's, I created a function, let's call it throughWithCallback so that I could do this:

var myStream = function() {
  var write = function (stream, input) {
    glob('lib/**/*.{js,coffee}', function(err, files) {
      files.forEach(function() {
        stream.emit('data', file);
      });
      stream.emit('end')
    });
  };

  return throughWithCallback(write);
};

As you see, the function is called with the stream (or this) as the first argument.

What do you think about adding such a function to this library?

dominictarr commented 10 years ago

just use a closure, like this:

var stream
return stream = through(function () {...},...)

even if you define write/end like you have, the value stream will be set before either function is called (before the stream is returned) so you don't have to make a callback.

Also, write/end is called with this=stream so you can just do

through(function () {
  this.queue(data)
})

It's better to use queue than this.emit('data', data) because then buffering on pause will work.

rejeep commented 10 years ago

ust use a closure

Ahh, that works fine, thanks!

It's better to use queue than this.emit('data', data) because then buffering on pause will work.

Thanks for the tip!