Skip to content

Commit d803355

Browse files
Aviv Kellertargos
Aviv Keller
authored andcommitted
lib: prefer optional chaining
PR-URL: #55045 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com> Reviewed-By: Chemi Atlow <chemi@atlow.co.il> Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com> Reviewed-By: Paolo Insogna <paolo@cowtech.it> Reviewed-By: Marco Ippolito <marcoippolito54@gmail.com> Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
1 parent cbfc980 commit d803355

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+228
-121
lines changed

eslint.config.mjs

+1
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,7 @@ export default [
313313
'node-core/no-unescaped-regexp-dot': 'error',
314314
'node-core/no-duplicate-requires': 'error',
315315
'node-core/prefer-proto': 'error',
316+
'node-core/prefer-optional-chaining': 'error',
316317
},
317318
},
318319
// #endregion

lib/_http_agent.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ function Agent(options) {
128128
}
129129

130130
const requests = this.requests[name];
131-
if (requests && requests.length) {
131+
if (requests?.length) {
132132
const req = requests.shift();
133133
const reqAsyncRes = req[kRequestAsyncResource];
134134
if (reqAsyncRes) {
@@ -437,7 +437,7 @@ Agent.prototype.removeSocket = function removeSocket(s, options) {
437437
}
438438

439439
let req;
440-
if (this.requests[name] && this.requests[name].length) {
440+
if (this.requests[name]?.length) {
441441
debug('removeSocket, have a request, make a socket');
442442
req = this.requests[name][0];
443443
} else {
@@ -449,7 +449,7 @@ Agent.prototype.removeSocket = function removeSocket(s, options) {
449449
for (let i = 0; i < keys.length; i++) {
450450
const prop = keys[i];
451451
// Check whether this specific origin is already at maxSockets
452-
if (this.sockets[prop] && this.sockets[prop].length) break;
452+
if (this.sockets[prop]?.length) break;
453453
debug('removeSocket, have a request with different origin,' +
454454
' make a socket');
455455
req = this.requests[prop][0];

lib/_http_client.js

+5-5
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ function ClientRequest(input, options, cb) {
174174

175175
const protocol = options.protocol || defaultAgent.protocol;
176176
let expectedProtocol = defaultAgent.protocol;
177-
if (this.agent && this.agent.protocol)
177+
if (this.agent?.protocol)
178178
expectedProtocol = this.agent.protocol;
179179

180180
if (options.path) {
@@ -190,7 +190,7 @@ function ClientRequest(input, options, cb) {
190190
}
191191

192192
const defaultPort = options.defaultPort ||
193-
(this.agent && this.agent.defaultPort);
193+
(this.agent?.defaultPort);
194194

195195
const optsWithoutSignal = { __proto__: null, ...options };
196196

@@ -553,7 +553,7 @@ function socketOnData(d) {
553553
socket.destroy();
554554
req.socket._hadError = true;
555555
emitErrorEvent(req, ret);
556-
} else if (parser.incoming && parser.incoming.upgrade) {
556+
} else if (parser.incoming?.upgrade) {
557557
// Upgrade (if status code 101) or CONNECT
558558
const bytesParsed = ret;
559559
const res = parser.incoming;
@@ -591,7 +591,7 @@ function socketOnData(d) {
591591
// Requested Upgrade or used CONNECT method, but have no handler.
592592
socket.destroy();
593593
}
594-
} else if (parser.incoming && parser.incoming.complete &&
594+
} else if (parser.incoming?.complete &&
595595
// When the status code is informational (100, 102-199),
596596
// the server will send a final response after this client
597597
// sends a request body, so we must not free the parser.
@@ -838,7 +838,7 @@ function tickOnSocket(req, socket) {
838838

839839
if (
840840
req.timeout !== undefined ||
841-
(req.agent && req.agent.options && req.agent.options.timeout)
841+
(req.agent?.options?.timeout)
842842
) {
843843
listenSocketTimeout(req);
844844
}

lib/_http_common.js

+1-2
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,7 @@ function parserOnHeadersComplete(versionMajor, versionMinor, headers, method,
8585
}
8686

8787
// Parser is also used by http client
88-
const ParserIncomingMessage = (socket && socket.server &&
89-
socket.server[kIncomingMessage]) ||
88+
const ParserIncomingMessage = (socket?.server?.[kIncomingMessage]) ||
9089
IncomingMessage;
9190

9291
const incoming = parser.incoming = new ParserIncomingMessage(socket);

lib/_http_incoming.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ IncomingMessage.prototype._destroy = function _destroy(err, cb) {
242242

243243
IncomingMessage.prototype._addHeaderLines = _addHeaderLines;
244244
function _addHeaderLines(headers, n) {
245-
if (headers && headers.length) {
245+
if (headers?.length) {
246246
let dest;
247247
if (this.complete) {
248248
this.rawTrailers = headers;

lib/_http_outgoing.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -423,7 +423,7 @@ OutgoingMessage.prototype._send = function _send(data, encoding, callback, byteL
423423
OutgoingMessage.prototype._writeRaw = _writeRaw;
424424
function _writeRaw(data, encoding, callback, size) {
425425
const conn = this[kSocket];
426-
if (conn && conn.destroyed) {
426+
if (conn?.destroyed) {
427427
// The socket was destroyed. If we're still trying to write to it,
428428
// then we haven't gotten the 'close' event yet.
429429
return false;
@@ -789,7 +789,7 @@ OutgoingMessage.prototype.getHeader = function getHeader(name) {
789789
return;
790790

791791
const entry = headers[name.toLowerCase()];
792-
return entry && entry[1];
792+
return entry?.[1];
793793
};
794794

795795

@@ -1073,7 +1073,7 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
10731073
};
10741074

10751075
function onFinish(outmsg) {
1076-
if (outmsg && outmsg.socket && outmsg.socket._hadError) return;
1076+
if (outmsg?.socket?._hadError) return;
10771077
outmsg.emit('finish');
10781078
}
10791079

@@ -1188,7 +1188,7 @@ OutgoingMessage.prototype._finish = function _finish() {
11881188
OutgoingMessage.prototype._flush = function _flush() {
11891189
const socket = this[kSocket];
11901190

1191-
if (socket && socket.writable) {
1191+
if (socket?.writable) {
11921192
// There might be remaining data in this.output; write it out
11931193
const ret = this._flushOutput(socket);
11941194

lib/_http_server.js

+5-5
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,7 @@ function connectionListenerInternal(server, socket) {
738738
socket.setEncoding = socketSetEncoding;
739739

740740
// We only consume the socket if it has never been consumed before.
741-
if (socket._handle && socket._handle.isStreamBase &&
741+
if (socket._handle?.isStreamBase &&
742742
!socket._handle._consumed) {
743743
parser._consumed = true;
744744
socket._handle._consumed = true;
@@ -783,7 +783,7 @@ function socketOnDrain(socket, state) {
783783
}
784784

785785
function socketOnTimeout() {
786-
const req = this.parser && this.parser.incoming;
786+
const req = this.parser?.incoming;
787787
const reqTimeout = req && !req.complete && req.emit('timeout', this);
788788
const res = this._httpMessage;
789789
const resTimeout = res && res.emit('timeout', this);
@@ -918,7 +918,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) {
918918
prepareError(ret, parser, d);
919919
debug('parse error', ret);
920920
socketOnError.call(socket, ret);
921-
} else if (parser.incoming && parser.incoming.upgrade) {
921+
} else if (parser.incoming?.upgrade) {
922922
// Upgrade or CONNECT
923923
const req = parser.incoming;
924924
debug('SERVER upgrade or connect', req.method);
@@ -963,7 +963,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) {
963963

964964
function clearIncoming(req) {
965965
req = req || this;
966-
const parser = req.socket && req.socket.parser;
966+
const parser = req.socket?.parser;
967967
// Reset the .incoming property so that the request object can be gc'ed.
968968
if (parser && parser.incoming === req) {
969969
if (req.readableEnded) {
@@ -1180,7 +1180,7 @@ function onSocketResume() {
11801180
}
11811181

11821182
function onSocketPause() {
1183-
if (this._handle && this._handle.reading) {
1183+
if (this._handle?.reading) {
11841184
this._handle.reading = false;
11851185
this._handle.readStop();
11861186
}

lib/_tls_wrap.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,7 @@ function initRead(tlsSocket, socket) {
489489
return;
490490

491491
// Socket already has some buffered data - emulate receiving it
492-
if (socket && socket.readableLength) {
492+
if (socket?.readableLength) {
493493
let buf;
494494
while ((buf = socket.read()) !== null)
495495
tlsSocket._handle.receive(buf);
@@ -1683,7 +1683,7 @@ function onConnectSecure() {
16831683
if (!verifyError && !this.isSessionReused()) {
16841684
const hostname = options.servername ||
16851685
options.host ||
1686-
(options.socket && options.socket._host) ||
1686+
(options.socket?._host) ||
16871687
'localhost';
16881688
const cert = this.getPeerCertificate(true);
16891689
verifyError = options.checkServerIdentity(hostname, cert);

lib/assert.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ function expectedException(actual, expected, message, fn) {
446446
message = 'The error is expected to be an instance of ' +
447447
`"${expected.name}". Received `;
448448
if (isError(actual)) {
449-
const name = (actual.constructor && actual.constructor.name) ||
449+
const name = (actual.constructor?.name) ||
450450
actual.name;
451451
if (expected.name === name) {
452452
message += 'an error with identical name but a different prototype.';
@@ -569,7 +569,7 @@ function expectsError(stackStartFn, actual, error, message) {
569569

570570
if (actual === NO_EXCEPTION_SENTINEL) {
571571
let details = '';
572-
if (error && error.name) {
572+
if (error?.name) {
573573
details += ` (${error.name})`;
574574
}
575575
details += message ? `: ${message}` : '.';
@@ -627,7 +627,7 @@ function expectsNoError(stackStartFn, actual, error, message) {
627627
expected: error,
628628
operator: stackStartFn.name,
629629
message: `Got unwanted ${fnType}${details}\n` +
630-
`Actual message: "${actual && actual.message}"`,
630+
`Actual message: "${actual?.message}"`,
631631
stackStartFn,
632632
});
633633
}

lib/child_process.js

+3-5
Original file line numberDiff line numberDiff line change
@@ -392,17 +392,15 @@ function execFile(file, args, options, callback) {
392392
let stderr;
393393
if (encoding ||
394394
(
395-
child.stdout &&
396-
child.stdout.readableEncoding
395+
child.stdout?.readableEncoding
397396
)) {
398397
stdout = ArrayPrototypeJoin(_stdout, '');
399398
} else {
400399
stdout = Buffer.concat(_stdout);
401400
}
402401
if (encoding ||
403402
(
404-
child.stderr &&
405-
child.stderr.readableEncoding
403+
child.stderr?.readableEncoding
406404
)) {
407405
stderr = ArrayPrototypeJoin(_stderr, '');
408406
} else {
@@ -855,7 +853,7 @@ function spawnSync(file, args, options) {
855853

856854
// We may want to pass data in on any given fd, ensure it is a valid buffer
857855
for (let i = 0; i < options.stdio.length; i++) {
858-
const input = options.stdio[i] && options.stdio[i].input;
856+
const input = options.stdio[i]?.input;
859857
if (input != null) {
860858
const pipe = options.stdio[i] = { ...options.stdio[i] };
861859
if (isArrayBufferView(input)) {

lib/dgram.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,8 @@ function Socket(type, listener) {
128128
bindState: BIND_STATE_UNBOUND,
129129
connectState: CONNECT_STATE_DISCONNECTED,
130130
queue: undefined,
131-
reuseAddr: options && options.reuseAddr, // Use UV_UDP_REUSEADDR if true.
132-
ipv6Only: options && options.ipv6Only,
131+
reuseAddr: options?.reuseAddr, // Use UV_UDP_REUSEADDR if true.
132+
ipv6Only: options?.ipv6Only,
133133
recvBufferSize,
134134
sendBufferSize,
135135
};

lib/internal/bootstrap/switches/is_main_thread.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ function getStdin() {
251251
// `stdin` starts out life in a paused state, but node doesn't
252252
// know yet. Explicitly to readStop() it to put it in the
253253
// not-reading state.
254-
if (stdin._handle && stdin._handle.readStop) {
254+
if (stdin._handle?.readStop) {
255255
stdin._handle.reading = false;
256256
stdin._readableState.reading = false;
257257
stdin._handle.readStop();

lib/internal/child_process.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -855,7 +855,7 @@ function setupChannel(target, channel, serializationMode) {
855855
if (handle) {
856856
if (!this._handleQueue)
857857
this._handleQueue = [];
858-
if (obj && obj.postSend)
858+
if (obj?.postSend)
859859
obj.postSend(message, handle, options, callback, target);
860860
}
861861

@@ -871,7 +871,7 @@ function setupChannel(target, channel, serializationMode) {
871871
}
872872
} else {
873873
// Cleanup handle on error
874-
if (obj && obj.postSend)
874+
if (obj?.postSend)
875875
obj.postSend(message, handle, options, callback);
876876

877877
if (!options.swallowErrors) {
@@ -1116,8 +1116,8 @@ function spawnSync(options) {
11161116
}
11171117
}
11181118

1119-
result.stdout = result.output && result.output[1];
1120-
result.stderr = result.output && result.output[2];
1119+
result.stdout = result.output?.[1];
1120+
result.stderr = result.output?.[2];
11211121

11221122
if (result.error) {
11231123
result.error = new ErrnoException(result.error, 'spawnSync ' + options.file);

lib/internal/cluster/child.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ cluster._getServer = function(obj, options, cb) {
122122
cluster.worker.state = 'listening';
123123
const address = obj.address();
124124
message.act = 'listening';
125-
message.port = (address && address.port) || options.port;
125+
message.port = (address?.port) || options.port;
126126
send(message);
127127
});
128128
};

lib/internal/crypto/hashnames.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ function normalizeHashName(name, context = kHashContextNode) {
7070
if (typeof name !== 'string')
7171
return name;
7272
name = StringPrototypeToLowerCase(name);
73-
const alias = kHashNames[name] && kHashNames[name][context];
73+
const alias = kHashNames[name]?.[context];
7474
return alias || name;
7575
}
7676

lib/internal/debugger/inspect_repl.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,7 @@ function createRepl(inspector) {
694694

695695
function handleBreakpointResolved({ breakpointId, location }) {
696696
const script = knownScripts[location.scriptId];
697-
const scriptUrl = script && script.url;
697+
const scriptUrl = script?.url;
698698
if (scriptUrl) {
699699
ObjectAssign(location, { scriptUrl });
700700
}
@@ -733,7 +733,7 @@ function createRepl(inspector) {
733733
function setBreakpoint(script, line, condition, silent) {
734734
function registerBreakpoint({ breakpointId, actualLocation }) {
735735
handleBreakpointResolved({ breakpointId, location: actualLocation });
736-
if (actualLocation && actualLocation.scriptId) {
736+
if (actualLocation?.scriptId) {
737737
if (!silent) return getSourceSnippet(actualLocation, 5);
738738
} else {
739739
print(`Warning: script '${script}' was not loaded yet.`);

lib/internal/dns/callback_resolver.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ function resolver(bindingName) {
6767
req.callback = callback;
6868
req.hostname = name;
6969
req.oncomplete = onresolve;
70-
req.ttl = !!(options && options.ttl);
70+
req.ttl = !!(options?.ttl);
7171
const err = this._handle[bindingName](req, name);
7272
if (err) throw new DNSException(err, bindingName, name);
7373
if (hasObserver('dns')) {

lib/internal/dns/promises.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ function resolver(bindingName) {
336336
function query(name, options) {
337337
validateString(name, 'name');
338338

339-
const ttl = !!(options && options.ttl);
339+
const ttl = !!(options?.ttl);
340340
return createResolverPromise(this, bindingName, name, ttl);
341341
}
342342

lib/internal/error_serdes.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ function GetConstructors(object) {
8585
current !== null;
8686
current = ObjectGetPrototypeOf(current)) {
8787
const desc = ObjectGetOwnPropertyDescriptor(current, 'constructor');
88-
if (desc && desc.value) {
88+
if (desc?.value) {
8989
ObjectDefineProperty(constructors, constructors.length, {
9090
__proto__: null,
9191
value: desc.value, enumerable: true,
@@ -98,7 +98,7 @@ function GetConstructors(object) {
9898

9999
function GetName(object) {
100100
const desc = ObjectGetOwnPropertyDescriptor(object, 'name');
101-
return desc && desc.value;
101+
return desc?.value;
102102
}
103103

104104
let internalUtilInspect;

lib/internal/modules/esm/loader.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,7 @@ class ModuleLoader {
393393
if (cjsModule) {
394394
assert(finalFormat === 'commonjs-sync');
395395
// Check if the ESM initiating import CJS is being required by the same CJS module.
396-
if (cjsModule && cjsModule[kIsExecuting]) {
396+
if (cjsModule?.[kIsExecuting]) {
397397
const parentFilename = urlToFilename(parentURL);
398398
let message = `Cannot import CommonJS Module ${specifier} in a cycle.`;
399399
if (parentFilename) {

0 commit comments

Comments
 (0)