diff --git a/lib/net_legacy.js b/lib/net_legacy.js index 4221aa11461..3e451b7a3a3 100644 --- a/lib/net_legacy.js +++ b/lib/net_legacy.js @@ -728,7 +728,13 @@ Socket.prototype.connect = function() { // TCP require('dns').lookup(host, function(err, ip, addressType) { if (err) { - self.emit('error', err); + // net.createConnection() creates a net.Socket object and + // immediately calls net.Socket.connect() on it (that's us). + // There are no event listeners registered yet so defer the + // error event to the next tick. + process.nextTick(function() { + self.emit('error', err); + }); } else { timers.active(self); self.type = addressType == 4 ? 'tcp4' : 'tcp6'; diff --git a/lib/net_uv.js b/lib/net_uv.js index 80d709fa4dc..1da43bce5da 100644 --- a/lib/net_uv.js +++ b/lib/net_uv.js @@ -449,7 +449,13 @@ Socket.prototype.connect = function(port /* [host], [cb] */) { debug("connect: find host " + host); require('dns').lookup(host, function(err, ip, addressType) { if (err) { - self.emit('error', err); + // net.createConnection() creates a net.Socket object and + // immediately calls net.Socket.connect() on it (that's us). + // There are no event listeners registered yet so defer the + // error event to the next tick. + process.nextTick(function() { + self.emit('error', err); + }); } else { timers.active(self);