diff --git a/lib/net.js b/lib/net.js index 9b0b1f87a636e5..cc80bb3a348da7 100644 --- a/lib/net.js +++ b/lib/net.js @@ -886,8 +886,13 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) { this._pendingData = data; this._pendingEncoding = encoding; this.once('connect', function connect() { + this.off('close', onClose); this._writeGeneric(writev, data, encoding, cb); }); + function onClose() { + cb(new ERR_SOCKET_CLOSED()); + } + this.once('close', onClose); return; } this._pendingData = null; diff --git a/test/parallel/test-net-write-cb-on-destroy.js b/test/parallel/test-net-write-cb-on-destroy.js new file mode 100644 index 00000000000000..92d1e58f3bfe8a --- /dev/null +++ b/test/parallel/test-net-write-cb-on-destroy.js @@ -0,0 +1,24 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); + +const server = net.createServer(); +server.listen(0, common.mustCall(() => { + const socket = new net.Socket(); + + socket.connect({ + port: server.address().port, + }); + + assert(socket.connecting); + + socket.write('foo', common.expectsError({ + code: 'ERR_SOCKET_CLOSED', + name: 'Error' + })); + + socket.destroy(); + server.close(); +}));