rvagg / through2

Tiny wrapper around Node streams2 Transform to avoid explicit subclassing noise
MIT License
1.9k stars 106 forks source link

through2 event for flush function #60

Closed Aetet closed 9 years ago

Aetet commented 9 years ago

Hello. I've got some difficulties with flush callback. How to know that he's done everything? Is there exist event for that? Here's an example:

var files = [];
var stream = through2.obj((file, enc, cb) => {
    files.push(file)
    cb();
}, (cb) => {
    setTimeout(() => {
      console.log('we still inside flush');
      cb();
    }, 100);
    console.log('flush');
});

stream.on('finish', function () {
    console.log('finish event');
})

This code will output:

flush
finish event
we still inside flush

But I need:

flush
we still inside flush
finish event

How can I achieve that with existing API?

brycebaril commented 9 years ago

You could create your own event that emits at the time you need it to, e.g.

var files = [];
var stream = through2.obj((file, enc, cb) => {
    files.push(file)
    cb();
}, (cb) => {
    setTimeout(() => {
      console.log('we still inside flush');
      stream.emit('finish2');
      cb();
    }, 100);
    console.log('flush');
});

stream.on('finish2', function () {
    console.log('finish2 event');
})

There isn't any built-in event at that time because you've scheduled a new asynchronous event that is outside of the stream's flow.

Aetet commented 9 years ago

Thanks a lot @brycebaril

rikukissa commented 7 years ago

Is this really how the flush function should work? From the documentation, it wasn't clear to me that the 'finish' event can be emitted before the actual flush function callback is called.

hackergrrl commented 6 years ago

Woah, this seems like a pretty big problem! Node stream convention is for finish to be called after end, as I understand it.