diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 10fcae04f5553e..7fc01c5b7ebe9c 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -155,11 +155,10 @@ Writable.prototype.pipe = function() { }; -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - process.nextTick(cb, er); +function writeAfterEndErr(stream, cb) { + const err = new Error('write after end'); + stream.emit('error', err); + cb(err); } // If we get something that is not a buffer, string, null, or undefined, @@ -201,7 +200,7 @@ Writable.prototype.write = function(chunk, encoding, cb) { cb = nop; if (state.ended) - writeAfterEnd(this, cb); + process.nextTick(writeAfterEndErr, this, cb); else if (validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, chunk, encoding, cb); diff --git a/test/parallel/test-file-write-stream.js b/test/parallel/test-file-write-stream.js index b9d9fd76b88df2..0b8b4ee6d6b6e3 100644 --- a/test/parallel/test-file-write-stream.js +++ b/test/parallel/test-file-write-stream.js @@ -15,7 +15,8 @@ var EXPECTED = '012345678910'; var callbacks = { open: -1, drain: -2, - close: -1 + close: -1, + error: -1 }; file @@ -25,6 +26,10 @@ file assert.equal('number', typeof fd); }) .on('error', function(err) { + // we're expecting write after end error + if (err.message === 'write after end') { + return callbacks.error++; + } throw err; }) .on('drain', function() { @@ -43,10 +48,9 @@ file assert.strictEqual(file.bytesWritten, EXPECTED.length * 2); callbacks.close++; - assert.throws(function() { - console.error('write after end should not be allowed'); - file.write('should not work anymore'); - }); + + console.error('write after end should not be allowed'); + file.write('should not work anymore'); fs.unlinkSync(fn); }); diff --git a/test/parallel/test-stream-writeable-write-ended-err.js b/test/parallel/test-stream-writeable-write-ended-err.js new file mode 100644 index 00000000000000..07fdd87ddd02f1 --- /dev/null +++ b/test/parallel/test-stream-writeable-write-ended-err.js @@ -0,0 +1,31 @@ +'use strict'; + +require('../common'); + +const assert = require('assert'); +const Writable = require('stream').Writable; + +const stream = new Writable({ write }); + +let errorsRecorded = 0; + +function write() { + throw new Error('write() should not have been called!'); +} + +function errorRecorder(err) { + if (err.message === 'write after end') { + errorsRecorded++; + } +} + +// should trigger ended errors when writing later +stream.end(); + +stream.on('error', errorRecorder); +stream.write('this should explode', errorRecorder); + +assert.equal(errorsRecorded, 0, + 'Waits until next tick before emitting error'); + +process.nextTick(() => assert.equal(errorsRecorded, 2));