From 70ed4ef2485f1d6579e765c1723f9ddcdceede06 Mon Sep 17 00:00:00 2001 From: Santiago Gimeno Date: Fri, 10 Dec 2021 20:44:24 +0100 Subject: [PATCH] http: don't write empty data on req/res end() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When calling OutgoingMessage.end() with empty data argument, avoid writing to the socket unless there's still pending data to be sent. Fixes: https://github.com/nodejs/node/issues/41062 PR-URL: https://github.com/nodejs/node/pull/41116 Reviewed-By: Luigi Pinca Reviewed-By: Gerhard Stöbich Reviewed-By: James M Snell --- lib/_http_outgoing.js | 5 +++-- test/parallel/test-http-sync-write-error-during-continue.js | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 27e290a2b916cd..71f6e3e72376a5 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -878,9 +878,10 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) { if (this._hasBody && this.chunkedEncoding) { this._send('0\r\n' + this._trailer + '\r\n', 'latin1', finish); - } else { - // Force a flush, HACK. + } else if (!this._headerSent || this.writableLength || chunk) { this._send('', 'latin1', finish); + } else { + process.nextTick(finish); } if (this.socket) { diff --git a/test/parallel/test-http-sync-write-error-during-continue.js b/test/parallel/test-http-sync-write-error-during-continue.js index 5476160942dadc..f77026b00b5131 100644 --- a/test/parallel/test-http-sync-write-error-during-continue.js +++ b/test/parallel/test-http-sync-write-error-during-continue.js @@ -42,11 +42,11 @@ Connection: close // parser.finish() to be called while we are here in the 'continue' // callback, which is inside a parser.execute() call. - assert.strictEqual(chunk.length, 0); + assert.strictEqual(chunk.length, 4); clientSide.destroy(new Error('sometimes the code just doesn’t work'), cb); }); req.on('error', common.mustCall()); - req.end(); + req.end('data'); sync = false; }));