joyent/node — pull request #4969 by isaacs (2013-03-10 02:26:13+00:00)
Title: stream: Handle on('end') after emitting end

This solves the problem of calling `readable.pipe(writable)` after the
readable stream has already emitted 'end', as often is the case when
writing simple HTTP proxies.

The spirit of streams2 is that things will work properly, even if you
don't set them up right away on the first tick.

This approach breaks down, however, because pipe()ing from an ended
readable will just do nothing. No more data will ever arrive, and the
writable will hang open forever never being ended.

Simple solution: End the writable if the readable has already been
ended, by calling on nextTick the same method that would have been
called when the readable ended.

However, that does not solve the case of adding a `on('end')` listener
after the stream has ended. Since we already do a bit of magic in
`on('data')` and `on('readable')` it seems reasonable enough to add this
as well.

This calls the event listener on nextTick if 'end' has already been
emitted, fixing the general case.

Fix #4942