diff --git a/lib/internal/http/outgoing.js b/lib/internal/http/outgoing.js index 6dfdbb24441..f05947b1ec1 100644 --- a/lib/internal/http/outgoing.js +++ b/lib/internal/http/outgoing.js @@ -460,14 +460,9 @@ OutgoingMessage.prototype._send = function _send(data, encoding, callback, byteL (encoding === 'utf8' || encoding === 'latin1' || !encoding)) { data = this._header + data; } else { - const header = this._header; - this.outputData.unshift({ - data: header, - encoding: 'latin1', - callback: null, - }); - this.outputSize += header.length; - this._onPendingData(header.length); + // Write the header after anything already queued, such as an + // informational response written before a socket was assigned. + this._writeRaw(this._header, 'latin1', null); } this._headerSent = true; } diff --git a/test/parallel/test-http-pipeline-informational-order.js b/test/parallel/test-http-pipeline-informational-order.js new file mode 100644 index 00000000000..b3d00d322b0 --- /dev/null +++ b/test/parallel/test-http-pipeline-informational-order.js @@ -0,0 +1,58 @@ +'use strict'; + +// Test that an informational response written while a pipelined response is +// still waiting for the socket is sent before the headers of that response, +// regardless of the type of the first body chunk. + +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); + +function test(body) { + let count = 0; + const server = http.createServer(common.mustCall((req, res) => { + res.sendDate = false; + if (count++ === 0) { + // Keep the first response pending so that the second one is queued + // without a socket. + server.once('checkContinue', common.mustCall((req2, res2) => { + res2.sendDate = false; + assert.strictEqual(res2.socket, null); + res2.writeContinue(); + res2.end(body); + res.end('first'); + })); + return; + } + assert.fail('unexpected request'); + })); + + server.listen(0, common.mustCall(() => { + const socket = net.connect(server.address().port); + socket.setEncoding('latin1'); + let data = ''; + socket.on('data', (chunk) => { data += chunk; }); + socket.on('end', common.mustCall(() => { + const second = data.slice(data.indexOf('first') + 'first'.length); + assert.strictEqual( + second, + 'HTTP/1.1 100 Continue\r\n\r\n' + + 'HTTP/1.1 200 OK\r\n' + + 'Connection: close\r\n' + + 'Content-Length: 6\r\n\r\n' + + 'second', + ); + server.close(); + })); + socket.write( + 'GET /1 HTTP/1.1\r\nHost: localhost\r\n\r\n' + + 'POST /2 HTTP/1.1\r\nHost: localhost\r\nExpect: 100-continue\r\n' + + 'Content-Length: 0\r\nConnection: close\r\n\r\n', + ); + })); +} + +test('second'); +test(Buffer.from('second')); +test(new Uint8Array(Buffer.from('second')));