Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

net: refactor Server.prototype.listen #4039

Closed
wants to merge 15 commits into from
15 changes: 8 additions & 7 deletions lib/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,9 @@ function normalizeArgs(args) {
}

var cb = args[args.length - 1];
return typeof cb === 'function' ? [options, cb] : [options];
if (typeof cb !== 'function')
cb = null;
return [options, cb];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment for normalizeArgs() needs to be updated now too.

}
exports._normalizeArgs = normalizeArgs;

Expand Down Expand Up @@ -1330,21 +1332,20 @@ Server.prototype.listen = function() {
var args = new Array(arguments.length);
for (var i = 0; i < arguments.length; i++)
args[i] = arguments[i];
args = normalizeArgs(args);
var [options, cb] = normalizeArgs(args);

if (args[1]) {
this.once('listening', args[1]);
if (typeof cb === 'function') {
this.once('listening', cb);
}

var options = args[0];
if (arguments.length === 0 || typeof arguments[0] === 'function') {
if (args.length === 0 || typeof args[0] === 'function') {
// Bind to a random port.
options.port = 0;
}

// The third optional argument is the backlog size.
// When the ip is omitted it can be the second argument.
var backlog = toNumber(arguments[1]) || toNumber(arguments[2]);
var backlog = toNumber(args[1]) || toNumber(args[2]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May want to do args.length checking before accessing [1] or [2].

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean like this?

var backlog = toNumber(args.length > 1 && args[1]) || toNumber(args.length > 2 && args[2]);

But is it really necessary / worth it to optimize this function? I don't think it's one of the hot functions in an usual node application, you call listen once during startup and not hundreds of times a second. What is your opinion?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ping @mscdex

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd still prefer it for consistency.


options = options._handle || options.handle || options;

Expand Down