diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index a5b3863abaeebb..a2d5723a71c19f 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -334,6 +334,12 @@ OutgoingMessage.prototype.destroy = function destroy(error) { // This abstract either writing directly to the socket or buffering it. OutgoingMessage.prototype._send = function _send(data, encoding, callback) { + if (typeof data === 'string' && encoding === 'hex') { + if (data.length % 2 !== 0) { + throw new ERR_INVALID_ARG_VALUE('data', data, 'is invalid hex string'); + } + } + // This is a shameful hack to get the headers and first body chunk onto // the same packet. Future versions of Node are going to take care of // this at a lower level and in a more general way. diff --git a/test/parallel/test-http-hex-write.js b/test/parallel/test-http-hex-write.js index a3cbec6b36c0ad..363fbe0538edc2 100644 --- a/test/parallel/test-http-hex-write.js +++ b/test/parallel/test-http-hex-write.js @@ -27,12 +27,11 @@ const http = require('http'); const expect = 'hex\nutf8\n'; -http.createServer(function(q, s) { +const server = http.createServer(function(q, s) { s.setHeader('content-length', expect.length); s.write('6865780a', 'hex'); s.write('utf8\n'); s.end(); - this.close(); }).listen(0, common.mustCall(function() { http.request({ port: this.address().port }) .on('response', common.mustCall(function(res) { @@ -46,4 +45,15 @@ http.createServer(function(q, s) { assert.strictEqual(data, expect); })); })).end(); + + // Refs: https://github.com/nodejs/node/issues/45150 + const invalidReq = http.request({ port: this.address().port }); + assert.throws( + () => { invalidReq.write('boom!', 'hex'); }, + { + code: 'ERR_INVALID_ARG_VALUE', + message: 'The argument \'data\' is invalid hex string. Received \'boom!\'' + } + ); + invalidReq.end(() => server.close()); }));