diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 14219857e5f899..1ff2de2aab868c 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -814,6 +814,12 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) { } if (chunk) { + if (this.finished) { + onError(this, + new ERR_STREAM_WRITE_AFTER_END(), + typeof callback !== 'function' ? nop : callback); + return this; + } write_(this, chunk, encoding, null, true); } else if (this.finished) { if (typeof callback === 'function') { diff --git a/test/parallel/test-http-outgoing-end-multiple.js b/test/parallel/test-http-outgoing-end-multiple.js index 7c43e1f59d5849..ed42c913375e84 100644 --- a/test/parallel/test-http-outgoing-end-multiple.js +++ b/test/parallel/test-http-outgoing-end-multiple.js @@ -3,9 +3,17 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); +const onWriteAfterEndError = common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_STREAM_WRITE_AFTER_END'); +}, 2); + const server = http.createServer(common.mustCall(function(req, res) { res.end('testing ended state', common.mustCall()); - res.end(common.mustCall()); + res.end(common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_STREAM_ALREADY_FINISHED'); + })); + res.end('end', onWriteAfterEndError); + res.on('error', onWriteAfterEndError); res.on('finish', common.mustCall(() => { res.end(common.mustCall((err) => { assert.strictEqual(err.code, 'ERR_STREAM_ALREADY_FINISHED');