Skip to content

Commit

Permalink
net: allow missing callback for Socket.connect
Browse files Browse the repository at this point in the history
Arguments of Socket.prototype.connect should be also normalized,
causing error when called without callback.

Changed Socket.prototype.connect's code same as net.connect and added
test.

Fixes: nodejs#11761
PR-URL: nodejs#11762
Reviewed-By: Sam Roberts <vieuxtech@gmail.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Evan Lucas <evanlucas@me.com>
  • Loading branch information
vhain authored and italoacasas committed Mar 13, 2017
1 parent 52f0092 commit 1dff218
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 15 deletions.
24 changes: 9 additions & 15 deletions lib/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -899,24 +899,18 @@ function connect(self, address, port, addressType, localAddress, localPort) {
}


Socket.prototype.connect = function(options, cb) {
Socket.prototype.connect = function() {
const args = new Array(arguments.length);
for (var i = 0; i < arguments.length; i++)
args[i] = arguments[i];
// TODO(joyeecheung): use destructuring when V8 is fast enough
const normalized = normalizeArgs(args);
const options = normalized[0];
const cb = normalized[1];

if (this.write !== Socket.prototype.write)
this.write = Socket.prototype.write;

if (options === null || typeof options !== 'object') {
// Old API:
// connect(port[, host][, cb])
// connect(path[, cb]);
const args = new Array(arguments.length);
for (var i = 0; i < arguments.length; i++)
args[i] = arguments[i];
const normalized = normalizeArgs(args);
const normalizedOptions = normalized[0];
const normalizedCb = normalized[1];
return Socket.prototype.connect.call(this,
normalizedOptions, normalizedCb);
}

if (this.destroyed) {
this._readableState.reading = false;
this._readableState.ended = false;
Expand Down
20 changes: 20 additions & 0 deletions test/parallel/test-net-socket-connect-without-cb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';
const common = require('../common');

// This test ensures that socket.connect can be called without callback
// which is optional.

const net = require('net');

const server = net.createServer(common.mustCall(function(conn) {
conn.end();
server.close();
})).listen(0, common.mustCall(function() {
const client = new net.Socket();

client.on('connect', common.mustCall(function() {
client.end();
}));

client.connect(server.address());
}));

0 comments on commit 1dff218

Please sign in to comment.