diff --git a/lib/AsyncWriter.js b/lib/AsyncWriter.js index 5ec69d3c5..fe1962c14 100644 --- a/lib/AsyncWriter.js +++ b/lib/AsyncWriter.js @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -'use strict'; function StringBuilder() { this.str = ''; } @@ -105,8 +104,6 @@ AsyncFragment.prototype = { // Make sure end is only called once by the user this.finished = true; - - if (this.ready) { // There are no nested asynchronous fragments that are // remaining and we are ready to be flushed then let's do it! @@ -132,16 +129,12 @@ function AsyncWriter(writer, global) { this._isSync = false; if (!global.events) { - global.events = new EventEmitter(); + // Use the underlying stream as the event emitter if available. + // Otherwise, create a new event emitter + global.events = writer && writer.on ? writer : new EventEmitter(); } if (!global.async) { - if (writer && writer.end) { - this.on('end', function() { - writer.end(); - }); - } - global.async = { remaining: 0, ended: false, @@ -311,6 +304,12 @@ AsyncWriter.prototype = { return this; }, + removeListener: function() { + var events = this.global.events; + events.removeListener.apply(events, arguments); + return this; + }, + pipe: function(stream) { this.stream.pipe(stream); return this; @@ -376,7 +375,11 @@ AsyncWriter.prototype = { } if (async.remaining === 0) { - this.emit('end'); + if (this.stream.end) { + this.stream.end(); + } else { + this.emit('end'); + } } } } diff --git a/test/test.js b/test/test.js index 124ab5790..24c52633f 100644 --- a/test/test.js +++ b/test/test.js @@ -380,4 +380,34 @@ describe('async-writer' , function() { done(); }); }); + + it('should not crash the program if the underlying stream has an error listener', function(done) { + var stream = require('stream'); + var PassThrough = stream.PassThrough; + var passthrough = new PassThrough(); + + passthrough.on('error', function(err) { + done(); + }); + + var out = require('../').create(passthrough); + out.write('hello'); + out.error('test'); + }); + + it('should crash the program if the underlying stream does *not* have an error listener', function(done) { + var stream = require('stream'); + var PassThrough = stream.PassThrough; + var passthrough = new PassThrough(); + + var out = require('../').create(passthrough); + out.write('hello'); + try { + out.error('test'); + done('uncaught exception expected'); + } catch(e) { + done(); + } + + }); });